Skip to content

Google Play Games login Add-on

An Add-on that handles Google Play Games login on Android with GamesSignInClient of Play Games Services v2. It provides authentication status retrieval, login, and issuance of an authorization code for server exchange as separate, independent methods. Exchange the issued authorization code with ExchangeProviderTokenAsync() of the Auth module, and then pass it to LoginProviderAsync() to log in.

Module information

  • Package: com.com2usplatform.hiveaxyl.auth.addon.gpg
  • Interface: IGooglePlayGamesPlugin
  • Namespace: Hive.Axyl.Auth.Addon.GPG
  • Registration method: AddGooglePlayGames()
  • Supported platforms: Android
  • Minimum requirements: Android API 29+, Unity 6000.0+
Prerequisites

The SDK does not configure the Play Games project for you. The app must declare the Games services project ID itself as com.google.android.gms.games.APP_ID metadata in the Android manifest. For how to set it up, see Install the Add-on and configure Android.

You do not need to write Play Games SDK initialization code, because the Play Games SDK initializes itself through PlayGamesInitProvider, which it includes in its own manifest. If you remove this provider and also do not call PlayGamesSdk.initialize(), no exception is thrown; instead, a Failure whose Code is FailedPrecondition is returned.

To get an authorization code for server exchange, you must prepare a Web application type OAuth 2.0 client and connect it to Play Games Services. For how to prepare it, see Check the Google Play Games login credentials.

Registration and retrieval

Register the Add-on in the registration step of HiveBootstrap.Initialize, and then retrieve it with HiveCore.TryResolve<T>().

using Hive.Axyl.Auth;
using Hive.Axyl.Auth.Addon.GPG;
using Hive.Axyl.Core;
using Hive.Axyl.Core.Unity;   // HiveBootstrap

HiveBootstrap.Initialize(config, builder =>
{
    builder.AddAuth()
           .AddToken()
           .AddGooglePlayGames();
});

if (HiveCore.TryResolve<IGooglePlayGamesPlugin>(out var gpg))
{
    // Code that runs only in Android builds
}
Not registered in the Unity Editor

This Add-on is registered only in players built for Android. In the Unity Editor, it is not registered even if you switch the platform to Android, so using HiveCore.Resolve<T>() throws RegistrationNotFoundException. Always check with TryResolve<T>() before you use it.

For the package installation and registration procedure, see Install and initialize the module.

Method summary

Asynchronous methods take CancellationToken ct = default as the last parameter. For the calling conventions, see Call context.

IsAuthenticatedAsync(), SignInAsync(), and RequestServerSideAccessAsync() are independent calls. The SDK does not bundle these methods into a single run, so call them from the app yourself in the order you need.

Methods

IsAuthenticatedAsync

Gets the current Play Games authentication status with GamesSignInClient.isAuthenticated(). It does not show a login screen.

It is safe to call from any thread, and you can call it multiple times concurrently.

Task<GooglePlayGamesServiceIsAuthenticatedResult> IsAuthenticatedAsync(IsAuthenticatedRequest request, CancellationToken ct = default)

Result cases — GooglePlayGamesServiceIsAuthenticatedResult

Result case Wire code Description
Success — The user is authenticated.
NotAuthenticated not_authenticated The user is not authenticated. Log in with SignInAsync().
UnknownOutcome UNKNOWN A new result unknown to this SDK version.
Failure FAILURE The call could not be completed. Check the cause with the HiveError in Problem.
NotAuthenticated is not an error

A state in which the user is not logged in is returned as NotAuthenticated, not as Failure. Handle it separately from error handling, and proceed with login through SignInAsync().

Exceptions

  • ArgumentNullException: When request is null

SignInAsync

Shows the Play Games account selection screen with GamesSignInClient.signIn(). If the app user already has a default Play Games account, login completes without a screen.

It is safe to call from any thread. Only one login proceeds at a time. If you call it again while a login is in progress, it leaves the in-progress login as is and immediately returns a Failure whose Code is FailedPrecondition.

Task<GooglePlayGamesServiceSignInResult> SignInAsync(SignInRequest request, CancellationToken ct = default)

Result cases — GooglePlayGamesServiceSignInResult

