主要流程:
1、在微信公众测试平台上注册账号,关注测试公众号,新增消息模板
2、拿到需要的参数openId appId appsecret 模板Id后进行开发
微信公众平台测试号管理地址 https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index

微信开放文档地址 https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html

微信模板消息接口文档1 https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html

微信模板消息接口文档2 https://mp.weixin.qq.com/debug/cgi-bin/readtmpl?t=tmplmsg/faq_tmpl

微信获取Access_token接口文档 https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html

3、消息参数定义规则


4、完了之后就只需简单的在Java中调用外部第三方接口了,完整代码如下

package com.nearfartec.travel.commodity.wx;import lombok.*;import java.io.Serializable;/*** <p>ClassName:DataEntity</p>* <p>Description: 公众号推送数据  </p>** @author XiangBo* @date 2022-05-18 14:35*/
@Setter
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class DataEntity implements Serializable {private String value;private String color;}
package com.nearfartec.travel.commodity.wx;import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nearfartec.framework.lib.utils.DateUtils;
import com.nearfartec.travel.commodity.enums.RoomServiceTypeEnum;
import lombok.extern.slf4j.Slf4j;import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;/*** <p>ClassName:WeChatMsgUtil</p>* <p>Description: xxxxxx  </p>** @author XiangBo* @date 2022-05-18 13:37*/
@Slf4j
//@Component
public class WeChatMsg {private final static String GET = "GET";private final static String POST = "POST";/*** 授予形式**/private final static String GRANT_TYPE = "client_credential";/** 发送模板消息url **/private final static String SEND_MSG_API_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";/** appId **/@Value("${weixin.msg.appid}")private String appId = "xxxxxxxxxxx";/** appSecret **/@Value("${weixin.msg.app-secret}")private String appSecret = "xxxxxxxxxxxxxxxxx";/** 模板ID **/@Value("${weixin.msg.msg-template-id}")private String msgTemplateId = "24uPs-Rw5Q8sKPheSWoG4NmINkwc9WUm6NgJZ0Aw66k";/** 模板跳转链接 **/@Value("${weixin.msg.template-to-url}")private String templateToUrl = "www.baidu.com";/** 模板跳转小程序AppId **/@Value("${weixin.msg.mini-program-app-id}")private String miniProgramAppId;/** 模板跳转小程序路径 **/@Value("${weixin.msg.mini-program-page-path}")private String miniProgramPagePath;/*** 获取token** @return token*/public String getToken() {//接口地址拼接参数String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + GRANT_TYPE + "&appid=" + appId + "&secret=" + appSecret;String tokenJsonStr = doGetPost(getTokenApi, GET, null);JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);String token = tokenJson.get("access_token").toString();log.info("获取到的TOKEN :{}", token);return token;}/*** 发送微信推送消息** @param openId 微信openId* @param roomStoreName param1 参数1* @param roomName param2 参数2* @param roomServiceType param3 参数3* @param applyTime param3 参数3*/public void sendWeChatMsg(String openId,String roomStoreName,String roomName,String roomServiceType,String applyTime) {//接口地址String sendMsgApi = SEND_MSG_API_URL + getToken();//openId//String toUser = "oBH8O0kmvQ5nXiDN0JWQ_79gfP1g";//消息模板ID//String template_id = "dMprAMJa_FA6KuimBWNonuyFtyp43_SJw8Um3jyeuZM";//模板跳转链接//String toUrl = "http://weixin.qq.com/download";//整体参数mapMap<String, Object> paramMap = new HashMap<>();//点击消息跳转相关参数mapMap<String, String> miniprogramMap = new HashMap<>();//消息主题显示相关mapMap<String, Object> dataMap = new HashMap<>();miniprogramMap.put("appid", miniProgramAppId);miniprogramMap.put("pagepath", miniProgramPagePath);dataMap.put("roomStoreName", DataEntity.builder().value(roomStoreName).color("#173177").build());dataMap.put("roomName", DataEntity.builder().value(roomName).color("#173177").build());dataMap.put("roomServiceType", DataEntity.builder().value(roomServiceType).color("#173177").build());dataMap.put("applyTime", DataEntity.builder().value(applyTime).color("#173177").build());paramMap.put("touser", openId);paramMap.put("template_id", msgTemplateId);paramMap.put("url", templateToUrl);paramMap.put("miniprogram", miniprogramMap);paramMap.put("data", dataMap);String postResult = doGetPost(sendMsgApi, POST, paramMap);log.info("openId : {} ,推送结果:{}",openId,postResult);}/*** 调用接口 post** @param apiPath URL*/public String doGetPost(String apiPath, String type, Map<String, Object> paramMap) {OutputStreamWriter out ;InputStream is = null;String result = null;try {// 创建连接URL url = new URL(apiPath);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setDoInput(true);connection.setUseCaches(false);connection.setInstanceFollowRedirects(true);// 设置请求方式connection.setRequestMethod(type);// 设置接收数据的格式connection.setRequestProperty("Accept", "application/json");// 设置发送数据的格式connection.setRequestProperty("Content-Type", "application/json");connection.connect();if (StrUtil.equals(type, POST)) {// utf-8编码out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);out.append(JSON.toJSONString(paramMap));out.flush();out.close();}// 读取响应is = connection.getInputStream();// 获取长度int length = (int) connection.getContentLength();if (length != -1) {byte[] data = new byte[length];byte[] temp = new byte[512];int readLen = 0;int destPos = 0;while ((readLen = is.read(temp)) > 0) {System.arraycopy(temp, 0, data, destPos, readLen);destPos += readLen;}// utf-8编码result = new String(data, StandardCharsets.UTF_8);}} catch (IOException e) {log.error("IO异常", e);} finally {try {if (ObjectUtil.isNotNull(is)) {is.close();}} catch (IOException e) {log.error("IO流关闭异常", e);}}return result;}public static void main(String[] args) {String openId = "oEuw462CDmk62pPRWQbxLRDyTvGM";//String openId = "oEuw46zox6DYwSncYZ5UNPJS0nk8";WeChatMsg chatMsg = new WeChatMsg();chatMsg.sendWeChatMsg(openId,"波罗蜜多酒店","酒店一楼1106", RoomServiceTypeEnum.CLEAN.getName(), DateUtils.getTime());}
}

