好记性不如烂笔头
调用微信的每个接口,都需要传access_token进行身份验证。 微信文档链接。
也是一个简单的get请求接口,可以用postman先测试一下。(这里测试需要在服务器进行。微信有接口IP验证,请求的IP与公众号配置的IP地址一致)
返回字符格式:{"access_token":"30_XjvzoAz2Ow8B-pn7IrPrNe5rXfW-Np2nwkmd-xMXnmWNzDm5w3-9LfAQG9E3fVS6VnGc1f8L66zEPepN1E1aAVhJpF0tVDMonS6FeiG0SQew97lxG0HA9Vxo7XUlk6VLDvNWc1s8e_SIUtxfXZSgAIADFY","expires_in":7200}
代码如下:
/// <summary> /// 获取微信公众号AccessToken /// </summary> /// <returns></returns> public AccessToken GetAccessToken() { var accesstoken = new AccessToken(); try { string str1 =Utils.HttpGet($"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={(object) appid}&secret={(object) AppSecret}"); if (str1.Contains("access_token")) { JObject Jobj = (JObject) JsonConvert.DeserializeObject(str1); string str2 = Jobj.Value<string>("access_token"); int num = Jobj.Value<int>("expires_in") / 2; accesstoken.Token = str2; accesstoken.ExpiresTime= DateTime.Now.AddSeconds((double)num); return accesstoken; } } catch (Exception e) { Utils.WriteTxt("生成AccessToken出错1:" + e.Message, "/debugLog.txt"); } return accesstoken; }
Utils.HttpGet中get请求方法:
public static string HttpGet(string url) { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Method = "GET"; httpWebRequest.Accept = "*/*"; string str = ""; using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse()) { using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8)) str = streamReader.ReadToEnd(); } return str; }
好啦。
得到了access_token,也能进行了微信对接的第一步。
千里之行始于足下。