(1)小程序端调用 wx.login方法获取用户登录凭证code,将code发送给小程序后台服务器;服务器调用登录凭证校验接口(需要传参appid+appsecret+code),进而换取用户登录态信息,包括用户的唯一标识(openid)及本次登录的会话密钥(session_key)等,将这些信息存入缓存中。
(2)点击button按钮触发获取微信手机号弹框!
(3)绑定微信账号,存在相应手机号账号时自动登录;不存在时自动创建
具体代码如下:
<template>
<view class="longinelse-btns">
<!-- #ifdef MP-WEIXIN -->
<button class="longinelse-btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber"@click="getUserInfo()">
<image src="../../static/login/wx.png" class="_img"></image>
</button>
<!-- #endif -->
<button class="longinelse-btn" @click="open">
<image src="../../static/login/wb.png" class="_img"></image>
</button>
<button class="longinelse-btn" @click="open">
<image src="../../static/login/qq.png" class="_img"></image>
</button>
</view>
</template>
export default {
data() {
return {
openid: null,
session_key: null,
hkey_code: null,
nickName: null,
gender: '男',
}
},
methods: {
// #ifdef MP-WEIXIN
// 获取用户信息
getUserInfo() {
uni.getUserProfile({
desc: '登录xxx',
success: (res) => {
console.log(res);
this.nickName = res.userInfo.nickName;
this.gender = res.userInfo.gender == 0 ? '男' : '女';
},
fail: (err) => {
console.log(err);
}
});
},
//#endif
// #ifdef MP-WEIXIN
// ========================微信授权相关==========================
/**
* 尝试进行微信授权登录,成功后跳转到下一页
* @param {String} _code [in] 微信授权代码
*/
tryLoginWx(_code) {
utils.api.sso.wx.login.call(null, {
code: _code
}).then((_res) => {
console.log("utils.api.sso.wx.login", _res)
this.openid = _res.data.wx.openid;
this.session_key = _res.data.wx.session_key;
this.hkey_code = _res.data.hkey_code;
if (!_res.data.user) {
utils.local.ls.token.value = _res.data.user.token;
//utils.local.ls.userName.value = this.account;
uni.switchTab({
url: "/pages/function",
});
}
}).catch(utils.api.sso.wx.login.doCatch)
},
onGetPhoneNumber(e) {
console.log("onGetPhoneNumber", e);
if (e.detail.errMsg == "getPhoneNumber:fail user deny") { //用户决绝授权
console.log("用户决绝授权")
return;
} else {
console.log("允许授权")
//获取手机号,查询是否有相应的用户
utils.api.sso.wx.getphone.call(null, {
key: this.session_key,
v: e.detail.iv,
data: e.detail.encryptedData
}).then((_res) => {
console.log("utils.api.sso.wx.getphone", _res);
this.bindLoginWx(_res.data.phoneNumber);
}).catch(utils.api.sso.wx.getphone.doCatch)
}
},
/**
* 绑定微信账号,存在相应手机号账号时自动登录;不存在时自动创建
* @param {Object} _phone
*/
bindLoginWx(_phone) {
utils.api.sso.wx.bindLogin.call(null, {
code: this.hkey_code,
openid: this.openid,
phone: _phone,
login: true
}).then((_res) => {
console.log("utils.api.sso.wx.bindLogin", _res)
if (_res.data) {
utils.local.ls.token.value = _res.data.token;
utils.local.ls.userName.value = _phone;
uni.switchTab({
url: "/pages/function",
});
} else {
this.newUser(_phone);
}
}).catch(utils.api.sso.wx.bindLogin.doCatch)
},
},
onLoad() {
//获取code信息
uni.login({
provider: 'weixin',
success: (loginRes) => {
var code = loginRes.code
console.log("获取信息", code)
this.tryLoginWx(code);
}
});
}
}
//#endif