代码改变世界

获取微信Token接口数据

2020-07-26 09:25  idea555  阅读(531)  评论(0)    收藏  举报

/// <summary>
/// 微信Token接口
/// </summary>
public static class TokenApi
{
private static object locker = new object();
private static Dictionary<string, DateTime> expiresDic = new Dictionary<string, DateTime>();
private static Dictionary<string, string> access_tokenDic = new Dictionary<string, string>();


#region 1.0 获得Token
/// <summary>
/// 获得Token
/// </summary>
/// <returns></returns>
public static string GetToken(string appId, string secret)
{
//异步加锁
lock (locker)
{
DateTime now = DateTime.Now;
//获得过期时间
DateTime expires = expiresDic.ContainsKey(appId) ? expiresDic[appId] : now;
double span = (now - expires).TotalSeconds;

//如果access_token不存在,或者超过7000秒,则重新获取token
if (!access_tokenDic.ContainsKey(appId) || span > 7000)
{
string tokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + appId + "&corpsecret=" + secret;
// DbHelperSQL.ExecuteSql("insert into test (content) values ('" + tokenUrl + "')");
string json = Utilities.HttpHelper.GetJson(tokenUrl);
Token token = Utilities.JsonHelper.JsonToObject<Token>(json);

//缓存token
access_tokenDic.Remove(appId);
access_tokenDic.Add(appId, token.access_token);

//过期时间
expiresDic.Remove(appId);
expiresDic[appId] = DateTime.Now;
}
return access_tokenDic[appId];
}
}
#endregion

 


}