uniapp小程序云开发登陆篇最佳实践

3,063 阅读1分钟

第一步,检查是否登录

// App.vue
<script>
	global.isLogin = function() {
		try {
			var openid = uni.getStorageSync('openid');
		} catch (e) {

		}
		if (openid === '') {
			return false
		} else {
			return {
				openid
			}
		}
	};
	export default {
		onLaunch: function() {
			console.log('App Launch')
			wx.cloud.init({
				traceUser: true
			});
		}
	}
</script>

第二步,登陆页面

// login.vue
<template>
	<view>
		<!-- #ifdef MP-WEIXIN -->
		<button class='bottom' type='primary' open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getuserinfo="wxGetUserInfo">
			授权登录
		</button>
		<!-- #endif -->
	</view>
</template>
<script>
	const db = wx.cloud.database();
	export default {
		data() {
			return {}
		},
		methods: {
			wxGetUserInfo(msg) {
				console.log(msg)
				var that = this;
				if (!msg.detail.iv) {
					uni.showToast({
						title: '您取消了授权,登录失败',
						icon: 'none'
					});
					return false
				}
				uni.showLoading({
				    title: '加载中'
				});
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						console.log(loginRes)
						that.getOpenid(msg);
					},
					fail: function(r) {
						console.log(r)
					}
				})
			},
			getOpenid(msg) {
				var that = this;
				wx.cloud.callFunction({
					name: 'getOpenid',
					complete: res => {
						console.log('云函数获取到的openid: ', res);
						try {
							uni.setStorageSync('openid', res.result.openId);
						} catch (e) {
							// error
						}
						that.saveToDb(msg, res.result.openId)
					},
				});
			},
			saveToDb(msg, openid) {
				console.log(openid)
				db.collection('user').where({
					_openid: openid
				}).get().then(res => {
					console.log(res)
					if (res.errMsg === 'collection.get:ok') {
						if (res.data.length === 0) {
							db.collection('user').add({
								data: {
									...msg.detail.userInfo,
									_openid: res.result.openId
								}
							}).then(res => {
								console.log(res);
							});
						}
						uni.hideLoading();
						uni.showToast({
							title: '授权成功',
							icon: 'success'
						});
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {}
				})

			}
		},
		onLoad() {

		}
	}
</script>