小程序绑定公众号,通过公众号进行消息推送,首先要在小程序上进行公众号的授权
授权不可以直接在小程序上打开,所以必须要小程序先跳到其他网页,再跳回小程序

1.我们是做了一个先做账号绑定小程序,再做公众号绑定小程序,没有绑定的话,就跳到外部链接

 wxBind () {
    // 绑定账号之后,再绑定小程序
    let that = this.data;
    const data = {
      account: that.userInfo.account,
      openid: wx.getStorageSync(\'openid\')
    };
    WXAPI.wxBind(data).then((response) => {
      if (response.code === \'0000\') {
        this.setData({showUnbind: true});
        Toast(response.msg);
        setTimeout(() => {
          this.getUrl()
        }, 300)
      } else {
        this.getUrl()
        Toast(response.msg)
      }
    })
  },
  //判断小程序是否与帐号绑定,没绑定就表示还没有登录,之前是登录之后自动绑定的
  getUrl() {
    let data = {}
    WXAPI.isBind(data).then((res) => {
      if (res.code === \'0000\' && !res.data) {
        let userInfo = wx.getStorageSync(\'userInfo\');
        if (userInfo) {
          wx.navigateTo({
            url: "/pages/saas/saas?wxbind=wxbind"
          });
        } else {
          Toast(\'尚未登录,请前往登录\')
          setTimeout(() => {
            wx.navigateTo({
              url: "/pages/login/login"
            })
          }, 300)
        }
      }
    })
  },

2.外部链接,将token带上
saas 页面的代码

<view>
  <web-view src="{{saasUrl}}"></web-view>
</view>
Page({
  data: {
    saasUrl: \'\'
  },
  onReady: function () {
    wx.setNavigationBarTitle({
      title: \'saas\'
    })
  },
  onLoad (options) {
    let type = options.wxbind
    var url
    if (type && type == \'wxbind\') {
      url = \'xxxxx/#/miniProgram?\' 
    } else {
      url = \'xxxxx?\'
    }
    let userInfo = wx.getStorageSync(\'userInfo\')
    let param = []
    for (let key in userInfo) {
      if (key !== \'tenancyCodeList\') {
        param.push(key + \'=\' + userInfo[key])
      }
    }
    url = url + param.join(\'&\')
    if (type && type == \'wxbind\') {
      url =  url + \'&wxbind=wxbind\'  
    }   
    this.setData({saasUrl: url})
  }
})

xxxxx这个就是网页的网址,你可以跳去一个h5页面,根据路由跳到需要做公众号授权的页面

3.我的H5授权页面的代码

<template>
    <div>
        <!-- 公众号授权测试 -->
    </div>
</template>
<script>
import apiProgram from \'@/api/miniProgram\'
import store from \'../../store\'
export default {
    data() {
        return {
            url: \'\',
            wechatCode: \'\',
            token: \'\'
        }
    },
    methods: {
        getCode() {
            let tenancyCode = this.getQueryParam(\'tenancyCode\')
            let data = {
                tenancyCode: tenancyCode,
                redirectUri: `xxxxxx/#/miniProgram?token=${this.token}`,
                state: 2,
                scope: \'snsapi_userinfo\'
            }
            apiProgram.pageUrl(data, (res) => {
                if (res.code === \'0000\') {
                    let url = res.data.url
                    this.url = url
                    window.location.href = this.url
                } else {
                    this.$message.warning({ message: res.msg })
                }
            })
        },
         //切割字符串
        getQueryParam(key) {
            const pairs = location.href.split(\'?\')[1].split(\'&\')
            for (let i = 0; i < pairs.length; i++) {
                if (pairs[i].indexOf(key + \'=\') === 0) {
                    return pairs[i].substr(key.length + 1)
                }
            }
        },
        // 获取token
        getToken(key) {
            const pairs = location.href.split(\'?\')[2].split(\'&\')
            for (let i = 0; i < pairs.length; i++) {
                if (pairs[i].indexOf(key + \'=\') === 0) {
                    return pairs[i].substr(key.length + 1)
                }
            }
        },
        //小程序绑定公众号
        bind(code) {  
            var token = this.getToken(\'token\')
            this.$store.dispatch("SetAccount", {
                token
            })
            let data = {
                code: code
            }
            apiProgram.weChatBind(data, (res) => {
                if (res.code === \'0000\') {
                    this.$message.success({ message: res.msg })
                    setTimeout(() => {
                        wx.miniProgram.switchTab({
                            url: "/pages/index/index"
                        });
                    }, 300)
                } else {
                    this.$message.warning({ message: res.msg })
                }
            })
        }
    },
    mounted() {
        if (location.href.indexOf(\'code=\') !== -1 && location.href.indexOf(\'state=\') !== -1) {
            this.wechatCode = this.getQueryParam(\'code\')
            if (parseInt(this.getQueryParam(\'state\')) === 2) { // 状态2为绑定
            // 如果这里有code的话
                this.bind(this.wechatCode)
            }
        } else {
            this.token = this.getQueryParam(\'token\') || \'\'
            // 更新一下token
            this.getCode()
        }
    }
}
</script>

一定要注意去更新token,也可以存在内存去,返回之后再从内存里面拿,这里的redictUrl必须去公众号后台去配置~只用配置xxxx就行,绑定必须拿到授权后的code

附上:

import service from \'./axios-service\'
const module = \'admin\'
const API_TODO_ROUTER = module + \'/api/\' + process.env.API_VERSION

const pageUrl = function (data, callback) {
    service.get(API_TODO_ROUTER + \'/wechat/authorization/page/url\', data, callback)
}
// 绑定小程序
const weChatBind = function (data, callback) {
    service.get(API_TODO_ROUTER + \'/wechat/bind\', data, callback)
}

const miniProgram = {
    pageUrl: pageUrl,
    weChatBind: weChatBind
} 
export default miniProgram

store.js

import Vue from \'vue\'
import Vuex from \'vuex\'
import app from \'./modules/app\'
import materiel from \'./modules/materiel\'
import getters from \'./getters\'
import permission from \'./modules/permission\'
import reconclie from \'./modules/reconclie\'
import order from \'./modules/order\'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        footerNavHeight: 51,
        footerBtnHeight: 44
    },
    modules: {
        app,
        materiel,
        permission,
        reconclie,
        order
    },
    getters
})

export default store

最后:

小程序代码: wxBind方法— 帐号绑定小程序, getUrl方法—判断是不是帐号绑定小程序绑定了, 是的就跳到h5授权
h5代码: getCode方法—获取授权后的code , bind方法—就是公众号与小程序绑定

版权声明:本文为antyhouse原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/antyhouse/p/12169169.html