Overview

Firebase Cloud Messaging (FCM) tokens are essential for delivering push notifications to your customers’ devices. This guide covers the complete lifecycle of FCM token management in Masivo, including user registration, migration scenarios, and proper token cleanup when users opt out or tokens expire.

FCM tokens can change periodically due to app updates, device restores, or Firebase SDK refreshes. Always implement proper token refresh handling in your application.

1. User Registration

Understanding FCM Token Registration

When registering users for push notifications, you need to associate their FCM token with their customer profile in Masivo. This enables targeted messaging and automatic subscription to audience topics.

Register a New Device Token

Use the PATCH /customers/{id}/devices endpoint to register or update a customer’s device token:

const customerId = "your-customer-id";
const fcmToken = "duPXivAiS_uR1o2WGFb5fb:APA91bHYGH0sQcTWtJwSPTRB...";

const payload = {
  device_token: fcmToken,
  device_info: {
    platform: "android",
    model: "SM-S918B",
    osVersion: "34"
  }
};

const response = await fetch(
  `https://app.masivo.ai/api/storefront/v1/customers/${customerId}/devices`,
  {
    method: "PATCH",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify(payload)
  }
);

if (response.ok) {
  const result = await response.json();
  console.log("Device registered successfully:", result.message);
  // Returns: "FCM token registered successfully"
} else {
  const error = await response.json();
  console.error("Registration failed:", error.details);
}

What Happens During Registration

When you register a device token, Masivo automatically:

  1. Sets Token Expiration: Calculates expires_at based on your account’s device_token_ttl setting
  2. Unsubscribes from Previous Topics: Removes the token from any existing audience subscriptions
  3. Updates Customer Record: Stores the device token in the customer’s devices array
  4. Subscribes to Current Audiences: Automatically subscribes the token to topics for audiences the customer belongs to
  5. Updates Device Token Mapping: Calls the update_customer_device_token stored procedure

Token Expiration Configuration

Token expiration is controlled by your account’s marketing automation settings:

  • device_token_ttl: Number of days before token expires
  • Marketing Automation: Must be enabled in account settings

If marketing automation is not enabled or device_token_ttl is not configured, the registration will fail with a 400 error: “Marketing automation is not enabled, enable it in the marketing_automation settings”

2. Token Unregistration and Expiration

Unregister a Device Token

Use the DELETE /customers/{id}/devices endpoint to remove a device token:

const unregisterDeviceToken = async (
  customerId: string,
  deviceToken: string
) => {
  const response = await fetch(
    `https://app.masivo.ai/api/storefront/v1/customers/${customerId}/devices?device_token=${encodeURIComponent(deviceToken)}`,
    {
      method: "DELETE",
      headers: {
        Authorization: `Bearer ${accessToken}`,
        "Content-Type": "application/json",
        "x-account-id": "your-account-id"
      }
    }
  );

  if (response.ok) {
    const result = await response.json();
    console.log("Token unregistered:", result.message);
    // Returns: "FCM token unregistered successfully"
    return result;
  } else {
    const error = await response.json();
    throw new Error(`Unregistration failed: ${error.details}`);
  }
};

What Happens During Unregistration

When you unregister a device token, Masivo automatically:

  1. Clears Device Array: Sets the customer’s devices array to empty []
  2. Unsubscribes from Topics: Removes the token from all audience topic subscriptions
  3. Updates Device Token Mapping: Calls the update_customer_device_token stored procedure to clean up mappings

Handling User Opt-out

Implement a user-friendly opt-out flow:

const handlePushNotificationOptOut = async (customerId: string) => {
  try {
    // Get current FCM token
    const currentToken = await messaging().getToken();

    // Unregister from Masivo
    await unregisterDeviceToken(customerId, currentToken);

    // Update local preferences
    await AsyncStorage.setItem("pushNotificationsEnabled", "false");

    console.log("Successfully opted out of push notifications");
  } catch (error) {
    console.error("Error during opt-out:", error);
  }
};

Automatic Token Expiration

Masivo automatically handles token expiration based on your configured TTL:

  • Tokens are created with an expires_at timestamp
  • Expired tokens are automatically excluded from push notification targeting
  • No manual cleanup is required for expired tokens

Audience Topic Management

Masivo automatically manages FCM topic subscriptions:

  • Topic Format: {account_id}_audience_{audience_id}
  • Auto-Subscribe: When registering a token, it’s automatically subscribed to topics for audiences the customer belongs to
  • Auto-Unsubscribe: When unregistering a token, it’s removed from all topic subscriptions

Conclusion

Proper FCM token management in Masivo involves understanding the automatic topic subscription system, token expiration handling, and the relationship between customers and audiences. By following this guide, you’ll ensure reliable message delivery while leveraging Masivo’s built-in audience segmentation capabilities.

For more information about push notifications in Masivo, see the Push Notification Integration Guide.