package com.qianwen.core.notify.provider.wechat.mp; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSONObject; import com.qianwen.core.http.HttpRequest; import com.qianwen.core.log.exception.BizServiceException; import com.qianwen.core.notify.DefaultNotifyType; import com.qianwen.core.notify.NotifyType; import com.qianwen.core.notify.Provider; import com.qianwen.core.notify.notifier.AbstractNotifier; import com.qianwen.core.notify.notifier.NotifierProperties; import com.qianwen.core.notify.provider.wechat.WechatProvider; import com.qianwen.core.notify.template.TemplateManager; import com.qianwen.core.tool.api.BizMessage; import com.qianwen.core.tool.metadata.Values; import com.qianwen.core.tool.utils.Func; import com.qianwen.core.tool.utils.StringUtil; import me.chanjar.weixin.mp.bean.template.WxMpTemplateData; import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage; public class WeixinMpNotifier extends AbstractNotifier { private static final Logger log = LoggerFactory.getLogger(WeixinMpNotifier.class); private final AtomicReference accessToken; private long refreshTokenTime; private final long tokenTimeOut; private static final String tokenApi = "https://api.weixin.qq.com/cgi-bin/token"; private static final String notify = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="; private final WechatMpProperties properties; private final String notifierId; private NotifierProperties notifierProperties; @Override // com.qianwen.core.notify.notifier.Notifier public String getNotifierId() { return this.notifierId; } @Override // com.qianwen.core.notify.notifier.Notifier public NotifierProperties getNotifierProperties() { return this.notifierProperties; } public WeixinMpNotifier(NotifierProperties properties, TemplateManager templateManager) { super(templateManager); this.accessToken = new AtomicReference<>(); this.tokenTimeOut = Duration.ofSeconds(7000L).toMillis(); WechatMpProperties wechatMpProperties = (WechatMpProperties) new JSONObject(properties.getConfiguration()).toJavaObject(WechatMpProperties.class); this.properties = wechatMpProperties; this.notifierProperties = properties; this.notifierId = properties.getId(); } @Override // com.qianwen.core.notify.notifier.Notifier public NotifyType getType() { return DefaultNotifyType.weiXinMp; } @Override // com.qianwen.core.notify.notifier.Notifier public Provider getProvider() { return WechatProvider.mpMessage; } public void send(WechatMpMessageTemplate template, String traceId, Values context, List notifiedParty) { String access_token = getToken(); Map maps = context.getAllValues(); List templateDataList = new ArrayList<>(); if (Func.isNotEmpty(maps)) { maps.forEach((k, v) -> { WxMpTemplateData temp = new WxMpTemplateData(); temp.setValue(v.toString()); temp.setName(k); templateDataList.add(temp); }); } HttpRequest httpRequest = HttpRequest.post(notify.concat(access_token)); if (Func.isNotEmpty(notifiedParty)) { notifiedParty.forEach(x -> { WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage(); wxMpTemplateMessage.setTemplateId(template.getTemplateId()); wxMpTemplateMessage.setToUser(x); wxMpTemplateMessage.setUrl(template.getUrl()); wxMpTemplateMessage.setMiniProgram(template.getMiniProgram()); wxMpTemplateMessage.setData(templateDataList); Map result = httpRequest.bodyString(wxMpTemplateMessage.toJson()).execute().onFailed((k2, v2) -> { log.info(StringUtil.format("发送微信公众号模板消息{}失败,原因{}", new Object[]{k2.url(), v2.getMessage()})); }).asMap(Object.class); if (result.containsKey("errcode") && !result.get("errcode").equals(0)) { BizMessage bizMessage = new BizMessage(); bizMessage.setMessage(result.get("errcode").toString()); bizMessage.setMessage(result.get("errmsg").toString()); throw new BizServiceException(bizMessage); } }); } } private String getToken() { if (System.currentTimeMillis() - this.refreshTokenTime > this.tokenTimeOut || this.accessToken.get() == null) { return requestToken(); } return this.accessToken.get(); } private String requestToken() { HttpRequest httpRequest = HttpRequest.get(tokenApi); Map queries = new HashMap<>(); queries.put("grant_type", "client_credential"); queries.put("appid", this.properties.getAppid()); queries.put("secret", this.properties.getSecret()); httpRequest.queryMap(queries); Map result = httpRequest.execute().onFailed((k, v) -> { log.info(StringUtil.format("发送微信公众号模板消息{}失败,原因{}", new Object[]{k.url(), v.getMessage()})); }).asMap(String.class); if (result.containsKey("access_token")) { this.refreshTokenTime = System.currentTimeMillis(); this.accessToken.set(result.get("access_token").toString()); return result.get("access_token").toString(); } BizMessage bizMessage = new BizMessage(); bizMessage.setMessage(result.get("errcode").toString()); bizMessage.setMessage(result.get("errmsg").toString()); throw new BizServiceException(bizMessage); } @Override // com.qianwen.core.notify.notifier.Notifier public void close() { this.accessToken.set(null); this.refreshTokenTime = 0L; } }