In Senparc. Weixin. MPSDK public platform development tutorial (8): General Interface description, I introduced how to obtain the AccessToken (general interface. In the actual development process, AccessToken must be provided for all advanced interfaces. Therefore, each time we call an advanced interface, we need to execute a method to obtain the AccessToken. for example: in public platform development: General Interface description, I introduced how to obtain the AccessToken (general interface.
In the actual development process, AccessToken must be provided for all advanced interfaces. Therefore, each time we call an advanced interface, we need to execute a method to obtain the AccessToken. for example:
var accessToken = AccessTokenContainer.TryGetAccessToken(appId, appSecret);
Or after you register appId and appSecret globally, you can do the following:
var accessToken = AccessTokenContainer.GetAccessToken(_appId);
Then, use the accessToken to enter the advanced interface method. for example, we can obtain the menu as follows:
var result = CommonApi.GetMenu(accessToken);
Generally, this is a simple API call process. But we don't want to stop it like this. we are going to shorten almost all API calls to one line.
In addition to making the code easier, we also have two wishes:
Allow the API to automatically process the changed AccessToken (when multiple servers such as server load balancer operate on the same public account at the same time, the AccessToken may be refreshed externally, if the AccessToken of the local machine fails, and the API returns the correct API result.
It does not change the current API call method and is fully backward compatible.
Call code
After the modification, we can directly call the API in this line. each time we only need to provide an appId:
var result = CommonApi.GetMenu(appId);
Before execution, we need to register appId and appSecret globally as before:
AccessTokenContainer. Register (_ appId, _ appSecret); // you only need to Register it once globally. for example, you can store it in the Global Application_Start () method.
You can see that the original accessToken is replaced with appId (the new version still supports the input accessToken), saving the process of obtaining the accessToken. The specific process is described below.
SDK source code implementation process
Previously, the SDK provided the Senparc. Weixin. MP/AccessTokenHandlerWapper. Do () method to automatically process (unexpected) expired AccessToken. 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 {////// Automatic processing class that is invalid or expired for AccessToken ///Public static class ApiHandlerWapper {////// If an AccessToken error occurs when you use the AccessToken, obtain the AccessToken again and try again. /// Before using this method, you must use AccessTokenContainer. register (_ appId, _ appSecret); or JsApiTicketContainer. register (_ appId, _ appSecret); the method registers the account information. Otherwise, an error occurs. //////
//////AccessToken or AppId. If it is null, the first registered appId/appSecret is automatically obtained to obtain the AccessToken.///Keep the default value true without entering it.///
Public static T TryCommonApi
(Func
Fun, string keys = 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 ("You have no registered AppId. use AccessTokenContainer first. register completes registration (you can execute it once globally )! ") ;}} Else if (ApiUtility. IsAppId (accessTokenOrAppId) {if (! AccessTokenContainer. CheckRegistered (accessTokenOrAppId) {throw new WeixinException ("this appId has not been registered. please use AccessTokenContainer. Register to complete registration (you can execute it once globally )! ");} AppId = signature;} else {// 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. appSecret error when access_token is obtained or access_token is invalid) {// verify var accessTokenResult = AccessTokenContainer again. getAccessTokenResult (appId, true); accessToken = accessTokenResult. access_token; result = TryCommonApi (fun, appId, false) ;}} return result ;}}}
The source code of the corresponding API is as follows:
////// Obtain the current menu. if the menu does not exist, null is returned /////////
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
(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 ;}
After the TryCommonApi () method is used:
////// Obtain the current menu. if the menu does not exist, null is returned //////AccessToken or AppId. When the value is AppId, if the AccessToken is incorrect, it is automatically obtained once. If it is null, obtain the first registered AppId.///
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
(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 the following changes:
1. change the original accessToken variable name to accessTokenOrAppId (all related interfaces in the new version will change this way ).
After modification, this parameter can be set to accessToken (backward compatible) or appId (no accessToken is required). The SDK automatically determines the type of parameter based on the string length. There are three possible parameters:
A) appId. To use appId, you must register appId and appSecret in advance (as mentioned above). when the cache AccessToken expires, the SDK automatically refreshes the AccessToken, and try the API request again to ensure that the correct results are returned. If the appId is not registered, an exception is thrown.
B) accessToken. In this case, the original request method will be used. if the accessToken is invalid, an exception will be thrown directly and no retry will be performed.
C) null. When the accessTokenOrAppId parameter is null, the SDK automatically obtains the first appId registered globally. This method can be used if an application is only developed for a specified number. If no appId is registered globally, an exception is thrown.
2. the code used to access the API in the original method is not modified, but is nested into return ApiHandlerWapper. tryCommonApi (accessToken => {...}, the accessTokenOrAppId) method appears in the form of a delegate to automatically execute the same code after the first possible request failure.
This feature has been released in Senparc. Weixin. MP v12.1.
For more public platform development: articles on the AccessToken automatic management mechanism, please follow the PHP Chinese network!