第一步 我们先把页面画出来
-
<template>
-
-
<!-- #ifdef MP-WEIXIN -->
-
<view v-if="isCanUse">
-
<view>
-
<view class='headers'>
-
<image src='../../static/img/logo.png'>
</image>
-
</view>
-
<view class='content'>
-
<view>申请获取以下权限
</view>
-
<text>获得你的公开信息(昵称,头像、地区等)
</text>
-
</view>
-
-
<button style="background: #E10A07;background-color: #E10A07;" class='bottom' type='primary' open-type="getUserInfo"
-
withCredentials=
"true"
lang=
"zh_CN" @
getuserinfo=
"wxGetUserInfo">
-
授权登录
-
</button>
-
</view>
-
</view>
-
<!-- #endif -->
-
</template>
第二步再methods中写下三个方法
-
//第一授权获取用户信息===》按钮触发
-
wxGetUserInfo() {
-
let _this =
this;
-
-
uni.getUserInfo({
-
provider:
'weixin',
-
success: function(infoRes) {
-
let nickName = infoRes.userInfo.nickName;
//昵称
-
let avatarUrl = infoRes.userInfo.avatarUrl;
//头像
-
try {
-
uni.setStorageSync(
'isCanUse',
false);
//记录是否第一次授权 false:表示不是第一次授权
-
if (_this.$queue.getData(
"openid")) {
-
//有openid就直接更新昵称和头像
-
_this.getWeixinInfo(nickName, avatarUrl);
-
}
else {
-
//没有openid就直接执行登录
-
_this.login()
-
}
-
-
}
catch (e) {}
-
},
-
fail(res) {}
-
});
-
},
-
//登录 这个方法用于获取用户昵称和头像同步给后台接口
-
getWeixinInfo(nickName, avatarUrl) {
-
uni.showLoading({
-
title:
'登录中...'
-
});
-
this.$Request.postJson(
"/user/mp/update", {
-
invitation:
this.invitation,
-
unionid:
this.$queue.getData(
"unionid"),
-
imageUrl: avatarUrl,
-
nickName: nickName,
-
openid:
this.$queue.getData(
"openid")
-
}).then(res => {
-
if (res.status ===
0) {
-
this.$queue.setData(
"token", res.data.uuid);
-
this.$queue.setData(
"userId", res.data.userId);
-
this.$queue.setData(
"mobile", _this.phoneData);
-
this.getUserInfo(res.data.userId, res.data.uuid);
-
}
else {
-
-
uni.hideLoading();
-
uni.showModal({
-
showCancel:
false,
-
title:
'登录失败',
-
content: res.msg,
-
});
-
}
-
});
-
},
-
//使用到的登录接口
-
login() {
-
let _this =
this;
-
uni.showLoading({
-
title:
'登录中...'
-
});
-
// 1.wx获取登录用户code
-
uni.login({
-
provider:
'weixin',
-
success: function(loginRes) {
-
//获取到code 拿着code去请求后台接口换openid和unionid 这里说到unionid只有关联了微信开放平台才会有
-
let code = loginRes.code;
-
-
_this.$Request.getT(
"/wx/mp/login?code=" + code).then(res => {
-
if (res.status ===
0) {
-
_this.$queue.setData(
"openid", res.data.open_id)
-
_this.$queue.setData(
"unionid", res.data.unionid)
-
uni.hideLoading()
-
//非第一次授权获取用户信息
-
uni.getUserInfo({
-
provider:
'weixin',
-
success: function(infoRes) {
//获取用户信息后向调用信息更新方法
-
let nickName = infoRes.userInfo.nickName;
//昵称
-
let avatarUrl = infoRes.userInfo.avatarUrl;
//头像
-
if (nickName) {
-
_this.getWeixinInfo(nickName, avatarUrl);
-
}
-
}
-
});
-
}
-
});
-
},
-
});
-
},
具体可以参考这个:https://ext.dcloud.net.cn/plugin?id=1798
转载:https://blog.csdn.net/weixin_39706415/article/details/111588465
查看评论