1、前期準備 1.申請微信公眾號測試號及微信模板配置 2.申請一個微信公眾號測試號。測試號申請:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login 3.掃碼登陸註冊,註冊成功後就會生成微信公號的appID和appsecret ...
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(){{ "touser":"ogwdJ6w7Om9sKtFc9xxxxxxxx", "template_id":"yBVd_hZR1q5-hko3eP9BsuFfxxxxxxxxxx", "url": "www.baidu.com", "data":{ "city": { "value":"廣州" } } }
// 模板參數
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.請求參數
6.效果