package com.xinelu.mobile.utils; import com.alibaba.fastjson2.JSON; import com.xinelu.common.config.WeChatOfficialAccountConfig; import com.xinelu.common.constant.Constants; import com.xinelu.common.entity.AccessToken; import com.xinelu.common.exception.ServiceException; import com.xinelu.common.utils.http.HttpUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.Objects; import java.util.concurrent.TimeUnit; /** * @Description 院后公众号公众方法工具类 * @Author 纪寒 * @Date 2024-03-21 13:42:31 * @Version 1.0 */ @Component public class WeChatOfficialAccountUtils { @Resource private RedisTemplate redisTemplate; @Resource private WeChatOfficialAccountConfig weChatOfficialAccountConfig; /** * 返回成功状态码 */ private static final int SUCCESS_CODE = 0; /** * 获取院后微信公众号accessToken * * @return 微信公众号的accessToken */ public String getWeChatOfficialAccountAccessToken() { String accessToken; String accessTokenRedisKey = Constants.WE_CHAT_OFFICIAL_ACCOUNT_ACCESS_TOKEN + "accessToken"; //从Redis中取出accessToken Object object = redisTemplate.opsForValue().get(accessTokenRedisKey); if (Objects.isNull(object)) { //没有,获取accessToken String accessTokenUrl = Constants.WE_CHAT_ACCESS_TOKEN_URL + "&appid=" + weChatOfficialAccountConfig.getOfficialAccountAppId() + "&secret=" + weChatOfficialAccountConfig.getOfficialAccountAppSecret(); //发送请求 String result = HttpUtils.sendGet(accessTokenUrl); if (StringUtils.isBlank(result)) { throw new ServiceException("获取微信公众号accessToken信息失败", 201); } AccessToken officialAccountAccessToken = JSON.parseObject(result, AccessToken.class); if (Objects.isNull(officialAccountAccessToken)) { throw new ServiceException("获取微信公众号accessToken信息失败"); } if (Objects.nonNull(officialAccountAccessToken.getErrcode()) && officialAccountAccessToken.getErrcode() != SUCCESS_CODE) { throw new ServiceException("获取微信公众号accessToken信息失败,失败信息为:" + officialAccountAccessToken.getErrmsg(), 201); } if (StringUtils.isBlank(officialAccountAccessToken.getAccessToken())) { throw new ServiceException("微信公众号accessToken信息为空"); } accessToken = officialAccountAccessToken.getAccessToken(); //存入Redis中 redisTemplate.opsForValue().set(accessTokenRedisKey, accessToken, 3600, TimeUnit.SECONDS); } else { accessToken = (String) object; } return accessToken; } }