PC網頁微信授權登錄
一:網頁外鏈跳轉的方式
01.請求后臺的接口逾苫,會返回一個微信掃碼的界面地址铅搓,使用js跳轉過去即可
wxlogin () {
User.wxlogins().then(res => {
console.log(res)
window.location.href = res.result.url
})
},
02.用戶在掃完碼點擊確定授權后星掰,后臺會拿到微信授權用戶的信息后,會幫我們跳轉到事先給后臺重定向的地址頁面(這里我是新建了一個空白頁用來接收后臺返回的數(shù)據)怀偷,在地址后面后臺會拼接一個token播玖,我們拿到這個token,去獲取用戶信息维蒙,跳轉到首頁颅痊,即可完成登錄
let token = this.$route.query.token
if (token) {
this.getUserInfo().then(ures => {
this.$router.push({
name: 'home'
})
})
}
二:網頁內嵌二維碼方式
01.配置好下面相關參數(shù)局待,即可生成微信授權登錄/綁定二維碼,(注意:setWxerwma ()此方法需在mounted中調用)
setWxerwma () {
const s = document.createElement('script')
s.type = 'text/javascript'
s.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
const wxElement = document.body.appendChild(s)
wxElement.onload = function () {
var obj = new WxLogin({
id: '', // 需要顯示的容器id
appid: '', // 公眾號appid wx*******
scope: 'snsapi_login', // 網頁默認即可
redirect_uri: encodeURIComponent(''), // 授權成功后回調的url
state: Math.ceil(Math.random() * 1000), // 可設置為簡單的隨機數(shù)加session用來校驗
style: 'black', // 提供"black"、"white"可選重绷。二維碼的樣式
href: '' // 外部css文件url昭卓,需要https
})
}
},
02.后面的邏輯根據后臺返回的數(shù)據來處理即可愤钾,同方法一步驟二類似
微信公眾號網頁授權登錄
01.創(chuàng)建一個按鈕瘟滨,點擊觸發(fā)事件,跳轉到微信授權頁面
wxlogin () {
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${this.url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
}
//this.appid 公眾號APPID this.url 用戶點擊授權后,會跳轉到后臺幫我們重定向的頁面(這里我是新建了一個空白頁能颁,專門接收code)
02.在重定向的頁面拿到微信那邊給我們返回的code杂瘸,會拼接在URL后面,我們拿到這個code再請求后臺的接口換取token伙菊,完成微信登錄