参考的链接:

微信公众平台测试号——模板消息发送Demo_a816120的博客-CSDN博客

开放接口 | 微信开放文档

微信公众平台

功能一:代码实现发送微信公众平台配置的模板消息

1、事先获取好appID和appsecret

2、书写发送的工具类

package com.talk915.common.templateMsg;import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.talk915.common.redis.RedisUtil;
import com.talk915.model.pojo.WxAccessToken;
import com.talk915.model.pojo.WxOpenIdInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** @ClassName : WxTemplateMsgUtil* @Author : cong* @Date : 2021/11/16 17:33* @Description : 微信模板消息工具类*/@Slf4j
public class WxTemplateMsgUtil {/*** @param* @return* @Author LK* @Description 获取accessToken* @Date 2021/7/26 17:36*/public static WxAccessToken getAccessToken() {WxAccessToken cacheInfo = RedisUtil.getWxAccessToken();if(cacheInfo != null){Long expiresIn = cacheInfo.getExpiresIn();if (expiresIn > 150){return cacheInfo;}}//重新请求String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WxTemplateMsgConstant.WX_TEMPLATE_MSG_APP_ID + "&secret=" + WxTemplateMsgConstant.WX_TEMPLATE_MSG_APP_SECRET;String ret = HttpUtil.get(url);if (StringUtils.isBlank(ret)) {return null;}Map<String, Object> map = JSONObject.parseObject(ret, Map.class);String errCode = String.valueOf(map.get("errcode"));if (StringUtils.isNotBlank(errCode) && !"null".equals(errCode)) {String errMsg = String.valueOf(map.get("errmsg"));log.error("微信获取AssessToken失败,错误码:" + errCode + ";错误消息:" + errMsg);return null;}String accessToken = String.valueOf(map.get("access_token"));String expiresIn = String.valueOf(map.get("expires_in"));WxAccessToken wxAccessToken = new WxAccessToken();wxAccessToken.setAccessToken(accessToken);wxAccessToken.setExpiresIn(Long.parseLong(expiresIn));//设置缓存RedisUtil.setWxAccessToken(wxAccessToken);return wxAccessToken;}/*** @param* @return* @Author LK* @Description 模板消息* @Date 2021/7/26 18:37*/public static String sendMsg(TemplateMessage templateMessage) {WxAccessToken accessTokenInfo = getAccessToken();String accessToken = accessTokenInfo.getAccessToken();String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;String paramStr = JSON.toJSONString(templateMessage);String ret = HttpUtil.post(url, paramStr);if (StringUtils.isBlank(ret)) {log.error("微信模板消息推送失败!");return "";}Map<String, Object> retMap = JSONObject.parseObject(ret, Map.class);Integer errCode = (Integer) retMap.get("errcode");if (errCode != 0) {String errMsg = String.valueOf(retMap.get("errmsg"));log.error("微信模板消息推送失败!,错误信息:" + errMsg);return "";}return String.valueOf(retMap.get("msgid"));}}

3、书写模板类

package com.talk915.common.templateMsg;import org.springframework.beans.factory.annotation.Value;/*** @ClassName : TemplateMsgContent* @Author : cong* @Date : 2021/11/16 16:54* @Description :*/public class TemplateMsgContent {private static boolean allowSiteEnvironment;//补偿课时通知(测试)public static String CLASS_COMPENSATE_MSG = "ygJSffhiKZOp5BjreTk3GSurJ8vqWticSbzaTEW5Nwc";//课程取消通知(测试)private static String CLASS_CANCEL_MSG = "7L3Zel6GFltH0xrf4-qNxC_wE22f_9t-Yi_-O8hT0xw";/*** @param* @return* @Author cong* @Description 课时补偿通知* @Date 2021/11/11 16:43*/public static TemplateMessage getCompensateClassTime(String compensationNum, String userName, String openId) {First first = new First("亲,您有" + compensationNum + "个课时返还信息!");Keyword[] keywords = new Keyword[2];Keyword keyword1 = new Keyword(compensationNum, "#173177");Keyword keyword2 = new Keyword(userName, "#173177");keywords[0] = keyword1;keywords[1] = keyword2;Remark remark = new Remark("感谢您的支持!");Data data = new Data(first, remark, keywords);return new TemplateMessage(openId, CLASS_COMPENSATE_MSG, data);}/*** @param* @return* @Author cong* @Description 取消课程通知* @Date 2021/11/11 16:43*/public static TemplateMessage getCancelClass(String className, String userName, String reason, String classTime, String openId) {First first = new First("你好,你的课程已被取消!");Keyword[] keywords = new Keyword[4];Keyword keyword1 = new Keyword(className, "#173177");Keyword keyword2 = new Keyword(userName, "#173177");Keyword keyword3 = new Keyword(reason, "#173177");Keyword keyword4 = new Keyword(classTime, "#173177");keywords[0] = keyword1;keywords[1] = keyword2;keywords[2] = keyword3;keywords[3] = keyword4;Remark remark = new Remark("敬请谅解,有疑问请联系管理员!");Data data = new Data(first, remark, keywords);return new TemplateMessage(openId, CLASS_CANCEL_MSG, data);}/*** @param* @return* @Author cong* @Description 正式服的相关配置* @Date 2021/3/20 10:21*/@Value("${allow.site.environment}")private void setAllowSend(boolean allowSiteEnvironment) {TemplateMsgContent.allowSiteEnvironment = allowSiteEnvironment;if (allowSiteEnvironment) {CLASS_COMPENSATE_MSG = "***";CLASS_CANCEL_MSG = "***";}}}
public class First {private String value;private String color;public First (String value){this.value = value;}
}public class Remark {private String value;private String color;public Remark (String value){this.value = value;}
}public class Data {private  First first;private Keyword keyword1;private Keyword keyword2;private Keyword keyword3;private Keyword keyword4;private Remark remark;public Data(First first, Remark remark, Keyword... keyword) {this.first = first;int count = 1;for (Keyword keyword1 : keyword) {if (count == 1) {this.keyword1 = keyword1;} else if (count == 2) {this.keyword2 = keyword1;} else if (count == 3) {this.keyword3 = keyword1;} else if (count == 4) {this.keyword4 = keyword1;}count++;}this.remark = remark;}

功能二:代码实现输入关键字推送对应的内容

1、首先在微信公众平台配置回调地址         url/weChat/check

2、编写接收的接口逻辑

package com.talk915.async.controller.wx;import cn.hutool.crypto.SecureUtil;
import com.talk915.async.service.UserBindService;
import com.talk915.common.templateMsg.AesException;
import com.talk915.common.templateMsg.SHA1;
import com.talk915.common.templateMsg.WxMsgInfo;
import com.talk915.common.templateMsg.WxTemplateMsgConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;/*** @ClassName : WeChatController* @Author : cong* @Date : 2021/11/12 14:41* @Description : 微信服务号使用*/
@RestController
@RequestMapping(value = "/weChat")
public class WeChatController {@Autowiredprivate UserBindService userBindService;/*** 微信加密字符串*/private static final String token = "talk915";/*** @param* @return* @Author LK* @Description 接收微信发送数据* @Date 2021/8/12 14:44*/@PostMapping(value = "/check",produces = MediaType.APPLICATION_XML_VALUE)public String wxPostConnect(HttpServletRequest request) {try {Marshaller marshaller;Unmarshaller unmarshal;//解析对象JAXBContext jaxbContext = JAXBContext.newInstance(WxMsgInfo.class);unmarshal = jaxbContext.createUnmarshaller();//xml解码成bean对象WxMsgInfo wxMsgInfo = (WxMsgInfo) unmarshal.unmarshal(request.getInputStream());String event = wxMsgInfo.getEvent();String msgType = wxMsgInfo.getMsgType();//关注用户openIdString fromUserName = wxMsgInfo.getFromUserName();//接收的内容String msg = wxMsgInfo.getContent();//判断 1.关注/取关  2.发送消息 3.找不到相应的就推送客服链接// 判断是否为关注,subscribe(订阅)、unsubscribe(取消订阅)String content = "";if (StringUtils.isNotBlank(event)){//关注boolean isSubscribe = "subscribe".equals(event);//关注或取关boolean subscribe = "subscribe".equals(event) || "unsubscribe".equals(event);//推送默认消息if (isSubscribe) {content = WxTemplateMsgConstant.createTextMsg(1,"");}//添加/编辑 关注/取关记录if (subscribe){userBindService.addOrEditSubscribeStatus(fromUserName,isSubscribe);}} else if (StringUtils.isNotBlank(msgType) && "text".equals(msgType) && WxTemplateMsgConstant.BIND_TEXT.contains(msg)) {content = WxTemplateMsgConstant.createTextMsg(2, SecureUtil.md5(fromUserName + "TaLk#915"));} else if (StringUtils.isNotBlank(msgType) && "text".equals(msgType) && WxTemplateMsgConstant.UN_BIND_TEXT.contains(msg)){content = WxTemplateMsgConstant.createTextMsg(3,"");} else if (StringUtils.isNotBlank(msgType) && "text".equals(msgType) && StringUtils.isNotBlank(WxTemplateMsgConstant.checkUnBindText(msg))){//解除绑定content = userBindService.unBindAccount(WxTemplateMsgConstant.checkUnBindText(msg),fromUserName);} else {content = WxTemplateMsgConstant.createTextMsg(4,"");}WxMsgInfo msgInfo = new WxMsgInfo();msgInfo.setFromUserName(wxMsgInfo.getToUserName());msgInfo.setToUserName(wxMsgInfo.getFromUserName());msgInfo.setCreateTime(new Date().getTime());msgInfo.setMsgType("text");msgInfo.setContent(content);marshaller = jaxbContext.createMarshaller();StringWriter writer = new StringWriter();marshaller.marshal(msgInfo, writer);return writer.toString();} catch (Exception e) {e.printStackTrace();}return "";}
}
package com.talk915.common.templateMsg;import com.talk915.common.pattern.PatternCheckUtil;
import com.talk915.common.util.FileUrlConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;import java.util.Arrays;
import java.util.List;/*** @ClassName : WxTemplateMsgConstant* @Author : cong* @Date : 2021/11/10 18:14* @Description : 微信模板信息*/public class WxTemplateMsgConstant {private static boolean allowSiteEnvironment;/*** 测试服appId*/public static String WX_TEMPLATE_MSG_APP_ID = "wx11d4e0f54f0cbbbb";/*** 测试服appSecret*/public static String WX_TEMPLATE_MSG_APP_SECRET = "774b8b69b473fd2b03930f6bfe80010b";/*** 客服地址*/public static final String DEFAULT_CS_LINK = "服务号暂时不支持其他功能,正在完善中!若您有其他问题,您可以咨询 <a href=\"https://platform.usongshu.com/im/index.html#/robot?platformType=0&platformUserId=&platformUserType=7&platformPhone=&platformNickName=&platformTerminalType=1\">在线客服</a>";/*** 账号绑定基础链接*/private static final String  BIND_BASE_URL = FileUrlConstant.getPrefixUrl() + "h5/wxBind?code=";//前缀private static final String BIND_URL_PREFIX = "<a href=\"";//后缀private static final String BIND_URL_SUFFIX = "\">点击完成账号绑定</a>";/*** 账号绑定关键词*/public static final List<String> BIND_TEXT = Arrays.asList("账号绑定","绑定账号","账号关联","关联","上课提醒","绑定","通知");/*** 账号解绑*/public static final List<String> UN_BIND_TEXT = Arrays.asList("账号解绑","解绑账号","解绑");/*** @Author  LK* @Description  创建文本消息* @Date 2021/8/16 10:18* @param* @return*/public static String createTextMsg(int type,String baseContent) {String content = "";switch (type) {//1.关注默认消息case 1://content = "感谢您关注说客英语服务号!目前服务号提供上课提醒功能,回复 绑定账号,根据提示完成账号绑定即可!";content = "感谢您关注说客英语服务号!" +"目前服务号提供课前提醒和上课迟到提醒,回复:绑定,根据提示完成帐号绑定即可接收推送信息." +"如需解绑,回复:解绑_帐号,例如:解绑_12345678901";break;//2.账号绑定case 2:content = BIND_URL_PREFIX + BIND_BASE_URL + baseContent + BIND_URL_SUFFIX;break;//账号解绑case 3:content = "按照如下格式输入您需要解绑的账号即可:解绑_13700000001";break;//其他内容暂时推送客服链接default:content = DEFAULT_CS_LINK;}return content;}/*** @Author  LK* @Description  检测解绑格式* @Date 2021/8/24 18:06* @param* @return*/public static String checkUnBindText(String text){if (StringUtils.isBlank(text)){return "";}boolean contains = text.contains("_");if(!contains){return "";}String[] arr = StringUtils.split(text, "_");if (!arr[0].equals("解绑")){return "";}String account = arr[1];if (StringUtils.isBlank(account)){return "";}boolean checked = PatternCheckUtil.isPhone(account);if (!checked){return "";}return account;}/*** @param* @return* @Author cong* @Description 正式服的相关配置* @Date 2021/3/20 10:21*/@Value("${allow.site.environment}")private void setAllowSend(boolean allowSiteEnvironment) {WxTemplateMsgConstant.allowSiteEnvironment = allowSiteEnvironment;if (allowSiteEnvironment) {WX_TEMPLATE_MSG_APP_ID = "***";WX_TEMPLATE_MSG_APP_SECRET = "***";}}
}

微信订阅号发送模板消息相关推荐

  1. springboot微信公众号发送模板消息

    springboot微信公众号发送模板消息 1.准备工作 申请你所需要模板 配置ip白名单(你所需要部署的服务器ip) 2.编写模板消息的请求参数封装类 import java.util.HashMa ...

  2. php 微信模板消息url,【求助】php 微信公众号 发送模板消息改变不了颜色

    php 微信公众号 发送模板消息改变不了颜色 不知道为什么 1.模板消息内容: 2.发送的模板消息效果: 序列化的模板消息内容如下: 大家可以测试下,touser需要另外添加下 a:4:{s:11:& ...

  3. 微信公众号 发送模板消息和获取关注公众号人数

    微信公众号发送模板消息 1.创建模板,拿到模板ID 2.创建发送消息工具类 import cn.hutool.http.HttpUtil; import com.alibaba.fastjson.JS ...

  4. php之微信公众号发送模板消息

    讲一下开发项目中微信公众号发送模板消息的实现过程(我用的还是Thinkphp5.0).先看一下效果,如图: 就是类似于这样的,下面讲一下实现过程: 第一步:微信公众号申请模板消息权限: 立即申请: 申 ...

  5. 使用微信公众号发送模板消息

    使用微信公众号 API 本文所有内容均使用微信公众号测试号平台来演示 打开公众平台的测试号管理页面后我们可以在页面中看到测试号的信息 图中的 appId 和 appSecret 就是我们需要用到的 图 ...

  6. 微信公众号 java发送消息_微信公众号发送模板消息 Java实现。

    本博文是测试公众号调用模板接口测试.请不要完全复制我的代码.里面的测试代码中有本人测试号的微信模板id.麻烦替换成自己的可以吗? 第一步:创建模板信息 第二步:准备模板代码实体类用到的属性自行加入就行 ...

  7. 微信开放平台(第三方平台)代替微信公众号发送模板消息(基于lavarel框架开发,EasyWeChat)

    1.公众号必须得把模板消息授权到第三方平台. 2.我用的是 EasyWeChat 3.通过接口修改账号所属行业 (实质上就是开通模板消息) //修改账号所属行业public function set_ ...

  8. (Java)微信公众号发送模板消息

    模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等.不支持广告等营销类消息以及其它所有可能对用户造成骚扰的消息. 1.模板消息调用时主要 ...

  9. JAVA连接微信服务号发送模板消息

    最近因为业务需要使用微信服务号推送模板消息,所以就研究了下,在这也回顾和总结下开发流程和注意事项. 1. 微信公众号推送模板消息,需要开通服务号并且需要进行微信认证(这点就不过多记录了).申请到服务号 ...

最新文章

  1. java 中的内部类介绍
  2. 入职阿里啦!java面试技巧之不要给自己挖坑实战干货
  3. 构建 RESTful Web 服务
  4. JQuery EasyUI combobox(下拉列表框)
  5. python命令行进入帮助模式_python命令行模式直接查看帮助
  6. SAP Spartacus Storefront 页面 cx-page-layout 的赋值逻辑
  7. 几何画板菜单栏有哪些功能
  8. 2017-2018-1 20155301 《信息安全系统设计基础》第十三周学习总结
  9. Android 解决双卡双待手机解析短信异常
  10. 10个最佳的网站和App开发工具
  11. php文件开头加数据,在PHP中附加到文件的开头
  12. React封装多个日期段组件--BatchDate组件
  13. 深度测试oppo软件,OPPO深度测试app
  14. 利用Python实现图片信息隐藏
  15. 荣耀手机用什么蓝牙耳机好?适合荣耀手机的蓝牙耳机推荐
  16. Ubuntu系统SSH免密登录,以及SSH免密登录原理
  17. bios和boot menu的关系?
  18. Ps抠图之魔棒简易使用
  19. C语言中的分支结构和循环结构有哪些,【单选题】下面哪种不是C语言中的基本结构______。 A. 顺序结构 B. 分支结构 C. 跳转结构 D. 循环结构...
  20. 如何利用 GitHub 从零开始搭建一个博客

热门文章

  1. Linux下提权常用小命令
  2. 盘点适合入门学习的C/C++开源项目
  3. 中国十大险峻山路:最弯的公路,7公里68个拐(组图)(ZT)
  4. Avalanche:公链中的隐形冠军
  5. 和平精英封十年修改服务器,和平精英反开挂系统升级,观战作弊最低封号十年,网友:大快人心...
  6. 【JavaWeb】之富文本编辑器
  7. win7 微信 代理服务器,Win7系统使用电脑版微信如何@别人
  8. 电脑开机卡顿解决方法
  9. 每一次人生的最低点便是最好的修炼阶段,只有坚持过好最低点,才能挑战更高点---致自己
  10. Windows10系统部分软件出现中文乱码解决方法