Integrate offline push

Updated

Integrate push notifications.

Follow this guide to integrate and test push notifications in your environment.

Prerequisites

Before proceeding, ensure that you meet the following requirements:

  • You have initialized the Chat SDK. For details, see SDK quickstart.
  • You understand the call frequency limit of the Chat APIs supported by different pricing plans as described in Limitations.

Integrate FCM push

This section guides you through how to integrate FCM with Chat.

1. Create a project in Firebase

  1. Log in to Firebase console, and click Add project.

  2. On the Create a project page, enter a project name, and proceed with prompts.

  3. Query the sender ID. On the Project settings page, select the Cloud Messaging tab and view Sender ID. When uploading the FCM certificate to Agora Console, set the certificate name to the FCM sender ID.

  4. On the Project settings page, select the Service accounts tab and click Generate new private key to generate a JSON file. Save this file and upload it to Agora Console when using the V1 certificate.

  5. After the project is created, add an iOS application or an Android application according to the following steps:

  • Add an iOS app:

    1. The package name is the same as that of the iOS app;
    2. Once created, move the downloaded GoogleService-Info.plist file to the root directory of the Xcode project, and add it to all targets;
    3. Upload the APNs certificate on the Cloud Messaging page.
  • Add an Android app:

    1. The package name is the same as that of the Android app;
    2. Once created, move the downloaded google-services.json file to your module (application level) root directory.

For detailed FCM configurations, you can see the React Native Firebase document.

2. Upload FCM certificate to Agora Console

After successfully logging into Chat, you can upload the FCM push certificate to Agora Console:

  1. Log in to Agora Console, and click Project Management in the left navigation bar.

  2. On the Project Management page, locate the project that has Chat enabled and click Config.

  3. On the project edit page, click Config next to Chat.

  4. On the project config page, select Features > Push Certificate and click Add Push Certificate.

  5. In the pop-up window, select the Google tab, and configure the following fields:

    ParameterTypeRequiredDescription
    Certificate TypeNoSelect whether to use a V1 certificate or a legacy certificate. V1: Recommended. You need to configure a Private Key. Legacy: Will soon be deprecated. You need to configure a Push Key.
    Private KeyfileYesClick Generate new private key on the Project settings > Service accounts page of the Firebase Console to generate the .json file, then upload it to Agora Console.
    Push KeyStringYesFCM Server Key. Obtain the server key in the Cloud Messaging API (Legacy) area of the Project settings > Cloud Messaging page of the Firebase Console. This parameter is only valid for legacy certificates.
    Certificate NameStringYesThe sender ID configured for the FCM. For the new version of the certificate, you can find the sender ID on the Project settings > Cloud Messaging page of the Firebase Console. For legacy certificates, go to the *Project settings > Cloud Messaging page of the Firebase Console, and get the sender ID in the Cloud Messaging API (Legacy) area. The certificate name is the only condition used by the Agora server to determine which push channel the target device uses, so ensure that the sender set when integrating FCM in Chat is consistent with what is set here.
    SoundStringNoThe ringtone flag for when the receiver gets the push notification.
    Push PriorityNoMessage delivery priority. See Setting the priority of a message.
    Push Msg TypeNoThe type of the message sent to the client through FCM. See Message types: Data: Data message, processed by the client application. Notification: Notification message, automatically processed by FCM SDK. Both: Notification messages and data messages can be sent through the FCM client.

Switch from legacy to the V1 certificate

The legacy HTTP or XMPP API is being retired on June 20, 2024. In view of this, switch to the latest FCM API (HTTP v1) version of the certificate as soon as possible. See Firebase Console for details.

Make sure that the uploaded V1 certificate is available, as the legacy one will be deleted upon upload. If the new certificate is not available, the push will fail.

Take the following steps to switch from the old to the new certificate:

  1. Click Edit in the Action column of the old certificate on the Push Certificate page.

  2. In the Google tab of the Edit Push Certificate window, switch the Certificate Type to V1.

  3. Click Upload to upload the locally saved V1 certificate file (.json).

  4. Click OK to complete the switch.

3. Integrate FCM on the client

