1. Explain the WeChat applet AccessToken
Get the interface instructions in the same way as the public number, specify the appid and appsecret, and use get requests to get them.
Currently encapsulated and used in.net Core:
/// <summary> /// AccessToken Status Value Maintenance /// </summary> public class AccessTokenManage { /// <summary> ///Applet token /// </summary> public static string AccessToken = null; /// <summary> ///Expiration time /// </summary> public static DateTime NextTime { get; set; } /// <summary> ///Specifies whether the current thread can run /// </summary> private static bool EnableRun = true; /// <summary> ///Start maintenance /// </summary> public static void Run() { if (AccessToken == null) { Task.Factory.StartNew(() => { while (EnableRun) { //Timeout Re, Get //1. Get access_token first RequestAccessToken(); //Polling per minute Thread.Sleep(60000); } }); } } /* access_token The public number is the globally unique ticket that calls each interface using access_token.Developers need to save properly. access_token Store in at least 512 character spaces. access_token The validity period is currently 2 hours and needs to be refreshed periodically. Repeated fetches will invalidate access_token acquired last time. */ public static void RequestAccessToken() { try { string url = new LinkManage().GetAccessToken(); string result = NetHelper.Get(url); Access_TokenData data = JsonConvert.DeserializeObject<Access_TokenData>(result); if (string.IsNullOrEmpty(data.access_token)) { throw new Exception("Deserialization Get Access_TokenData fail"); } //Success AccessToken = data.access_token; NextTime = DateTime.Now.AddSeconds(data.expires_in - 60); //Test Code LogHelper.Write("Refresh Access_Token Success:" + AccessToken); } catch (Exception ex) { throw new Exception("Obtain AccessToken fail", ex); } } /// <summary> ///Result object returned by request /// </summary> public class Access_TokenData { public string access_token { get; set; } public int expires_in { get; set; } public string errcode { get; set; } public string errmsg { get; set; } } }
2. Start maintenance in program Startup
public Startup(IConfiguration configuration) { Configuration = configuration; //Configure refresh access_token MiniPackage.AccessTokenManage.Run(); }
3. Use static variables directly elsewhere.
More:
WeChat applet obtains QR code interface collation,.Net Core background obtains QR code of applet
WeChat applet to get QR code interface collation, the foreground to get QR code