赞
踩
微信公众平台:https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
public String getAccessToken() {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
String response = restTemplate.getForObject(url, String.class);
JSONObject object = JSONObject.parseObject(response);
String accessToken = object.getString("access_token");
return accessToken;
}
获取用户列表文档:https://developers.weixin.qq.com/doc/offiaccount/User_Management/Getting_a_User_List.html
public List<String> getOpenIdsFromWX(String accessToken) {
// https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID
String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken;
ResponseEntity<String> response = restTemplate.postForEntity(url, null, String.class);
JSONObject object = JSONObject.parseObject(response.getBody());
List<String> openIds = JSONObject.parseArray(object.getJSONObject("data").getString("openid"), String.class);
return openIds;
}
{
"total": 2,
"count": 2,
"data": {
"openid": [
"oDoMF58rOTDxUCCiIjh3H0gkg0ek",
"oDoMF51KUpL7WwPzdZZHYV5ChC_c"
]
},
"next_openid": "oDoMF51KUpL7WwPzdZZHYV5ChC_c"
}
模板消息文档:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html
public void sendMessage(String templateId, Map<String, WXMessage> data) {
String accessToken = getAccessToken();
List<String> openIds = getOpenIdsFromWX(accessToken);
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
Map<String, Object> body = new HashMap<>();
body.put("template_id", templateId);
body.put("data", data);
for (String openId : openIds) {
body.put("touser", openId);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, body, String.class);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
System.out.println("推送消息异常: " + openId);
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。