Implement Google Play Games login
To implement Google Play Games login with the recipe code, complete the following procedure in order.
Before you begin, complete the common prerequisites.
Overall flow
What you configure and call in each step is as follows.
| Step | Category | What you do |
|---|---|---|
| 1 | External console | Prepare credentials in the Google Cloud Console and the Google Play Console |
| 2 | Hive Console | Register credentials and enable Play Games login |
| 3 | Hive Axyl SDK | Install the authentication module and the Play Games login Add-on |
| 4 | Hive Axyl SDK | Initialize the SDK and register modules |
| 5 | Recipe code | Copy the recipe folders |
| 6 | App code | Prepare ClientId and DeviceKey |
| 7 | Recipe code | Prepare the Play Games credential source |
| 8 | Recipe code | Call Play Games login |
| 9 | App code | Handle login results |
| 10 | App code | Verify the behavior |
Two types of client IDs appear
The Web application type OAuth client ID you get from the Google Cloud Console and the Client ID you check in the Hive Console are different values. You put the former in the credential source in step 7 and the latter in the recipe constructor in step 6.
1. Set up the Google external console
-
External console Configure this in the Google Cloud Console and the Google Play Console.
Detailed procedure: Check the Google Play Games login credentials
First, prepare the credentials to use for login in the Google Cloud Console and the Google Play Console. The Hive Axyl authentication server uses the Web application type OAuth client you create here to turn the Play Games authorization code into credentials.
Prepare them in the following order.
- First, decide on the HTTPS redirect URI that the app server will use. For details, see Prepare the app server redirect URI.
- In the Google Cloud Console, create an Android type OAuth client, and register the app's package name and the SHA-1 certificate fingerprint of the signing key.
- In the same place, create a Web application type OAuth client, and register the URI you decided on in item 1 in Authorized redirect URIs. Copy this client's ID and client secret.
- In Play Games Services in the Google Play Console, link the two OAuth clients, and copy the Games services project ID.
You use the Web application type client ID in both the Hive Console in step 2 and the credential source in step 7, the client secret in the Hive Console in step 2, and the Games services project ID in the Android manifest in step 3.
2. Configure the Hive Console
-
Hive Console Configure or check this in the Hive Console.
Detailed procedure: Google Play Games login credentials, Login method types
Register the prepared credentials in the Hive Console and enable Play Games login. If the login method is disabled, the recipe call is rejected.
| Setting | Required | Where to check |
|---|---|---|
| Register the Web Client ID and Web Client Secret | Required | Google Play Games login credentials |
| Enable Google Play Games login | Required | Login method types |
| Per-App ID login settings | Optional | Per-App ID login settings |
The settings you register here apply to all App IDs in the project. To show different login methods only for a specific App ID, use per-App ID login settings. However, on the Per-App ID settings tab, the Play Games input field appears only for App IDs whose runtime environment is Android.
3. Install SDK modules and Add-ons
-
Hive Axyl SDK Call the Hive Axyl SDK from the app.
Detailed procedure: Install modules, Install the Add-on and configure Android
Install the authentication module and the Play Games login Add-on in your Unity project. The Add-on is a Hive Axyl SDK extension package that displays the Play Games login screen and receives an authorization code, and the credential source you prepare in step 7 calls this Add-on.
| Package | Needed | Role |
|---|---|---|
com.com2usplatform.hiveaxyl.core | Required | SDK initialization and login session management |
com.com2usplatform.hiveaxyl.auth | Required | Authorization code exchange, login with Play Games credentials, and token issuance |
com.com2usplatform.hiveaxyl.auth.addon.gpg | Required | Displaying the Play Games login screen and issuing authorization codes |
com.com2usplatform.hiveaxyl.storage | Recommended | Encrypted storage of the DeviceKey and session tokens |
If you do not install the Add-on package, the recipe's Play Games credential source is excluded from compilation, so you cannot use it in your app code.
After you install the Add-on, declare the Games services project ID you copied in step 1 in the Android manifest template. If you do not declare it, Play Games does not recognize the app. What to put in the manifest is described in Install the Add-on and configure Android.
You do not need to write initialization code for the Play Games SDK itself. The Play Games SDK initializes itself when the app starts.
4. Initialize the SDK
-
Hive Axyl SDK Call the Hive Axyl SDK from the app.
Detailed procedure: Initialize modules
Initialize the SDK once at the app's entry point, and register the authentication, token, and Play Games login modules. The recipe does not initialize the SDK, so calling it without initialization fails with a FailedPrecondition error.
The following example code registers the modules required for Play Games login and initializes the SDK.
using Hive.Axyl.Auth;
using Hive.Axyl.Auth.Addon.GPG;
using Hive.Axyl.Core;
using Hive.Axyl.Core.Unity;
using Hive.Axyl.Storage;
var config = CoreConfig.CreateBuilder("{appId}").Build();
HiveBootstrap.Initialize(config, builder =>
{
builder
.AddAuth()
.AddToken()
.AddSecureStorage()
.AddGooglePlayGames();
});
For {appId}, enter the Android App ID you created in the Hive Console.
AddGooglePlayGames() actually registers the module only on Android and skips registration on other OSs and in the Unity Editor. Calling it on any OS does not cause an error, so you can register it without branching.
If your app already uses secure storage, you do not need to register AddSecureStorage(). Even in this case, the app must be able to read the DeviceKey and session tokens again after it restarts.
5. Install the recipe code
- Recipe code Copy the recipe code into your project.
A recipe is source code that you copy into your project instead of installing as a package. Copy the following items from the axyl-samples-unity repository to Assets/Recipes/ in your Unity project.
The items to copy and their roles are as follows.
- Recipes.asmdef: Common assembly definition for recipes
- AssemblyInfo.cs: Setting that exposes internal helpers to other recipe assemblies
- Helper/: Common code shared by multiple recipes
- ProviderLogin/:
ProviderLoginRecipe, result types, and the credential source contract - ProviderLogin.Gpg/:
GooglePlayGamesCredentialSource
To call recipes from your app code, add the following assembly to references in your app's assembly definition. Because autoReferenced in the original Recipes.asmdef is false, your app assemblies do not reference it automatically.
Replace MyApp with the assembly name your app uses, and keep your existing settings and references. Unity assemblies do not pass references on transitively, so you must list here every assembly that your app code uses directly. Hive.Axyl.Core contains CoreConfig and HiveError, Hive.Axyl.Auth contains AddAuth() and AddToken(), Hive.Axyl.Auth.Addon.GPG contains AddGooglePlayGames(), and Hive.Axyl.Storage contains AddSecureStorage(). If you do not register AddSecureStorage(), you do not need to list Hive.Axyl.Storage.
The code does not compile if you copy only ProviderLogin.Gpg/
GooglePlayGamesCredentialSource uses the credential source contract and the authorization code exchange code in ProviderLogin/, and ProviderLoginRecipe uses the PKCE generation code and the session preparation code in Helper/. Copy Helper/, Recipes.asmdef, AssemblyInfo.cs, and ProviderLogin/ together.
6. Prepare ClientId and DeviceKey
The constructor of ProviderLoginRecipe takes ClientId and DeviceKey. ClientId is the value you checked in the common prerequisites, which the Hive Console issues for each project. DeviceKey is the value the Hive Axyl authentication server uses to distinguish login sessions by device, and the app creates and keeps it itself.
The recipe does not create or save DeviceKey, so create and manage it according to the following conditions.
- A different value for each device. A random value such as a UUID is recommended
- A value created and saved once on first launch and reused for every later login
- A length of 22 to 64 characters
- A value made up only of ASCII characters, excluding spaces and control characters
Do not overwrite it with a new DeviceKey just because the storage could not be read
The value may not be gone; only the read may have failed. First fix the storage access problem or try reading again.
You do not need to prepare PKCE values. Each time it is called, the recipe creates a pair itself and passes them separately to the login call and the token issuance call.
Passing an empty value throws an exception
If ClientId or DeviceKey is empty, the recipe throws an ArgumentException instead of returning a result. It also throws an ArgumentNullException when you pass the credential source as null. Before you pass a value read from storage as is, first check whether it is empty.
7. Prepare the Play Games credential source
-
Recipe code Call the recipe code from the app.
Detailed procedure: Get Google Play Games credentials
To tell the recipe which external authentication provider to log in with, you must create a credential source and pass it. A credential source is an object that displays the Play Games login screen and receives the user identifier and the authentication result. The Play Games credential source also performs the call that turns the authorization code issued by Play Games into credentials on the Hive Axyl authentication server.
Pass the Web application type OAuth client ID you copied in step 1 to the constructor. It is not the Client ID from the Hive Console, so do not swap the two values. If it is empty or contains only white space, an ArgumentException is thrown.
If you omit the second argument, forceRefreshToken, it is false. If you set this value to true, the source requests an authorization code that also yields a refresh token, and the consent screen is shown to the user one more time. Set it only when the app server needs to call Google APIs even while the user is not running the app.
You do not pass the redirect URI to the credential source. The RedirectUri preparation described in the detailed procedure is needed only when you call the Hive Axyl SDK methods directly.
8. Call Play Games login
- Recipe code Call the recipe code from the app.
Pass the prepared credential source to LoginWithProviderAsync(). The recipe receives credentials from Play Games, logs in, and also activates the session. The login screen appears only when no Play Games profile is logged in on the device.
Also prepare a CancellationTokenSource in case the app needs to stop waiting for login by itself.
Call cancellation.Cancel() when the app needs to end the wait first, such as when it leaves the scene that displayed the login screen, and clean up with cancellation.Dispose() when the call finishes. Do not call it when the user closes the Play Games login screen. The recipe reports that case as UserCanceled.
The recipe performs the following tasks internally.
| Category | Call | Where to check |
|---|---|---|
| Recipe code | Checks that the authentication, token, and session modules are registered | None |
| Add-on | Checks the Play Games authentication status with IsAuthenticatedAsync() | Get Google Play Games credentials |
| Add-on | If the user is not authenticated, displays the Play Games login screen with SignInAsync() | Get Google Play Games credentials |
| Add-on | Obtains an authorization code for server exchange with RequestServerSideAccessAsync() | Get Google Play Games credentials |
| Hive Axyl SDK | Exchanges the authorization code for ProviderUserId and ProviderToken with ExchangeProviderTokenAsync() | Exchange external authorization codes |
| Recipe code | Creates a pair of PKCE values and passes them separately to the login call and the token issuance call | Prepare the call parameter values |
| Hive Axyl SDK | Passes the Play Games credentials with LoginProviderAsync() and receives an authorization code | Log in with an external authentication provider |
| Hive Axyl SDK | Exchanges the authorization code for an access token and a refresh token with IssueTokenAsync() | Issue tokens and activate the session |
| Hive Axyl SDK | Activates the login session with SetSession() | Issue tokens and activate the session |
The authorization code appears twice, but the two are different values. The first authorization code is issued by Play Games and exchanged with Google by the Hive Axyl authentication server. The second authorization code is issued by the Hive Axyl authentication server and exchanged for an access token.
The detailed procedures in the table above are written for calling the Hive Axyl SDK methods directly. Do not reimplement in the app the steps that the recipe handles for you, such as creating PKCE values. Refer to them only to check what each call sends and receives.
If the modules are not registered, the recipe stops at the module check step with a FailedPrecondition error. When Success is returned, the session is already ready, so do not call the token issuance or session activation code separately. The session is activated only after usable tokens are received, so a failed attempt does not affect a session that was already open.
9. Handle login results
-
App code Implement this in the app.
Detailed procedure: HiveError information
LoginWithProviderOutcome reports the login result through Status. FailedStep is a diagnostic value, so do not use it as the basis for branching the app's normal flow.
Status | Value to check | App handling |
|---|---|---|
Success | PlayerId, IsBlocked | If the account is not under a usage restriction, move to the post-login screen. |
BusinessOutcome | BusinessOutcome, UnknownOutcomeCode | Branch according to the rejection reason, and handle and record unknown values as failures. |
UserCanceled | None | The user closed the Play Games login screen or stopped authentication in a later step, so return to the previous screen. |
Failure | Error.Code, Error.TraceId | Record the technical problem and provide a retry flow. |
If IsBlocked is true, login succeeded, but the account is under a usage restriction. For restriction types and how to notify users, see Usage restriction.
PlayerId is the unique identifier that Hive Axyl assigns to each user. If the user logs in again with the same Play Games profile, the same value is returned, so the app uses this value to distinguish the user's play data.
When you record errors, also record FailedStep. It has five values, None, Resolve, AcquireCredential, LoginProvider, and SessionSetup, and it tells you at which step the process stopped. AcquireCredential covers everything up to and including the authorization code exchange.
9.1. Handle rejection reasons
A BusinessOutcome value is the reason login did not succeed, so the message to show the user differs for each value. The recipe combines the rejection reasons from three server calls into a single value and returns it, so check all three places.
ExchangeProviderTokenAsync(): External authorization code exchange response statusLoginProviderAsync(): External authentication provider login response statusIssueTokenAsync(): Issue an access token and a refresh token
Even when the recipe cannot interpret a result returned by the Play Games Add-on or the server, Status becomes BusinessOutcome, and the BusinessOutcome value is Unrecognized. In this case, use UnknownOutcomeCode to distinguish two cases. If it has a value, it is a result code that this SDK version does not know. If it is empty, the SDK knows the result, but the recipe has not given it a name. In either case, do not look it up in the three places above; record UnknownOutcomeCode and RawJson, and then handle it as a failure.
The recipe renames the names written in the detailed procedures as follows before returning them.
TerminateService:ServiceTerminatedInvalidClientId:InvalidClientInvalidGrant:InvalidAuthorizationCodeInvalidGrantExpired:ExpiredAuthorizationCodeInvalidGrantCodeChallenge:CodeChallengeMismatchInvalidGrantRefreshToken:InvalidRefreshToken
ProviderConfigNotFound and ProviderClientInfoNotExists mean that the Hive Console settings in step 2 are empty. ProviderTokenError means that Google rejected the authorization code issued by Play Games, so have the user authenticate again. These three values come from both the authorization code exchange and the login call.
TemporarilyUnavailable means that the Hive Axyl authentication server could not make a decision and returned the request, so send the same request again. Do not repeat it immediately; retry at increasing intervals, such as 1 second, 3 seconds, and 6 seconds.
9.2. Handle cancellation and unsupported environments
Not every result whose Status is Failure should be reported to the user as a failure. Cases where the app stopped waiting and environments where Play Games login cannot run also end up here, so distinguish them with Error.Code.
If you cancel login with a CancellationToken, Error.Code becomes HiveErrorCode.Cancelled. This is a different result from UserCanceled, in which the user closed the Play Games login screen, so use a different message for each.
If Error.Code is HiveErrorCode.Unavailable, the call could not run to completion. There are four causes.
- Play Games Add-on not registered: On OSs other than Android, hide the Play Games login button, and on Android, check the
AddGooglePlayGames()registration in step 4. - Play Games login failed on the device: Offer a different login method.
- No login state for issuing an authorization code: Offer a different login method.
- Network disconnection or temporary service outage: Guide the user to try again after a while.
If Error.Code is HiveErrorCode.FailedPrecondition, the state required for the call is not ready. If FailedStep is Resolve, the authentication and token modules were not registered in step 4, or the SDK was not initialized. If FailedStep is AcquireCredential, the Play Games settings are incomplete, so check the Google external console settings in step 1 and the Android manifest declaration in step 3 again.
If Error.Code is HiveErrorCode.Internal, the call succeeded, but the response did not contain a value needed for the next step. Retrying does not solve it, so record Error.TraceId and FailedStep.
Do not show UnknownOutcomeCode and RawJson to users. Use them only when you need to record app errors, and do not assume that an unknown result is one you already know.
10. Verify the behavior
- App code Verify the behavior in the app.
Verify Play Games login on a real Android device. In the Unity Editor, the Play Games login Add-on is not registered and an Unavailable error is returned, so you cannot verify the flow from the login screen onward.
- Build with the package name and signing key you registered in the Android type OAuth client in the Google Cloud Console. If the values differ, Play Games cannot verify the app, and login does not proceed to completion.
- Check that a Google account is logged in on the device, and run the app.
- Run Play Games login, check that the login screen appears, and then complete login.
- Check for
SuccessandPlayerId, and check that the app moves to the post-login screen. - Quit the app completely, run it again, log in with the same Play Games profile, and check that
PlayerIdis the same. - On a device where no Play Games profile is logged in, cancel when the login screen appears, and check that
UserCanceledis returned.
If a Play Games profile is already logged in on the device, the login screen does not appear in step 3, and the process moves directly to the next step. This is because the recipe checks the authentication status first and displays the screen only when needed.
Next steps
To let logged-in users skip the login screen when they relaunch the app, see Automatic login.
To link another login method to an account that is already logged in, see the External authentication provider linking practical guide.
To let users leave the logged-in account and log in with a different account, see the Logout practical guide.