在uni-app中如何使用一键登录,如何使用手机号一键登录

1、首先需要在dcloud开发者控制台开通一键登录,

dcloudhttps://dev.dcloud.net.cn/uniLoginicon-default.png?t=L9C2https://dev.dcloud.net.cn/uniLogin

 充值,获取关键参数 ApiKey 和 ApiSecret

2、登录云服务空间,创建云服务空间,选择运营商等  https://unicloud.dcloud.net.cn/home

3、在项目中创建 云开发环境 ,本项目演示选择的是阿里云服务器 

4、项目目录  创建 getPhoneNumber/index.js

一键登录云函数 uni-app官网

 getPhoneNumber/index.js

// 云函数
'use strict';

const db = uniCloud.database()
exports.main = async (event) => {
	const res = await uniCloud.getPhoneNumber({
		appid: '__UNI__123456', // 替换成自己开通一键登录的应用的DCloud appid
		provider: 'univerify',
		apiKey: 'abcdefghjklokdsadsadsa', // 在开发者中心开通服务并获取apiKey
		apiSecret: 'abscdshjksdhjakdahshjdsad', // 在开发者中心开通服务并获取apiSecret
		access_token: event.access_token,
		openid: event.openid
	})
	// 执行入库等操作,正常情况下不要把完整手机号返回给前端	
	await db.collection('regUser').add({
		openid: event.openid, //前端提交过来的数据
		PhoneNumber: res.phoneNumber,
		createTime: Date.now()
	})

	return res
}

5、右键关联云服务空间 

 

 选择创建的云空间

关联后上传云函数

6、一键登录本地方法

import Vuex from '@/store/index.js'

export function univerifyLogin(cb, fun, fun1) {
	const commit = Vuex.commit;
	const PROVIDER = 'univerify';
	const univerifyStyle = {
		"fullScreen": true,
		"icon": {
			"path": "static/icon/logo.png" // 自定义显示在授权框中的logo,仅支持本地图片 默认显示App logo   
		},
		"authButton": {
			"normalColor": "#00A861", // 授权按钮正常状态背景颜色 默认值:#3479f5  
			"highlightColor": "#008B50", // 授权按钮按下状态背景颜色 默认值:#2861c5(仅ios支持)  
			"disabledColor": "#7fd4b0", // 授权按钮不可点击时背景颜色 默认值:#73aaf5(仅ios支持)  
			"textColor": "#ffffff", // 授权按钮文字颜色 默认值:#ffffff  
			"title": "本机号码一键登录", // 授权按钮文案 默认值:“本机号码一键登录”  
			"borderRadius": "24px" // 授权按钮圆角 默认值:"24px" (按钮高度的一半)
		},
		"privacyTerms": {
			"defaultCheckBoxState": true, // 条款勾选框初始状态 默认值: true
			"uncheckedImage": "", // 可选 条款勾选框未选中状态图片(仅支持本地图片 建议尺寸 24x24px)(3.2.0+ 版本支持)   
			"checkedImage": "", // 可选 条款勾选框选中状态图片(仅支持本地图片 建议尺寸24x24px)(3.2.0+ 版本支持)   
			"textColor": "#BBBBBB", // 文字颜色 默认值:#BBBBBB  
			"termsColor": "#00A861", //  协议文字颜色 默认值: #5496E3  
			"prefix": "我已阅读并同意", // 条款前的文案 默认值:“我已阅读并同意”  
			"suffix": "并使用本机号码登录", // 条款后的文案 默认值:“并使用本机号码登录”  
		},
	}
	return new Promise((resolve, reject) => {
		uni.getProvider({
			service: 'oauth',
			success: (res) => {
				if (res.provider.indexOf(PROVIDER) !== -1) {
					// 一键登录已在APP onLaunch的时候进行了预登陆,可以显著提高登录速度。登录成功后,预登陆状态会重置

					uni.login({
						provider: PROVIDER,
						univerifyStyle: univerifyStyle,
						success: (res) => {
							let loginRes = res.authResult
							uni.closeAuthView();
							uni.showLoading({
								title: "登录中..."
							});
							uniCloud.callFunction({
								name: 'getPhoneNumber', // 你的云函数名称
								data: {
									access_token: loginRes
									.access_token, // 客户端一键登录接口返回的access_token
									openid: loginRes
										.openid // 客户端一键登录接口返回的openid
								}
							}).then(e => {
								console.log('login success', e);
								if (e.result.code == 0) {
									typeof fun == "function" && fun(e.result)
									resolve('suc');
								} else {
									console.log('登录失败', e);
								}
							})
							.catch(err => {
								// 处理错误
								console.error("获取手机号err", err)
								uni.showModal({
									title: `登录失败`,
									content: err.errMsg ||
										"网络异常,请选择其他方式登录",
									showCancel: false
								})
								typeof fun1 == "function" && fun1(err)
								reject('err')
							})

						},
						fail: (err) => {
							console.error('授权登录失败:' + JSON.stringify(err));

							univerifyErrorHandler(err, cb);
						}
					})


				} else {
					cb && cb()
				}
			},
			fail: (err) => {
				console.error('获取服务供应商失败:' + JSON.stringify(err));
				cb && cb()
			}
		});

	})
}

export function univerifyErrorHandler(err, cb) {
	const state = Vuex.state;
	const obj = {
		showCancel: true,
		cancelText: '其他登录方式',
		success(res) {
			console.log("rinima", res)
			if (res.confirm) {
				uni.redirectTo({
					url: '/pages/login/login'
				});
			}
			if (res.cancel) {
				cb && cb()
			}
		}
	} 

	switch (true) {
		// 一键登录点击其他登录方式
		case err.code == 30002:
			uni.closeAuthView();
			cb && cb()
			break;
			// 未开通
		case err.code == 1000:
			uni.showModal(Object.assign({
				title: `登录失败: ${err.code}`,
				content: `${err.errMsg}\n开通指南:https://ask.dcloud.net.cn/article/37965`,
				/* confirmText: '开通指南',
				cancelText: '确定',
				success: (res) => {
					if (res.confirm) {
						setTimeout(() => {
							plus.runtime.openWeb('https://ask.dcloud.net.cn/article/37965')
						}, 500)
					}
				} */
			}, obj));
			break;
			// 预登陆失败
		case err.code == 30005:
			uni.showModal(Object.assign({
				showCancel: false,
				title: `登录失败`,
				content: `${state.univerifyErrorMsg ||err.metadata.desc || err.errMsg}`
			}, obj));
			break;
			//用户关闭验证界面
		case err.code == 30003:
			setTimeout(() => {
				uni.redirectTo({
					url: '/pages/login/login'
				});
			},500)

			break;
	}
}

7、调用

 引入
import { univerifyLogin } from '@/common/univerify.js'

 async openUnLogin() {
				    await univerifyLogin(() => {
					uni.redirectTo({
						url: '/pages/login/login'
					});
				}, res => {
					console.log("个人中心一键登录:", res)
					let loginMobile = res.phoneNumber

					this.userStoreLogin(loginMobile).then(res => {
						console.error("登录成功llllllllllll", res)
						this.userStoreUserInfos()
						util.showText("登录成功");
					})
				})
			},

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

随便起的名字也被占用

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值