微信小程序消息推送至微信公众平台总结
场景:由于业务需要,通过微信小程序给用户推消息(本篇文章使用的是使用openid直接推送的)
准备工作
1、注册公众号(需要服务号,订阅号不能推送消息)
2、完成微信认证(后面获取code及发送模板接口都需要拿到接口授权)
3、将开发好的小程序与公众号绑定,如下图示:

讯享网
4、将开发者绑定到开发者工具下(成为一名公众平台开发者),如下图示:

5、公众号设置及基本配置,如下图:


按要求配置好js接口安全域名及网页授权域名、配置IP白名单及获取appid和secret。
实现步骤
1.获取code
参考链接:
2.通过获取的code获取openid
前台代码如下(示例,仅供参考):
<view> <web-view :src="link"></web-view> </view> data() {
return {
openId: '', link:"https://open.weixin..com/connect/oauth2/authorize?appid=appid&redirect_uri=回调页面地址&response_type=code&scope=snsapi_base&state=1#wechat_redirect" } }, onLoad:function(e) {
let that=this; console.log(e.code) if(e.code != null){
that.ajax(that.url.getOpenId,'GET',e.code,function(resp){
that.openId=resp.data.openId; console.log(that.openId) }); } },
讯享网
后台代码如下(仅供参考)
讯享网public String getOpenId(String code) {
String url = "https://api.weixin..com/sns/oauth2/access_token?appid=" + appId + "&code=" + code + "&secret=" + secret + "&grant_type=authorization_code"; String openId = ""; // 发送请求 JSONObject result = restTemplate.getForObject(url,JSONObject.class); log.info("返回数据:" + result); try {
if (result != null){
openId = (String) result.get("openid"); } } catch (JSONException e) {
e.printStackTrace(); } log.info("获取的openID:" + openId); return openId; }
3.配置消息模板

4.调用微信接口发送模板消息
代码示例如下(仅后台):
1、调用接口获取token
public String getAccessToken(){
String url = "https://api.weixin..com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret; String token= ""; cn.hutool.json.JSONObject json = JSONUtil.parseObj(HttpUtil.get(url)); token = (String) json.get("access_token"); return token; }
2、调用接口发送模板消息
讯享网public String sendMsg(TemplateContentEntity request) {
String result = null; if(StringUtils.isBlank(request.getTouser()) || StringUtils.isBlank(request.getTemplate_id())){
throw new RuntimeException("入参有误,请联系管理员"); } // 获取access_token String token = this.getAccessToken(); String url="https://api.weixin..com/cgi-bin/message/template/send?access_token=" + token; // 组织入参 cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(request); String response= HttpUtil.post(url,jsonObject.toString()); cn.hutool.json.JSONObject json = JSONUtil.parseObj(response); String errmsg = json.getStr("errmsg"); System.out.println(errmsg); return result; }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/53381.html