模板层代码
<template>
<view class="login">
<view class="login_text">您尚未登录需要获取您的授权后进入小程序</view>
<view class="login_but_box">
<view class="login_but_box_a" @click="getWX()" v-if="!vuex_id">微信登入</view>
<view class="login_but_box_a" @click="goindex()">暂不登入</view>
<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" class="login_but_box_b" v-if="vuex_id">绑定手机号</button>
</view>
</view>
</template>
视图层业务逻辑代码
<script>
import $http from '@/common/request.js'
import { mapState } from "vuex"
export default {
data() {
return {
code: '', //code值
nickName: '', //昵称
avatarUrl: '', //头像
iv: '', //用户接口返回数据
encryptedData: '', //
session_key: '', //密钥
openid: '', //id
gender: '', //性别
vuex_id: '', //用户id
}
},
onLoad() {},
methods: {
getWX() { // 微信登录获取用户数据
var that = this;
uni.showLoading({ // 展示加载框
title: '加载中',
});
uni.getUserProfile({ //获取到用户信息
desc: '登录后可同步数据',
success: async (obj) => {
console.log('obj', obj); //登录后返回用户的数据
that.nickName = obj.userInfo.nickName //用户名
that.avatarUrl = obj.userInfo.avatarUrl //用户头像
that.gender = obj.userInfo.gender //性别
that.iv = obj.iv //数据
that.encryptedData = obj.encryptedData //数据
// 调用 action ,请求登录接口
uni.login({
provider: 'weixin',
success: (res) => {
console.log('res-login', res);
//获取到code
that.code = res.code;
//请求登录接口
if (res.errMsg == 'login:ok') {
var params = {
code: that.code,
nickname: that.nickName,
avatar: that.avatarUrl
}
$http.request({
url: "/api/subscriber/login", //封装请求的接口
data: {
code: that.code
}
}).then((res) => {
that.session_key = res.data.session_key //接收后端返回的密钥
that.openid = res.data.openid //返回的oppenid
that.getMyInfo()
}).catch((res) => {
uni.showToast({
title: '请求失败',
icon: 'none'
})
})
}
},
});
},
fail: () => {
uni.showToast({
title: '授权已取消',
icon: 'error',
mask: true,
});
},
complete: () => {
// 隐藏loading
uni.hideLoading();
},
});
},
getMyInfo() { //获取用户信息后返回后端存入数据库
$http.request({
url: "/api/subscriber/information",
data: {
openid: this.openid,
nickname: this.nickName,
gender: this.gender,
avatar: this.avatarUrl,
},
method: "POST",
}).then((res) => {
this.$store.commit('getuserName', res.data.id)
this.vuex_id = this.$store.state.user.userId
console.log(this.vuex_id)
}).catch((res) => {
uni.showToast({
title: '请求失败',
icon: 'none'
})
})
},
getPhoneNumber(e) { //获取用户手机号并存入数据库
console.log(e)
$http.request({
url: "/api/subscriber/phones",
data: {
encryptedData: this.encryptedData,
iv: this.iv,
appid: this.openid,
sessionKey: this.session_key,
user_id: this.vuex_id,
code: e.detail.code,
},
method: "POST",
}).then((res) => {
console.log(res.data)
uni.showToast({
title: res.data.msg,
icon: 'error',
mask: true,
});
if (res.data.code == 200) {
setTimeout(() => {
uni.redirectTo({
url: "/pages/index/index"
})
}, 1500)
}
}).catch((res) => {
uni.showToast({
title: '请求失败',
icon: 'none'
})
})
},
goindex() {
uni.navigateTo({
url: "/pages/index/index"
})
}
}
}
</script>
图文讲解逻辑:
一、未登录
二、登录后返回用户数据信息、code值、用户id
三、点击绑定手机号
四、用户授权之后返回的手机号信息抛给后端数据库