/// <summary>
 /// 注册应用凭证信息,此操作只是注册,不会马上获取Token,并将清空之前的Token,
 /// </summary>
 /// <param name="appId"></param>
 /// <param name="appSecret"></param>
 public static void Register(string appId, string appSecret)
 {
     AccessTokenCollection[appId + "_" + appSecret] = new AccessTokenBag()
     {
         AppId             = appId,
         AppSecret         = appSecret,
         ExpireTime        = DateTime.MinValue,
         AccessTokenResult = new AccessTokenResult()
     };
 }
Exemplo n.º 2
0
        /// <summary>
        /// 获取可用Token
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="getNewToken">是否强制重新获取新的Token</param>
        /// <returns></returns>
        public static AccessTokenResult GetAccessTokenResult(string appId, string appSecret, Func <string, string, string, AccessTokenResult> func, bool getNewToken = false)
        {
            string strKey = appId + "_" + appSecret + "_" + typeof(AccessTokenBag).Name;

            if (!CheckRegistered(strKey))
            {
                Register(appId, appSecret);
            }

            var accessTokenBag = AccessTokenCollection[strKey];

            lock (accessTokenBag.Lock)
            {
                if (getNewToken || accessTokenBag.ExpireTime <= DateTime.Now)
                {
                    var strDBFlag = System.Configuration.ConfigurationManager.AppSettings["TokenStoreType"];


                    AccessTokenBag token = null;

                    if (string.IsNullOrEmpty(strDBFlag) || strDBFlag != "Server")
                    {
                        token = AccessTokenCache <AccessTokenBag, AccessTokenResult> .GetAccessTokenResult(appId, appSecret, func, getNewToken);
                    }
                    else
                    {
                        var    strUrlTemp = System.Configuration.ConfigurationManager.AppSettings["TokenServer"];
                        string strUrl     = string.Format("{0}?corpId={1}&corpSecret={2}", strUrlTemp, appId, appSecret);
                        var    objToken   = Innocellence.Weixin.HttpUtility.Get.GetJson <TokenEntity>(strUrl);
                        token = new AccessTokenBag()
                        {
                            TokenResult = new AccessTokenResult()
                            {
                                access_token = objToken.Token, expires_in = objToken.expires_in
                            },
                            ExpireTime = objToken.AccessTokenExpireTime,
                            CorpId     = appId,
                            CorpSecret = appSecret
                        };
                    }

                    //已过期,重新获取
                    accessTokenBag.TokenResult = token.TokenResult;
                    accessTokenBag.ExpireTime  = token.ExpireTime.AddMinutes(5); //让缓存先过期
                }
            }
            return(accessTokenBag.TokenResult);
        }