小程序嵌入网页向小程序跳转并传参,微信小程序中实现公众号授权获取openId

大家好,最近我们接触了一个小程序的项目,涉及到了消息通知,介于微信服务通知的限制性因素,我们改用公众号推送,给大家分享一下经验。
首先,我们新建一个html文件,引入微信相关js文件:

<!-- 一定要注意,H5需要引入微信相关js -->
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>

接着,我们写入自定义的js一些方法,里面注释我加的比较清晰,如何跳转小程序,如何效验判断逻辑等,简单明了

<script>
  const gzhId = '123456789'; // 公众号appid
  const url   = 'http://sharedbk.com/getOpenId.html'; // 授权回调链接
  init(); // 初始化
  // 初始化效验
  function init(){
    if (!getUrlKey("code") && !sessionStorage.openId) {
      // 如果没有code和openId,就让跳转微信授权
      window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + gzhId + "&redirect_uri=" + url +"&response_type=code&scope=snsapi_userinfo";
    } else if (!sessionStorage.openId) {
      // 反之有code,没有openId就调用后台接口获取openId
      getOpenId();
    } else if (sessionStorage.openId) {
      // 如果有存在openId,那么直接跳转小程序
      jumpBtn(sessionStorage.openId);
    }
  }

  // 请求后台接口,获取openId
  function getOpenId(){
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    var raw = JSON.stringify({"code": getUrlKey("code")});

    var requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: raw,
      redirect: 'follow'
    };

    fetch("http://sharedbk.com/getOpen", requestOptions)
      .then(response => response.text())
      .then(result => {
        let res = JSON.parse(result);
        if(res.code == '200'){
          console.log('授权成功');
          sessionStorage.setItem("openId", res.data.openId); // 存储openId
          jumpBtn(res.data.openId); // 跳转微信小程序
        } else {
          console.log('授权失败');
          window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + gzhId + "&redirect_uri=" + url +"&response_type=code&scope=snsapi_userinfo";
        }
      })
      .catch(error => console.log('error', error));
  }

  // 跳转至小程序
  function jumpBtn(val){
    alert(val)
    // val为传的openId,小程序路径自行配置
    wx.miniProgram.navigateTo({
      url:`/views/login?gzhOpenId=` + val,
      success: (res) => {
        console.log(res);   // 页面跳转成功的回调函数
      },
      fail: (err) => {
        console.log(err);   // 页面跳转失败的回调函数
      }
    })
  }

  // 获取参数(http://sharedbk.com/post/188.html)
  function getUrlKey (name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
  }

</script>

将html文件保存,上传至服务器,这样你就可以获取到页面链接,记得在上面js中修改你自己的链接,然后需要在小程序后台中(开发管理=>开发设置=>业务域名),将服务器绑定的域名配置到业务域名中,这样就可以调用web-view组件。

完成上方工作,我们再继续在小程序中进行下方工作(我是uniapp,做了一个微信端判断,setStorageData和getStorageSyncData是我封装了一个本地存取方法,这个你可以直接用微信小程序的存储方法),也就是访问小程序时,先判断下访问是否带参数,如果带了就直接存储下来,没有携带参数就利用web-view跳转到网页进行授权(自己小程序写个web-view页面实现就行)。

onLoad: function(val) {
    // #ifdef MP
    if(val.gzhOpenId){ // 获取传递的参数
        setStorageData('gzhOpenId', val.gzhOpenId); // 存储公众号的openId
    }
    // 判断是否存在公众号的openId,不存在就利用web-view访问授权链接获取
    if(!getStorageSyncData('gzhOpenId')){
        uni.navigateTo({
            url: '/views/webViewPage/index?url=http://sharedbk.com/getOpenId.html'
        });
    }
    // #endif
}
posted @ 2022-10-28 14:04  牵手相守  阅读(294)  评论(0编辑  收藏  举报