Actual development notes for generating and refreshing Doudian tokens

Table of contents

Preface

1. Preparations for obtaining token

Point 1, obtaining app_key

Point 2, get the method

 Point 3, get grant_type

2. Steps to generate and use tokens

1.Token generation code logic

3. Preparations for refreshing token

1. Obtain refresh_token

2. Obtaining grant_type

 4. Steps to refresh and use token

1. Token refresh code logic

Summarize


Preface

This article mainly summarizes the process records of generating and refreshing Doudian tokens.

1. Preparations for obtaining token

First of all, all the interfaces we use to connect to the Doudian open platform require tokens, so obtaining this token is very important. How should we obtain the token? How can we ensure that the token is always valid and will not expire and affect our business? What about interface calls? This is something worth thinking about.

First, before obtaining the token, we need to prepare the token related preparations.

Point 1, obtaining app_key

We first fill in the relevant information and then create the application so that we can have app_key

 Then, we first click on the application details of the store you registered, and we will come to the page in the picture. Then, when we click on the application overview, we will see the application information and certificate information. When we click on the certificate information, we can When you see APP_Key, this is the app_key of your current store;

Point 2, get the method

Obtaining this is very simple, just look at the documentation of this interface, as shown in the figure.

 Point 3, get grant_type

Similarly, you also need to read the documentation for this, as shown in the figure

 The above parameters are all necessary. There are two ways to obtain the token. The first is to assemble the request URL yourself, and the other is to use the official SDK. This is relatively simple and is recommended.

2. Steps to generate and use tokens

1.Token generation code logic

First, we first write the controller layer to provide the entrance for external access.

    /**
     * 
     * 新的生成token的方法
     * @param
     * @return
     * @throws 
     */

    @ApiOperation(tags = "TikTok", value = "createToken", httpMethod = "POST",
            notes = "抖店_获取accessToken")
    @PostMapping("/createToken")
    public DataResult<AccessToken> createToken() throws Exception {
        return DataResults.ok(tiktokBaseBiz.createToken());
    }

Step 2, we do processing at the business layer. The idea is like this. We first obtain the new accessToken through the build method in the sdk method. Then, we save this new token into our redis. , the advantage of this is that when we need to use this token when connecting to its other interfaces, we can just get it directly from redis.

    /**
     * 抖店_获取accessToken
     * 该方法会调取抖店接口,使旧token失效并覆盖缓存
     * @return
     * @throws 
     */
    public AccessToken createToken() throws Exception {
       
        Long shopId = Long.valueOf(projectConfig.getTiktokECommerceDefaultStoreId());    // 抖店店铺id
        GlobalConfig.initAppKey(projectConfig.getTiktokECommerceAppId());  // 配置 
        GlobalConfig.initAppSecret(projectConfig.getTiktokECommerceAppSecret());  
        AccessToken accessToken = AccessTokenBuilder.build(shopId);  // set店铺ID 
        logger.info("抖店生成的token======"+ JSON.toJSONString(accessToken));
        try {
            redisCacheService.putTikTokAccessToken(projectConfig.getTikTokProductDefaultStoreCode(), accessToken.getAccessToken(), accessToken.getExpireIn(), accessToken.getRefreshToken(), accessToken.getScope(), Long.valueOf(accessToken.getShopId()), accessToken.getShopName(), accessToken.getLogId());
        }catch (Exception e){
            logger.info("更新的token到存储redis异常"+e);
            logger.error("更新的token到存储redis异常"+e);
        }
        return accessToken;
    }

3. Preparations for refreshing token

We talked about the generation of tokens earlier, so next, how we guarantee and renew the tokens is very critical. Of course, this is achieved by refreshing the tokens. How to achieve this, see the documentation

From the official documents, we can know that refresh_token is used to refresh access_token, so this interface method is /token/refresh; in addition to knowing this, we also need to know the various scenarios of its use.

Its usage scenarios are as follows:

