vue移動端,點擊微信授權登錄


封裝微信登錄接口:

const wxLogin = (appid, url) => {
  let redirect_uri = encodeURIComponent(url)
  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATUS#wechat_redirect`
}
參數說明:

1、let redirect_uri = encodeURIComponent(url)  ——  授權后重定向的回調鏈接地址,並把字符串編碼為 URI 組件。

2、windows.location.href="/url"  ——  當前頁面打開URL頁面
3、appid  -  公眾號的唯一標識(必填)
4、redirect_uri  -  授權后重定向的回調鏈接地址, 請使用 urlEncode 對鏈接進行處理(必填)
5、response_type  -  返回類型,請填寫code(必填)
6、scope  -  應用授權作用域,snsapi_base(靜默登錄,不彈出授權頁面,直接跳轉,只能獲取用戶openid),snsapi_userinfo (彈出授權頁面,可通過openid拿到昵稱、性別、所在地。並且, 即使在未關注的情況下,只要用戶授權,也能獲取其信息 )(必填)
7、state  -  重定向后會帶上state參數,開發者可以填寫a-zA-Z0-9的參數值,最多128字節(非必填)
8、#wechat_redirect  -  無論直接打開還是做頁面302重定向時候,必須帶此參數(必填)

1、第一個參數用?號隔開,之后的參數用&隔開,最后的#wechat_redirect不用加&
2、open.weixin.qq.com/connect/oauth2/authorize  微信默認地址
3、文檔地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842


頁面中使用:
template:
 <div @click="wxlogin">
     <p>使用微信登錄</p>
 </div>

 

script
import {wxLogin} from "@/api/apis";

// methods
wxlogin(){
        wxLogin('wx546563fe38304393', 'http://whc.mouhua.cn/mobile/v-accredit')
}
 第一個參數是公眾號的appid,第二個是跳轉的默認空白頁。

accredit空白頁:
<template>
<div>
</div>
</template>

<script>
import { login } from '@/api'
import { getUrlParam } from '@/utils/utils'
export default {
name: 'accredit',
data(){
return{
}
},
mounted() {
let code = this.$route.query.code || getUrlParam('code');
let state = this.$route.query.state || getUrlParam('state');
login({
code
})
.then( res => {
let role = res.data.role;
localStorage.setItem('accessToken', res.data.accessToken)
localStorage.setItem('role', role)
this.$router.replace(state);
this.$message({
message:'登錄成功',
type:'success',
onClose(){
_this.$router.push('/')
localStorage.setItem('ifLoading', '1')
}
})
      })
},
methods: {
}
}
</script>

1.import { getUrlParam } from '@/utils/utils'    ——  引用

封裝獲取url的參數的方法:

// 獲取url上的參數
export const getUrlParam = (name) => {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");      //構造一個含有目標參數的正則表達式對象
  let r = window.location.search.substr(1).match(reg);        //匹配目標參數
  if (r != null) return decodeURIComponent(r[2]); return null;   //返回參數值 
}

 

2.import { wechatLogin } from '@/api/apis'  ——  引用微信登錄接口

const wechatLogin = get('/api/v1/user/wechatLogin');

 

3.

let code = this.$route.query.code || getUrlParam('code');

login({
code
})
.then( res => {
localStorage.setItem('accessToken', res.data.accessToken)
})

  ——  獲取url上的code,調用微信登錄傳入code,localStorage.setItem('accessToken',存儲登錄時的token


特殊項目,非必需

this.$route.query(獲取參數)

state(重定向后會帶上state參數,非必填,用於記錄多頁面)

role (獲取用戶的角色)

this.$router.replace(同樣是跳轉到指定的url,但是這個方法不會向history里面添加新的記錄,點擊返回,會跳轉到上上一個頁面。上一個記錄是不存在的。)

 

this.$message(element框架登錄成功后的提示)

 


免責聲明!

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



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