微信掃碼登錄


微信掃碼登錄

場景 ① 直接跳轉一個新鏈接頁面; ② 網站將微信登錄二維碼內嵌到自己頁面中

① 直接跳轉一個新鏈接頁面
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"
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM