vue实现绑定微信登录全过程
一、需求說明
通過vue綁定微信登錄,首次進入獲取code,通過code獲取openId查用戶,然后進行登錄,第二次進入若綁定過微信,直接登錄進入主界面,若沒綁定過微信,則跳轉到登錄頁面。
二、準備工作
(1)開通微信公眾號的相關功能
測試賬號會有appID和appsecret,記住這兩個,后續會用到
填寫js接口安全域名,這里填的就是你的服務器接口訪問地址
這里先填自己本機的地址,記住不要加http等協議,端口號是你項目的端口號,例如我的項目端口號是8368
(2)其他準備工作
redirect_uri和appid
appid就是你測試號類里面的appId
redirect_uri是自己配置的,比如你想訪問http:192.168.1.117:8080/zy/project/index.html,那么你的redirect_uri可以就寫成這個,那么這個地址下面的網頁都可以訪問
當你用瀏覽器訪問https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxxxxxxxxxxxxx&redirect_uri=xxxxxxxxxxx&response_type=code&scope=snsapi_base#wechat_redirect這個鏈接的時候,會提示請在微信客戶端打開,這個時候需要用微信開發者工具打開,在地址欄中輸入這個鏈接,就可以了,成功訪問后,會跳轉到你redirect_uri重定向到的那個頁面,并且地址欄中還會多了一個code,這樣顯示就說明成功獲取到了code
scoped參數錯誤或者沒有scoped權限
出現這個錯誤可以查一下你的redirect_uri填寫是否正確,看一下微信公眾平臺的網頁賬號授權域名填寫是否正確,看一下js接口安全域名填寫是否正確
三、代碼實現
// 你的路由 const routes = [{path:'/',redirect:'/login',component:()=> import('@/App'),},] // App.vue中 <template><div id="app"><router-view> </router-view></div> </template> <script> import { getWxId, queryUser, bindWx } from '@/api/user' import { getUrlParam } from '@/utils' import { mapGetters } from 'vuex'export default {name: 'App',computed: {...mapGetters(['wxCode', 'wxId', 'userId']),//這里將獲取到的code和openId都存到了store中了},created() {if (this.wxCode && this.wxId) {//如果獲取到code和微信Id就去登錄this.Login()return}//若沒獲取到就走下面這一步const code = getUrlParam('code') // 截取路徑中的codeif (!code) {console.log('獲取微信code失敗')return}this.$store.commit('user/SET_WX_CODE', code)this.getOpenIdAndWxUser(code)},methods: {getOpenIdAndWxUser(code) {getWxId(code).then((res) => {console.log(res)if (!res.data) {console.log('獲取微信openId失敗', res)return}this.$store.commit('user/SET_WX_ID', res.data)//通過code獲取到微信IDconsole.log(this.wxCode, this.wxId)this.Login()// return getWxUser(result.data)}).catch((err) => {console.log(err)})},Login() {queryUser({//根據微信ID查詢用戶page: 1,limit: 999,wxId: this.wxId,}).then((res) => {console.log(res)if (res.data.rows[0].wxId) {//查到了就去登錄const Base64 = require('js-base64').Base64const username = Base64.encode(Math.random().toString(16).substr(2) +res.data.rows[0].username)const password = Base64.encode(Math.random().toString(16).substr(2) +res.data.rows[0].realPwd)this.$store.dispatch('user/login', {username: username,password: password,}).then(() => {this.$router.push({path: '/home',})}).catch((err) => {console.log(err)})} else {//查不到就去登陸頁面this.$router.push({path: '/',})this.$store.commit('user/SET_USER_ID',res.data.rows[0].userId)console.log(this.$store.state.user.userId)this.getWxUser()//綁定用戶,將微信ID添加到用戶表里面}})},getWxUser() {console.log(this.$store.state.user.userId)bindWx({userId: this.$store.state.user.userId,wxId: this.wxId,}).then((res) => {console.log(res)if (res.code == 200) {//修改成功去登錄this.Login()}})},}, } </script><style></style>總結
以上是生活随笔為你收集整理的vue实现绑定微信登录全过程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 话说嵌入式软件工程师的工资待遇
- 下一篇: 使用vue完成点击鼠标产生小心心特效