uniapp 微信小程序 微信登录 请求微信用户基本信息

335 阅读1分钟

小程序登录流程

html部分


<button class="login-btn" type="primary" @click="getUserInfo">
  微信用户一键登录
</button>
<view class="user">
  用户名+头像
  <view>
    {{userName}} // 昵称
  </view>
  <img :src="pic" alt="" style="width: 100px; height:100px;"> // 头像
</view>

登录请求


<script>
	export default {
		name: 'Index',
		data() {
			return {
				userName: '',
				pic: ''
			}
		},
		onLoad() {
			// this.getUserInfo();
		},
		methods: {
      // 获取微信用户信息,一键登录
			getUserInfo() {
				var that = this
				uni.showModal({
					title: '温馨提示',
					content: '亲,授权微信登录后才能正常使用小程序功能',
					success(res) {
            if (res.confirm) {
							uni.getUserProfile({ // 获取微信用户的基本信息
								desc: "注册用户信息使用",
								lang: "zh_CN",
								success: (res) => {
									console.log('res', res)
									that.userName = res.userInfo.nickName, // 拿到用户昵称
									that.pic = res.userInfo.avatarUrl, // 用户头像
									uni.login({ // 登录,拿code 
                    // 微信接口服务器需要通过code换取 openid、unionid、session_key 等信息
										provider: 'weixin',
										success: function(loginRes) {
											console.log('loginRes.authResult', loginRes);
											// 在这个地方普通开发中就应该去调用后端给的api进行登录操作了
											// 现在这个地方我们需要换成云函数进行相关操作
											uni.request({  // 获取openid
                        url: 'https://api.weixin.qq.com/sns/jscode2session',  
                        method:'GET',
                        data: {  
                          appid: "wxxxxxxxxxxx", // 你的小程序的APPID 
                          secret: "xxxxxxxxxx",       //你的小程序的secret,
                          js_code: loginRes.code       //wx.login 登录成功后的code  
                        },  
                        success: (cts) => {  
                          console.log(cts); // 获得openid
                        }  
                      });  
											// 调用云函数user,将基本信息存储到云数据库
											// uniCloud.callFunction({
												// name: 'user',
												// data: {
													// code : loginRes.code,
													// userName: res.userInfo.nickName,
													// gender: res.userInfo.gender,
													// city: res.userInfo.city,
													// province: res.userInfo.province,
													// country: res.userInfo.country,
													// avatarUrl: res.userInfo.avatarUrl,
											// 	}
											// }).then(res => {})
										}
									});
								}
							})
						} else {
							uni.showToast({
								title: '您取消了授权',
								duration: 2000
							});
						}
					}
				})
			},
    }
}