WeChat applet - get access_token for interface call credentials

problem background

Today, when I was working on a WeChat applet, I encountered the problem of publishing content, and then wanted to use the WeChat request interface. As a result, I encountered the request interface and needed to obtain the calling credential access_token.

View WeChat Mini Program Development Documentation

After opening the WeChat applet development document, open the server-related documents, as shown in the figure below:

You can see the description of the function in the figure. It is to obtain the globally unique background interface call certificate, which is valid for 7200 seconds, and we need to save it ourselves, and we need to maintain and update this token regularly.

If we use cloud hosting, we can call the acctess_token without maintenance through the WeChat open interface

Here, we use https calls, using our own server to call the WeChat server, neither through the cloud call nor through the front-end call,

Implementation plan

public static String getAccessToken(String appid,String appsecret){

    String reqUrl = ACCESS_TOKEN_URL.replaceAll("APPID",appid).replaceAll("APPSECRET",appsecret);

    String result = HttpUtils.httpsRequest(reqUrl, "GET", null);
    JSONObject jsonObject = JSONObject.parseObject(result);
    String  access_token = (String) jsonObject.get("access_token");
    System.out.println(access_token);
    return result;
}

public static void main(String[] args) {
    String accessToken = getAccessToken("wx7cbdf2fc3c123456", "fd54746d6eb3bf2b9770be4081234567");
    System.out.println(accessToken);
}

Through the implementation code above, we can see that the APPID in the request address is replaced by our own appid, and the appsecret is also replaced by our own secret key.

Then, initiate a GET request, request to the WeChat server to obtain the returned access_token result, convert it into a JSONObject object, and then obtain its value according to the key.

In this way, both the access_token and its valid time can be obtained.

Then according to the expiration time, we can cache the token again.

I haven't written the specific cache structure. The simplest solution is to judge whether it exists in the cache first. If it does not exist, call the interface, return a normal token, put it in our cache, and return the result.

Well, that’s all for today’s sharing about obtaining the access_token of the interface call certificate in the WeChat applet. Welcome to leave a message and exchange.

You are also welcome to pay attention to my job "coder trainee"

Guess you like

Origin blog.csdn.net/ybb_ymm/article/details/128769109