All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zopen.wechat.work.service.WechatWorkAccessTokenService Maven / Gradle / Ivy

There is a newer version: 1.0.5
Show newest version
package com.zopen.wechat.work.service;

import com.zcj.util.UtilRandom;
import com.zcj.web.context.SystemContext;
import com.zopen.wechat.exception.WechatAssert;
import com.zopen.wechat.mp.dto.base.AccessToken;
import com.zopen.wechat.work.task.WechatWorkInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component("atoWechatWorkAccessTokenService")
public class WechatWorkAccessTokenService {

    private static final Logger logger = LoggerFactory.getLogger(WechatWorkAccessTokenService.class);

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 刷新 access_token,保存到 WechatWorkInfo 中
     *
     * @param corpId     * 企业ID
     * @param agentId    * 应用ID
     * @param corpSecret * 应用秘钥
     */
    public void init(final String corpId, final String agentId, final String corpSecret) {
        String logId = UtilRandom.getRandomChar(4);
        logger.info("[{}]开始刷新 access_token,corp_id[{}] agentId[{}]", logId, corpId, agentId);
        String accessToken = httpGetAccessToken(corpId, corpSecret, logId);
        logger.debug("[{}]刷新结束,corp_id[{}] agentId[{}] corp_secret[{}], access_token[{}]", logId, corpId, agentId, corpSecret, accessToken);
        WechatWorkInfo.saveAccessToken(corpId, agentId, corpSecret, accessToken);
    }

    // 异步执行刷新 access_token,保存到 WechatWorkInfo 中(出错不会影响主线程)
    public void initAsyn(final String corpId, final String agentId, final String corpSecret) {
        SystemContext.getExecutorService().execute(() -> {
            init(corpId, agentId, corpSecret);
        });
    }

    // 远程获取 access_token 的值
    private String httpGetAccessToken(String corpId, String corpSecret, String logId) {
        WechatAssert.notNullAndEmpty(corpId, "corpId 不能为空");
        WechatAssert.notNullAndEmpty(corpSecret, "corpSecret 不能为空");
        String url = String.format(WechatWorkHttpUrl.WORK_GET_ACCESS_TOKEN, corpId, corpSecret);
        AccessToken accessToken = restTemplate.getForObject(url, AccessToken.class);
        WechatAssert.notNull(accessToken, "获取 access_token 失败");
        accessToken.valid("获取 access_token 失败");
        logger.debug("[{}]获取 access_token 成功: corp_id[{}] corp_secret[{}] access_token[{}]", logId, corpId, corpSecret, accessToken.getAccess_token());
        return accessToken.getAccess_token();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy