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的流程

在這裏插入圖片描述

第一步:

配置公衆號:設置-公衆號設置-功能設置,切記必須是在線域名,localhost不行
在這裏插入圖片描述
把下圖txt文件下載,放到前臺頁面服務器目錄下,域名寫在輸入框中。
域名規則:例:https://admin.serve.com.cn;填寫:admin.serve.com.cn;不要加https|http在這裏插入圖片描述

至此,後臺配置完事兒

第二步:

//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了,回家明天再搞。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章