Skip to content

Register device tokens

Register the device token issued by the push notification service of each OS (FCM/APNs) with the Hive Axyl push server.

This document explains how to get a device token issued for each OS, link the issued token to the logged-in user, and include it in the send targets of push messages.


The device token registration order is as follows.

※ Prerequisites: Complete Install and initialize the module, and complete login before you call the token registration API. Token registration uses the logged-in session.

  1. Issue device tokens for each OS
  2. Register device tokens
  3. Handle token refresh

The Hive Axyl push module registers tokens issued by the external push service of each OS with the Hive Axyl push server. The app client performs OS-specific token issuance, token storage, and notification permission requests directly.

Note
  • The user identifier (Player ID) linked to the token is extracted from the login token and is not included separately in the request.
  • The server processes the registration request asynchronously after accepting it (202).


1. Issue device tokens for each OS

Before token registration, get a device token issued by the messaging infrastructure service for each OS environment.

OS How to issue tokens ProviderType at registration
Android Get a device token issued with the FCM plugin. Fcm
iOS Get a device token issued with the APNs plugin and check the push environment. Apns or ApnsSandbox


Considerations when calling

  • On Android, get the FCM token issued and then set ProviderType to Fcm.
  • On iOS, after the APNs token is issued, set ProviderType to Apns or ApnsSandbox according to the result of Check the push environment.
  • Call the registration API whenever the token state may change, such as at app start, login, or token refresh, to keep the server information up to date.


2. Register device tokens

Method

public Task UpsertTokenAsync();


Registers the issued device token with the Hive Axyl push server or fully synchronizes it. If information is already registered with the same token, the method updates all of it with the request values; otherwise, it registers the token as new.

Because the token validity period is renewed to one year each time you register, call this method at periodically repeated moments, such as app start or login, to keep the token up to date. Sending the same request again gives the same result, so retrying is safe.

A token registration request is linked to the user of the logged-in session. You do not include the user identifier directly in the request.


Call parameters

Field name Type Required Description
request UpsertTokenRequest Required Request object that contains the token information to register.
context ApiCallContext Optional Per-call settings object. If omitted, the default values are used.

UpsertTokenRequest

Field name Type Required Description
Token string Required The device token value issued by FCM/APNs.
TimezoneId string Required The time zone name of the device. Pass it in IANA format (for example, Asia/Seoul). An invalid name fails request value validation.
Country string Required The country code of the device. Pass it in ISO 3166-1 alpha-2 format. Used for country filtering when sending campaigns.
Language LanguageCode Required The language code of the device token. Used to localize the language of notification messages. Specify it as an enum member (for example, LanguageCode.Ko).
ProviderType UpsertTokenRequestProviderType Required The push service that issued the token. Use Fcm for Android, Apns for the iOS production environment, and ApnsSandbox for the iOS development environment.
Agreement Agreement Required Notification consent settings. Fill in all three item values.
AppVersion string Optional The app version.
SdkVersion string Optional The Hive Axyl SDK version.
ServerId string Optional The ID of the app server the user is connected to.
EventType string Optional The type of event that triggered the token registration. A value for logging, up to 32 characters (for example, LOGIN).

Agreement

Field name Type Required Description
Info bool Required Consent to receive informational notifications.
Advertise bool Required Consent to receive advertising notifications.
Night bool Required Consent to receive nighttime advertising notifications. Cannot be set to true if Advertise is false.


Call example

The PushUpsertTokenResult object returned by UpsertTokenAsync() is divided into success, target resource scope error, user identifier error, and failure states. The method call does not throw exceptions (Exception), and all processing results are delivered through the returned object. Therefore, instead of using a separate try/catch statement, branch on the response status with a switch statement.

using Hive.Axyl.Core;
using Hive.Axyl.Push;

IPushService push = HiveCore.Resolve<IPushService>();

var request = new UpsertTokenRequest {
    Token        = fcmToken,            // Device token issued by FCM or APNs
    TimezoneId   = "Asia/Seoul",        // IANA time zone of the device
    Country      = "KR",                // ISO 3166-1 alpha-2
    Language     = LanguageCode.Ko,
    ProviderType = UpsertTokenRequestProviderType.Fcm,
    AppVersion   = "{appVersion}",
    SdkVersion   = "{sdkVersion}",
    ServerId     = "KR-01",             // ID of the app server the user is connected to
    Agreement    = new Agreement {      // Notification consent - pass all three items.
        Info      = true,
        Advertise = false,
        Night     = false,
    },
    EventType    = "LOGIN",             // Event that triggered the registration (for logging)
};

PushUpsertTokenResult result = await push.UpsertTokenAsync(request);

