.NET自动获取Token,
我就直接上图片了,后面是完整代码,可以复制到你的项目,
我这个方法有点笨,但是没有任何问题
--------------------------------------------------------------从下方开始复制------------------------------------------------------
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; using System.Web.Script.Serialization; using WeChat.Models;
namespace WeChat.DAL {
public class WeChatCommon { #region 获取Access_token
/// <summary> /// Token /// </summary> private static string _access_token { get; set; } /// <summary> /// 时间,用来判断是否该更新了 /// </summary> private static int _datetime = 0;
/// <summary> /// Access_token,每个小时获取一次 /// </summary> private static string Access_token { get { //第二次判断防止多次申请 if (_datetime != DateTime.Now.Hour) { _datetime = DateTime.Now.Hour; if (GetAccess_token()) return _access_token; else return null; } else return _access_token; } } #endregion
#region 获取Access_token /// <summary> /// 返回Access_token /// </summary> /// <returns></returns> private static string ReturnAccess_token() { //第一次判断,每小时刷新一次Token,此处带锁 if (_datetime != DateTime.Now.Hour) { lock (Access_token) { return Access_token; } } return _access_token;
}
/// <summary> /// 获取GetAccess_token /// </summary> /// <returns>Access_token</returns> private static bool GetAccess_token() { string Secret = ""; string APPID = ""; //url string uri =string.Format( @"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}",APPID,Secret);
//初始化http请求 HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest; request.Method = "GET";//请求方法 request.AllowAutoRedirect = false;//禁止重定向
//获取返回的信息 using (WebResponse web = request.GetResponse()) { StreamReader reader = new StreamReader(web.GetResponseStream(), Encoding.UTF8); string json = reader.ReadToEnd(); JavaScriptSerializer js = new JavaScriptSerializer(); Access_token access_token = js.Deserialize<Access_token>(json);
if (access_token.errcode != "41004" && access_token.errcode != null) { _access_token = access_token.access_token; return true; } else return false;
} }
#endregion } }
-------------------------------------------------------------------------------------------------------