微信模板消息
1、注册登陆微信公众平台公众号
2、申请测试账号
3、关注微信公众号、添加测试模板
发消息实现代码
package org.example.weixin; import cn.hutool.core.util.ObjectUtil; import cn.hutool.http.HttpUtil; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import java.util.HashMap; import java.util.Map; /** * @author pei */ public class TestGongZongHao { //https请求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET private static String URLADDRESS = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"; private static String APPID = "自己的appid"; private static String SECRET = "自己的SECRET"; public static void main(String[] args) { String result = requestGet(); JSONObject obj = JSONUtil.parseObj(result); requestPost(null,obj.get("access_token").toString()); } private static String requestGet(){ String url = URLADDRESS+"&appid="+APPID+"&secret="+SECRET; // 发送GET请求 String result = HttpUtil.get(url); System.out.println("GET请求返回结果:" + result); return result; } private static String requestPost(Map<String,Object> dataMap,String accessToken){ String openId = "自己的openid"; String templateId = "Ge22EqnRXHCyor11HyvIY3nQ2akZAuZG7x_bYmhlhws";//模板id String messageUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken; if(ObjectUtil.isEmpty(dataMap)){ dataMap = new HashMap<>(); } dataMap.put("url","https://www.cnblogs.com/xianz666/p/18606752"); dataMap.put("touser",openId); dataMap.put("template_id",templateId); dataMap.put("client_msg_id","MSG_000001"); Map<String,Object> data = new HashMap<>(); Map<String,Object> keyword1 = new HashMap<>(); keyword1.put("value","巧克力"); Map<String,Object> keyword2 = new HashMap<>(); keyword2.put("value","39.8元"); Map<String,Object> keyword3 = new HashMap<>(); keyword3.put("value","2024年10月22日"); data.put("keyword1",keyword1); data.put("keyword2",keyword2); data.put("keyword3",keyword3); dataMap.put("data",data); // 发送JSON格式的POST请求 String jsonPostResult = HttpUtil.post(messageUrl, JSONUtil.toJsonStr(dataMap)); System.out.println("JSON POST请求返回结果:" + jsonPostResult); return jsonPostResult; } }