第二步,获取第三方平台的 coponent_access_token

令牌的获取是有限制的,每个令牌的有效期为 2 小时,请自行做好令牌的管理,在令牌快过期时,重新调用接口获取。

令牌需要保存【我redis存了一份,mysql存了一份,后边需要用,直接redis取】

请求地址:

POST https://api.weixin.qq.com/cgi-bin/component/api_component_token

 

上代码:

public void getComponentAccessToken(String accessTokenCountFlag) {
    Map<String, String> reMap;
    //查询马上超时的accessToken数量
    Integer tokenCount = componentAccessTokenDao.selectWillOverTokenCount();
    if ((tokenCount > NumConstant.ZERO && accessTokenCountFlag.equals(ModuleConstant.ACCOUNT_TOKEN_FLAG_TWO)) || accessTokenCountFlag.equals(ModuleConstant.ACCOUNT_TOKEN_FLAG_ONE)) {
        log.info(String.format(EXIST_UPCOMING_EXPIRED));
        String componentVerifyTicket = redisThird.getComponentVerifyTicket();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(ModuleConstant.COMPONENT_APPID, componentAppId);
        jsonObject.put(ModuleConstant.COMPONENT_APPSECRET, appSecret);
        jsonObject.put(ModuleConstant.TICKET_UNDERLINE_KEY, componentVerifyTicket);
        log.info(String.format(ThirdRunTimeInfoConstant.COMPONENT_ACCESS_TOKEN,componentVerifyTicket));
        String post = HttpClientManager.getInstance().sendPostByJSON(“https://api.weixin.qq.com/cgi-bin/component/api_component_token”, JSON.toJSONString(jsonObject)).getData();
        Map hashMap = JSON.parseObject(post, Map.class);
        if (!hashMap.containsKey(“errmsg”)) {
            String componentAccessToken = hashMap.get("component_access_token").toString();
            Integer expiresIn = (Integer) hashMap.get("expires_in");
            Date expiresInTime = this.countExpirationTime(expiresIn.toString());
            if (StringUtils.isNotEmpty(componentAccessToken)) {
                //令牌信息存DB
                ComponentAccessTokenFormDTO formDTO = new ComponentAccessTokenFormDTO();
                formDTO.setComponentAccessToken(componentAccessToken);
                formDTO.setExpiresInTime(expiresInTime);
                //先删,在插入
                log.info(ThirdRunTimeInfoConstant.START_DELETE_COMPONENT_ACCESS_TOKEN);
                componentAccessTokenDao.deleteOldComponentAccessToken();
                componentAccessTokenDao.insertComponentAccessToken(formDTO);
                //存缓存
                redisThird.setComponentAccessToken(componentAccessToken);
            } else {
                throw new RenException(ThirdRunTimeInfoConstant.FAILURE_ACCESS_TOKEN);
            }
            log.info(ThirdRunTimeInfoConstant.SUCCESS_ACCESS_TOKEN);
        }
    }
}
Logo

更多推荐