Developer Guide

Push Integration

To send push notification campaigns, LightCDP needs to know which device tokens belong to which of your users. Your backend reports those tokens to CDP through the public push-device API.

Overview

Token registration is server-to-server. The mobile app never talks to CDP directly:

text
Mobile app ──(token, signed-in user)──► Your backend ──POST /api/public/v1/push/devices──► LightCDP
                                         (holds the push token API key)

Push campaign ──► LightCDP looks up the user's devices ──► FCM / APNs ──► Mobile app
  1. The app obtains a token
    From Firebase Cloud Messaging (Android, or iOS via FCM) or directly from APNs (iOS).
  2. The app sends the token to your backend
    Through your own API, together with the signed-in user (if any).
  3. Your backend registers it with CDP
    POST /api/public/v1/push/devices with external_user_id = your user ID.
  4. Campaigns reach the user's devices
    A push campaign's Send to user property is matched against external_user_id to find the devices to send to.
MethodPathUse it whenLimit
POST /api/public/v1/push/devices The app gets or refreshes a token, the user signs in, or the notification setting changes 1–500 devices
POST /api/public/v1/push/devices/unbind The user signs out 1–500 devices
POST /api/public/v1/push/devices/remove The app knows a token is no longer valid (replaced, app uninstalled) 1–500 devices
POST /api/public/v1/push/devices/remove-user The user deletes their account or asks for their data to be deleted 1–100 users

Prerequisites

Set these up in the CDP admin panel before calling the API:

  1. A Mobile Push provider
    Under Channels, add a Mobile Push provider with your credentials: a Firebase service account JSON (FCM) and/or an APNs Auth Key (.p8, Key ID, Team ID) for sending to iOS directly through APNs. One provider can serve several apps.
  2. A push app and its App ID
    Under System → App Settings, add your app and choose its App ID (for example shop_a). If iOS sends directly through APNs, also enter the iOS Bundle ID. The App ID cannot be changed later - it is the app_id you send with every device.
  3. A push token API key
    Adding the push app also creates its first API key: the key and its secret are shown once, right after the app is created - copy them or download the JSON and store them securely on your backend. Each key belongs to exactly one push app. To add more keys (for example for a second backend), open the app under System → App Settings and click Add API key.
⚠️
Not the API Integration screen Data sources → API Integration creates Raw data keys only. A Raw data key is rejected by the push endpoints with 403 WrongWriteKeyType, and a push token key is rejected by the raw-data endpoints the same way. If your backend does both, use two keys. Push token keys are listed, added, revoked and deleted on their push app's page (System → App Settings → your app → API keys).

Authentication

Every request uses HTTP Basic Authentication with the push token API key:

http
Authorization: Basic <base64(api_key:secret_key)>
Content-Type: application/json
bash
echo -n "your_push_api_key:your_push_secret_key" | base64
🔒
Keep the key on your backend - never in the mobile app Anything shipped inside an app binary can be extracted. A leaked key would let anyone register tokens to any of your users. The app sends its token to your API; only your backend calls CDP.

Authentication is checked before the request body: a missing or invalid key answers 401, and a key of the wrong purpose answers 403, even if the body is also invalid. Each item's app_id must be one of the apps the key is allowed to use; otherwise that item is rejected with APP_NOT_ALLOWED (see Response).

Register Devices

Endpoint: POST /api/public/v1/push/devices
Registers or refreshes 1–500 devices per request (also usable for a bulk import of existing tokens).

  • Upsert on (app_id, token), last write wins. Re-registering a token with a different external_user_id moves the token to that user. A token that was INVALID becomes ACTIVE again.
  • If the same (app_id, token) appears twice in one request, the last item wins.
  • external_user_id is trimmed and otherwise stored as-is. null or omitted means the device is not signed in: it is stored, but no campaign reaches it.
  • Credentials are not checked at registration. If the provider used by a campaign has no credential for the token's transport, the problem appears when the campaign sends.

Request Body Reference

The body is { "devices": [ ... ] } with 1–500 items. Each item:

