微信公众号关联小程序,实现消息推送。

1.首先需要公众号绑定好微信小程序。

 https://jingyan.baidu.com/article/f96699bbfc499b894e3c1b00.html 这个是百度上绑定的案例可以参考绑定。

2.创建H5页面,获取授权,拿到公众号的code。下面是页面代码,直接复制即可。

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
user-scalable=no,initial-scale=1.0,maximum=1.0,minimum=1.0">
<title></title>
<!-- 引入jquery-->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- 引入 1.3.2的js-sdk文件 -->
<script src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
</head>

<body>

</body>
<script>
function getCode() {
var code = "";
var local = window.location.href; // 获取页面url
var appid = "wx064d2db6a22696a5";
code = getUrlCode().code; // 截取code
if (code == null || code === "") {
// 如果没有code,则去请求
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(
local
)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
// scope=snsapi_base 静默授权,自动跳转到回调页的 特点:用户无感知;
// scope=snsapi_userinfo 非静默授权,第一次有弹框
} else {
// url 填写的是授权成功后调转到小程序的页面并且把获取到的code传递给小程序
wx.miniProgram.redirectTo({
url: '/page/login/login?code=' + code 
})
}
}
getCode()
// 截取url中的code方法
function getUrlCode() {
var url = location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
var strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
}
}
return theRequest;
}
</script>

</html>

3.在小程序中用web-view 将H5引入到小程序中。下面直接上代码:

index.js   只需要在data中添加链接即可
  /**
   * 页面的初始数据
   */
  data: {
    link:"https://open.weixin.qq.com/connect/oauth2/authorize?appid=你的公众号appid&redirect_uri=你的H5页面地址&response_type=code&scope=snsapi_base&state=1#wechat_redirect"
  }
index.wxml
<!--page/index/index.wxml-->
<text>page/index/index.wxml</text>

<view>
  <view class="">
    <web-view src="{{link}}"></web-view>
  </view>
</view>
4.拿到公众号的code后,需要将code传入到后台,获取拿到openid。下面放个关于后台获取openid连接的教程
https://blog.csdn.net/kongwei521/article/details/79741509(C#案例)
至此就可以通过公众号的openid 来给关注的用户推送消息啦。

 

 前人种树,后人乘凉。记住小程序的获取小程序的openid是没有用的,只能获取公众号的openid才可以。

posted on 2021-10-25 15:28  叶远明  阅读(3467)  评论(0编辑  收藏  举报

导航