

# Setting up a mobile app in Amazon SNS
<a name="mobile-push-send"></a>

This topic describes how to set up mobile applications in the AWS Management Console using the information described in [Prerequisites for Amazon SNS user notifications](sns-prerequisites-for-mobile-push-notifications.md).

# Prerequisites for Amazon SNS user notifications
<a name="sns-prerequisites-for-mobile-push-notifications"></a>

To begin using Amazon SNS mobile push notifications, you'll need the following:
+ A set of credentials for connecting to one of the supported push notification services: ADM, APNs, Baidu, FCM, MPNS, or WNS.
+ A device token or registration ID for the mobile app and device.
+ Amazon SNS configured to send push notification messages to the mobile endpoints.
+ A mobile app that is registered and configured to use one of the supported push notification services.

Registering your application with a push notification service requires several steps. Amazon SNS needs some of the information you provide to the push notification service in order to send direct push notification messages to the mobile endpoint. Generally speaking, you need the required credentials for connecting to the push notification service, a device token or registration ID (representing your mobile device and mobile app) received from the push notification service, and the mobile app registered with the push notification service. 

The exact form the credentials take differs between mobile platforms, but in every case, these credentials must be submitted while making a connection to the platform. One set of credentials is issued for each mobile app, and it must be used to send a message to any instance of that app. 

The specific names will vary depending on which push notification service is being used. For example, when using APNs as the push notification service, you need a *device token*. Alternatively, when using FCM, the device token equivalent is called a *registration ID*. The *device token* or *registration ID* is a string that is sent to the application by the operating system of the mobile device. It uniquely identifies an instance of a mobile app running on a particular mobile device and can be thought of as unique identifiers of this app-device pair. 

Amazon SNS stores the credentials (plus a few other settings) as a platform application resource. The device tokens (again with some extra settings) are represented as objects called *platform endpoints*. Each platform endpoint belongs to one specific platform application, and every platform endpoint can be communicated with using the credentials that are stored in its corresponding platform application.

The following sections include the prerequisites for each of the supported push notification services. Once you've obtained the prerequisite information, you can send a push notification message using the AWS Management Console or the Amazon SNS mobile push APIs. For more information, see [Setting up push notifications with Amazon SNS](sns-mobile-application-as-subscriber.md#sns-user-notifications-process-overview). 

# Creating an Amazon SNS platform application
<a name="mobile-push-send-register"></a>

To send notifications from Amazon SNS to mobile endpoints—whether directly or through subscriptions to a topic—you must first create a platform application. After registering the app with AWS, you need to create an endpoint for both the app and the mobile device. This endpoint allows Amazon SNS to send messages to the device.

**To create a platform application**