FieldTypeRequiredConstraintsDescription
app_id string REQUIRED 1–100 chars The App ID of the push app (System → App Settings).
token string REQUIRED 1–4096 chars The FCM registration token, or - with transport APNS - the APNs device token as hex (even length, at most 200 chars).
platform string REQUIRED IOS | ANDROID The device's operating system.
transport string REQUIRED FCM | APNS Where the token came from. ANDROID accepts only FCM; iOS can use either.
apns_environment string | null OPTIONAL PRODUCTION | SANDBOX Transport APNS only (ignored for FCM). SANDBOX for debug builds run from Xcode, PRODUCTION for TestFlight / App Store builds. Omitted = PRODUCTION, so only debug builds need to send it. The environment belongs to the token, not to the provider: the two builds get different tokens, and each one only works on its own APNs server.
external_user_id string | null OPTIONAL ≤ 255 chars The user ID in your system. Must equal the value of the user property that push campaigns use as Send to. null / omitted = not signed in.
notification_enabled boolean OPTIONAL default true false when the user turned notifications off in the OS settings. Such devices receive no campaigns.
device_id string | null OPTIONAL ≤ 255 chars Your own device identifier, for display.
app_version string | null OPTIONAL ≤ 50 chars For example 3.2.1.
os_version string | null OPTIONAL ≤ 50 chars For example 17.5.
locale string | null OPTIONAL ≤ 35 chars For example ja-JP.
timezone string | null OPTIONAL ≤ 64 chars For example Asia/Tokyo.
ℹ️
external_user_id must match "Send to" A push campaign picks a user property as Send to (for example a user_id property you send to CDP as raw data). CDP compares that property's value with external_user_id exactly, after trimming. If they use different IDs - or different formats of the same ID - the campaign finds no device for the user.

Example

bash
CDP_API_URL="https://<your-cdp-api-host>"
CREDENTIALS=$(echo -n "your_push_api_key:your_push_secret_key" | base64)

curl -X POST "${CDP_API_URL}/api/public/v1/push/devices" \
  -H "Authorization: Basic ${CREDENTIALS}" \
  -H "Content-Type: application/json" \
  -d '{
    "devices": [
      {
        "app_id": "shop_a",
        "token": "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90",
        "platform": "IOS",
        "transport": "APNS",
        "apns_environment": "PRODUCTION",
        "external_user_id": "12345",
        "notification_enabled": true,
        "app_version": "3.2.1",
        "os_version": "17.5",
        "locale": "ja-JP",
        "timezone": "Asia/Tokyo"
      },
      {
        "app_id": "shop_a",
        "token": "fcm-registration-token",
        "platform": "ANDROID",
        "transport": "FCM",
        "external_user_id": "67890"
      }
    ]
  }'
javascript
// Node.js 18+ (built-in fetch). Runs on YOUR backend, never in the app.
const CDP_API_URL = 'https://<your-cdp-api-host>';
const credentials = Buffer.from(
  `${process.env.CDP_PUSH_API_KEY}:${process.env.CDP_PUSH_SECRET_KEY}`,
).toString('base64');

