4, interface calls to obtain credentials

Get access_token timing diagram

Outline

Gets called voucher essence of the interface is to get access_token. In the micro-channel interface development, the use of many services are inseparable from the Access Token, Access Token equivalent to opening these key services, under normal circumstances will expire in 7200 seconds, repeat the acquisition will result in failure of the previous acquisition of Token, this article will first describes how to obtain Access Token.

According to the official description of micro-channel, access_token interface call is a globally unique number of public credentials are required to use when public access_token number to call for each interface. Developers need to be properly preserved. access_token memory you want to keep at least 512 characters of space. access_token currently valid two hours, to be regularly updated, repeat the acquisition will result in the last acquired access_token failure.

Public platform API calls required access_token use and generation by way of illustration:

1, the proposed public No. developers to use in the control server unified access and refresh access_token, access_token other business logic used by the server are from the central control server, should not each go to refresh, or likely to cause conflicts, resulting in access_token coverage affect business ;

2, currently valid access_token to convey through expire_in return, the current value is within 7200 seconds. According to the central control server needs ahead of time effective to refresh new access_token. In the refresh process, the control server can continue to output outside of the old access_token, this time the background will ensure that the public platform within 5 minutes, old and new access_token are available, which guarantee a smooth transition of business to third parties;

3, the effective time access_token might have in the future to adjust, so the central control server need not only internal timing initiative to refresh, also need to provide passive refresh access_token interface, it is easy to service server API call informed of the case access_token has timed out, it can trigger access_token refresh process.

How to obtain access_token?

No public use and applets can be AppID and AppSecret call interface to get the access_token. AppID and AppSecret in the "micro-channel public platform - Development - Basic Configuration" page to get (need has become a developer and account no abnormal state). When the call interface, please visit "micro-channel public platform - Development - Basic Configuration" in advance to add the server IP address to the IP whitelist, click View setting method, otherwise it can not be called successful. Applets do not need to configure the IP whitelist.

To note here is : all use https protocol when calling all micro-channel interfaces; if there is a central control server does not use a third-party, but the business logic to select individual points each to refresh access_taken, then there may be conflicts , resulting in an unstable service.

Gets Access Token interface at the following address:

https请求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=[APPID]&secret=[APPSECRET]

APPID parameters bracketed with APPSECRET that break up into a number of our public information, as shown below:

appID and appsecret

Because the resulting access_token interface supports Get request, because we can access this interface directly with the browser to get access_token look at the results, as shown below:

Access_token get direct access to the browser

Normally, micro-channel return data packet to the public number JSON following:
{ "the access_token": "ACCESS_TOKEN", "expires_in": 7200}

Micro-channel error returned error code information, JSON data packets as a real example (the example is a valid error AppID):
{ "The errcode": 40013, "ErrMsg": "invalid AppID"}

See Json returns a string format contains the expiration time of 7200 seconds, i.e. failure within 2 hours, after previous request URL need to obtain a new Token.

The actual application process, we generally recommend a unified interface to periodically refresh micro letter access_token, to ensure the normal operation of the entire micro-channel applications. As long as 2 hours to refresh unity. At the same time to obtain credentials for the general unity to save, can exist in the database, you can also put redis or configuration file.

Note : Using the access_token time to pay attention this interface is call frequency limit, when more than the maximum daily call frequency micro-channel server will do the interface limitations of the current public number, specific details, please read the official document ( micro-channel public number Interface Frequency restrictions Note )

Method to realize

Get access_token reference code as follows:

  List<KeyValuePair<string, object>> parmeters = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>(WeixinOfficialAccountTable.FieldDeleteMark, 0) }; var listOfficialAccount = BaseEntity.GetList<WeixinOfficialAccountEntity>(RDIFrameworkService.Instance.WeixinBasicService.GetOfficialAccountDTByValues(parmeters)); if (listOfficialAccount != null && listOfficialAccount.Count() > 0) { foreach (WeixinOfficialAccountEntity entity in listOfficialAccount) { try { if (entity.Category == (int)WeChatSubscriberEnum.EnterpriseSubscriber) { if (!string.IsNullOrEmpty(entity.AppId) && !string.IsNullOrEmpty(entity.AppSecret)) { //方法一:使用Senparc.WeiXin SDK的方法 entity.AccessToken = Senparc.Weixin.QY.CommonAPIs.CommonApi.GetToken(entity.AppId, entity.AppSecret).access_token; //方式二,直接调用微信的接口方法 //var url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", "client_credential".AsUrlData(), entity.AppId.AsUrlData(), entity.AppSecret.AsUrlData()); //AccessTokenResult result = Get.GetJson<AccessTokenResult>(url); //entity.AccessToken = result.access_token; entity.ModifiedOn = DateTime.Now; returnValue += RDIFrameworkService.Instance.WeixinBasicService.UpdateOfficialAccount(entity); } } else { if (!string.IsNullOrEmpty(entity.AppId) && !string.IsNullOrEmpty(entity.AppSecret)) { //方法一:使用Senparc.WeiXin SDK的方法 entity.AccessToken = Senparc.Weixin.MP.CommonAPIs.CommonApi.GetToken(entity.AppId, entity.AppSecret).access_token; //方式二,直接调用微信的接口方法 //var url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", "client_credential".AsUrlData(), entity.AppId.AsUrlData(), entity.AppSecret.AsUrlData()); //AccessTokenResult result = Get.GetJson<AccessTokenResult>(url); //entity.AccessToken = result.access_token; entity.ModifiedOn = DateTime.Now; returnValue += RDIFrameworkService.Instance.WeixinBasicService.UpdateOfficialAccount(entity); } } } catch (Exception ex) { } } }

The code above encapsulates our corporate subscription number, media subscription number, a personal subscription number, certificate number of test calls. Meanwhile Senparc.WeiXin SDK interfaces directly to obtain credentials method used, everyone for reference, I get the certificate exists in the database, while the number of public support multi uniform maintenance, refer to the detailed article will introduce the micro-channel public number behind the unified management and regularly updated public certificate number.

Debugging acquired credentials effect is as follows:

Code debugging get access_token

Reprinted: https: //www.cnblogs.com/huyong/p/10641208.html

Guess you like

Origin www.cnblogs.com/zhipeng007/p/11004609.html