uni.login(OBJECT) : 登录接口
我们可以看到uni.login() 不支持H5,所以这里我们需要把APP 和 H5分开来
<template>
<view class="login">
<button class="wechat" lang="zh_CN" @click="login">微信登录</button>
</view>
</template>
当前在什么平台进入对应登录
data() {
return {
dataList: {
openId: "",
unionId: "",
nickName: "",
headPortrait: ""
},
isWeixin: false
}
}
login() {
let that = this;
// #ifdef APP-PLUS
// APP登录
this.appLogin();
// #endif
// #ifdef H5
// H5登录
this.getWeChatCode()
// #endif
}
一、APP微信登录
// app微信登录
appLogin(){
uni.login({
provider: 'weixin',
success: function(loginRes) {
console.log(loginRes);
if (loginRes.errMsg === 'login:ok') {
// 获取用户信息
uni.getUserInfo({
provider: 'weixin',
success: function(infoRes) {
console.log(infoRes);
if (infoRes.errMsg === 'getUserInfo:ok') {
that.dataList.openId = infoRes.userInfo.openId;
that.dataList.unionId = infoRes.userInfo.unionId;
that.dataList.nickName = infoRes.userInfo.nickName;
that.dataList.headPortrait = infoRes.userInfo.avatarUrl;
request({
url: app_user_code_wx_login_api,//请求后台API
isLoading: false,
isResponseMsg: false,
isResponseErr:false,
isContentType: true,
data: JSON.stringify(that.dataList),
method: 'POST'
}).then(res => {
if (res.code === 0) {
uni.setStorageSync("token", res.data.token);
uni.setStorageSync("userId", res.data.userId);
uni.reLaunch({
url: '../../home/index',
})
}
})
}
}
});
}
}
});
}
二、H5微信登录
// 是否为微信浏览器
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.h5Login(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";
},
h5Login(code) {
// H5登录
let params = {
code: code
};
request({
url: app_user_code_h5_login_api, // 请求后台API
isLoading: false,
isResponseMsg: false,
isResponseErr:false,
isContentType: true,
data: JSON.stringify(params),
method: 'POST'
}).then(res => {
if (res.code === 0) {
uni.setStorageSync("token", res.data.token);
uni.setStorageSync("userId", res.data.userId);
uni.reLaunch({
url: '../../home/index',
})
}
})
}
onLoad() {
this.isWeixin = this.isWechat()
if (this.isWeixin) {
this.checkWeChatCode() //通过微信官方接口获取code之后,会重新刷新设置的回调地址【redirect_uri】
}
}