/// <summary> ///【异步方法】获取可用Token /// </summary> /// <param name="componentAppId"></param> /// <param name="getNewToken">是否强制重新获取新的Token</param> /// <returns></returns> public static async Task <PreAuthCodeResult> GetPreAuthCodeResultAsync(string componentAppId, bool getNewToken = false) { if (!CheckRegistered(componentAppId)) { throw new WeixinOpenException(UN_REGISTER_ALERT); } var componentBag = TryGetItem(componentAppId); using (Cache.BeginCacheLock(LockResourceName + ".GetPreAuthCodeResult", componentAppId))//同步锁 { if (getNewToken || componentBag.PreAuthCodeExpireTime <= DateTime.Now) { //已过期,重新获取 var componentVerifyTicket = TryGetComponentVerifyTicket(componentAppId); var accessToken = TryGetComponentAccessToken(componentAppId, componentBag.ComponentAppSecret, componentVerifyTicket); var preAuthCodeResult = await ComponentApi.GetPreAuthCodeAsync(componentBag.ComponentAppId, accessToken); componentBag.PreAuthCodeExpireTime = ApiUtility.GetExpireTime(preAuthCodeResult.expires_in); componentBag.PreAuthCodeResult = preAuthCodeResult; ////TODO:这里有出现expires_in=0的情况,导致始终处于过期状态(也可能是因为参数过期等原因没有返回正确的数据,待观察) //var expiresIn = componentBag.PreAuthCodeResult.expires_in > 0 // ? componentBag.PreAuthCodeResult.expires_in // : 60 * 20;//默认为20分钟 //componentBag.PreAuthCodeExpireTime = DateTime.Now.AddSeconds(expiresIn); } } return(componentBag.PreAuthCodeResult); }