Result case Wire code Description
Success — Login succeeded.
UserCanceled user_canceled The app user closed the login screen.
NotAuthenticated not_authenticated The call finished, but the user is still not authenticated. This rarely occurs.
UnknownOutcome UNKNOWN A new result unknown to this SDK version.
Failure FAILURE The call could not be completed. Check the cause with the HiveError in Problem.

UserCanceled implements IUserCanceledOutcome.

User cancellation and code cancellation are different

If the app user closes the login screen, the result is UserCanceled. In contrast, if you cancel from code with CancellationToken or CancelCurrentSignIn(), the result is a Failure whose Code is Cancelled.

Exceptions

  • ArgumentNullException: When request is null

RequestServerSideAccessAsync

Gets an authorization code for server exchange with GamesSignInClient.requestServerSideAccess(). The code is issued only while the user is logged in to Play Games. If the user is not logged in, it returns NotAuthenticated.

It is safe to call from any thread, and you can call it multiple times concurrently.

Task<GooglePlayGamesServiceRequestServerSideAccessResult> RequestServerSideAccessAsync(RequestServerSideAccessRequest request, CancellationToken ct = default)

Result cases — GooglePlayGamesServiceRequestServerSideAccessResult

Result case Wire code Description
Success — The authorization code has been issued. Data.ServerAuthCode contains the authorization code.
NotAuthenticated not_authenticated The user is not authenticated. Log in with SignInAsync(), and then call it again.
UnknownOutcome UNKNOWN A new result unknown to this SDK version.
Failure FAILURE The call could not be completed. Check the cause with the HiveError in Problem.

Exceptions

  • ArgumentNullException: When request is null
  • ArgumentException: When request.WebClientId is null or empty

Call example

using Hive.Axyl.Auth.Addon.GPG;

// 1. Check the authentication status, and log in if the user is not authenticated.
var authState = await gpg.IsAuthenticatedAsync(new IsAuthenticatedRequest());

if (authState is GooglePlayGamesServiceIsAuthenticatedResult.NotAuthenticated)
{
    var signIn = await gpg.SignInAsync(new SignInRequest());

    if (signIn is not GooglePlayGamesServiceSignInResult.Success)
    {
        return;
    }
}

// 2. Get an authorization code for server exchange.
var access = await gpg.RequestServerSideAccessAsync(new RequestServerSideAccessRequest
{
    WebClientId = "{webClientId}",
    ForceRefreshToken = true,
});

if (access is GooglePlayGamesServiceRequestServerSideAccessResult.Success success)
{
    string serverAuthCode = success.Data.ServerAuthCode;   // ProviderCode of ExchangeProviderTokenAsync
}

After you get the authorization code, pass it as ProviderCode to exchange it with ExchangeProviderTokenAsync(), and then call LoginProviderAsync() with the exchange result. For the implementation procedure, see Get Google Play Games credentials.

CancelCurrentSignIn

Cancels an in-progress login from code. A pending SignInAsync() ends with a Failure whose Code is Cancelled. If no login is in progress, it does nothing.

IsAuthenticatedAsync() and RequestServerSideAccessAsync(), which do not show a screen, are not affected by this method. It is safe to call from any thread.

void CancelCurrentSignIn()

Data types

IsAuthenticatedRequest

No fields. Pass an empty instance instead of null.

IsAuthenticatedResponse

No fields. The Success result itself means that the user is authenticated.

RequestServerSideAccessRequest

Field Type Required Description
WebClientId string Required The Web application type OAuth 2.0 client ID used when the authorization code is exchanged at the Google token endpoint. For how to get it, see Check the Google Play Games login credentials. If it is empty, ArgumentException is thrown.
ForceRefreshToken bool Required Whether to request a new refresh token. If true, Google issues a new refresh token. If false, an existing valid refresh token can be reused. We recommend true for the first server exchange or after a previous server-side token refresh has failed.

RequestServerSideAccessResponse

Field Type Required Description
ServerAuthCode string Required A short-lived authorization code for server exchange. Put it as is, without conversion, into ProviderCode of the ExchangeProviderTokenAsync() request. It can be used only once, and its validity period follows Google's policy.
Do not log the authorization code

ServerAuthCode is a sensitive value that is exchanged for an access token and a refresh token at the Google token endpoint. Do not record it in logs, crash reports, or analytics events.

SignInRequest

No fields. Pass an empty instance instead of null.

SignInResponse

No fields. The Success result itself means that the user is authenticated.