java实现微信公众平台发送模板消息的示例代码实现微信公众平台发送模板消息的示例代码
主要介绍了java实现微信公众平台发送模板消息的示例代码,文中通过示例代码介绍的非常详细,对大家的学习
或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
最近开发公众号项目,前端采用vue开发,后台使用java开发,由于业务需求,需要实现公众号向用户发送重要的服务通知,提
醒工作人员进行业务审核。这时候就需要用到微信平台的模板消息,为了保证用户不受到骚扰,在开发者出现需要主动提醒、
通知用户时,才允许开发者在公众平台网站中模板消息库中选择模板,选择后获得模板ID,再根据模板ID向用户主动推送提
醒、通知消息。常用的服务场景,如信用卡刷卡通知,商品下单成功、购买成功通知等。
获取template_id(注意:仅微信开放平台同事可获取)
通过向微信公众平台申请模板,来获取模板id,模板消息调用时主要需要模板ID和模板中各参数的赋值内容。请注意:
1.模板中参数内容必须以".DATA"结尾,否则视为保留字;
2.模板保留符号"{{ }}"
下图是在微信测试公众号申请模板
请求模板消息接口请求模板消息接口
1)微信网页授权
//前端发请请求
this.axios.get('/wx/get_code_num').then((res) => {
window.location.href = res.data;
}).catch((error) => {
console.log(error)
});
/**
* 1.用户同意授权,获取code
*/
@RequestMapping(value = "/get_code_num", method = RequestMethod.GET)
public String getCode() throws UnsupportedEncodingException {
return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Constants.APPID + "&redirect_uri="
+ URLEncoder.encode("http://192.168.0.152:8085/wx/send_wx_msg", "UTF-8") + "&response_type=code&scope="
+ Constants.GRANTSCOPE + "&state=STATE#wechat_redirect";
}
2)获取用户openid
/**
* 2.通过code换取网页授权access_token及openid
*/
@RequestMapping(value = "/send_wx_msg", method = RequestMethod.GET)
public String sendWxMsg(String code) {
String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
String accessTokenObj = HttpClientUtil.sendGet(access_token_url, "appid=" + Constants.APPID + "&secret="
+ Constants.APPSECRET + "&code=" + code + "&grant_type=authorization_code");
评论0