


WeChat public platform development: AccessToken automatic management mechanism
Feb 27, 2017 pm 01:40 PMIn "WeChat Public Platform Development: General Interface Description", I introduced the method of obtaining AccessToken (general interface).
In the actual development process, all high-level interfaces need to provide AccessToken, so every time we call the high-level interface, we need to execute a method to obtain AccessToken, for example:
var accessToken = AccessTokenContainer.TryGetAccessToken(appId, appSecret);
Or after you have globally registered appId and appSecret, you can also do this:
var accessToken = AccessTokenContainer.GetAccessToken(_appId);
Then use this accessToken to enter the method of the advanced interface. For example, we can get the menu like this:
var result = CommonApi.GetMenu(accessToken);
Normally, this is already a very simple API calling process. But we don't want to stop there, we're going to shorten almost all API calls to one line.
While doing this, in addition to making the code simpler, we also have two wishes:
Let the API automatically handle the changed AccessToken (when multiple servers operate at the same time such as load balancing) In the case of a WeChat official account, the AccessToken may be refreshed externally, causing the local AccessToken to become invalid), and the final correct API result must be re-obtained and returned.
Does not change the current API calling method and is completely backward compatible.
Calling code
After modification, we can directly call the API with this line, and only need to provide an appId each time:
var result = CommonApi.GetMenu(appId);
Currently before execution , we need to register appId and appSecret globally as before:
AccessTokenContainer.Register(_appId, _appSecret);//全局只需注冊一次,例如可以放在Global的Application_Start()方法中。
As you can see, the original accessToken is replaced by appId (the new version still supports entering accessToken), eliminating the process of obtaining accessToken. The specific process is explained below.
SDK source code implementation process
Previously, in order to automatically handle (unexpected) expired AccessToken, the SDK has provided the Senparc.Weixin.MP/AccessTokenHandlerWapper.Do() method. This upgrade renamed AccessTokenHandlerWapper.cs to ApiHandlerWapper.cs, abolished the Do() method, and added the TryCommonApi() method. The code is as follows:
namespace Senparc.Weixin.MP { /// <summary> /// 針對AccessToken無效或過期的自動(dòng)處理類 /// </summary> public static class ApiHandlerWapper { /// <summary> /// 使用AccessToken進(jìn)行操作時(shí),如果遇到AccessToken錯(cuò)誤的情況,重新獲取AccessToken一次,并重試。 /// 使用此方法之前必須使用AccessTokenContainer.Register(_appId, _appSecret);或JsApiTicketContainer.Register(_appId, _appSecret);方法對賬號信息進(jìn)行過注冊,否則會出錯(cuò)。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fun"></param> /// <param name="accessTokenOrAppId">AccessToken或AppId。如果為null,則自動(dòng)取已經(jīng)注冊的第一個(gè)appId/appSecret來信息獲取AccessToken。</param> /// <param name="retryIfFaild">請保留默認(rèn)值true,不用輸入。</param> /// <returns></returns> public static T TryCommonApi<T>(Func<string, T> fun, string accessTokenOrAppId = null, bool retryIfFaild = true) where T : WxJsonResult { string appId = null; string accessToken = null; if (accessTokenOrAppId == null) { appId = AccessTokenContainer.GetFirstOrDefaultAppId(); if (appId == null) { throw new WeixinException("尚無已經(jīng)注冊的AppId,請先使用AccessTokenContainer.Register完成注冊(全局執(zhí)行一次即可)!"); } } else if (ApiUtility.IsAppId(accessTokenOrAppId)) { if (!AccessTokenContainer.CheckRegistered(accessTokenOrAppId)) { throw new WeixinException("此appId尚未注冊,請先使用AccessTokenContainer.Register完成注冊(全局執(zhí)行一次即可)!"); } appId = accessTokenOrAppId; } else { //accessToken accessToken = accessTokenOrAppId; } T result = null; try { if (accessToken == null) { var accessTokenResult = AccessTokenContainer.GetAccessTokenResult(appId, false); accessToken = accessTokenResult.access_token; } result = fun(accessToken); } catch (ErrorJsonResultException ex) { if (!retryIfFaild && appId != null && ex.JsonResult.errcode == ReturnCode.獲取access_token時(shí)AppSecret錯(cuò)誤或者access_token無效) { //嘗試重新驗(yàn)證 var accessTokenResult = AccessTokenContainer.GetAccessTokenResult(appId, true); accessToken = accessTokenResult.access_token; result = TryCommonApi(fun, appId, false); } } return result; } } }
The source code of the corresponding API originally looked like this:
/// <summary> /// 獲取當(dāng)前菜單,如果菜單不存在,將返回null /// </summary> /// <param name="accessToken"></param> /// <returns></returns> public static GetMenuResult GetMenu(string accessToken) { var url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", accessToken); var jsonString = HttpUtility.RequestUtility.HttpGet(url, Encoding.UTF8); //var finalResult = GetMenuFromJson(jsonString); GetMenuResult finalResult; JavaScriptSerializer js = new JavaScriptSerializer(); try { var jsonResult = js.Deserialize<GetMenuResultFull>(jsonString); if (jsonResult.menu == null || jsonResult.menu.button.Count == 0) { throw new WeixinException(jsonResult.errmsg); } finalResult = GetMenuFromJsonResult(jsonResult); } catch (WeixinException ex) { finalResult = null; } return finalResult; }
Now after using the TryCommonApi() method:
/// <summary> /// 獲取當(dāng)前菜單,如果菜單不存在,將返回null /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId。當(dāng)為AppId時(shí),如果AccessToken錯(cuò)誤將自動(dòng)獲取一次。當(dāng)為null時(shí),獲取當(dāng)前注冊的第一個(gè)AppId。</param> /// <returns></returns> public static GetMenuResult GetMenu(string accessTokenOrAppId) { return ApiHandlerWapper.TryCommonApi(accessToken => { var url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", accessToken); var jsonString = HttpUtility.RequestUtility.HttpGet(url, Encoding.UTF8); //var finalResult = GetMenuFromJson(jsonString); GetMenuResult finalResult; JavaScriptSerializer js = new JavaScriptSerializer(); try { var jsonResult = js.Deserialize<GetMenuResultFull>(jsonString); if (jsonResult.menu == null || jsonResult.menu.button.Count == 0) { throw new WeixinException(jsonResult.errmsg); } finalResult = GetMenuFromJsonResult(jsonResult); } catch (WeixinException ex) { finalResult = null; } return finalResult; }, accessTokenOrAppId); }
We can observe several changes:
1. The original accessToken variable name was changed to accessTokenOrAppId (all related in the new version The interfaces will all change like this).
After modification, this parameter can be entered with accessToken (downward compatibility) or appId (no need to obtain accessToken). The SDK will automatically determine which type of parameter it belongs to based on the length of the string. There are 3 possible parameters provided:
a) appId. Using appId requires global registration of appId and appSecret in advance (as mentioned above). When the cached AccessToken is found to have expired during the API call, the SDK will automatically refresh the AccessToken and retry the API request to ensure that the correct result is returned. . If the appId has not been registered, an exception will be thrown.
b) accessToken. In this case, the original request method will be used. If the accessToken is invalid, an exception will be thrown directly without retrying.
c) null. When the accessTokenOrAppId parameter is null, the SDK will automatically obtain the first appId registered globally. If an application is only developed for a certain WeChat ID, this method can be used. When no appId is registered globally, an exception will be thrown.
2. The code for accessing the API in the original method has not been modified in any way. It is just nested into the method return ApiHandlerWapper.TryCommonApi(accessToken =>{...},accessTokenOrAppId) to delegate The purpose is to allow the SDK to automatically execute the exact same code after the first possible request fails.
This feature has been released in Senparc.Weixin.MP v12.1.
For more articles related to WeChat public platform development: AccessToken automatic management mechanism, please pay attention to the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
