微信掃碼登入
阿新 • • 發佈:2021-11-09
微信掃碼登入
場景 ① 直接跳轉一個新連結頁面; ② 網站將微信登入二維碼內嵌到自己頁面中
① 直接跳轉一個新連結頁面
pc端展示登入按鈕,點選登入按鈕,開啟二維碼頁面,手機微信掃描二維碼,授權同意,pc頁面跳轉新頁面
<template> <div class="container"> <!-- pc端展示 登入按鈕 --> <button @click="login">微信登入</button> </div> </template> <script> const APPID = 'wx536e555555555555' export default { data () { return { }; }, async created () { // const wxCode = this.getQueryString('code') const wxCode = this.getQs('code') if (wxCode){ /* 微信授權獲取code成功後,重定向到某個頁面,這裡寫的是當前頁,再次來到beforeCreate生命週期,可以通過location的search來獲取code 獲取到code值後,將code傳送介面到後臺,後臺獲取到code後,通過code獲取 access_token,再通過access_token來獲取使用者info,後臺返回前端一個token,登入用的token */ const response = await this.$http.post('getToken', { wxCode: wxCode }) token = response.data.openid this.$cookie.set('token', token) /* 業務邏輯,在路由守衛進行許可權控制 */ /* 使用者微信授權成功後,會進入redirect_uri中的地址,這裡設定的是本頁, 此時會重新走一遍vue的生命週期,來到created時,獲取到code值,傳送介面 ,獲取到了token 同時,頁面跳轉到別的頁面 */ this.$router.push('/list') } }, methods: { login () { /* 展示二維碼: https://open.weixin.qq.com/connect/qrconnect appid=xxxxxxxxxxxxxxxx redirect_uri=https://xxxxxx.com/index.html // 二維碼登入成功後跳轉的連結地址 response_type=code scope=snsapi_login state=state #wechat_redirect */ window.location.href = 'https://open.weixin.qq.com/connect/qrconnect?appid=wxafc256bf83583323&redirect_uri=http://www.yiyuanlive.com/mall/index.html&response_type=code&scope=snsapi_login&state=state#wechat_redirect' }, getQs (name) { const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); const r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; }, } }; </script>
② 支援網站將微信登入二維碼內嵌到自己頁面中,使用者使用微信掃碼授權後通過JS將code返回給網站
<div id="wxqr" class="wxqr"></div> //步驟1:在頁面中先引入如下JS檔案(支援https): http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js //步驟2:在需要使用微信登入的地方例項以下JS物件: const obj = new WxLogin({ id:"wxqr", appid: "wxb9e2238ff05c7bd7", scope: "snsapi_login", redirect_uri: "https://test.2or3m.com/newWeb/binding_phone.html", state: "2or3m", style: "white" });