Usage scenarios: 1. When the access_token expires, use refresh_token to obtain new acces_token and refresh_token; it is guaranteed to be a valid access_token.

2. The access_token is valid for 7 days. The refresh_token is used to refresh the access_token refresh token. The validity period is: 14 days; Notes: 1. Before the access_token expires 1 hour ago, when the ISV uses the refresh_token to refresh, the original access_token and refresh_token will be returned, but The validity period of the two will not change; 2. Within 1 hour before the access_token expires, when the ISV uses refresh_token to refresh, new access_token and refresh_token will be returned, but the original access_token and refresh_token will continue to be valid for one hour;

3. After the access_token expires, when the ISV uses refresh_token to refresh, it will obtain new acces_token and refresh_token, and the original acces_token and refresh_token will become invalid;

1. Obtain refresh_token

 The acquisition of this is generated in the previous token generation, that is, when the previous token is generated, this parameter has already been generated. We only need to use the previously generated one.

2. Obtaining grant_type

The acquisition of this parameter mainly depends on the documentation provided, as shown below,


 4. Steps to refresh and use token

1. Token refresh code logic

Here, we need to refresh and use the token generated previously. The advantage of this is that it ensures that the token is always valid, and the interface call using the token is always stable.

First, we first write the control layer to provide an interface for external access.

    /**
     * 抖店:
     *      刷新token
     * @return
     * @throws 
     */
    @ApiOperation(tags = "JOB", value = "tiktokRefreshToken", httpMethod = "POST",
            notes = "抖店_刷新token")
    @PostMapping("/tiktokRefreshToken")
    @AllowAnonymous
    public DataResult<AccessToken> tiktokRefreshToken() throws Exception {
        return DataResults.ok(tiktokBaseBiz.refreshToken());
    }

Then, we are doing processing in the business layer. What is the idea here? First, get the refreshToken from the cache, because we don’t know whether it is valid or not. It is stored in redis, so we have to judge first. If it no longer exists, we can directly regenerate a new token.

If it is valid, then we only need to refresh it. How to refresh it?

We use the SDK method, just like the one in the picture.

Then, save all the refreshed things to redis.

   /**
     * 抖店_刷新accessToken
     * @return
     * @throws 
     */
    public AccessToken refreshToken() throws Exception {
        AccessToken accessToken = null;
        //从缓存里获取refreshToken,缓存存的一直有效token
        TiktokAccessTokenRedisBean redisTokenBean = redisCacheService.getTiktokToken(projectConfig.getTikTokDefaultStoreCode());
        if(redisTokenBean==null){
            //缓存不存在的情况直接createToken
             accessToken = this.createToken();  // 直接调用这个生成token的方法生成
        }else{
                logger.info("抖店的token有效时长===="+redisTokenBean.getExpiresIn());
                logger.info("进来到这,说明这个token在redis中已经存在了,只需要重新刷新即可!!!");
                String refreshToken = redisTokenBean.getRefreshToken();
               
                // TODO 采用sdk
                GlobalConfig.initAppKey(projectConfig.getTiktokECommerceAppId());
                GlobalConfig.initAppSecret(projectConfig.getTiktokECommerceAppSecret());
                accessToken = AccessTokenBuilder.refresh(refreshToken);     //刷新token
                logger.info("抖店刷新的token======"+ JSON.toJSONString(accessToken));
                try {
                    redisCacheService.putTikTokAccessToken(projectConfig.getTikTokDefaultStoreCode(), accessToken.getAccessToken(), accessToken.getExpireIn(), accessToken.getRefreshToken(), accessToken.getScope(), Long.valueOf(accessToken.getShopId()), accessToken.getShopName(), accessToken.getLogId());
                } catch (Exception e) {
                    logger.info("更新的token到存储redis异常" + e);
                    logger.error("更新的token到存储redis异常" + e);
                }
        }
        return accessToken;
    }

Summarize

This article mainly summarizes the process records of generating and refreshing Doudian tokens.

Guess you like

Origin blog.csdn.net/weixin_46442877/article/details/127924734