首页 > 热点 > 微信 > 正文

微信公众号平台接口开发 获取access_token过程解析

2024-07-22 01:17:45
字体:
来源:转载
供稿:网友

新建Asp.net MVC 4.0项目

WeChatSubscript是项目UI层

WeChatTools是封装操作访问公众号接口的一些方法类库

获取AccssToken

我们要的得到AccessToken,这是所有接口访问的基础,我们看看官方给出的接口调用文档

很简单明了,grant_type=client_credential,这是固定的不会变

appid与secret就是前面一章我叫大家记起来的那个认证口令数据。

下边我们来实现这个功能,新建WeCharBase.cs

public class WeCharBase  {    private static readonly string appId;    private static readonly string appSecret;    static WeCharBase()    {      appId = "**********";      appSecret = "832090bfddabbac19cc8da5053aea47b";    }    public static string AccessToken    {      get { return GetAccessToken(); }    }    /// <summary>获取access_token</summary>    /// <param name="appId"></param>    /// <param name="appSecret"></param>    /// <returns></returns>    private static string GetAccessToken()    {      if (HttpContext.Current == null)      {        return GetToken();      }      var accessTokenCache = HttpContext.Current.Cache["access_token"];      if (accessTokenCache != null)      {        return accessTokenCache.ToString();      }      else      {        return GetToken();      }    }    /// <summary>获取ccess_token</summary>    /// <returns></returns>    private static string GetToken()    {      try      {        var client = new WebClient();        client.Encoding = Encoding.UTF8;        var responseData = client.DownloadString(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appId, appSecret));        var javaScriptSerializer = new JavaScriptSerializer();        var accessDictionary = javaScriptSerializer.Deserialize<Dictionary<string, object>>(responseData);        var accessToken = accessDictionary["access_token"];        if (accessToken == null)        {          return string.Empty;        }        HttpContext.Current.Cache.Insert("access_token", accessToken, null, DateTime.Now.AddSeconds(7100), TimeSpan.Zero, CacheItemPriority.Normal, null);        HttpContext.Current.Cache.Remove("ticket");        GetTicket();        return accessToken.ToString();      }      catch (Exception ex)      {        return ex.Message;      }    }  }

细心的童鞋功能注意到这里用了HttpContext.Current.Cache,为什么呢?

因为access_token在官方服务器会缓存2个小时,请求一次,这个access_token在2个小时内都有效

所以请求一次得到access_token后,在以后的2个小时内都可以用这个access_token去访问其他接口

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表