使用Springboot开发微信公众号实现发送模板消息
1.controller 代码如下(示例):
@RequestMapping(value = "/sendTest", method = RequestMethod.GET)
@ResponseBody
public String sendTest(String openid) {
System.out.println("----------------------------------------发送模板消息执行了---------------------------------");
templateMsgService.sendTest(openid);
return "success";
}
2.service
代码如下(示例):
**
* Author: Eric.Chen
* DateTime: 2021/3/19 9:53
*/
public interface TemplateMsgService {
/**
* 向一个用户推送消息(测试)
* @param openId
* @param
*/
void sendTest(String openId);
}
3.service实现类
代码如下(示例):
**
* Author: Eric.Chen
* DateTime: 2021/3/19 9:53
*/
/**
* Author: Eric.Chen
* DateTime: 2021/3/19 9:53
*/
@Service
public class TemplateMsgServiceImpl extends BaseWeChatServiceImpl implements TemplateMsgService {
/**
* 1、发送模版消息-拼接数据(测试信息)
* @param openId 微信用户的openId
*/
@Override
public void sendTest(String openId) {
// 模板Id
String templateId = "BU_tKpAIPmlE3qmzSHojbZrCuLIS0TG2ySh1B-guK8g";
// 发送
this.send(openId, templateId);
}
/**
* 2、发送模版消息
* openId 用户Id
* templateId 模板Id 测试: "模板id"
* data 模板参数
*/
private void send(String openId, String templateId) {
Map<String, Object> sendBody = new HashMap<>();
String accessToken = coreService.getToken();
String url = WxChatConstant.Url.SEND_URL.replace("ACCESS_TOKEN", accessToken);
//基础数据
WxTemplateMsg data = new WxTemplateMsg();
Map<String, Object> key = new HashMap<>();
key.put("value", "快递详情"); //标题
key.put("color", "#173117");
data.setFirst(key);
Map<String, Object> d1 = new HashMap<>();
d1.put("value", "订单id:888888888888888"); //其他内容根据需求添加
d1.put("color", "#173117");
data.setKeyword1(d1);
Map<String, Object> d2 = new HashMap<>();
d2.put("value", "发货地址:南京");
d2.put("color", "#173117");
data.setKeyword2(d2);
//拼接base参数
sendBody.put("touser", openId); // openId
sendBody.put("url", "www.baidu.com"); // 点击模板信息跳转地址
sendBody.put("topcolor", "#FF0000"); // 顶色
sendBody.put("data", data); // 模板参数
sendBody.put("template_id", templateId); // 模板Id
JSONObject json = new JSONObject(sendBody);
System.out.println("========================发送模板数据:"+json.toString()+"");
String str = HttpClientUtils.post(url,json.toString());
System.out.println(str);
}
}
总结
通过这种方式可轻松实现微信公众号模板消息的发送,如有问题请评论留言!。