主要流程:
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";
//整体参数map
Map<String, Object> paramMap = new HashMap<>();
//点击消息跳转相关参数map
Map<String, String> miniprogramMap = new HashMap<>();
//消息主题显示相关map
Map<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());
}
}