The latest update

Please see >>> wechat authorization

Vue wechat page authorization, based on VUE-Cli3.0 + WebPack 4+ Vant UI + SASS + REM adaptation scheme + AXIOS, the development of wechat authorization scheme. Project Address: VUe-Weike-Auth

Again and again to write wechat page authorization, wrote a year ago [VUE wechat authorization solutions].

Reference [vue-Weike-login], the idea is somewhat different, this paper is based on the operation that access to all pages must be authorized first.

Different from the license written earlier

This time the logic is all done on the beforeEach of the router, which is much cleaner. Before, it was in a middle page author.vue, adding wechat authorization to jump many times

You can find it here

  1. Wechat web page authorization front-end solution, official documents
  2. How to use Natapp(ngrok) for wechat local development and debugging, official documents
  3. How to configure the wechat development test account

About test accounts and local development Settings

Because the article is too long here [wechat test account and local development and debugging] remember to come back oh ~

Wechat web page authorization

All set up well then start wechat web development the first and most important step, wechat web page authorization

The first thing you need to know about authorization is that the server needs to use wechat OpenID or wechat UnionID. The difference between the two is that if you want unionID, then you need to bind the test account in [wechat Open Platform]. The appId and AppSecret of the test number can be found in the test number of wechat public platform. Wechat public account background -> Developer tools -> public platform test account -> Enter

If you do not need the unionID, then you can omit this, if the server does need the unionID, then the authorization will not bind to the error. Be sure to check with the server developers.

The development of

First of all, let’s look at the flow chart of wechat authorization, about wechat webpage authorization

What the front end needs to do is

The first step: Redirect_uri is your current address. Some people get the appID through the interface. I’ll write it directly in the global variable of the project. After successful authorization, wechat will jump back with the code and status

https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${this.redirect_uri}&response_type= code&scope=${this.scope}&state=${this.state}#wechat_redirectCopy the code

Step 2, access the login interface, pass the code to the server, and perform a series of operations.Exchange web page authorization access_token with code.Pull user information (scope is snsapi_userinfo), returns whether the login is successful, and then returns the user information and login token token

The route interceptor does this in Permission.js, and the code comments are detailed

permission.js

import router from './router' import store from './store' import getPageTitle from '@/utils/get-page-title' import WechatAuth from './plugins/wechatAuth' const qs = require('qs') router. BeforeEach ((to, from,) next) => { const loginStatus = Number(store.getters.loginStatus) console.log('loginStatus=' + loginStatus) Console. log('token=' + store.getters. Token) document.title = getPageTitle(to.meta. Title) if (loginStatus === 0) Const url = window.location.href const parseUrl = qs.parse(url.split('? ')[1]) let loginUrl if (parseUrl.code && parseUrl.state) { delete parseUrl.code delete parseUrl.state loginUrl = `${url.split('? ') [0]}? ${qs.stringify(parseUrl)} '} else {loginUrl = url} wechatauth. redirect_uri = loginUrl store.dispatch('user/setLoginStatus', Href = wechatAuth.authUrl} else if (loginStatus === 1) {if (loginStatus === 1) { Access code try {/ / through setting code correction link status wechatAuth. ReturnFromWechat (to.. fullPath)} the catch (err) {/ / failure, set the state did not log in, Store.dispatch ('user/setLoginStatus', 0) location.reload()} Const code = wechatauth. code if (code) {store. Dispatch ('user/loginWechatAuth', Store. Dispatch ('user/setLoginStatus', 2) next()}). Catch (() => {// failed to set the loginstatus state, Store.dispatch ('user/setLoginStatus', 0) location.reload()})} else {store.dispatch('user/setLoginStatus', 0) location.reload()}} else {// Next ()}})Copy the code

After successful login, save user information, token. When accessing all interfaces, the token is carried in the header. If the token is invalid, the server returns to 401 to exit the interface, delete the login status, user information, and token, and refresh the page to enter the interface again.

request.js

If (res.status === 401) {store.dispatch('user/fedLogOut').then(() => {location.reload()})}Copy the code

After a user logs in, the token and user information are stored in the storage and the login status is set to the cookie. In Store User, the user information is stored and deleted

store/modules/user.js

import { loginByCode } from '@/api/user' import { saveToken, saveLoginStatus, saveUserInfo, removeToken, removeUserInfo, removeLoginStatus, loadLoginStatus, loadToken, LoadUserInfo} from '@/utils/cache' const state = {loginStatus: loadLoginStatus(), // Open mutations = {SET_USERINFO: open mutations = {SET_USERINFO: open mutations = {SET_USERINFO: open mutations = {SET_USERINFO: (state, userInfo) => { state.userInfo = userInfo }, SET_LOGIN_STATUS: (state, loginStatus) => { state.loginStatus = loginStatus }, SET_TOKEN: (state, token) => {state.token = token}} const actions = {// Login related, Obtain token and user information by code loginWechatAuth({commit}, code) {const data = {code: Code} return new Promise((resolve, reject) => {loginByCode(data). Then (res => { token commit('SET_USERINFO', saveUserInfo(res.data.user)) commit('SET_TOKEN', SaveToken (res.data.token)) resolve(res)}). Catch (error => {reject(error)})})}, // Set state setLoginStatus({commit}, Query) {if (query = = = 0 | | query = = = 1) {/ / open online comments, local debugging commented out, Commit ('SET_LOGIN_STATUS', saveLoginStatus(query))}, // Exit fedLogOut() {// Delete token, user information, RemoveToken () removeUserInfo() removeLoginStatus()}} export default {namespaced: true, state, mutations, actions }Copy the code

Set wechat appID in the three files beginning with. Env under the root directory

VUE_APP_WECHAT_APPID='12345678' Copy codeCopy the code

Authorization is no longer difficult for me. If there is a problem, PLEASE leave a message for me to correct it and learn from each other

About me

For more technology-related articles, follow the public account “front-end girls juku”.

Return to front end to join “Front End Fairy Group”

You can scan and add wechat below and note Sol plus front-end exchange group for exchange and learning.

If it will be helpful to you, send me a little star (the better you guys will be)