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

How to realize the unified management of token in Mini Program development

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

Share

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

This article mainly explains "how to achieve token unified management in Mini Program development". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to achieve token unified management in Mini Program development".

TOKEN timing refresher 1. Background

For developers who have used the API function of the public platform, access_token is no stranger. It is like a key to the home. As long as you hold it, you can use most of the API functions of the public platform. Therefore, for developers, the way access_token is used becomes particularly important. In the daily operation of the API interface, we often encounter all kinds of questions: why is my access_token suddenly illegal? Why is the access_token that I just got expired after using 10min? For these questions, we provide the design of access_token, which makes it easy for developers to understand the way access_token is used.

II. The internal design of access_token 2.1The timeliness of access_token

It is well known that access_token is generated through appid and appsecret. The steps for the internal design are as follows:

(1) developers pass the parameters of appid and apppsecret via https request: GET https://API.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

(2) the backend of the public platform will verify whether the appid and appsecret match the storage, and if so, generate a new access_token combined with the current timestamp.

(3) when a new access_token is generated, the expiration timestamp of the old access_token is updated to the current timestamp.

(4) return the new access_token to developers.

Here is a graphic illustration of the process of alternating between the old and the new token:

There are a few points to pay attention to from the above picture:

(1) the public platform storage layer will only store the new and old access_token, which means that if the developer repeatedly calls the API 3 times, the earliest access_token will become invalid immediately.

(2) after requesting a new access_token, the old access_token expiration time will be updated to the current time, but it will not expire immediately. For the principle, please refer to [2.2 access_token gradual invalidation]

(3) for the sake of information security, the public platform does not store appsecret in clear text, but only stores the hash values of appid and appsecret. Therefore, developers should take good care of appsecret. When appsecret is suspected to be compromised, you need to log in to mp.weixin.qq.com in time to reset the appsecret.

2.2 gradual invalidation of access_token

Learn from [timeliness of access_token] that when a developer requests a new access_token, the old access_token expiration time will be updated to the current time, but it will not expire immediately, because the public platform will provide [5 minutes of alternating buffer time for new and old access _ token], so it is also called access_token.

The gradual invalidation of.

The principle of implementation is as follows:

Since the old access_token expiration timestamp has been refreshed, during the API API request, after the access_token is unlocked, the expiration timestamp will be added for 5 minutes, and then compared with the current device time. If it exceeds the current device time, it will be judged to be invalid.

Devices on public platforms will keep their clocks synchronized, but there may still be 1-2 minute time differences between devices, so [5 minutes] is not an absolute time value. Developers should switch to the new access_token as soon as they get the new access_token.

There are a few points to pay attention to from the above picture:

(1) due to the difference in device time synchronization, developers may encounter requests for API interfaces with the old access_token, some of which are successful and some of them fail. It is recommended that developers use the new access_token as soon as possible.

(2) by understanding the two illustrations, access_token is a critical and untuned interface for developers. It is recommended that developers manage access_token uniformly to avoid invalidation of access_token caused by multiple requests.

III. Unified management of access_token

Send the update of access_token to the timing trigger to complete all the interface calls that use access_token. Instead of passing in access_token, the backend reads it from the database.

The following shows the unified management access_token code of Mini Program cloud function as an example.

Index.js requests and updates access_token

If it is on the other side, you need to pass in APPID.

Const cloud = require ("wx-server-sdk") cloud.init ({env: cloud.DYNAMIC_CURRENT_ENV}) const timeutil = require (". / timeutil"); / / configuration item to be modified const APPSECRET = "" const axios = require ("axios"); const db = cloud.database (); / / regular refresh to get configuration information const CONFIG = "cloud-token" / get TOKENconst URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}"function getAccessToken (APPID,APPSECRET) {let url = URL; url = url.replace (" {APPID} ", APPID) url = url.replace (" {APPSECRET} ", APPSECRET) return new Promise (function (resolve,reject) {axios.get (url) .then (function (response) {console.log (response)) Resolve (response)}) .catch (function (error) {console.log (error); reject (error)});})} / / Cloud function entry function exports.main = async (event, context) = > {const wxContext = cloud.getWXContext () / / automatically get the current application APPID var APPID = wxContext.APPID Return new Promise (function (resolve,reject) {getAccessToken (APPID,APPSECRET) .then (async res= > {console.log (res) let access_token = res.data.access_token) Let ans = await db.collection (CONFIG) .doc ("access_token") .set ({data: {value:access_token, _ updateTime:timeutil.TimeCode ()}) resolve (ans)}

Config.json timing trigger

Trigger every hour

{"triggers": [{"name": "myTrigger", "type": "timer", "config": "0 *"}]}

Timeutil.js time utility class

Function TimeCode () {var date = new Date () Var year = date.getFullYear () var month = date.getMonth () + 1 var day = date.getDate () var hour = date.getHours () var minute = date.getMinutes () var second = date.getSeconds () return [year, month, day] .map (formatNumber) .join ("-") + "+ [hour, minute Second] .map (formatNumber) .join (":")} / / get date function _ formatTime (time) {var date = time.getFullYear () + "year" + time.getMonth () + "month" + time.getDate () + "Day" var ftime = time.getHours () + "hour" + time.getMinutes () + "minutes" + time.getSeconds () + "seconds" return date + ftime } function TimeCodeYmd () {var date = new Date (); var year = date.getFullYear () var month = date.getMonth () + 1 var day = date.getDate () return [year, month, day] .map (formatNumber) .join ("-");} function formatNumber (n) {n = n.toString () return n [1]? N: "0" + n} module.exports= {TimeCode, TimeCodeYmd}

Where access_token is used in other cloud functions, it is obtained by querying the database, and the two are logically coupled through the database.

Access_token query usage

Const TOKEN = "cloud-token"; / / get access_token try {let tres = await db.collection (TOKEN) .doc ("access_token") .get (); access_token = tres.data.value Console.log (access_token)} catch (error) {console.log ("--No token record--") return {errCode:-1, errMsg: "No TOKEN information in the database"}} Thank you for reading. This is the content of "how Mini Program developers achieve unified token management". After the study of this article I believe that you have a deeper understanding of how to achieve unified token management in Mini Program development, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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