跳转到正文

Android 端 Google Login

GitHub

在本指南中,你将学习如何使用 Capgo Social Login 在 Android 上配置 Google Login。 我假设你已经阅读了 通用设置指南.

在本部分中,你将学习如何在 Android 上配置 Google login。

  1. 创建 Android client ID

    1. 点击搜索栏

      Google Console 搜索栏
    2. 搜索 credentials 并点击 APIs and Services 其中之一(见截图中的第 2 项)

      搜索结果显示了“凭据”选项,并高亮了“API 和服务”
    3. 点击 create credentials

      Google Console 中的“创建凭据”按钮
    4. 选择 OAuth client ID

      凭据创建菜单中的“OAuth 客户端 ID”选项
    5. 选择 Android 应用类型

      选择应用类型,并高亮显示 Android 选项
    6. 打开 Android Studio

    7. 在导航栏的最底部,找到 Gradle Scripts

      Android Studio 项目导航器中的 Gradle Scripts 部分
    8. 找到 build.gradle 针对该模块 app

      Gradle Scripts 部分中的 build.gradle (Module: app) 文件
    9. 复制 android.defaultConfig.applicationId。这将是你的 package name 在 Google 控制台中

      显示 applicationId 配置的 Build.gradle 文件
    10. 现在,打开终端。确保你处于 android 应用文件夹并运行 ./gradlew signInReport

    终端显示 gradlew signInReport 命令
    1. 滚动到该命令顶部。你应该能看到以下内容。复制 SHA1.
    终端输出显示的 SHA1 证书指纹
    1. 现在,回到 Google Console。输入你的 applicationId 作为 Package Name 并在证书字段中输入你的 SHA1,然后点击 create
    已填写包名和 SHA1 字段的 Android 客户端创建表单
  2. 创建一个 Web 客户端(Android 开发必选)

    1. 前往 Create credentials Google Console 中的页面

    2. 将应用类型设置为 Web

      应用类型选择,Web 选项已高亮
    3. 点击 Create

      Web 客户端创建表单,底部有“创建”按钮
    4. 复制 Client ID,稍后你会在 webClientId JS/TS code 中用到它

      Client ID 详情,显示可复制的 Web Client ID
  3. 修改您的 MainActivity

    1. 请在 Android Studio 中打开您的应用。您可以运行 cap open android

    2. 找到 MainActivity.java

      1. 打开 app 文件夹

        Android Studio 项目导航器中的 App 文件夹
      2. 找到 java

        Android Studio 项目结构中的 Java 文件夹
      3. 找到你的 MainActivity.java 并点击它

        包结构中的 MainActivity.java 文件
    3. 修改 MainActivity.java。请添加以下 code

      import ee.forgr.capacitor.social.login.GoogleProvider;
      import ee.forgr.capacitor.social.login.SocialLoginPlugin;
      import ee.forgr.capacitor.social.login.ModifiedMainActivityForSocialLoginPlugin;
      import com.getcapacitor.PluginHandle;
      import com.getcapacitor.Plugin;
      import android.content.Intent;
      import android.util.Log;
      import com.getcapacitor.BridgeActivity;
      // ModifiedMainActivityForSocialLoginPlugin is VERY VERY important !!!!!!
      public class MainActivity extends BridgeActivity implements ModifiedMainActivityForSocialLoginPlugin {
      @Override
      public void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (requestCode >= GoogleProvider.REQUEST_AUTHORIZE_GOOGLE_MIN && requestCode < GoogleProvider.REQUEST_AUTHORIZE_GOOGLE_MAX) {
      PluginHandle pluginHandle = getBridge().getPlugin("SocialLogin");
      if (pluginHandle == null) {
      Log.i("Google Activity Result", "SocialLogin login handle is null");
      return;
      }
      Plugin plugin = pluginHandle.getInstance();
      if (!(plugin instanceof SocialLoginPlugin)) {
      Log.i("Google Activity Result", "SocialLogin plugin instance is not SocialLoginPlugin");
      return;
      }
      ((SocialLoginPlugin) plugin).handleGoogleLoginIntent(requestCode, data);
      }
      }
      // This function will never be called, leave it empty
      @Override
      public void IHaveModifiedTheMainActivityForTheUseWithSocialLoginPlugin() {}
      }
    4. 保存文件

  4. 在应用中使用 Google Login

    1. 首先,导入 SocialLogin

      import { SocialLogin } from '@capgo/capacitor-social-login';
    2. 调用 initialize。此方法只应调用一次。

      // onMounted is Vue specific
      // webClientId is the client ID you got in the web client creation step not the android client ID.
      onMounted(() => {
      SocialLogin.initialize({
      google: {
      webClientId: '673324426943-avl4v9ubdas7a0u7igf7in03pdj1dkmg.apps.googleusercontent.com',
      }
      })
      })
    3. 调用 SocialLogin.login。创建一个按钮,并在点击时运行以下 code。

      const res = await SocialLogin.login({
      provider: 'google',
      options: {}
      })
      // handle the response
      console.log(JSON.stringify(res))
  5. 配置用于测试的模拟器

    1. 进入 Device manager 并点击加号按钮

      Android Studio 中的 Device Manager,加号按钮已高亮
    2. 创建虚拟设备

      Virtual Device Configuration 中的 Create Virtual Device 按钮
    3. 选择任何带有 Play Store 图标的设备

      硬件选择界面,显示支持 Play Store 的设备

      如你所见, pixel 8 支持 Play Store 服务 (services)

    4. 点击 next

      设备创建向导中的“下一步”按钮
    5. 请确保 OS 镜像类型为 Google Play. 必须 类型为 Google Play

      显示 Google Play 类型镜像的系统镜像选择界面
    6. 点击下一步

      系统镜像选择界面中的“下一步”按钮
    7. 确认你的设备。你可以按自己的喜好为模拟器命名

      带有“完成”按钮的设备配置验证界面
    8. 进入 Device Manager 并启动你的模拟器

      设备管理器中列出虚拟设备并显示播放按钮
    9. 模拟器启动后,进入其设置界面

      显示设置应用的 Android 模拟器
    10. 进入 Google Play

    带有 Google Play 选项的设置界面
    1. 点击 Update 并等待约 60 秒
    带有“更新”按钮的 Google Play 更新界面
  6. 测试你的应用

    如果操作无误,你应该能看到 Google 登录流程正常运行:

    Android 端 Google 登录流程演示,展示登录过程及成功认证

