vue+vant 微信公众号内嵌单页面获取openid

介绍:

以前做的是,直接www.baidu.com?openid=xxx,由第三方提供openid,现在需要我们包产到户,全部有我们来做。
2019-12-16:由于vuex刷新会重置,所以导致在一个有路由守卫的页面刷新,会出现空白,后台报错:[获取openid的results:{"errcode":40163,"errmsg":"code been used, hints: [ req_id: PHHFbxXIRa-rC_V3 ]"},原因就是store存的openid刷新消失后,5分钟内又去getCode,微信返回如上结果,于今日优化有vuex版本。

备注:获取openid的流程

vue+vant 微信公众号内嵌单页面获取openid_第1张图片

第一步:

配置公众号:设置-公众号设置-功能设置,切记必须是在线域名,localhost不行
vue+vant 微信公众号内嵌单页面获取openid_第2张图片
把下图txt文件下载,放到前台页面服务器目录下,域名写在输入框中。
域名规则:例:https://admin.serve.com.cn;填写:admin.serve.com.cn;不要加https|httpvue+vant 微信公众号内嵌单页面获取openid_第3张图片

至此,后台配置完事儿

第二步:

//main.js;利用到了vuex的store.js;
//如果没有用到vuex请移步至最后,无vuex版

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
import my from './assets/js/lbc.js'
import { Toast} from "vant";

Vue.prototype.$my=my
Vue.config.productionTip = false

router.beforeEach((to, from, next) => {
  //微信公众号appid-开发-基本配置中获取
  const appId = my.appId
  //获取code后再次跳转路径 window.location.href;例:www.baido.com/#/Home
  const toPath = my.host+'/#'+to.path 
  //核心步骤,获取code
  const hrefurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+encodeURIComponent(toPath)+"&response_type=code&scope=snsapi_base&state=dcabe11a-751f-490f-9dcc-606881c6fcdb#wechat_redirect";
  //从地址栏获取code
  const code = my.getQueryString('code')
  const isLogin = ()=>{//是否登录   
  	let openid = localStorage.getItem('openId') || store.state.loginInfo.openId;
    axios.post(my.api+'/wet/due/checkIsBind',{openId:openid })
    .then((res) => {         
      if (res.data&&res.data.code == 200) {//已登录
        store.commit('setLoginInfo',{...res.data.data})//存登陆信息
        next() 
      } else {//未登录   
        next({
          path: '/Register',
        })
      }
    })
  }

  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  /* 判断该路由是否需要登录权限 */
  if (to.matched.some(record => record.meta.requireAuth)) {
    if(localStorage.getItem('openId') || store.state.loginInfo.openId){ 
      isLogin()//是否登录 正式环境 store.state.loginInfo.openId加上此代码,方便测试
    }else{ //openId不存在
      if(code){ //根据code获取openId
        axios.post(my.api+"/wet/chat/getOpenId", {code:code}).then((res) => {
          if (res.data&&res.data.code == 200) {
          	localStorage.setItem('openId',res.data.data.openid)
            //commit同步,dispatch 异步
            store.commit('setLoginInfo',{openId:res.data.data.openid})
            isLogin()//是否登录
          } else {
            Toast(res.data?res.data.message:'请求失败!');
          }
        })
      }else{  //获取code
        window.location.replace(hrefurl)
      }
    }
  }else{
    next()
  }
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
//lbc.js
import Vue from 'vue'

const api = 'https://xxxx.cn' 
const host = 'https://xxxx.com.cn'//授权所需域名
const appId = 'wx09999999'

//获取地址栏参数
const getQueryString = (name) => {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
} 

export default  {
    getQueryString,
    api,
    host,
    appId 
}
//store.js
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import my from './assets/js/lbc.js'

Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    loginInfo:{
      openId:'', //正式环境制空
      // openId:'1',//测试环境
      // id:2//测试环境
    }
    
  },
  getters: {

  },
  mutations: {
    setLoginInfo(state, playload){
      state.loginInfo = {...state.loginInfo,...playload}
    },
  },
  actions: {
  }
})

//router.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)

import Home from './view/Home'
import Register from './view/Register'
//项目申请
import ProjectApply from './view/ProjectApply/ProjectApply'

export default new Router({
  //mode: 'history', 
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      meta: {
        title:'首页',
        requireAuth: false
      }
    },
    {
      path: '/Register',
      name: 'Register',
      component:Register,
      meta: {
        title: '注册',
        requireAuth: false//false 不需要openid
      }
    },
    {
      path: '/ProjectApply',
      name: 'ProjectApply',
      component:ProjectApply,
      meta: {
        title: '申请',
        requireAuth: true //true 需要openid
      }
    },
  ]
})

无vuex版:

由于很多时候只是一个简单的页面,不要vuex,因此只需要localStorage就可以了
代码如下:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import my from './assets/js/lbc.js'
import axios from 'axios'
import api from './api/url'

   Vue.prototype.axios = axios 
   Vue.config.productionTip = false

//判断是否注册,路由的跳转
router.beforeEach((to,from,next) => {
   //微信公众号appid基本备置中获取
   const appId = 'wx399999e'
   const toPath = my.host+'/#' + to.path
   //核心步骤,获取code
   const hrefurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+encodeURIComponent(toPath)+"&response_type=code&scope=snsapi_base&state=dcabe11a-751f-490f-9dcc-606881c6fcdb#wechat_redirect";
   //从地址栏获取code
   const code = my.getQueryString('code')
   
   const isLogin = (openid)=>{//是否登录,此为java后台提供接口
      axios.get(api.isRegister+'?openId=' + openid)
      .then(function (res) {         
         if (res.data&&res.data.code == 200) {//已登录
            localStorage.setItem("userInfo",JSON.stringify(response.data.data))//存登陆信息
            next() 
         } else {//未登录   
         //此处应该跳转到注册页面(由于第三方所以跳转到别人的系统)
         //自己系统直接 next('/register')
         window.location.href = 'http://xxxx/register'  
         }
      })
      }
      
   const getOpenid = (code)=>  { //获取openid,此为java后台提供接口
      axios.get('http://获取openid接口?code=' + code)
         .then(function (response) {
            localStorage.setItem('openid',response.data);
            isLogin(response.data);//是否注册
      }).catch(function (error) {
         console.log(error)
      })
   }

   /* 路由发生变化修改页面title */
   if(to.meta.title){
      document.title = to.meta.title;
   }

   /* 判断该路由是否需要登录权限 */
   if (to.matched.some(record => record.meta.requireAuth)){
      //是否注册过信息~
      const openid = localStorage.getItem('openid');
      if(openid){
         isLogin(openid)
      }else{
         if(code){
            getOpenid(code) //我把获取openid请求提出去,简单明了很多
         }else{
            window.location.replace(hrefurl)
         }
      }
   }else{
      next()
   }
   
})

new Vue({
  api,
  router,
  store,
  render: h => h(App)
}).$mount('#app')

结尾:没了,csdn又boom了,回家明天再搞。

你可能感兴趣的:(微信公众号,Vant)