async function cdpPush(path, body) {
  const res = await fetch(`${CDP_API_URL}/api/public/v1/push/devices${path}`, {
    method: 'POST',
    headers: {
      Authorization: `Basic ${credentials}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(10_000),
  });
  const data = await res.json();
  if (!res.ok) {
    throw Object.assign(new Error(`${res.status} ${data.error}: ${data.message ?? ''}`), {
      status: res.status,
      body: data,
    });
  }
  return data; // { accepted, rejected: [{ index, code, message }] }
}

// Called by your own endpoint when the app reports its token
async function registerDevice({ token, platform, transport, userId, notificationsOn }) {
  const result = await cdpPush('', {
    devices: [{
      app_id: 'shop_a',
      token,
      platform,                       // 'IOS' | 'ANDROID'
      transport,                      // 'FCM' | 'APNS'
      external_user_id: userId ?? null,
      notification_enabled: notificationsOn,
    }],
  });
  for (const r of result.rejected) {
    console.warn(`device #${r.index} rejected: ${r.code} - ${r.message}`);
  }
  return result;
}

With the Node.js SDK (@cdp/sdk-node) the same call is one method. The SDK validates the body locally, retries transient errors, and also offers unbindDevices, removeDevices and removeUsers. Push uses its own client class, CdpPushClient - CdpClient is for raw data with a raw-data key.

javascript
// Node.js SDK - same request, validated and retried by the client
import { CdpPushClient } from '@cdp/sdk-node';

const push = new CdpPushClient({
  host: 'https://<your-cdp-api-host>',
  writeKey: process.env.CDP_PUSH_API_KEY,     // a push token key
  writeSecret: process.env.CDP_PUSH_SECRET_KEY,
});

const result = await push.registerDevices([
  { app_id: 'shop_a', token, platform: 'IOS', transport: 'FCM', external_user_id: userId ?? null },
]);
// result = { accepted, rejected: [{ index, code, message }] }

Unbind (Logout)

Endpoint: POST /api/public/v1/push/devices/unbind
Call it when the user signs out. The token stays ACTIVE but is detached from its user (external_user_id becomes null), so it stops receiving campaigns. When someone signs in on the device again, register the token again with their external_user_id.

FieldTypeRequiredConstraintsDescription
devices array REQUIRED 1–500 items Each item is { "app_id", "token" } (same constraints as for register).
bash
curl -X POST "${CDP_API_URL}/api/public/v1/push/devices/unbind" \
  -H "Authorization: Basic ${CREDENTIALS}" \
  -H "Content-Type: application/json" \
  -d '{ "devices": [ { "app_id": "shop_a", "token": "fcm-registration-token" } ] }'
javascript
// cdpPush() from the register example
await cdpPush('/unbind', { devices: [{ app_id: 'shop_a', token }] });

A token CDP does not know is still counted as accepted, so retries are safe.

Remove Devices

Endpoint: POST /api/public/v1/push/devices/remove
Marks the tokens INVALID (reason CLIENT_REMOVED) - for example when the app knows a token was replaced. INVALID tokens receive nothing. The body is the same as for unbind: { "devices": [ { "app_id", "token" } ] }, 1–500 items. Idempotent.

bash
curl -X POST "${CDP_API_URL}/api/public/v1/push/devices/remove" \
  -H "Authorization: Basic ${CREDENTIALS}" \
  -H "Content-Type: application/json" \
  -d '{ "devices": [ { "app_id": "shop_a", "token": "old-fcm-registration-token" } ] }'
javascript
await cdpPush('/remove', { devices: [{ app_id: 'shop_a', token: oldToken }] });

Registering the same token again later makes it ACTIVE again.

Remove a User's Devices

Endpoint: POST /api/public/v1/push/devices/remove-user
Permanently deletes every token of each (app_id, external_user_id) pair. Use it when a user deletes their account or asks for their personal data to be deleted.

FieldTypeRequiredConstraintsDescription
users array REQUIRED 1–100 items Each item is { "app_id", "external_user_id" }; app_id 1–100 chars, external_user_id 1–255 chars.
bash
curl -X POST "${CDP_API_URL}/api/public/v1/push/devices/remove-user" \
  -H "Authorization: Basic ${CREDENTIALS}" \
  -H "Content-Type: application/json" \
  -d '{ "users": [ { "app_id": "shop_a", "external_user_id": "12345" } ] }'
javascript
const { deleted_devices } = await cdpPush('/remove-user', {
  users: [{ app_id: 'shop_a', external_user_id: '12345' }],
});

The response adds deleted_devices. A user without devices is still accepted (deleted_devices grows by 0), so the call is safe to repeat.

Response

All four endpoints answer HTTP 200 once the body is valid. Validation is per item: an item that fails a check is listed in rejected and the rest of the request is still applied - one bad token never loses the other 499.

json
{
  "accepted": 1,
  "rejected": [
    { "index": 1, "code": "APP_NOT_FOUND", "message": "No push app with app_id \"shop_b\"." }
  ]
}
FieldTypeDescription
acceptednumberNumber of items applied (items sent minus items rejected).
rejectedarray{ index, code, message } per rejected item; index is the item's position (0-based) in the request array.
deleted_devicesnumber/remove-user only - number of tokens deleted.

Per-item rejection codes

CodeEndpointsCauseFix
APP_NOT_ALLOWED all The API key is not allowed to use this app_id Use an API key of that push app - each key works for its own app only
APP_NOT_FOUND all No push app with this app_id Check the App ID under System → App Settings (case-sensitive)
PLATFORM_TRANSPORT_MISMATCH register platform: ANDROID with transport: APNS Android tokens always use FCM
INVALID_TOKEN_FORMAT register An APNS token that is not hex, has an odd length or exceeds 200 chars Convert the APNs deviceToken bytes to a hex string; if the token comes from Firebase, send transport: FCM
⚠️
Always inspect rejected A 200 does not mean every item was stored. Log rejected items - they are configuration problems that retrying will not fix.

Error Handling

Request-level errors reject the whole request:

StatusErrorCauseFix
401 Unauthorized Missing Authorization header, malformed credentials, or the key is unknown, revoked or its secret does not match Send Basic base64(api_key:secret_key); check the key is still active
403 WrongWriteKeyType The key is a Raw data key, not a push token key Use the push app's API key (System → App Settings → your app → API keys)
400 ValidationError Body shape is wrong: empty or too many items (over 500 devices / 100 users), missing required field, wrong type or enum value, field too long See the issues array (path, message, code) in the response
5xx - Temporary server-side problem Retry with exponential backoff

The request body is limited to 1 MB; larger bodies are refused, so keep within the item limits above (500 devices or 100 users per request) and split bigger batches.

Every endpoint is idempotent - register is an upsert, and unbind / remove / remove-user are no-ops for tokens or users CDP does not know - so a request can be retried safely. Do not retry 400, 401 or 403.

javascript
async function cdpPushWithRetry(path, body, maxRetries = 3) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await cdpPush(path, body);
    } catch (err) {
      const retryable = !err.status || err.status >= 500 || err.status === 429;
      if (!retryable || attempt >= maxRetries) throw err;
      await new Promise(r => setTimeout(r, 2 ** attempt * 500));
    }
  }
}

