@Component
@Slf4j
public class WeChatUtil {
@Autowired
private RedisService redisService;
/**
* 日志管理器
*/
private static final Logger LOGGER = LoggerFactory.getLogger(WeChatUtil.class);
/**
* 获取ACCESS_TOKEN
*
* @return
*/
public WxAccessToken getWxAccessToken() {
// String key = redisKeyUtil.getKey("WX", "APPID", ConstantUtil.WX_CONFIG_APPID);
String key = String.format("%s:%s:%s:%s", "SG", "WX", "APPID", ConstantUtil.WX_CONFIG_APPID);
String keyData = redisService.get(key);
log.info("获取key结果:{}", key);
log.info("获取keyData结果:{}", keyData);
if (!CommonUtil.isEmpty((keyData))) {
return GsonUtil.gsonToBean(keyData, WxAccessToken.class);
} else {
return flushRedisWxAccessToken();
}
}
/**
* 更新redis缓存token
*
* @return
*/
public WxAccessToken flushRedisWxAccessToken() {
try {
String key = String.format("%s:%s:%s:%s", "SG", "WX", "APPID", ConstantUtil.WX_CONFIG_APPID);
redisService.delete(key);
String url = String.format(ConstantUtil.WX_ACCESS_TOKEN_URL, ConstantUtil.WX_CONFIG_APPID, ConstantUtil.WX_CONFIG_APPSECRET);
String res = HttpUtil.getForObject(url);
WxAccessToken token = GsonUtil.gsonToBean(res, WxAccessToken.class);
log.info("获取accessToken结果:{}", res);
if (res != null && token != null && !CommonUtil.isEmpty(token.getAccess_token())) {
//缓存AccessToken 120分钟
redisService.setForTimeMIN(key, res, 120);
return token;
}
} catch (Exception e) {
e.printStackTrace();
log.error("获取accessToken失败:", e);
}
return null;
}
/**
* 获取微信Ticket
*
* @return
*/
public WxTicket getWxTicket() {
try {
// String key = redisKeyUtil.getKey("WX", "TICKET", ConstantUtil.WX_CONFIG_APPID);
String key = String.format("%s:%s:%s:%s", "SG", "WX", "TICKET", ConstantUtil.WX_CONFIG_APPID);
String keyData = redisService.get(key);
log.info("获取key结果:{}", key);
log.info("获取keyData结果:{}", keyData);
if (!CommonUtil.isEmpty((keyData))) {
return GsonUtil.gsonToBean(keyData, WxTicket.class);
} else {
String url = String.format(ConstantUtil.WX_JSSDK_TICKET, getWxAccessToken().getAccess_token());
String res = HttpUtil.getForObject(url);
log.info("获取ticket结果:{}", res);
WxTicket ticket = GsonUtil.gsonToBean(res, WxTicket.class);
if (res != null && ticket != null && !CommonUtil.isEmpty(ticket.getTicket())) {
// 缓存ticket 120分钟
redisService.setForTimeMIN(key, res, 120);
return ticket;
}
}
} catch (Exception ex) {
log.error("获取ticket失败:", ex);
}
return null;
}
/**
* 获取微信服务器IP地址
*
* @param access_token
* @return
*/
public String getCallBackIP(String access_token) {
String url = String.format(ConstantUtil.WX_SERVER_IP_URL, access_token);
String res = HttpUtil.getForObject(url);
return res;
}
/**
* 网络检测
*
* @param access_token
* @return
*/
public String checkNetwork(String access_token) {
String url = String.format(ConstantUtil.WX_INTERNET_URL, access_token);
return HttpUtil.getForObject(url);
}
/**
* 根据微信OpenID获取微信用户信息
*
* @param openId
* @return
*/
public WeChatUser getWeChatUser(String openId) {
WxAccessToken wxAccessToken = getWxAccessToken();
if (wxAccessToken != null) {
String url = String.format(ConstantUtil.WX_USERINFO_URL, wxAccessToken.getAccess_token(), openId);
String res = HttpUtil.getForObject(url);
LOGGER.info(String.format("根据微信OpenID获取微信用户信息:%s", res));
if (res != null) {
try {
String json = res.replace("\\/", "/");
return GsonUtil.gsonToBean(json, WeChatUser.class);
} catch (Exception ex) {
throw new BaseException("解析微信用户信息出错");
}
}
} else {
throw new BaseException("获取AccessToken出错");
}
return null;
}
/**
* 根据微信Code获取微信用户openid
*
* @param code
* @return
*/
public WeChatUserSampleInfo getWeChatUserByCode(String code) {
String url = String.format(ConstantUtil.WX_OPENID_URL, ConstantUtil.WX_CONFIG_APPID, ConstantUtil.WX_CONFIG_APPSECRET, code);
String res = HttpUtil.getForObject(url);
LOGGER.info(String.format("根据微信Code获取微信用户信息:%s", res));
if (res != null) {
try {
return GsonUtil.gsonToBean(res, WeChatUserSampleInfo.class);
} catch (Exception ex) {
throw new BaseException("解析微信用户信息出错");
}
}
return null;
}
}
@Component
@Slf4j
public class PushUtils {
@Autowired
private WeChatUtil weChatUtil;
//消息提醒记录服务
@Autowired
private PushNoticeRecordService pushNoticeRecordService;
private static PushUtils pushUtils;
@PostConstruct
public void init() {
pushUtils = this;
pushUtils.weChatUtil = this.weChatUtil;
pushUtils.pushNoticeRecordService = this.pushNoticeRecordService;
}
/**
* 此模版会根据连接跳转详情页面
*
* @param openId
* @param pushType
* @param param
* @param urlParams
*/
public static void pushToWX(String openId, PushType pushType, WeChatPushParam param, String urlParams) {
pushUtils.pushNoticeRecordService.addNewRecord(new PushNoticeRecord(openId, pushType.name(), param));
String accessToken = pushUtils.weChatUtil.getWxAccessToken().getAccess_token();
String url = String.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", accessToken);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
SendTemplate template = new SendTemplate();
template.setTouser(openId);
template.setData(param);
template.setTemplate_id(pushType.getId());//消息模板id
template.setUrl(pushType.getUrl() + urlParams);//跳转的路由
HttpEntity<String> requestEntity = new HttpEntity<>(GsonUtil.gsonString(template), headers);
log.info("推送消息内容{}", requestEntity.toString());
RestOperations restOperations = new RestTemplate();
ResponseEntity<String> response = restOperations.postForEntity(url, requestEntity, String.class);
log.info("推送消息响应{}", response.toString());
}
/**
* 此模版不跳转详情页面
*
* @param openId
* @param pushType
* @param param
* @param urlParams
*/
public static void pushToWXIN(String openId, PushType pushType, WeChatPushParam param) {
pushUtils.pushNoticeRecordService.addNewRecord(new PushNoticeRecord(openId, pushType.name(), param));
String accessToken = pushUtils.weChatUtil.getWxAccessToken().getAccess_token();
String url = String.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", accessToken);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
SendTemplate template = new SendTemplate();
template.setTouser(openId);
template.setData(param);
template.setTemplate_id(pushType.getId());//消息模板id
HttpEntity<String> requestEntity = new HttpEntity<>(GsonUtil.gsonString(template), headers);
log.info("推送消息内容{}", requestEntity.toString());
RestOperations restOperations = new RestTemplate();
ResponseEntity<String> response = restOperations.postForEntity(url, requestEntity, String.class);
log.info("推送消息响应{}", response.toString());
}
}