1. Sign in to the [Amazon SNS console](https://console.aws.amazon.com/sns/home).

1. In the navigation pane, select **Push notifications**.

1. In the **Platform applications** section, choose **Create platform application**.

1. Choose your **AWS Region**. For a list of AWS Regions where you can create mobile applications, see [Amazon SNS mobile application supported Regions](sns-mobile-push-supported-regions.md).

1. Enter the following **application details**:
   + **Application name** – Provide a **name** for your platform application. The name must be between 1 and 256 characters and can contain uppercase and lowercase letters, numbers, underscores, hyphens, and periods.
   + **Push notification platform** – Select the appropriate **notification service** that the app is registered with (For example, Apple Push Notification Service (APNs), Firebase Cloud Messaging (FCM)).

1. Depending on the platform you selected, you’ll need to provide specific credentials:
   + For **APNs** (Apple Push Notification Service) – Choose between **token-based** or **certificate-based** authentication.
     + For token-based authentication, upload a **.p8 file** (generated via Keychain Access).
     + For certificate-based authentication, upload a **.p12 file** (also exported from Keychain Access).
   + For **FCM** (Firebase Cloud Messaging) – Enter the **Server key** from Firebase Console.
   + For **other platforms** (such as ADM or GCM) – Enter the respective **API keys** or **credentials**.

1. After entering the necessary details, choose **Create platform application**. This action registers the app with Amazon SNS and creates the corresponding platform application object.

1. Upon creation, Amazon SNS generates and returns a [https://docs.aws.amazon.com/sns/latest/api/API_PlatformApplication.html](https://docs.aws.amazon.com/sns/latest/api/API_PlatformApplication.html) (Amazon Resource Name). This ARN uniquely identifies your platform application and is used when creating endpoints for mobile devices.

# Setting up an Amazon SNS platform endpoint for mobile notifications
<a name="mobile-platform-endpoint"></a>

When an app and mobile device register with a push notification service (such as APNs or Firebase Cloud Messaging), the push notification service returns a device token. Amazon SNS uses this device token to create a platform endpoint, which acts as a target for sending direct push notification messages to the app on the device. The platform endpoint serves as a bridge, routing messages sent by Amazon SNS to the push notification service for delivery to the corresponding mobile device. For more information, see [Prerequisites for Amazon SNS user notifications](sns-prerequisites-for-mobile-push-notifications.md) and [Setting up push notifications with Amazon SNS](sns-mobile-application-as-subscriber.md#sns-user-notifications-process-overview).

## Understanding device tokens and platform endpoints
<a name="device-token-platform-endpoint"></a>

A device token uniquely identifies a mobile device registered with a push notification service (for example, APNs, Firebase Cloud Messaging). When an app registers with the push notification service, it generates a device token specific to that app and device. Amazon SNS uses this device token to create a platform endpoint within the corresponding platform application.

The platform endpoint allows Amazon SNS to send push notification messages to the device through the push notification service, maintaining the connection between your app and the user's device.

## Create a platform endpoint
<a name="mobile-platform-endpoint-create"></a>

To push notifications to an app with Amazon SNS, that app's device token must first be registered with Amazon SNS by calling the create platform endpoint action. This action takes the Amazon Resource Name (ARN) of the platform application and the device token as parameters and returns the ARN of the created platform endpoint.

The [https://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformEndpoint.html](https://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformEndpoint.html) action does the following:
+ If the platform endpoint already exists, do not create it again. Return to the caller the ARN of the existing platform endpoint.
+ If the platform endpoint with the same device token but different settings already exists, do not create it again. Throw an exception to the caller.
+ If the platform endpoint does not exist, create it. Return to the caller the ARN of the newly-created platform endpoint.

You should not call the create platform endpoint action immediately every time an app starts, because this approach does not always provide a working endpoint. This can happen, for example, when an app is uninstalled and reinstalled on the same device and the endpoint for it already exists but is disabled. A successful registration process should accomplish the following:

1. Ensure a platform endpoint exists for this app-device combination.

1. Ensure the device token in the platform endpoint is the latest valid device token.

1. Ensure the platform endpoint is enabled and ready to use.

## Pseudo code
<a name="mobile-platform-endpoint-pseudo-code"></a>

The following pseudo code describes a recommended practice for creating a working, current, enabled platform endpoint in a wide variety of starting conditions. This approach works whether this is a first time the app is being registered or not, whether the platform endpoint for this app already exists, and whether the platform endpoint is enabled, has the correct device token, and so on. It is safe to call it multiple times in a row, as it will not create duplicate platform endpoints or change an existing platform endpoint if it is already up to date and enabled.

```
retrieve the latest device token from the mobile operating system
if (the platform endpoint ARN is not stored)
  # this is a first-time registration
  call create platform endpoint
  store the returned platform endpoint ARN
endif

call get endpoint attributes on the platform endpoint ARN 

if (while getting the attributes a not-found exception is thrown)
  # the platform endpoint was deleted 
  call create platform endpoint with the latest device token
  store the returned platform endpoint ARN
else 
  if (the device token in the endpoint does not match the latest one) or 
      (GetEndpointAttributes shows the endpoint as disabled)
    call set endpoint attributes to set the latest device token and then enable the platform endpoint
  endif
endif
```

This approach can be used any time the app wants to register or re-register itself. It can also be used when notifying Amazon SNS of a device token change. In this case, you can just call the action with the latest device token value. Some points to note about this approach are:
+ There are two cases where it may call the create platform endpoint action. It may be called at the very beginning, where the app does not know its own platform endpoint ARN, as happens during a first-time registration. It is also called if the initial `GetEndpointAttributes` action call fails with a not-found exception, as would happen if the application knows its endpoint ARN but it was deleted.
+ The `GetEndpointAttributes` action is called to verify the platform endpoint's state even if the platform endpoint was just created. This happens when the platform endpoint already exists but is disabled. In this case, the create platform endpoint action succeeds but does not enable the platform endpoint, so you must double-check the state of the platform endpoint before returning success.

## AWS SDK example
<a name="mobile-platform-endpoint-sdk-examples"></a>

The following code shows how to implement the previous pseudo code using the Amazon SNS clients that are provided by the AWS SDKs.

To use an AWS SDK, you must configure it with your credentials. For more information, see [The shared config and credentials files](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html) in the *AWS SDKs and Tools Reference Guide*.

------
#### [ CLI ]

**AWS CLI**  
**To create a platform application endpoint**  
The following `create-platform-endpoint` example creates an endpoint for the specified platform application using the specified token.  

```
aws sns create-platform-endpoint \
    --platform-application-arn arn:aws:sns:us-west-2:123456789012:app/GCM/MyApplication \
    --token EXAMPLE12345...
```
Output:  

```
{
      "EndpointArn": "arn:aws:sns:us-west-2:1234567890:endpoint/GCM/MyApplication/12345678-abcd-9012-efgh-345678901234"
}
```

------
#### [ Java ]

**SDK for Java 2.x**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples). 

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointRequest;
import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointResponse;
import software.amazon.awssdk.services.sns.model.SnsException;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 *
 * In addition, create a platform application using the AWS Management Console.
 * See this doc topic:
 *
 * https://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-register.html
 *
 * Without the values created by following the previous link, this code examples
 * does not work.
 */

public class RegistrationExample {
    public static void main(String[] args) {
        final String usage = """

            Usage:     <token> <platformApplicationArn>

            Where:
               token - The device token or registration ID of the mobile device. This is a unique 
               identifier provided by the device platform (e.g., Apple Push Notification Service (APNS) for iOS devices, Firebase Cloud Messaging (FCM) 
               for Android devices) when the mobile app is registered to receive push notifications.

               platformApplicationArn - The ARN value of platform application. You can get this value from the AWS Management Console.\s

            """;

        if (args.length != 2) {
            System.out.println(usage);
            return;
        }

        String token = args[0];
        String platformApplicationArn = args[1];
        SnsClient snsClient = SnsClient.builder()
            .region(Region.US_EAST_1)
            .build();

        createEndpoint(snsClient, token, platformApplicationArn);
    }
    public static void createEndpoint(SnsClient snsClient, String token, String platformApplicationArn) {
        System.out.println("Creating platform endpoint with token " + token);
        try {
            CreatePlatformEndpointRequest endpointRequest = CreatePlatformEndpointRequest.builder()
                .token(token)
                .platformApplicationArn(platformApplicationArn)
                .build();

            CreatePlatformEndpointResponse response = snsClient.createPlatformEndpoint(endpointRequest);
            System.out.println("The ARN of the endpoint is " + response.endpointArn());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
    }
}
```

------

 For more information, see [Mobile push API actions](mobile-push-api.md).

## Troubleshooting
<a name="mobile-platform-endpoint-problems"></a>

### Repeatedly calling create platform endpoint with an outdated device token
<a name="mobile-platform-endpoint-problems-outdated"></a>

Especially for FCM endpoints, you may think it is best to store the first device token the application is issued and then call the create platform endpoint with that device token every time on application start-up. This may seem correct since it frees the app from having to manage the state of the device token and Amazon SNS will automatically update the device token to its latest value. However, this solution has a number of serious issues:
+ Amazon SNS relies on feedback from FCM to update expired device tokens to new device tokens. FCM retains information about old device tokens for some time, but not indefinitely. Once FCM forgets about the connection between the old device token and the new device token, Amazon SNS will no longer be able to update the device token stored in the platform endpoint to its correct value; it will just disable the platform endpoint instead.
+ The platform application will contain multiple platform endpoints corresponding to the same device token.
+ Amazon SNS imposes a quota on the number of platform endpoints that can be created starting with the same device token. Eventually, the creation of new endpoints will fail with an invalid parameter exception and the following error message: "This endpoint is already registered with a different token."

For more information on managing FCM endpoints, see [Amazon SNS management of Firebase Cloud Messaging endpoints](sns-fcm-endpoint-management.md).

### Re-enabling a platform endpoint associated with an invalid device token
<a name="mobile-platform-endpoint-problems-invalid"></a>

When a mobile platform (such as APNs or FCM) informs Amazon SNS that the device token used in the publish request was invalid, Amazon SNS disables the platform endpoint associated with that device token. Amazon SNS will then reject subsequent publishes to that device token. While you may think it is best to simply re-enable the platform endpoint and keep publishing, in most situations doing this will not work: the messages that are published do not get delivered and the platform endpoint becomes disabled again soon afterward.

This is because the device token associated with the platform endpoint is genuinely invalid. Deliveries to it cannot succeed because it no longer corresponds to any installed app. The next time it is published to, the mobile platform will again inform Amazon SNS that the device token is invalid, and Amazon SNS will again disable the platform endpoint.

To re-enable a disabled platform endpoint, it needs to be associated with a valid device token (with a set endpoint attributes action call) and then enabled. Only then will deliveries to that platform endpoint become successful. The only time re-enabling a platform endpoint without updating its device token will work is when a device token associated with that endpoint used to be invalid but then became valid again. This can happen, for example, when an app was uninstalled and then re-installed on the same mobile device and receives the same device token. The approach presented above does this, making sure to only re-enable a platform endpoint after verifying that the device token associated with it is the most current one available.

# Integrating device tokens with Amazon SNS for mobile notifications
<a name="mobile-push-send-devicetoken"></a>

When you first register an app and mobile device with a notification service, such as Apple Push Notification Service (APNs) and Firebase Cloud Messaging (FCM), device tokens or registration IDs are returned by the service. These tokens/IDs are added to Amazon SNS to create an endpoint for the app and device, using the [https://docs.aws.amazon.com/sns/latest/api/API_PlatformApplication.html](https://docs.aws.amazon.com/sns/latest/api/API_PlatformApplication.html) API. Once the endpoint is created, an [https://docs.aws.amazon.com/sns/latest/api/API_Endpoint.html](https://docs.aws.amazon.com/sns/latest/api/API_Endpoint.html) is returned, which Amazon SNS uses to direct notifications to the correct app/device.

You can add device tokens or registration IDs to Amazon SNS in the following ways:
+ Manually add a single token via the AWS Management Console
+ Upload several tokens using the [https://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformEndpoint.html](https://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformEndpoint.html) API
+ Register tokens for future devices

****To manually add a device token or registration ID****

1. Sign in to the [Amazon SNS console](https://console.aws.amazon.com/sns/home).

1. In the navigation pane, select **Push Notifications**.

1. In the **Platform applications** section, select your application, and then choose **Edit**. If you haven't already created a platform application, follow the [Creating an Amazon SNS platform application](mobile-push-send-register.md) guide to do so now.

1. Choose **Create Endpoint**.

1. In the **Endpoint Token** box, enter the **token** or **registration ID**, depending on the notification service you're using (for example, FCM registration ID).

1. (Optional) Enter additional data in the **User Data** field. This data must be UTF-8 encoded and less than 2 KB.

1. Choose **Create Endpoint**.

Once the endpoint is created, you can send messages directly to the mobile device or to mobile devices subscribed to an Amazon SNS topic.

****To upload several tokens using the `CreatePlatformEndpoint` API****

The following steps show how to use the sample Java app (`bulkupload` package) provided by AWS to upload several tokens (device tokens or registration IDs) to Amazon SNS. You can use this sample app to help you get started with uploading your existing tokens. 
**Note**  
The following steps use the Eclipse Java IDE. The steps assume you have installed the AWS SDK for Java and you have the AWS security credentials for your AWS account. For more information, see [AWS SDK for Java](http://aws.amazon.com/sdkforjava/). For more information about credentials, see [AWS security credentials](https://docs.aws.amazon.com/general/latest/gr/getting-aws-sec-creds.html) in the *IAM User Guide*. 

1. Download and unzip the [snsmobilepush.zip](samples/snsmobilepush.zip) file. 

1. Create a new **Java project** in Eclipse and import the `SNSSamples` folder to the project. 

1. Download the [OpenCSV library](http://sourceforge.net/projects/opencsv/) and add it to the build path.

1. In the `BulkUpload.properties` file, specify the following: 
   + Your `ApplicationArn` (platform application ARN).
   + The absolute path to your CSV file containing the tokens.
   + Logging filenames for successful and failed tokens. For example, `goodTokens.csv` and `badTokens.csv`.
   + (Optional) A configuration for delimiter, quote character, and number of threads to use.

   Your completed `BulkUpload.properties` should look similar to the following:

   ```
   applicationarn: arn:aws:sns:us-west-2:111122223333:app/FCM/fcmpushapp
   csvfilename: C:\\mytokendirectory\\mytokens.csv
   goodfilename: C:\\mylogfiles\\goodtokens.csv
   badfilename: C:\\mylogfiles\\badtokens.csv
   delimiterchar: ','
   quotechar: '"'
   numofthreads: 5
   ```

1.  Run the **BatchCreatePlatformEndpointSample.java** application to upload the tokens to Amazon SNS. Tokens uploaded successfully will be logged in `goodTokens.csv`, while malformed tokens will be logged in `badTokens.csv`.

**To register tokens from devices for future app installations**

You have two options for this process:

**Use the Amazon Cognito service**  
Your mobile app can use temporary security credentials to create endpoints. Amazon Cognito is recommended to generate temporary credentials. For more information, see the *[Amazon Cognito Developer Guide](https://docs.aws.amazon.com/cognito/latest/developerguide/)*   
To track app [registrations](application-event-notifications.md), use Amazon SNS events to receive notifications when new endpoint ARNs are created.  
Alternatively, you can use the [https://docs.aws.amazon.com/sns/latest/api/API_ListEndpointsByPlatformApplication.html](https://docs.aws.amazon.com/sns/latest/api/API_ListEndpointsByPlatformApplication.html) API to retrieve the list of registered endpoints.

**Use a proxy server**  
If your app infrastructure already supports device registration on installation, you can use your server as a proxy. It will forward device tokens to Amazon SNS via the [https://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformEndpoint.html](https://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformEndpoint.html) API.  
The endpoint ARN created by Amazon SNS will be returned and can be stored by your server for future message publishing.

# Amazon SNS Apple push notification authentication methods
<a name="sns-apple-authentication-methods"></a>

You can authorize Amazon SNS to send push notifications to your iOS or macOS app by providing information that identifies you as the developer of the app. To authenticate, provide either a *key* or a *certificate* [when creating a platform application](https://docs.aws.amazon.com/sns/latest/api/API_SetPlatformApplicationAttributes.html), both of which you can get from your Apple Developer account.

**Token signing key**  
A private signing key that Amazon SNS uses to sign Apple Push Notification Service (APNs) authentication tokens.  
If you provide a signing key, Amazon SNS uses a token to authenticate with APNs for every push notification that you send. With your signing key, you can send push notifications to APNs production and sandbox environments.  
Your signing key doesn't expire, and you can use the same signing key for multiple apps. For more information, see [Communicate with APNs using authentication tokens](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/establishing_a_token-based_connection_to_apns) in the **Developer Account Help** section of the Apple website.

**Certificate**  
A TLS certificate that Amazon SNS uses to authenticate with APNs when you send push notifications. You obtain the certificate from your Apple Developer account.  
Certificates expire after one year. When this happens, you must create a new certificate and provide it to Amazon SNS. For more information, see [Establishing a Certificate-Based Connection to APNs](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/establishing_a_certificate-based_connection_to_apns) on the Apple Developer website.

**To manage APNs settings using the AWS Management Console**

1. Sign in to the [Amazon SNS console](https://console.aws.amazon.com/sns/home).

1. In the navigation pane, select **Push notifications**.

1. In the **Platform applications** section, select the **application** whose APNs settings you want to edit, and then choose **Edit**. If you haven't already created a platform application, follow the [Creating an Amazon SNS platform application](mobile-push-send-register.md) guide to do so now.

1. Choose **Edit** to modify the settings for your platform application.

1. In the**Authentication type** section, choose one of the following options:
   + **Token-based authentication** (recommended for modern APNs integrations)
   + **Certificate-based authentication** (older method)

1. Configure your **credentials** based on the authentication type:
   + **For token-based authentication:**
     + Upload the **.p8 file**, which is the authentication token signing key you downloaded from your Apple Developer account.
     + Enter the **Signing Key ID** that you find in your Apple Developer account. Navigate to **Certificates**, **IDs & Profiles**, **Keys**, and select the **key** you want to use.
     + Provide the **Team Identifier** from your Apple Developer account. You can find this on the Membership page.
     + Enter the **Bundle Identifier** assigned to your app. You can find this under Certificates, IDs and Profiles, App IDs.
   + **For certificate-based authentication:**
     + Upload the **.p12 file** for your TLS certificate. This file can be exported from Keychain Access on macOS after downloading the certificate from your Apple Developer account.
     + If you assigned a **password** to your .p12 certificate, enter it here.

1. After entering the necessary credentials, choose **Save changes** to update the settings.

# Amazon SNS integration with Firebase Cloud Messaging authentication setup
<a name="sns-fcm-authentication-methods"></a>

This topic describes how to obtain the required FCM API (HTTP v1) credentials from Google to use with the AWS API, AWS CLI and the AWS Management Console.

**Important**  
March 26, 2024 – Amazon SNS supports FCM HTTP v1 API for Apple devices and Webpush destinations. We recommend that you migrate your existing mobile push applications to the latest FCM HTTP v1 API on or before June 1, 2024 to avoid application disruption.  
January 18, 2024 – Amazon SNS introduced support for FCM HTTP v1 API for mobile push notification delivery to Android devices.  
June 20, 2023 – Google deprecated their Firebase Cloud Messaging (FCM) legacy HTTP API. Amazon SNS now supports delivery to all device types using FCM HTTP v1 API. We recommend that you migrate your existing mobile push applications to the latest FCM HTTP v1 API on or before June 1, 2024 to avoid disruption.

You can authorize Amazon SNS to send push notifications to your applications by providing information that identifies you as the developer of the app. To authenticate, provide either an **API key** or a **token** [when creating a platform application](https://docs.aws.amazon.com/sns/latest/api/API_SetPlatformApplicationAttributes.html). You can get the following information from your [Firebase application console](https://firebase.google.com/?gad=1&gclid=CjwKCAiA0syqBhBxEiwAeNx9N27M7zxHjlS74_gp4mAS4QTMQH5J35sTO29od-yauuq259zzX_I2DRoCrbsQAvD_BwE&gclsrc=aw.ds):

**API Key**  
The API key is a credential used when calling Firebase’s Legacy API. The FCM Legacy APIs will be removed by Google June 20, 2024. If you are currently using an API key as your platform credential, you can update the platform credential by selecting **Token** as the option, and uploading the associated JSON file for your Firebase application.

**Token**  
A short lived access token is used when calling the HTTP v1 API. This is Firebase’s suggested API for sending push notifications. In order to generate access tokens, Firebase provides developers a set of credentials in the form of a private key file (also referred to as a service.json file).

## Prerequisite
<a name="sns-fcm-authentication-prerequisite"></a>

You must obtain your FCM service.json credentials before you can begin managing FCM settings in Amazon SNS. To obtain your service.json credentials, see [Migrate from legacy FCM APIs to HTTP v1](https://firebase.google.com/docs/cloud-messaging/migrate-v1) in the Google Firebase documentation.

## Managing FCM settings using the CLI
<a name="sns-fcm-authentication-api"></a>

You can create FCM push notifications using the AWS API. The number and size of Amazon SNS resources in an AWS account are limited. For more information, see [Amazon Simple Notification Service endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/sns.html) in the *AWS General Reference Guide*.

**To create an FCM push notification together with an Amazon SNS topic (AWS API)**  
When using **key** credentials, the `PlatformCredential` is `API key`. When using **token** credentials, the `PlatformCredential` is a JSON formatted private key file:
+ [https://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformApplication.html](https://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformApplication.html)

**To retrieve an FCM credential type for an existing Amazon SNS topic (AWS API)**  
Retrieves the credential type `"AuthenticationMethod": "Token"`, or ` "AuthenticationMethod": "Key"`:
+ [GetPlatformApplicationAttributes](https://docs.aws.amazon.com/sns/latest/api/API_GetPlatformApplicationAttributes.html)

**To set an FCM attribute for an existing Amazon SNS topic (AWS API)**  
Sets the FCM attribute:
+ [SetPlatformApplicationAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetPlatformApplicationAttributes.html)

## Managing FCM settings using the console
<a name="sns-fcm-authentication-cli"></a>

You can create FCM push notifications using the AWS Command Line Interface (CLI). The number and size of Amazon SNS resources in an AWS account are limited. For more information, see [Amazon Simple Notification Service endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/sns.html). 

**To create an FCM push notification together with an Amazon SNS topic (AWS CLI)**  
When using **key** credentials, the `PlatformCredential` is `API key`. When using **token** credentials, the `PlatformCredential` is a JSON formatted private key file. When using the AWS CLI, the file must be in string format and special characters must be ignored. To format the file correctly,Amazon SNS recommends using the following command: `SERVICE_JSON=`jq @json <<< cat service.json``:
+ [create-platform-application](https://docs.aws.amazon.com/cli/latest/reference/sns/create-platform-application.html)

**To retrieve an FCM credential type for an existing Amazon SNS topic (AWS CLI)**  
Retrieves the credential type `"AuthenticationMethod": "Token"`, or ` "AuthenticationMethod": "Key"`:
+ [get-platform-application-attributes](https://docs.aws.amazon.com/cli/latest/reference/sns/get-platform-application-attributes.html)

**To set an FCM attribute for an existing Amazon SNS topic (AWS CLI)**  
Sets the FCM attribute:
+ [set-platform-application-attributes](https://docs.aws.amazon.com/cli/latest/reference/sns/set-platform-application-attributes.html)

## Managing FCM settings (console)
<a name="sns-fcm-authentication-console"></a>

Use the following steps to enter and manage your Firebase Cloud Messaging (FCM) credentials in Amazon SNS.

1. Sign in to the [Amazon SNS console](https://console.aws.amazon.com/sns/home).

1. In the navigation pane, select **Push Notifications**.

1. In the **Platform applications** section, select the **FCM platform application** whose credentials you want to edit, and then choose **Edit**.

1. In the **Firebase Cloud Messaging Credentials** section, choose one of the following options:
   + **Token-based authentication** (recommended method) – Upload the **private key file** (JSON) that you downloaded from the Firebase Console. This file contains the credentials needed to generate short-lived access tokens for FCM notifications. To get this file:

     1. Go to your [Firebase application console](https://firebase.google.com/?gad=1&gclid=CjwKCAiA0syqBhBxEiwAeNx9N27M7zxHjlS74_gp4mAS4QTMQH5J35sTO29od-yauuq259zzX_I2DRoCrbsQAvD_BwE&gclsrc=aw.ds).

     1. In the **Project Settings**, select **Cloud Messaging**.

     1. Download the **Private key** JSON file (for use in the token-based authentication method).
   + **API key authentication** – If you prefer to use the older API key authentication method, enter the **Google API key** in the provided field. To get this file:

     1. Go to your [Firebase application console](https://firebase.google.com/?gad=1&gclid=CjwKCAiA0syqBhBxEiwAeNx9N27M7zxHjlS74_gp4mAS4QTMQH5J35sTO29od-yauuq259zzX_I2DRoCrbsQAvD_BwE&gclsrc=aw.ds).

     1. In **Project Settings**, select **Cloud Messaging**.

     1. Copy the **Server key** (API key) to use for sending notifications.

1. When you finish, choose **Save changes**.

**Related topics**
+ [Using Google Firebase Cloud Messaging v1 payloads in Amazon SNS](sns-fcm-v1-payloads.md)

# Amazon SNS management of Firebase Cloud Messaging endpoints
<a name="sns-fcm-endpoint-management"></a>

## Managing and maintaining device tokens
<a name="sns-managing-device-tokens"></a>

You can ensure deliverability of your mobile application's push notifications by following these steps:

1. Store all device tokens, corresponding Amazon SNS endpoint ARNs, and timestamps on your application server.

1. Remove all stale tokens and delete the corresponding Amazon SNS endpoint ARNs.

Upon your app's initial start-up, you'll receive a device token (also referred to as registration token) for the device. This device token is minted by the device’s operating system, and is tied to your FCM application. Once you receive this device token, you can register it with Amazon SNS as a platform endpoint. We recommend that you store the device token, the Amazon SNS platform endpoint ARN, and the timestamp by saving the them to your application server, or another persistent store. To set-up your FCM application to retrieve and store device tokens, see [Retrieve and store registration tokens](https://firebase.google.com/docs/cloud-messaging/manage-tokens#retrieve-and-store-registration-tokens) in Google's *Firebase* documentation.

It's important that you maintain up-to-date tokens. Your user’s device tokens can change under the following conditions:

1. The mobile application is restored on a new device.

1. The user uninstalls or updates the application.

1. The user clears application data.

When your device token changes, we recommended that you update the corresponding Amazon SNS endpoint with the new token. This allows Amazon SNS to continue communication to the registered device. You can do this by implementing the following pseudo code within your mobile application. It describes a recommended practice for creating and maintaining enabled platform endpoints. This approach can be executed each time the mobile applications starts, or as a scheduled job in the background.

### Pseudo code
<a name="sns-device-token-pseudo-code"></a>

Use the following FCM pseudo code to manage and maintain device tokens.

```
retrieve the latest token from the mobile OS
if (endpoint arn not stored)
    # first time registration
    call CreatePlatformEndpoint
    store returned endpoint arn
endif

call GetEndpointAttributes on the endpoint arn 

if (getting attributes encountered NotFound exception)
    #endpoint was deleted 
    call CreatePlatformEndpoint
    store returned endpoint arn
else 
    if (token in endpoint does not match latest) or 
        (GetEndpointAttributes shows endpoint as disabled)
        call SetEndpointAttributes to set the 
                     latest token and enable the endpoint
    endif
endif
```

To learn more about token update requirements, see [Update Tokens on a Regular Basis](https://firebase.google.com/docs/cloud-messaging/manage-tokens#update-tokens-on-a-regular-basis) in Google's *Firebase* documentation.

## Detecting invalid tokens
<a name="sns-detecting-invalid-tokens"></a>

When a message is dispatched to an FCM v1 endpoint with an invalid device token, Amazon SNS will receive one of the following exceptions:
+ `UNREGISTERED` (HTTP 404) – When Amazon SNS receives this exception, you will receive a delivery failure event with a `FailureType` of `InvalidPlatformToken`, and a `FailureMessage` of *Platform token associated with the endpoint is not valid*. Amazon SNS will disable your platform endpoint when a delivery fails with this exception.
+ `INVALID_ARGUMENT` (HTTP 400) – When Amazon SNS receives this exception, it means that the device token or the message payload is invalid. For more information, see [ErrorCode](https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode) in Google's *Firebase* documentation.

Since `INVALID_ARGUMENT` can be returned in either of these cases, Amazon SNS will return a `FailureType` of `InvalidNotification`, and a `FailureMessage` of *Notification body is invalid*. When you receive this error, verify that your payload is correct. If it is correct, verify that the device token is up-to-date. Amazon SNS will not disable your platform endpoint when a delivery fails with this exception.

Another case where you will experience an `InvalidPlatformToken` delivery failure event is when the registered device token doesn't belong to the application attempting to send that message. In this case, Google will return a *SENDER\$1ID\$1MISMATCH* error. Amazon SNS will disable your platform endpoint when a delivery fails with this exception.

All observed error codes received from the FCM v1 API are available to you in CloudWatch when you set up [delivery status logging](topics-attrib.md) for your application. 

To receive delivery events for your application, see [Available application events](application-event-notifications.md#application-event-notifications-events).

## Removing stale tokens
<a name="sns-removing-stale-tokens"></a>

Tokens are considered stale once message deliveries to the endpoint device start failing. Amazon SNS sets these stale tokens as disabled endpoints for your platform application. When you publish to a disabled endpoint, Amazon SNS will return a `EventDeliveryFailure` event with the `FailureType` of `EndpointDisabled`, and a `FailureMessage` of *Endpoint is disabled*. To receive delivery events for your application, see [Available application events](application-event-notifications.md#application-event-notifications-events).

When you receive this error from Amazon SNS, you need to remove or update the stale token in your platform application.