Token Lifecycle & Sending

TopicBehaviour
Expiry Tokens have no time-based expiry. A token becomes INVALID only when FCM / APNs report it dead during a send, or when you call /remove.
Clean-up INVALID tokens are deleted 30 days after they became INVALID. Tokens not bound to a user are deleted 30 days after your backend last registered them.
Who receives a campaign A device receives campaigns when its token is ACTIVE, notification_enabled is true and it is bound to an external_user_id.
Devices per user With the campaign's device target All devices, CDP sends to the user's 5 most recently seen devices. With Most recent device only, only to the newest one.
Last seen Each register call refreshes the device's Last seen time (at most once every 24 hours for an unchanged token), which decides which devices are "most recent".
ℹ️
Register on every app open Calling register on every app open (in addition to token refresh and login) keeps Last seen accurate, so the 5-device limit picks the phones people actually use. Sending still works without it.

Integration Checklist

In CDP

  1. Add a Mobile Push provider
    Under Channels, with your FCM service account JSON and/or APNs .p8 key.
  2. Add the push app
    Under System → App Settings: choose the App ID (cannot be changed later) and, for APNs direct, the iOS Bundle ID.
  3. Save the push app's API key
    It is shown once, right after the app is created. Store it on your backend only; add more keys on the app's page if needed.
  4. Make sure the "Send to" user property exists
    The user ID you send as external_user_id must also reach CDP as a user property (for example through raw data), so campaigns can use it as Send to.

In your backend

  1. Expose an endpoint for the app
    The app sends its token, platform, transport and notification setting; your backend adds the signed-in user's ID.
  2. Register when the app first gets a token, whenever the token changes, when the user signs in, when the notification setting changes, and (recommended) on every app open.
  3. Unbind when the user signs out.
  4. Remove-user when the user deletes their account or asks for data deletion.
  5. Log rejected items and retry only network errors and 5xx.

In the mobile app

SetupGet the tokenSend as
Android (FCM) Add the Firebase Messaging SDK; on Android 13+ request the POST_NOTIFICATIONS permission. Use FirebaseMessaging.getToken() and onNewToken(). platform: ANDROID, transport: FCM
iOS via FCM Upload your APNs Auth Key to Firebase, add the Firebase SDK, enable Push Notifications, call requestAuthorization + registerForRemoteNotifications. Use Messaging.messaging().token. platform: IOS, transport: FCM
iOS via APNs direct Enable Push Notifications, call requestAuthorization + registerForRemoteNotifications; in didRegisterForRemoteNotificationsWithDeviceToken convert the token bytes to hex. platform: IOS, transport: APNS, apns_environment: SANDBOX (Xcode debug) / PRODUCTION (TestFlight, App Store)
✅
Verify end to end After registering a test device, open the push app under System → App Settings and its Devices list to see it, then use a push campaign's Test send with your own external_user_id.

When a user taps a notification, read data.deep_link to open the right screen. Images on iOS need a Notification Service Extension in the app; without it the notification still shows, without the image.