- 微信內嵌瀏覽器運行H5版時,可以調起微信登錄
- 普通瀏覽器調起微信登陸是不開放的,只有個別開發者才有,比如京東
前置條件
在微信內嵌瀏覽器運行H5版時,調起微信登錄,需要配置回調域名 (請注意,這里填寫的是域名(是一個字符串),而不是URL,因此請勿加 http:// 等協議頭;),具體步驟如下
- 打開微信公眾平台,登錄上去
- 點擊【公眾號設置】
- 點擊【功能設置】
- 找到【網頁授權域名】,點擊旁邊的【設置】
- 在修改業務域名和JS接口域名時,已經上傳過這個文件的話,那么請直接跳過這一步。如果還沒上傳的,直接點擊文件下載,然后上傳到服務器。 (這個可以找后台人員去干)
- 上傳成功后,直接輸入授權域名,點擊【確認】即可
具體代碼如下
微信開發文檔:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
scope為snsapi_base時, 為靜默登錄
scope為snsapi_userinfo時,會彈出“xxx申請獲得你的微信頭像、昵稱、地區和性別信息”這樣的彈出框,需要經過用戶同意
<!-- 注冊頁面 -->
<template>
<view class="bottom-side-otherLogin" @click="getWeChatCode" v-if="isWeixin">
<text>其他社交賬號登錄</text>
<image src="https://xuezhifu-resource.oss-cn-hangzhou.aliyuncs.com/newxuefu/mwx/wx.png"></image>
</view>
</template>
<script>
export default {
data() {
return {
isWeixin: false,
};
},
onLoad() {
this.isWeixin = this.isWechat()
if(this.isWeixin){
this.checkWeChatCode()//通過微信官方接口獲取code之后,會重新刷新設置的回調地址【redirect_uri】
}
},
onShow() {
},
mounted() {
},
methods: {
/*微信登錄相關 start*/
//方法:用來判斷是否是微信內置的瀏覽器
isWechat() {
return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
},
//方法:用來提取code
getUrlCode(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1]
.replace(/\+/g, '%20')) || null
},
//檢查瀏覽器地址欄中微信接口返回的code
checkWeChatCode() {
let code = this.getUrlCode('code')
uni.showToast({
title:`微信code=${code}`
})
if (code) {
this.getOpenidAndUserinfo(code)
}
},
//請求微信接口,用來獲取code
getWeChatCode() {
let local = encodeURIComponent(window.location.href); //獲取當前頁面地址作為回調地址
let appid = '自己的appid'
//通過微信官方接口獲取code之后,會重新刷新設置的回調地址【redirect_uri】
window.location.href =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
appid +
"&redirect_uri=" +
local +
"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
},
//把code傳遞給后台接口,靜默登錄
getOpenidAndUserinfo(code) {
this.$http({
url:'api/login',
data:{
code:code
}
}).then((res) => {
console.log(res)
if (res.code != 0) {
uni.showToast({
title: res.msg,
duration: 3000,
icon: 'none'
});
return
}else{
this.afterLogin(res)
}
})
},
/*微信登錄相關 end*/
afterLogin(res){
let user = res.data.user
uni.setStorageSync('token', res.data.token);
let u = {
avatar: user.avatar ? user.avatar : this.avatar,
mobile: user.mobile,
nickname: user.nickname ? user.nickname : '土肥圓'
}
uni.setStorage({
key: 'u',
data: u,
success: () => {
let url = uni.getStorageSync('redirect')
uni.reLaunch({
url: url ? url : '/pages/index'
})
}
});
},
},
}
</script>