uniapp 一键登录

706 阅读2分钟

准备工作

1. 准备账号信息

dev.dcloud.net.cn/pages/uniLo…

在官方平台申请一个应用,并且要配置一键登录信息

注意:一键登录要预充值,并且没有余额提醒,每次调用登录 0.02 元,自己时常关注一下

2. 云函数

image.png

新建了一个云函数,one-click-login,上传部署到 unicloud 中

'use strict';
const  crypto = require("crypto");

function aesEncrypt(data,secretKey){
	var cipher = crypto.createCipher('aes-128-ecb',secretKey);
	return cipher.update(data,'utf8','hex') + cipher.final('hex');
}

exports.main = async (event, context) => {
  // event里包含着客户端提交的参数
  const res = await uniCloud.getPhoneNumber({
      appid: '__UNI__83CFF21', // 替换成自己开通一键登录的应用的DCloud appid,使用callFunction方式调用时可以不传(会自动取当前客户端的appid),如果使用云函数URL化的方式访问必须传此参数
      provider: 'univerify',
      apiKey: 'xxxxxxxxxx', // 在开发者中心开通服务并获取apiKey
      apiSecret: 'xxxxxxxxxxx', // 在开发者中心开通服务并获取apiSecret
      access_token: event.access_token,
      openid: event.openid
  })
  // 如果数据库不在uniCloud上,可以通过 uniCloud.httpclient API,将手机号通过http方式传递给其他服务器的接口,详见:https://uniapp.dcloud.net.cn/uniCloud/cf-functions?id=httpclient
  
  const httpRes1 = await uniCloud.httpclient.request(event.host + "/member/getAesKey", {
      method: 'POST',
      data: {
        iv: event.access_token
      },
      contentType: 'json', // 指定以application/json发送data内的数据
      dataType: 'json' // 指定返回值为json格式,自动进行parse
  })
  
  const secret = httpRes1.data.data;
  console.log(secret)
  
  const hmac = aesEncrypt(res.phoneNumber, secret);
  console.log(hmac)
  
  
  return {
    code: 0,
	data: {
		phone: res.phoneNumber,
		hmac
	},
    message: '获取手机号成功'
  }
}

可自行定义内容,根据需要编写

App代码

// 手机号登录
    phoneLogin () {
      if (this.isCanOneClickLogin) { // 可以一键登录
        const self = this
        uni.login({
          provider: 'univerify',
          univerifyStyle: univerifyStyle,
          success: (res) => { // 登录成功
            self.unicloudAnalysisUserPhone(res.authResult)
          },
          fail: (res) => {
            console.log(res)
            if (res.code === 30002) {
              this.jumpPhonePage()
            }
            uni.closeAuthView()
          }
        })
      } else {
        this.jumpPhonePage()
      }
    },
    // 获取一键登录信息后,云函数解析,传给后台
    unicloudAnalysisUserPhone ({ access_token, openid }) {
      // 在得到access_token后,通过callfunction调用云函数
      uniCloud.callFunction({
        name: 'one-click-login', // 你的云函数名称
        data: {
          host: API_URL,
          access_token, // 客户端一键登录接口返回的access_token
          openid // 客户端一键登录接口返回的openid
        }
      }).then(res => {
        uni.closeAuthView()
        if (res.result) {
          const { phone, hmac } = res.result.data
          this.oneClickData = {
            phone, hmac, access_token, openid
          }
          console.log(res.result.data)
        }
      }).catch(err => {
        this.jumpPhonePage()
        // 处理错误
      })
    },

这样即可获取手机号,留个记录