首先获取用户信息以及手机号必须要通过button按钮点击实现
一、获取用户信息(友情链接)
依据微信小程序开发文档描述,先写一个button按钮,open-type
设为 getUserProfile
,在uniapp页面中创建按钮
<button
style="border: none; height: 120rpx; width: 120rpx"
class="login obtain"
open-type="getUserProfile"
@click="getUserProfile"
withCredentials="true"
v-if="theUser == 1"
>获取用户信息</button>
在methods中:
getUserProfile() {
let that = this;
if (uni.getUserProfile) {
uni.getUserProfile({
desc: "获取用户信息仅用于展示",
success(res) {
console.log(res);
console.log("用户点击允许");
console.log("用户信息", that.userInfo);
const userInfo = res.userInfo;
//性别 0:未知、1:男、2:女
const {
nickName,
avatarUrl,
gender,
province,
city,
country,
} = userInfo;
uni.setStorageSync("userInfo", userInfo);
that.userInfo.nickName = userInfo.nickName;
that.userInfo.avatarUrl = userInfo.avatarUrl;
that.userInfo.gender = userInfo.gender;
that.theUser = 0;//获取成功之后用来判断按钮的显示与隐藏
},
fail(error) {
console.log("用户未授权", error);
that.theUser = 1;
// uni.showToast({
// title: "登录失败",
// duration: 3000,
// icon: "none",
// });
},
});
}
}
二、获取用户的手机号 参考文档
获取用户手机号跟获取用户信息差不多,先写一个button按钮,open-type
设为 getPhoneNumber
,在uniapp页面中创建按钮:
<button style="color: #999; font-size: 36rpx; border: none" class="login" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" withCredentials="true">点击登录</button>
首先微信小程序,点击微信第三方登录,获取到当前用户绑定的手机号与openId(或unionid)
在页面生命周期 onLoad() 中,调用 wx.login
接口,获取code;用 code
换取 session
和 openId(前端获取)
onLoad(){
wx.login({
success: (res) => {
if (res.code) { //微信登录成功 已拿到code
this.jsCode=res.code //保存获取到的code
uni.request({
url: 'https://api.weixin.qq.com/sns/jscode2session',
method:'GET',
data: {