uni-app 中安卓 Google 登录接入指南

140 阅读3分钟

uni-app 中安卓 Google 登录接入指南

本文介绍如何在 uni-app App(Android) 中接入 Google 登录(OAuth) ,基于 plus.oauth 实现。
⚠️ 不支持 H5 / 小程序 / 官方基座


一、前置条件

在开始之前,请确保已完成以下准备工作:

1️⃣ Google 账号

  • 需要一个可访问 Google Cloud Console 的 Google 账号

2️⃣ Android 打包证书(Keystore)

⚠️ 强烈建议使用自有证书

Google OAuth 配置中需要使用 证书 SHA1 指纹,如果使用默认证书,后期将无法正常登录。

生成完成后请妥善保存以下信息:

  • keystore 文件
  • keystore 密码
  • alias
  • alias 密码
  • SHA1 指纹(Google Console 中需要)

3️⃣ manifest.json 配置 Google OAuth

路径:

manifest.json → App 模块配置 → OAuth

勾选:

  • Google

未勾选将无法获取 google OAuth Service


二、Google Cloud Console 配置

1️⃣ 创建项目

  • 登录 Google Cloud Console
  • 创建新项目(或使用已有项目)

2️⃣ 启用 Google Identity 服务

确保启用以下服务:

  • Google Identity / OAuth 2.0

3️⃣ 创建 OAuth 客户端 ID

选择客户端类型:

  • Android

填写信息:

  • 包名(必须与 uni-app AppId 对应)
  • SHA1 指纹(来自你的 keystore)

⚠️ 包名 / SHA1 不匹配会直接导致登录失败


三、配置自定义基座(必须)

❌ 官方基座 无法使用 Google 登录
✅ 必须 云打包自定义基座

自定义基座配置位置

HBuilderX → 运行 → 运行到手机或模拟器 → 使用自定义基座

四、Google 登录代码实现

仅支持 App(Android / iOS)
基于 plus.oauth

1️⃣ 获取 Google OAuth Service

/**
 * 获取 Google OAuth 服务
 */
function getGoogleService() {
  return new Promise((resolve, reject) => {
    if (typeof plus === 'undefined') {
      reject(new Error('当前环境不支持 plus.oauth'))
      return
    }

    plus.oauth.getServices(
      services => {
        const google = services.find(item => item.id === 'google')
        if (!google) {
          reject(new Error('未找到 Google OAuth 服务'))
        } else {
          resolve(google)
        }
      },
      err => reject(err)
    )
  })
}

2️⃣ Google 登录方法封装

/**
 * Google 登录
 * @returns Promise<{
 *  idToken: string,
 *  accessToken: string,
 *  userInfo: object | null,
 *  raw: any
 * }>
 */
export function loginByGoogle() {
  return new Promise(async (resolve, reject) => {
    try {
      const google = await getGoogleService()

      google.login(
        res => {
          const authResult = res.authResult || {}

          resolve({
            idToken: authResult.id_token || authResult.idToken,
            accessToken: authResult.access_token,
            userInfo: res.userInfo || null,
            raw: res
          })
        },
        err => {
          reject(err)
        }
      )
    } catch (e) {
      reject(e)
    }
  })
}

3️⃣ 使用示例

loginByGoogle()
  .then(res => {
    console.log('Google 登录成功', res)

    // 通常只需要 idToken
    // 发送到后端进行校验 / 登录
    // res.idToken
  })
  .catch(err => {
    console.error('Google 登录失败', err)
  })

五、返回数据说明

字段说明
idToken推荐使用,用于服务端校验
accessTokenGoogle OAuth Access Token
userInfo用户基本信息(可能为空)
raw原始返回数据

⚠️ 建议:
前端只负责获取 idToken,由后端向 Google 校验 token 合法性


六、常见问题 & 踩坑记录

❌ 找不到 Google OAuth 服务

  • 未在 manifest.json 勾选 Google
  • 未使用自定义基座 / 云打包
  • 使用了官方基座

❌ 登录直接失败 / 无反应

  • SHA1 指纹不匹配
  • 包名错误
  • Google Console 中 OAuth 客户端类型选错(必须 Android)

❌ 本地调试可以,正式包不行

  • 本地基座与正式包 证书不同
  • 正式包使用了不同 keystore

七、注意事项总结

  • ✅ 必须使用 自有 keystore
  • ✅ 必须使用 自定义基座或云打包
  • ❌ 官方基座不可用
  • ❌ H5 / 小程序不可用
  • ❌ google登录会被拦截,检查网络配置

八、参考资料