コード例 #1
0
        public async Task <string> GetWxAccessTokenAsync(string appId, string secret)
        {
            var key = KeyForOther($"Weixin:AccessToken:{appId}");
            var now = DateTime.Now;
            var ret = await Database.StringGetAsync(key);

            JObject json = null;

            if (!ret.IsNull)
            {
                json = JObject.Parse(ret);
                if (json["expire_time"].Value <DateTime>() > now)
                {
                    return(json["access_token"].Value <string>());
                }
            }

            var token = await WeixinHelper.GetAccessTokenAsync(appId, secret);

            json = JObject.Parse(token);
            if (json["errcode"] != null && json["errcode"].Value <int>() > 0)
            {
                throw new Exception($"获取令牌错误,{json["errmsg"].Value<string>()}");
            }
            json.Add("expire_time", now.AddSeconds(7000));      // 距离获取时间7000秒后过期
            await Database.StringSetAsync(key, json.ToJson());

            return(json["access_token"].Value <string>());
        }