Take the following steps to integrate FCM on the client:

  1. Add dependencies:

    yarn add @react-native-firebase/app @react-native-firebase/messaging react-native-agora-chat
  2. Add native platform configuration:

    Android

    1. Download the google-services.json file and put it in the following path in your project: /android/app/google - services.json.

    2. In your /android/build.gradle file, add the google-services plugin as a dependency:

      buildscript {
        dependencies {
          classpath 'com.google.gms:google-services:4.3.15'
        }
      }
    3. Add the google-services plugin to the /android/app/build.gradle file and execute the plugin:

      apply plugin: 'com.google.gms.google-services' //  true
        pod 'FirebaseCore', :modular_headers => true
      end
    4. Run the pod install command in the ios directory to install dependencies.

    5. Open the /ios/{projectName}.xcworkspace file in Xcode.

    6. Right-click the project name, select Add files , then select the downloaded GoogleService-Info.plist file from your local computer, and make sure to select Copy items if needed.

    7. To do this, open the /ios/{projectName}/AppDelegate.mm file (AppDelegate.m in earlier versions of React Native).

    8. At the top of the file, import the Firebase SDK after #import "AppDelegate.h".

      #import
    9. In the didFinishLaunchingWithOptions method, add the following code at the top:

      - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        [FIRApp configure];
      }

FCM push code implementation

  1. Set up message notifications:

    React.useEffect(() => {
      const sub1 = messaging().onMessage(async (remoteMessage) => {
        // Process offline message notifications, such as printing logs and displaying messages.
        console.log("A new FCM message arrived!", JSON.stringify(remoteMessage));
      });
      return sub1;
    }, []);
  2. Initialize the Chat SDK:

    // Get the device token.
    fcmToken.current = await messaging().getToken();
    // Push settings.
    const pushConfig = new ChatPushConfig({
      deviceId: senderId,
      deviceToken: fcmToken.current,
    });
    // Configure push settings in the ChatOptions class.
    let o = new ChatOptions({
      autoLogin: false ,
      appKey: appKey,
      pushConfig: pushConfig,
    });
    // Execute settings and initialize the IM SDK.
    ChatClient.getInstance()
      . heat ( o )
      .then(() => {
        // Initialization successful.
      })
      .catch((error) => {
        // Initialization failed and error message is returned.
      });
  3. Log in to the server:

    // Log in to the server using user ID and token.
    ChatClient.getInstance()
      .loginWithAgoraToken(username, token)
      .then(() => {
        // Login successful.
      })
      .catch((reason) => {
        // Login failed, return error message.
      });
  4. Send the device token to the server:

    // Send device token to the server.
    ChatClient.getInstance()
      .updatePushConfig(
        new ChatPushConfig({ deviceId: senderId, deviceToken: fcmToken.current })
      )
      .then(() => {
        // Sent successfully.
      })
      .catch((reason) => {
        // Sending failed, returning error information.
      });

Test FCM push

After integrating and enabling FCM, you can test whether the push feature is successfully integrated.

Make sure your test device meets the following conditions:

  • Uses foreign IP addresses to establish connections.
  • Supports Google GMS services (Google Mobile Services).
  • Can access Google network services; otherwise, the device won't be able to receive push notifications from the FCM service.

For more reliable testing, use a physical device.

Test push notifications

  1. Log in to the app on your device and confirm that the device token is successfully bound.

    You can check the log or call RESTful API for getting user details to confirm whether the device token is successfully bound. If successful, there will be a pushInfo field under the entities field, and pushInfo will have relevant information such as device_Id, device_token, notifier_name, and others.

  2. Enable app notification bar permissions.

  3. Kill the application process.

  4. Send a test message in the Agora Console.

    Select Operation Management > User in the left navigation bar. On the Users page, select Send Admin Message in the Action column for the corresponding user ID. In the dialog box that pops up, select the message type, enter the message content, and then click Send .

    In the Push Certificate page, in the Action column of each certificate, click More and Test will appear. This is to directly call the third-party interface to push. The message sending test in the Users page first calls the Chat message sending interface and then the third-party interface when the conditions are met (that is, the user is offline, the push certificate is valid and bound to the device token).

  5. Check your device to see if it has received the push notification.

Troubleshooting

In case of issues, take the following steps:

  1. Check whether FCM push is correctly integrated or enabled:

    Select Operation Management > User in the left navigation bar. On the User Management page, select Push Certificate in the Action column for the corresponding user ID. In the pop-up box, check whether the certificate name and device token are displayed correctly.

  2. Check whether the correct FCM certificate is uploaded in the Agora Console.

  3. Check whether the message is pushed in the chat room. The chat room does not support offline message push.

  4. Check if the device supports GMS.