TokenManager.java 6.61 KB
package cn.com.glsx.wechatbuild.manager;

import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.wechatbuild.model.*;
import cn.com.glsx.wechatbuild.util.CacheUtil;
import cn.com.glsx.wechatbuild.util.HttpUtils;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.oreframework.util.http.HttpUtil;
import org.oreframework.util.json.JacksonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class TokenManager {

  private static final String GET_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=YOUR_CORP_ID&corpsecret=YOUR_CORP_SECRET";

  @Autowired
  private Environment environment;

  private final String WORK_WECHAT_ACCESS_TOKEN = "SCRM_WORK_WECHAT_ACCESS_TOKEN";

  @Autowired
  private RedisTemplate<String, Object> redisTemplate;

  public String getAccessToken(WorkWechatBaseRequestDTO workWechatBaseRequestDTO) {
    String url = getUrl(workWechatBaseRequestDTO);
    // 授权方接口调用凭据(有效期2小时)
    Object accessToken = redisTemplate.opsForValue().get(
        CacheUtil.getCacheKey(WORK_WECHAT_ACCESS_TOKEN, workWechatBaseRequestDTO.getCorpId(),
            workWechatBaseRequestDTO.getCorpSecret()));
    if (accessToken != null) {
      return accessToken.toString();
    }
    try {
      log.info("get work wechat access token request url:{}", url);
      String response = HttpUtil.get(url, null);
      log.info("get work wechat access token response:{}", response);
      // 解析json获取access_token
      JSONObject object = JSONObject.parseObject(response);
      Integer errcode = object.getInteger("errcode");
      if (errcode != null && errcode != 0) {
        throw new RpcServiceException(errcode + "", object.getString("errmsg"));
      }
      accessToken = object.getString("access_token");
      int expiresIn = object.getIntValue("expires_in");
      // 授权方接口调用凭据(有效期2小时)
      redisTemplate.opsForValue().set(
          CacheUtil.getCacheKey(WORK_WECHAT_ACCESS_TOKEN, workWechatBaseRequestDTO.getCorpId(),
              workWechatBaseRequestDTO.getCorpSecret()), accessToken, expiresIn - 600,
          TimeUnit.SECONDS);
      return accessToken.toString();
      // 处理响应内容,例如解析access_token
    } catch (IOException e) {
      log.error("get work wechat access token error:" + e.getMessage(), e);
      throw new RpcServiceException(WechatErrorEnum.SERVICE_ERROR, e.getMessage());
    }
  }

  private String getUrl(WorkWechatBaseRequestDTO workWechatBaseRequestDTO) {
    String corp_id = null;
    String your_corp_secret = null;
    Integer merchantId = workWechatBaseRequestDTO.getMerchantId();
    String property = environment.getProperty("corpid.config");
    if (StringUtils.isNotEmpty(property)) {
      List<Map> maps = JSONObject.parseArray(property, Map.class);
      for (Map map : maps) {
        Integer o = Integer.parseInt(map.get("merchant_id") + "");
        if (merchantId.intValue() == o.intValue()) {
          corp_id = map.get("corp_id") + "";
          your_corp_secret = map.get("corp_secret") + "";
          workWechatBaseRequestDTO.setCorpId(corp_id);
          workWechatBaseRequestDTO.setCorpSecret(your_corp_secret);
        }
      }
    }
    return GET_TOKEN_URL.replace("YOUR_CORP_ID", corp_id)
        .replace("YOUR_CORP_SECRET", your_corp_secret);
  }

  private String getUrl(WechatTokenBaseRequestDTO request) {
    String corp_id = null;
    String your_corp_secret = null;
    String agentId = request.getAgentId();
    String property = environment.getProperty("base.corpid.config");
    if (StringUtils.isNotEmpty(property)) {
      List<Map> maps = JSONObject.parseArray(property, Map.class);
      for (Map map : maps) {
        String configAgentId = map.get("agent_id") + "";
        if (agentId.equals(configAgentId)) {
          corp_id = map.get("corp_id") + "";
          your_corp_secret = map.get("corp_secret") + "";
          request.setCorpId(corp_id);
          request.setCorpSecret(your_corp_secret);
        }
      }
    }
    if (StringUtils.isEmpty(corp_id) || StringUtils.isEmpty(your_corp_secret)) {
      throw new RpcServiceException(WechatErrorEnum.SERVICE_ERROR, "未找微信到配置");
    }
    return GET_TOKEN_URL.replace("YOUR_CORP_ID", corp_id)
            .replace("YOUR_CORP_SECRET", your_corp_secret);
  }

  public String getAccessToken(WechatTokenBaseRequestDTO request) {
    String url = getUrl(request);
    // 授权方接口调用凭据(有效期2小时)
    Object accessToken = redisTemplate.opsForValue().get(
            CacheUtil.getCacheKey(WORK_WECHAT_ACCESS_TOKEN, request.getCorpId(),
                    request.getCorpSecret()));
    if (accessToken != null) {
      return accessToken.toString();
    }
    try {
      log.info("get work wechat access token request url:{}", url);
      String response = HttpUtils.get(url);
      log.info("get work wechat access token response:{}", response);
      // 解析json获取access_token
      JSONObject object = JSONObject.parseObject(response);
      Integer errcode = object.getInteger("errcode");
      if (errcode != null && errcode != 0) {
        throw new RpcServiceException(errcode + "", object.getString("errmsg"));
      }
      accessToken = object.getString("access_token");
      int expiresIn = object.getIntValue("expires_in");
      // 授权方接口调用凭据(有效期2小时)
      redisTemplate.opsForValue().set(
              CacheUtil.getCacheKey(WORK_WECHAT_ACCESS_TOKEN, request.getCorpId(),
                      request.getCorpSecret()), accessToken, expiresIn - 600,
              TimeUnit.SECONDS);
      return accessToken.toString();
      // 处理响应内容,例如解析access_token
    } catch (IOException e) {
      log.error("get work wechat access token io error:" + e.getMessage(), e);
      throw new RpcServiceException(WechatErrorEnum.SERVICE_ERROR, e.getMessage());
    } catch (Exception e) {
      log.error("get work wechat access token system error:" + e.getMessage(), e);
      throw new RpcServiceException(WechatErrorEnum.SERVICE_ERROR, e.getMessage());
    }
  }


}