先看效果
1、微信模板消息官方文档
微信公众平台
2、申请微信公众平台接口测试账号
微信公众平台
3、创建3个实体
(1)、ConfigBean
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;/*** @Configuration 相当于 spring中的 application.xml* 参考文章:https://blog.csdn.net/PotatoWatermelon/article/details/125487951* 解决 'org.springframework.web.client.RestTemplate' that could not be found. 的问题*/
@Configuration
public class ConfigBean {@BeanRestTemplate restTemplate(){return new RestTemplate();}
}
(2)、WeChatTemplate
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;public class WeChatTemplate {@JsonProperty("touser")private String toUser;@JsonProperty("template_id")private String templateId;private String url;private Map<String,String> miniprogram;private Map<String, Map<String, String>> data = new HashMap<>();public static Map<String, String> initData(String value, String color) {HashMap<String, String> data = new HashMap<String, String>();data.put("value", value);data.put("color", color);return data;}public String getToUser() {return toUser;}public void setToUser(String toUser) {this.toUser = toUser;}public String getTemplateId() {return templateId;}public void setTemplateId(String templateId) {this.templateId = templateId;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public Map<String, String> getMiniprogram() {return miniprogram;}public void setMiniprogram(Map<String, String> miniprogram) {this.miniprogram = miniprogram;}public Map<String, Map<String, String>> getData() {return data;}public void setData(Map<String, Map<String, String>> data) {this.data = data;}}
(3)、WeiXinResponse
/*** 参数配置表 WeiXinResponse**/
public class WeiXinResponse
{private Integer errcode;private String errmsg;private Long msgid;public Integer getErrcode() {return errcode;}public void setErrcode(Integer errcode) {this.errcode = errcode;}public String getErrmsg() {return errmsg;}public void setErrmsg(String errmsg) {this.errmsg = errmsg;}public Long getMsgid() {return msgid;}public void setMsgid(Long msgid) {this.msgid = msgid;}
}
4、实现层
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.thirdpart.domain.WeChatTemplate;
import com.ruoyi.thirdpart.domain.WeiXinResponse;
import com.ruoyi.thirdpart.service.IWxOAuthchatService;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;/*** 模板通知 业务层处理*/
@Service
public class WxOAuthServiceImpl implements IWxOAuthchatService
{@Resourceprivate RestTemplate restTemplate;@Overridepublic void sendMessage(String accessToken) throws IOException {WeChatTemplate weChatTemplate = new WeChatTemplate();// 设置模板idweChatTemplate.setTemplateId("5Ag_P7K_C-iPxxxx");// 设置接收用户openId,这里填接收者的openidweChatTemplate.setToUser("owte76Js8Gexxxxxxxx");//点击详情跳转的地址weChatTemplate.setUrl("");/*** 设置模板data参数* {{keyword1.DATA}}*/weChatTemplate.getData().put("time3", WeChatTemplate.initData("2022-10-23 14:23:26","#459ae9"));//申请时间weChatTemplate.getData().put("thing1", WeChatTemplate.initData("张三","#459ae9"));//客户姓名weChatTemplate.getData().put("remark", WeChatTemplate.initData("如遇错误,请往当地社区服务中心进行解决。感谢您的使用!","#383838"));if(accessToken != null){// 发送消息的接口String pust_message_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";//调用微信接口,发送模板消息WeiXinResponse result = restTemplate.postForObject(String.format(pust_message_url, accessToken),weChatTemplate, WeiXinResponse.class);if (result.getErrcode() == 0){;System.out.println("==========成功"+result);}else{System.out.println("==========发送失败");}}else{System.out.println("==========失败");}}/*** 获取getAccessToken* @return*/@Overridepublic String getAccessToken() throws IOException {try {String appid = "xxxxxxx";//填写公众号的appidString secret = "xxxxxxxxxxx";//填写公众号的开发者密码(AppSecret)String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;StringBuilder json = new StringBuilder();URL oracle = new URL(url);URLConnection yc = oracle.openConnection();BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));String inputLine = null;while ((inputLine = in.readLine()) != null) {json.append(inputLine);}in.close();JSONObject object = (JSONObject) JSONObject.parse(String.valueOf(json));String access_token = object.getString("access_token");if (access_token != null) {System.out.println("=====access_token========"+access_token+"=============");return access_token;}return null;} catch (Exception e) {//log.error("获取accessToken异常" + e.getMessage());return null;}}
}
参数对应
5、调用层
@Autowiredprivate IWxOAuthchatService wxOAuthServiceImpl;/*** 微信 公众号 模板通知*/@GetMapping("/getAccessToken")public AjaxResult getAccessToken() throws IOException{AjaxResult ajax = AjaxResult.success();String token = wxOAuthServiceImpl.getAccessToken();ajax.put(AjaxResult.DATA_TAG, token);return ajax;}/*** 微信 公众号 模板通知*/@GetMapping("/sendMessage")public AjaxResult sendMessage(HttpServletRequest request) throws IOException{AjaxResult ajax = AjaxResult.success();String token = request.getParameter("token");wxOAuthServiceImpl.sendMessage(token);return ajax;}
6、其他
import java.io.IOException;/*** 模板通知 业务层* * @author ruoyi*/
public interface IWxOAuthchatService
{void sendMessage(String accessCode) throws IOException;String getAccessToken() throws IOException;
}
7、实现效果
8、参考文章
https://www.cnblogs.com/guduershi/p/13385293.html