五 login/ login.vue

130 阅读1分钟
	<view class='wx-login'>
		<button @click='wxLogin'>微信登录</button>
	</view>
</template>

<script>
import { loginByWechat , registerWechat } from '@/utils/api/login.js'
export default{
	methods:{
		//登录登录
		wxLogin(){
			let that = this;
			uni.getUserProfile({
				desc:'登录信息',
				success( ures ){
					uni.login({
						async success( lres ){
							let res = await loginByWechat({
								code:lres.code
							});
							//【微信小程序用户未注册】需要去注册
							if( res.code ==='60003' ){
								let data = res.data;
								let params = {
									unionId:data.unionid ? data.unionid : data.openid,
									openId:data.openid,	
									sessionKey:data.sessionKey,
									signature:ures.signature,
									rawData:ures.rawData,
									encryptedData:ures.encryptedData,
									iv:ures.iv,
								}
								
								uni.setStorage({
									key:"userIv",
									data:JSON.stringify({
										sessionKey:data.sessionKey,
										signature:ures.signature,
										rawData:ures.rawData,
										encryptedData:ures.encryptedData,
										iv:ures.iv,
									})
								})
								
								await that.register(params);
							}
							if( res.code == '200' ){
								
								//已经注册过
								//return that.register(params);
							}
						}
					})
				}
			})
		},
		//注册用户
		async register( params ){
			let res = await registerWechat(params);
			//如果绑定过
			if( res.data.member.mobile ) return;
			//存储token
			uni.setStorage({
				key:"token",
				data:res.data.token
			})
			//没有绑定过手机号
			uni.showModal({
				title:'提示',
				content:'根据国家要求,登录前需要绑定手机号',
				confirmText:'去完善',
				success( data ){
					if( data.confirm ){
						uni.navigateTo({
							url:'/login/bindPhone'
						})
					}
				}
			})
			
		}
	}
}
</script>

<style>
.wx-login{
	display: flex;
	justify-content: center;
	align-items: center;
}
</style>