1、前期准备
1.申请微信公众号测试号及微信模板配置
2.申请一个微信公众号测试号。测试号申请:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
3.扫码登陆注册,注册成功后就会生成微信公号的appID和appsecret
4.需要接收消息的人微信扫码关注 测试号二维码,微信会返回我们的openid,这个openid在推送时接收消息的用户id。
5.新增消息模板(模板ID是调用推送消息接口的重要参数),模板中参数内容必须以".DATA"结尾,否则视为保留字,模板保留符号"{{ }}"; 例如{{date.DATA}
6.配置之后就完成了微信公众号的配置
2、实现逻辑
1.获取微信基础accessToken
调用微信的接口,access_token肯定是需要的。access_token可以参考一下官方:https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/backend-api.html。accessToken有效期只有两小时(下面简称token),因此当调用一下方法一次后,就可以将其放入redis中,设置过期时间(低于两小时);
public void getAccessToken(){
String appId = "wxbac840efxxxxxxxx";
String appIdSecret = "dbf4aadaae8dab4e699xxxxxxxxxxxxx";
String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId +"&secret=" + appIdSecret;
String res = HttpUtil.get(requestUrl);
JSONObject jsonObject = JSONObject.fromObject(res);
String accessToken = jsonObject.getString("access_token");
log.info("accessToken:{}", accessToken);
}
2.获取关注公众号用户
public void getUserList(){
RestTemplate restTemplate = new RestTemplate();
String accessToken = "63_3G96dUuGl-r0rGQsD7Nh3IgoEi60z-hmfNqSHjbFTatwdDhlHRgKVwuzMzxzTenlEWoARYE3hgRgQF5yyCNbr9TWFYX7s_ABin_IxR6cROYnjwTkJ-VydFxHd_UQKBgAFAEYP";
String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+ accessToken;
ResponseEntity<String> response = restTemplate.postForEntity(requestUrl, null, String.class);
log.info("结果是: {}",response.getBody());
com.alibaba.fastjson.JSONObject result = com.alibaba.fastjson.JSONObject.parseObject(response.getBody());
com.alibaba.fastjson.JSONArray openIdJsonArray = result.getJSONObject("data").getJSONArray("openid");
Iterator iterator = openIdJsonArray.iterator();
if (iterator.hasNext()){
log.debug("用户openid:"+iterator.next());
}
}
3.消息推送的消息体
public class WeChatTemplateMsg {
/**
* 消息
*/
private String value;
/**
* 消息颜色
*/
private String color;
public WeChatTemplateMsg(String value) {
this.value = value;
this.color = "#173177";
}
public WeChatTemplateMsg(String value, String color) {
this.value = value;
this.color = color;
}
}
4.消息推送
通过以上获取的 openId, accessToken 和 前期准备的模板id即可,再调用官方url即可,公众号模板推送接口:POST https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
public void sendMessage(){
// 模板参数
Map<String, WeChatTemplateMsg> sendMag = new HashMap<String, WeChatTemplateMsg>();
// openId代表一个唯一微信用户,即微信消息的接收人
String openId = "ogwdJ6w7Om9sKtFc9mxxxxxxxxxx";
// 公众号的模板id(也有相应的接口可以查询到)
String templateId = "yBVd_hZR1q5-hko3eP9BsuFfpYnFxxxxxxxxxxxxxx";
// 微信的基础accessToken
String accessToken = "63_3G96dUuGl-r0rGQsD7Nh3IgoEi60z-hmfNqSHjbFTatwdDhlHRgKVwuzMzxzTenlEWoARYE3hgRgQF5yyCNbr9TWFYX7s_ABin_IxR6cROYnjwTkJ-VydFxHd_UQKBgAFAEYP";
String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
sendMag.put("city", new WeChatTemplateMsg("广州"));
RestTemplate restTemplate = new RestTemplate();
//拼接base参数
Map<String, Object> sendBody = new HashMap<>();
sendBody.put("touser", openId); // openId
sendBody.put("url", "https://www.baidu.com"); //跳转网页url
sendBody.put("data", sendMag); // 模板参数
sendBody.put("template_id", templateId); // 模板Id
ResponseEntity<String> response = restTemplate.postForEntity(requestUrl, sendBody, String.class);
log.info("结果是: {}",response.getBody());
com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response.getBody());
String messageCode = jsonObject.getString("errcode");
String msgId = jsonObject.getString("msgid");
System.out.println("messageCode : " + messageCode + ", msgId: " +msgId);
}
5.请求参数
{
"touser":"ogwdJ6w7Om9sKtFc9xxxxxxxx",
"template_id":"yBVd_hZR1q5-hko3eP9BsuFfxxxxxxxxxx",
"url":"www.baidu.com",
"data":{
"city":{
"value":"广州"
}
}
}
6.效果