switch (result)
{
    case PushUpsertTokenResult.Success:
        // Registration request accepted (202). The server processes it asynchronously.
        break;

    case PushUpsertTokenResult.ResourceNotInScope:
        // The requested App ID or resource cannot be used within the current project scope.
        break;

    case PushUpsertTokenResult.InvalidSubject:
        // The user identifier of the login session cannot be used. Check the login status.
        break;

    // Handle common failures - for the detailed error model, see [Error handling](PLACEHOLDER_에러처리_링크)
    case PushUpsertTokenResult.Failure failure:
        HiveError err = failure.Problem;
        Debug.LogError($"[{err.Code}] {err.Message} (trace: {err.TraceId})");
        break;

    // Safety net: unknown new results (UnknownOutcome)
    default:
        Debug.LogWarning($"Unhandled result: {result.GetType().Name}");
        break;
}


Considerations when calling

  • Fill in and pass all required fields, such as Token, ProviderType, and Agreement.
  • TimezoneId must be an IANA time zone name. If the value is invalid, invalid_parameter may be passed in HiveError.ExternalCode of Failure.
  • The server processes the registration request asynchronously. Success means that the request was accepted.
  • If the app should no longer receive notifications targeted at the user because of logout or account switching, call Detach the token identifier.


Response status

The returned PushUpsertTokenResult object branches into the following cases. No response data is returned on success.

Response case Description App client handling
Success The registration request was accepted (202). The server processes it asynchronously, and the token validity period is renewed to one year. Treat the registration as complete
ResourceNotInScope The requested App ID or resource cannot be used within the current project scope. Check the project and App ID settings
InvalidSubject The user identifier to link to the token cannot be confirmed from the login session. Check the login status and retry
Failure A network error, server error, or common failure response. Request value validation errors are passed in ExternalCode of Problem (HiveError) as values such as invalid_parameter, missing_field, and bad_request. Check ExternalCode, then fix the request values or retry


3. Handle token refresh

When the OS push service issues a new token, the app client must register the new token again. The Hive Axyl SDK does not automatically register the refreshed token with the Hive Axyl server.

fcm.TokenRefreshed += async newToken =>
{
    var result = await push.UpsertTokenAsync(new UpsertTokenRequest {
        Token        = newToken,
        ProviderType = UpsertTokenRequestProviderType.Fcm,
        // Fill in the remaining fields with the same values as the initial registration.
    });
    // Branch on the response status in the same way as in the [Register device tokens] step.
};

For the TokenRefreshed event on Android, see FCM token issuance. For the TokenRefreshed event on iOS, see APNs token issuance.


For reference: Implementation example from issuance to registration

This section provides a full implementation example that connects device token issuance (FCM/APNs) through the dedicated plugin of each OS with the push server registration step through the Hive Axyl core module.

The following implementation example code focuses on the success cases (exception handling is omitted by returning early). For the specific failure types and error handling of each method call step, see the switch examples in the individual document of that step.

using Hive.Axyl.Core;
using Hive.Axyl.Push;
#if UNITY_ANDROID
using Hive.Axyl.Push.Addon.FCM;
#elif UNITY_IOS
using Hive.Axyl.Push.Addon.APNS;
#endif

async Task RegisterDeviceTokenAsync()
{
    string token;
    UpsertTokenRequestProviderType providerType;

#if UNITY_ANDROID
    IFCMPlugin fcm = HiveCore.Resolve<IFCMPlugin>();
    if (await fcm.GetTokenAsync() is not FcmServiceGetTokenResult.Success fcmToken)
    {
        return; // Handle the failure branches by referring to the response status in [FCM token issuance].
    }
    token        = fcmToken.Data.Token;
    providerType = UpsertTokenRequestProviderType.Fcm;
#elif UNITY_IOS
    IAPNSPlugin apns = HiveCore.Resolve<IAPNSPlugin>();
    if (await apns.GetTokenAsync() is not ApnsServiceGetTokenResult.Success apnsToken)
    {
        return;
    }
    if (await apns.GetProviderEnvironmentAsync()
            is not ApnsServiceGetProviderEnvironmentResult.Success env)
    {
        return;
    }
    token        = apnsToken.Data.Token;
    providerType = env.Data.Environment == ProviderEnvironment.Apns
        ? UpsertTokenRequestProviderType.Apns
        : UpsertTokenRequestProviderType.ApnsSandbox;
#else
    return; // Unsupported OS.
#endif

    IPushService push = HiveCore.Resolve<IPushService>();

    var result = await push.UpsertTokenAsync(new UpsertTokenRequest {
        Token        = token,
        ProviderType = providerType,
        // Fill in the remaining fields, such as TimezoneId, Country, Language, and Agreement,
        // by referring to the call parameters table in [Register device tokens].
    });
    // Branch on the response status in the same way as in the [Register device tokens] step.
}


For reference: Linking tokens and users

When you register a token, the token is linked to the logged-in user (Player ID). If the app should no longer receive notifications targeted at the user because of logout or account switching, call Detach the token identifier.


The documents related to the content of this document are as follows.