【Java中实现微信公众号模板消息推送】相关推荐

  1. Nodejs + express 开发微信公众号模板消息推送功能

    第一步:申请测试号 1.打开微信测试号申请平台 http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login 2.点击"登录&q ...

  2. Java对接微信公众号模板消息推送(架包WxJava)

    内容有点多,请耐心! 最近公司的有这个业务需求,又很凑巧让我来完成: 首先想要对接,先要一个公众号,再就是开发文档了:https://developers.weixin.qq.com/doc/offi ...

  3. Java对接微信公众号模板消息推送

    最近公司的有这个业务需求,又很凑巧让我来完成: 首先想要对接,先要一个公众号,再就是开发文档了:https://developers.weixin.qq.com/doc/offiaccount/Get ...

  4. 微信公众号模板消息推送问题汇总

    总结:经常遇到的微信模版消息推送返回失败情况! 1.{"errcode":40037,"errmsg":"invalid template_id hi ...

  5. 微信公众号模板消息推送(附上完整代码)

    官方文档 会用到的调用函数 import logging import requests import time from pickle import dumps, loadsfrom request ...

  6. 微信公众号模板消息推送(PHP)

    1.发送模板消息 public function send_notice(){$access_token = '';//模板消息$json_template = $this->json_temp ...

  7. java程序集成微信公众号模板消息功能

    要在 Java 程序中集成微信公众号模板消息功能,您需要按照以下步骤进行: 在微信公众平台上申请并获取您的公众号的 appid 和 appsecret. 使用 appid 和 appsecret 调用 ...

  8. Java实现微信公众号模板消息推送给用户

    创建消息模板实体对象 package com.htdz.ydkx.wxModelMsg.entity;public class Content {private String value;//消息内容 ...

  9. 该微信用户未开启“公众号安全助手”的消息接收功能,请先开启后再绑定,Java微信公众号开发消息推送公众号用户绑定问题 的解决办法

    问题概述 在进行微信公众号开发的时候遇到的这个问题,通过Web开发公众号的模板消息推送,在调试的过程中,需要进行开发者接口联调&调试,在调试之前需要将当前的公众号与用户的微信号进行绑定, 绑定 ...

最新文章

  1. 【蓝桥杯】子串分值---笔记
  2. 【Canvas】如何用Canvas绘制折线图
  3. 程序员的春天来了,赏花去!说走就走
  4. Maven 依赖-镜像仓库替换为 -- 阿里云镜像仓库(飞快实现 pom 引入)
  5. K-近邻算法(KNN)概述
  6. github note
  7. 数据结构代码学习笔记(持续更新中)
  8. 他用代码卖手机,卖出年流水上亿
  9. matlab如何公式编辑器,公式编辑器怎么用 【搞定要领】
  10. 利用PLTS从F域Export出T域数据指南
  11. 对比修改过的两个BOM表
  12. IOS版Telegram启用中文界面的方法
  13. app运营,如何提高用户的参与度?
  14. Web前端如何快速的兼容手机
  15. 领悟《信号与系统》之 信号与系统的描述-上节
  16. 创建Oracle数据库和表
  17. ZBrush: Alpha纹理生成雕花
  18. Gin实战:Gin+Mysql简单的Restful风格的API
  19. 【HTCVR】VRTK插件模块功能分析之传送移动(二)
  20. 孙子兵法——3(将,五德五危)

热门文章

  1. 《致盛夏的七封情书》 ------------ 第一篇《晨曦》
  2. 你知道外卖cps是什么吗?(附裂变分销小程序源码搭建教程)
  3. 2021GMV目标10000亿,“好学生”抖音认真做电商
  4. 老周的ABP框架系列教程
  5. 任志强:房地产是夜壶 宏观经济不行就拿出来用
  6. 技术总监被开除了....
  7. 清除pycharm残留文件
  8. Word中设置不同的页眉或页脚
  9. STM32 FSMC TFT LCD
  10. 计算机应用基础在线试题,计算机应用基础试题.DOC