uniapp one-click login

Official website document address https://uniapp.dcloud.net.cn/univerify.html

1. Preparation before development

1. You need to activate the uni one-key login service first.

After successful activation, you will get apiKey and apiSecret. These two pieces of information need to be configured in the cloud function of uniCloud later. At the same time, pay attention to confidentiality, these two information are also billing vouchers

2. Open uniCloud service

It is recommended to use Alibaba Cloud service space~ 
Then you can enable the front-end web page hosting function, and the packaged Android apk package can be placed here or in cloud storage

3. Check manifest.json under the project - App module configuration - one-click login

2. Development

Concept Note:

Although uniCloud is required for one-click login, developers are not required to migrate all background services to uniCloud.

The code completion of one-click login is done by the front end itself. The backend only needs to provide an interface for logging in with a mobile phone number

1. Login page sample code

<template>
	<view class="login-container">
		<button v-if="isOneClickLogin" @click="oneClickLogin">一键登录</button>
        <button v-else @click="oneSmsLogin">短信登录</button>
	</view>
</template>

<script>
	import { mapState } from 'vuex'
	import store from '@/store'
	export default {
		data() {
			return {
				// 是否支持一键登录
				isOneClickLogin: false
			}
		},

		async onLoad() {
			// 是否支持一键登录
            await this.preLogin(true)
		},

		methods: {
			// 一键登录
			async oneClickLogin() {
				await this.preLogin(true)

				uni.login({
					provider: 'univerify',
					univerifyStyle: {
						fullScreen: true,
						backgroundColor: '#ffffff',
						otherLoginButton: {
							// 是否显示其他登录按钮
							visible: false
						},
						authButton: {
							normalColor: '#2dc8a1'
						},
						privacyTerms: {
							// 条款勾选框初始状态
							defaultCheckBoxState: false,
							privacyItems: [{
									url: 'https://xxx/agreement.html',
									title: '用户服务协议'
								},
								{
									url: 'https://xxx/privacypolicy.html',
									title: '隐私政策'
								}
							]
						}
					},
					success(res) {
						uniCloud.callFunction({
							name: 'login',
							data: {
								access_token: res.authResult.access_token,
								openid: res.authResult.openid,
								serversUrl: '这里上传你的接口地址'
							}
						}).then(async (dataRes) => {
							if (dataRes.result.code == 0) {
                                // 这里写你登录成功后的逻辑 ...

								uni.showToast({
									title: '登录成功',
									icon: 'success'
								})

								uni.setStorageSync('token', dataRes.result.data.access_token)

								setTimeout(async () => {
									uni.closeAuthView()
									uni.navigateBack()
								}, 1000)
							} else {
                                uni.showToast({
									title: dataRes.result.message,
									icon: 'none'
								})
							}
						}).catch((err) => {
							uni.showModal({
								title: '登录失败',
								content: err.errMsg,
								showCancel: false,
								success() {
									uni.closeAuthView()
								}
							})
						})
					},
					fail(err) {
						if (err.errCode != 30002 && err.errCode != '30003' && err.errCode != '30006') {
							uni.showModal({
								title: '登录失败',
								content: err.errMsg,
								showCancel: false,
								success() {
									// 客户端关闭一键登录授权界面
									uni.closeAuthView()
								}
							})
						}
					}
				})
			},
			
            /**
			 * 预登录
             * 1、预登录操作可以判断当前设备环境是否支持一键登录,如果能支持一键登录,此时可以显示一键登录选项,同时预登录会准备好相关环境,显著提升显示授权登录界面的速度。
             * 2、如果当前设备环境不支持一键登录,此时应该显示其他的登录选项。
             * 3、如果手机没有插入有效的sim卡,或者手机蜂窝数据网络关闭,都有可能造成预登录校验失败。
			 * @param Boolean isShowMsg: 是否显示错误提示
			 */
			preLogin(isShowMsg = false) {
				return new Promise((resolve, reject) => {
					uni.preLogin({
						provider: 'univerify',
						success() {
                            this.isOneClickLogin = true
							resolve(true)
						},
						fail(err) {
							// 如果手机没有插入有效的sim卡,或者手机蜂窝数据网络关闭,都有可能造成预登录校验失败。
                            this.isOneClickLogin = false
							if (isShowMsg && err.errMsg != 'login:ok') {
								// 不同运营商 返回的报错字段不同
								uni.showModal({
									title: '当前设备环境不支持一键登录',
									content: err.errMsg || err.metadata.resultMsg || err.metadata.error_data || err.metadata.resultDesc ||
										'请检查是否插入有效sim卡及开启蜂窝数据网络',
									showCancel: false
								})
							}
							resolve(false)
						}
					})
				})
			},

            // 短信登录
            oneSmsLogin() {
                // 跳转到短信登录页 ...
                uni.navigateTo({
					url: 'xxx'
				})
            }

</script>

<style lang="scss" scope></style>

2. uniClound login cloud function code

'use strict'
const crypto = require('crypto')
exports.main = async (event, context) => {
	const res = await uniCloud.getPhoneNumber({
		provider: 'univerify',
		apiKey: 'xxx', // 在开发者中心开通服务并获取apiKey
		apiSecret: 'xxx', // 在开发者中心开通服务并获取apiSecret
		access_token: event.access_token,
		openid: event.openid
	})
    
    // 这里需要改成你们自己后端登录成功后的接口地址 ...
	const url = event.serversUrl + '/auth/client/phoneLogin'

	// md5加密方式:手机号 时间戳 私钥
	const phone = res.phoneNumber
	const timestamp = new Date().getTime()
	const signKey = 'be6ff85f-20a1-76ce-f837-60933dca0975'
	const sign = crypto.createHash('md5').update(phone + timestamp + signKey).digest('hex')

	const result = await uniCloud.httpclient.request(url, {
		method: 'POST',
		data: {
			phone,
			timestamp,
			sign
		},
		contentType: 'json',
		dataType: 'json',
		// 是否在证书不受信任时返回错误
		rejectUnauthorized: false
	})
	console.log('服务端返回结果=', result)

	if (result.data.code == 200) {
		return {
			code: 0,
			message: '获取手机号成功',
			data: result.data.data
		}
	} else {
		return {
			code: result.data.code,
			message: result.data.msg,
			data: result.data.data
		}
	}
}

The directory structure is as follows:

Note: This uniClound directory is put together with our front-end code. After the cloud function code is written, it needs to be uploaded and deployed to the cloud service space.

Here for safety considerations. After successfully obtaining the mobile phone number through one-click login, directly call the back-end interface in the cloud function, and perform md5 encryption to ensure the security of the interface.

Instead of the front-end calling the back-end login interface after the cloud function returns the phone number~

Guess you like

Origin blog.csdn.net/qq_23375733/article/details/131479748