国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 熱點 > 微信 > 正文

微信公眾號平臺接口開發 獲取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去訪問其他接口

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 赤水市| 闸北区| 金坛市| 嵊州市| 霍山县| 枣庄市| 祁东县| 缙云县| 四川省| 泸水县| 永顺县| 左权县| 临城县| 宁蒗| 隆德县| 保定市| 湄潭县| 丰县| 平安县| 凤庆县| 崇左市| 和顺县| 通州市| 南昌县| 申扎县| 禄劝| 淳安县| 壶关县| 凌云县| 南涧| 木里| 呼伦贝尔市| 安陆市| 灵宝市| 潼南县| 遂溪县| 大竹县| 新龙县| 乌鲁木齐市| 曲沃县| 贺兰县|