access_token是公衆號的全局惟一票據,公衆號調用各接口時都需使用access_token。api
接口調用請求說明微信
http請求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
參數說明app
參數 | 是否必須 | 說明 |
---|---|---|
grant_type | 是 | 獲取access_token填寫client_credential |
appid | 是 | 第三方用戶惟一憑證 |
secret | 是 | 第三方用戶惟一憑證密鑰,即appsecret |
返回說明url
正常狀況下,微信會返回下述JSON數據包給公衆號:spa
{"access_token":"ACCESS_TOKEN","expires_in":7200}
參數 | 說明 |
---|---|
access_token | 獲取到的憑證 |
expires_in | 憑證有效時間,單位:秒 |
錯誤時微信會返回錯誤碼等信息,JSON數據包示例以下(該示例爲AppID無效錯誤):code
{"errcode":40013,"errmsg":"invalid appid"}
具體實現的代碼以下:
//獲取微信憑證access_token的接口 public static string getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}"; #region 獲取微信憑證 public string GetAccessToken(string wechat_id) { string accessToken = ""; //獲取配置信息Datatable DataTable dtwecaht = wechatdal.GetList("wechat_id='" + wechat_id + "'").Tables[0]; if (dtwecaht.Rows.Count > 0) { string respText = ""; //獲取appid和appsercret string wechat_appid = dtwecaht.Rows[0]["wechat_appid"].ToString(); string wechat_appsecret = dtwecaht.Rows[0]["wechat_appsecret"].ToString(); //獲取josn數據 string url = string.Format(getAccessTokenUrl, wechat_appid, wechat_appsecret); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream resStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(resStream, Encoding.Default); respText = reader.ReadToEnd(); resStream.Close(); } JavaScriptSerializer Jss = new JavaScriptSerializer(); Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText); //經過鍵access_token獲取值 accessToken = respDic["access_token"].ToString(); } return accessToken; } #endregion 獲取微信憑證
後面調用接口的時候,就直接調用這個方法獲取access_token便可。orm