Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of AccessToken automatic Management Mechanism in the Development of Wechat Public platform

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the example analysis of AccessToken automatic management mechanism in the development of Wechat public platform, which has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.

In the actual development process, all high-level interfaces need to provide AccessToken, so each time we need to execute a method to get AccessToken before calling the high-level interface, for example:

Var accessToken = AccessTokenContainer.TryGetAccessToken (appId, appSecret)

Or after you have registered appId and appSecret globally, you can do this:

Var accessToken = AccessTokenContainer.GetAccessToken (_ appId)

Then use this accessToken to input into the method of the advanced interface, for example, we can get the menu like this:

Var result = CommonApi.GetMenu (accessToken)

In general, this is already a very concise API call process. But we don't want to stop like this, and we're going to shorten almost all API calls to one line.

In doing so, in addition to making the code easier, we have two wishes:

Let API automatically deal with the changed AccessToken (when multiple servers, such as load balancer, operate the same Wechat official account at the same time, the AccessToken may be refreshed externally, resulting in the invalidation of the native AccessToken), and the final correct API result may be returned.

It does not change the current way of calling API, and is fully backward compatible.

Calling code

After modification, we can call API directly on this line, providing only one appId at a time:

Var result = CommonApi.GetMenu (appId)

Currently, before executing, we need to register appId and appSecret globally as before:

AccessTokenContainer.Register (_ appId, _ appSecret); / / Global only needs to be registered once, for example, it can be placed in the Application_Start () method of Global.

As you can see, the original accessToken has been replaced with appId (the new version still supports entering accessToken), eliminating the process of getting accessToken. The specific process is described below.

SDK source code implementation process

The Senparc.Weixin.MP/AccessTokenHandlerWapper.Do () method was previously provided for automatic handling of (unexpected) expired AccessToken,SDK. This upgrade renames AccessTokenHandlerWapper.cs to ApiHandlerWapper.cs, abolishes the Do () method, and adds the TryCommonApi () method as follows:

Namespace Senparc.Weixin.MP {/ public static class ApiHandlerWapper {/ when using AccessToken for automatic handling classes with invalid or expired AccessToken, if you encounter an AccessToken error, get AccessToken again and try again. / / before using this method, you must use AccessTokenContainer.Register (_ appId, _ appSecret); or JsApiTicketContainer.Register (_ appId, _ appSecret); to register the account information, otherwise an error will occur. / / AccessToken or AppId. If null, the first registered appId/appSecret is automatically fetched to obtain the AccessToken. / / Please leave the default value of true instead of input. / / public static T TryCommonApi (Func 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 ("there is no registered AppId yet, please use AccessTokenContainer.Register to complete the registration first (you can execute it 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 first (global execution once)!") ;} 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. AppSecret error or invalid access_token while getting access_token) {/ / attempt to revalidate var accessTokenResult = AccessTokenContainer.GetAccessTokenResult (appId, true); accessToken = accessTokenResult.access_token; result = TryCommonApi (fun, appId, false);}} return result }}}

The source code for the corresponding API turns out to be like this:

/ get the current menu. If the menu does not exist, it will return null/// 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;}

Now after using the TryCommonApi () method:

/ gets the current menu, and returns null/// AccessToken or AppId if the menu does not exist. When AppId, the AccessToken error will be automatically fetched once. When null, gets the first AppId currently registered. / / 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 several changes as follows:

1. The original accessToken variable name has been changed to accessTokenOrAppId (all relevant interfaces will change in the new version).

After modification, you can enter either accessToken (backward compatibility) or appId (no longer need to get accessToken). SDK will automatically determine which type of parameter belongs to based on the length of the string. There are three possibilities for the parameters provided:

A) appId. Using appId requires global registration of appId and appSecret in advance (mentioned above). When it is found that the cached AccessToken expires during the call to API, SDK automatically flushes the AccessToken and retries the API request to ensure that the correct result is returned. If 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 made.

C) null. When the accessTokenOrAppId parameter is null, SDK automatically gets the first appId registered globally. This method can be used if an application is developed only for a certain WeChat account. When no appId is registered globally, an exception is thrown.

two。 The code that accesses the API in the original method has not been modified, but is nested in the method of return ApiHandlerWapper.TryCommonApi (accessToken = > {...}, accessTokenOrAppId) in the form of a delegate, so that SDK can automatically execute exactly the same code after the first possible request fails.

This feature has been released in Senparc.Weixin.MP v12.1.

Thank you for reading this article carefully. I hope the article "sample Analysis of AccessToken automatic Management Mechanism in the Development of Wechat Public platform" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report