如果遇到问题,请先对比应用配置与 Google Cloud Console 中的值。Android Google Sign-In 失败通常是由于包名、SHA-1 或 Client ID 不匹配导致的。

Credential Manager、SHA-1 与 Firebase

“Credential Manager、SHA-1 与 Firebase”章节

在 Android 上,此插件使用 Google Credential Manager (androidx.credentials 以及 Sign in with Google),而非旧版的 GoogleSignInClient API。Logcat 错误例如 GetCredentialCustomException: [28444] Developer console is not set up correctly 均源自该技术栈。

登录失败后,使用 GoogleProvider 或 CapgoSocialLogin 过滤 Logcat。插件会记录您的包名、签名 SHA-1 以及脱敏后的 webClientId 以便您与 Google Cloud Console 进行比对。

你需要在同一个 Google Cloud 项目中配置两种 OAuth 2.0 client ID:

客户端类型用途使用位置
Web 应用服务器 / ID token 受众webClientId 中的 SocialLogin.initialize()
Android,每个签名密钥各一个证明你的 APK 有权调用 Google仅限 Google Cloud Console 使用。不要将此 ID 传给 webClientId

一个常见错误是把 Android client ID 当作 webClientId。Credential Manager 需要在这里使用 Web client ID。Android client 只需在控制台注册正确的 package name 和 SHA-1。

请为每个用于测试构建的签名证书创建一个 Android OAuth client:

  • Debug:从 ./gradlew signingReport 获取 debug variant 的信息。
  • Release:从你实际安装的 APK 或 AAB 获取。
  • Play App Signing:从 Play Console > App integrity > App signing key certificate 获取。即使你已经注册了 upload key 的 SHA-1,Play Store 构建也必须使用此证书。

本指南中介绍的 applicationId 中的 android/app/build.gradle 必须与 Android OAuth client 的 package name 完全一致,包括任何 .debug 后缀。

如果 OAuth consent screen 处于 Testing 模式,请在 Audience > Test users 下添加你用于测试的每个 Google 账号。无需将应用发布到 Production 即可 email 以及 profile scopes。Digital Asset Links(assetlinks.json)通过 Credential Manager 登录 Google 时并不需要。

Google Cloud 的更改最多可能需要几个小时才能生效。

这几乎总是意味着 Google 拒绝了已安装 APK 的签名证书、包名以及 webClientId。请按以下清单逐项排查:

  1. 确认 webClientId 是 Web 应用客户端 ID,且以 .apps.googleusercontent.com.
  2. 运行应用,复现故障,并查看 Logcat 中的 GoogleProvider, signingSha1=,以及 package=.
  3. 在 Google Cloud Console > 凭据打开你的 Android OAuth 客户端,核对 package name 和 SHA-1 是否完全一致。
  4. 如果测试的是 release build,请注册该 build 的 SHA-1,而不只是 debug keystore 的。
  5. 如果应用通过 Play Store 分发,还需注册 Play App Signing 的 SHA-1。
  6. 确保 Web 和 Android 客户端位于同一个 Google Cloud 项目中。
  7. 如果同意屏幕处于 Testing 状态,请确认该 Google 账号是测试用户。
  8. 控制台更改后,请稍候再重试。

USER_CANCELLED 在配置有误的 debug build 上选择账号后,问题仍可能是 SHA-1 或 client ID 不匹配。请先修复上面的控制台设置。

Debug 或本地 build:

终端窗口
cd android && ./gradlew signingReport

已签名的 Release APK:

终端窗口
keytool -printcert -jarfile android/app/release/app-release.apk

把该 SHA-1 添加到包名匹配的 Android OAuth 客户端,重新安装同一个已签名 APK,然后再次测试:

终端窗口
adb install android/app/release/app-release.apk

Token 嵌套在 result:

const login = await SocialLogin.login({ provider: 'google' });
const idToken = login.result?.idToken;

若使用 Firebase Auth,请用它创建凭据 idToken 并将 Web client ID 作为 webClientId 中的 initialize.

如果无法获取开发环境的 SHA-1 证书,请尝试使用自定义 keystore。 这条 issue 评论 说明了如何将 keystore 添加到项目中。

如果你正在使用 Android 端 Google Login 用来规划身份验证和账户流程,并将它与 使用 @capgo/capacitor-social-login 关于使用 @capgo/capacitor-social-login 的原生能力, @capgo/capacitor-social-login 在 @capgo/capacitor-social-login 中查看实现细节, @capgo/capacitor-passkey 有关 @capgo/capacitor-passkey 的实现细节, @capgo/capacitor-native-biometric 以及 @capgo/capacitor-native-biometric 中的实现细节, 双因素认证 有关双重身份验证的实现细节。