Mobile SDK

Mobile SDK

Send push notifications to Android and iOS apps via Firebase Cloud Messaging (FCM). Notirix acts as a unified backend — one API for all platforms.

FCM Setup

Mobile push is powered by Firebase Cloud Messaging. You need a Firebase project and a service account key to connect it to Notirix.

1
Create a Firebase project at console.firebase.google.com and enable Cloud Messaging.
2
Go to Project Settings → Service Accounts and click Generate new private key. Download the JSON file.
3
In Notirix Admin, open Settings → Integrations → FCM and paste the contents of the JSON file.
⚠️
Keep the service account JSON secret — it has full send access to your Firebase project. Never commit it to source control.

Android

Add the Firebase SDK to your Android project, then register the FCM token with Notirix.

Dependencies

gradle
// app/build.gradle
dependencies {
    implementation 'com.google.firebase:firebase-messaging:23.4.0'
}

Register token

Call this once after the user opens the app (or after login if you want to attach a user ID):

kotlin
import com.google.firebase.messaging.FirebaseMessaging
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import org.json.JSONObject

FirebaseMessaging.getInstance().token.addOnSuccessListener { token ->
    val body = JSONObject().apply {
        put("deviceToken", token)
        put("platform",    "android")
        put("externalId",  currentUserId)   // optional — your user ID
        put("externalIdHash", currentUserIdHash) // from your backend, if identity verification is on
    }
    val request = Request.Builder()
        .url("https://push.notirix.com/api/apps/APP_ID/mobile/register")
        .addHeader("X-API-Key", "YOUR_PUBLIC_KEY")
        .post(RequestBody.create("application/json".toMediaType(), body.toString()))
        .build()
    OkHttpClient().newCall(request).enqueue(/* callback */)
}
💡
externalId is your internal user identifier (e.g. database ID or email). Pass it to link the push token to a user so you can send targeted pushes via the API. Registering an anonymous device again with an externalId after login carries its tags, events and journeys over to that user. Optional fields appVersion, locale and timezone are stored with the device.
ℹ️
Registering a known device without externalId (a launch before sign-in, an expired session) keeps it with the user it belongs to. On logout, unbind it explicitly: call register with "logout": true (and no externalId) — the device stays subscribed as an anonymous one and no longer gets the signed-out user's pushes. To stop all pushes on the device instead, call DELETE /api/apps/:appId/mobile/unregister with { "deviceToken": "…" } and the same public key.
⚠️
If identity verification is on for your app, send externalIdHash together with externalId — see Identity verification below.

Handle incoming messages

kotlin
class MyFirebaseService : FirebaseMessagingService() {

    override fun onMessageReceived(message: RemoteMessage) {
        val title   = message.notification?.title ?: message.data["title"] ?: return
        val body    = message.notification?.body  ?: message.data["body"]  ?: ""
        val clickUrl = message.data["url"]

        val intent = Intent(this, MainActivity::class.java).apply {
            clickUrl?.let { putExtra("open_url", it) }
        }
        val pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)

        NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(title)
            .setContentText(body)
            .setContentIntent(pi)
            .setAutoCancel(true)
            .build()
            .also { NotificationManagerCompat.from(this).notify(msgId, it) }
    }

    override fun onNewToken(token: String) {
        // re-register when token rotates
        registerWithNotirix(token)
    }
}

iOS

iOS push uses APNs under the hood. FCM bridges APNs → Notirix, so setup is the same on your backend. You only need to configure APNs inside Firebase.

APNs key in Firebase

1
In Apple Developer, create an APNs Auth Key (.p8 file).
2
Upload it in Firebase Console → Project Settings → Cloud Messaging → APNs Authentication Key.

Register token (Swift)

swift
import FirebaseMessaging
import UserNotifications

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions opts: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in }
    application.registerForRemoteNotifications()
    Messaging.messaging().delegate = self
    return true
}

extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        guard let token = fcmToken else { return }
        // POST to Notirix
        var req = URLRequest(url: URL(string: "https://push.notirix.com/api/apps/APP_ID/mobile/register")!)
        req.httpMethod = "POST"
        req.setValue("application/json", forHTTPHeaderField: "Content-Type")
        req.setValue("YOUR_PUBLIC_KEY",     forHTTPHeaderField: "X-API-Key")
        req.httpBody = try? JSONSerialization.data(withJSONObject: [
            "deviceToken": token,
            "platform":   "ios",
            "externalId": currentUserId,   // optional
            "externalIdHash": currentUserIdHash, // from your backend, if identity verification is on
        ])
        URLSession.shared.dataTask(with: req).resume()
    }
}
ℹ️
Make sure Push Notifications and Background Modes → Remote notifications are enabled in your Xcode project's Signing & Capabilities.

Images in notifications

iOS does not download notification images itself. For a push with an image Notirix sends mutable-content: 1 and the image URL in fcm_options.image; the app needs a Notification Service Extension that downloads it. The Firebase helper below does the work — or read fcm_options.image from userInfo in your own code. Without the extension the push arrives as before, without the image.

swift
// Xcode → File → New → Target → Notification Service Extension
// Podfile: target 'NotificationService' do pod 'FirebaseMessaging' end
import UserNotifications
import FirebaseMessaging

class NotificationService: UNNotificationServiceExtension {
    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest,
                             withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent
        guard let content = bestAttemptContent else { return contentHandler(request.content) }
        // Downloads fcm_options.image and attaches it to the notification
        Messaging.serviceExtension().populateNotificationContent(content, withContentHandler: contentHandler)
    }

    override func serviceExtensionTimeWillExpire() {
        if let handler = contentHandler, let content = bestAttemptContent { handler(content) }
    }
}
ℹ️
Image requirements: HTTPS, JPEG / PNG / GIF, up to 10 MB. Web push on iOS and in Safari never shows an image.

Identity verification

The public key ships inside your app, so anyone can extract it and register a device with someone else's externalId. With identity verification on, Notirix binds a device to an externalId only when the request also carries externalIdHash — a signature made by your backend with the app's identity secret (notirix_idv_…, Admin → Settings → Identity verification).

  • Your backend computes externalIdHash = hex(HMAC-SHA256(key = identity secret, message = externalId)) and returns it to the app, e.g. in the sign-in or profile response. Never put the secret into the app and never compute the hash on the device.
  • The app passes it in POST /api/apps/:appId/mobile/register next to externalId. Registrations without externalId (before sign-in) and "logout": true need no hash.
  • An externalId starting with anon: or mobile: is ignored in every mode — these prefixes name anonymous users on the server. The request is handled as if no externalId came, and a warning is written to the SDK logs.
  • Modes: off — nothing is checked (default); warn — accepted as before, a missing or wrong hash is written to the app's SDK Debug Logs; enforce — rejected with HTTP 400 { "errorCode": "IDENTITY_VERIFICATION_FAILED" } and the device is not bound to that user. Register again without externalId if the device should stay subscribed anonymously.
kotlin
// Your backend (Node.js), e.g. in the sign-in response
const externalIdHash = crypto
  .createHmac('sha256', process.env.NOTIRIX_IDENTITY_SECRET) // 'notirix_idv_…'
  .update(user.id)
  .digest('hex')
res.json({ userId: user.id, notirixHash: externalIdHash })

// The app (Kotlin) — passes what the backend returned
val body = JSONObject().apply {
    put("deviceToken",    token)
    put("platform",       "android")
    put("externalId",     session.userId)
    put("externalIdHash", session.notirixHash)
}
💡
Ship app versions that send the hash first, switch the mode to warn and watch the unverified counter on the settings card, then switch to enforce. Older app builds that do not send the hash stop binding signed-in users once enforce is on.

Event tracking

Report delivery and clicks to Notirix so they show up in message analytics. Web push does this automatically; in a mobile app you send the events yourself to POST /api/apps/:appId/mobile/event with the public key, passing the deliveryId from the push data payload. Without these events deliveries stay sent: the device page in the admin panel and message stats show no deliveries, clicks or CTR for the app.

kotlin
// Example: report "clicked" when user taps a notification.
// Every Notirix push carries deliveryId and apiBaseUrl in its data payload.
val deliveryId = message.data["deliveryId"] ?: return
val apiBaseUrl = message.data["apiBaseUrl"] ?: "https://push.notirix.com"

val request = Request.Builder()
    .url("$apiBaseUrl/api/apps/APP_ID/mobile/event")
    .addHeader("X-API-Key", "YOUR_PUBLIC_KEY")
    .post(RequestBody.create(
        "application/json".toMediaType(),
        JSONObject().apply {
            put("deliveryId", deliveryId)
            put("event",      "clicked")
        }.toString()
    ))
    .build()
OkHttpClient().newCall(request).enqueue(/* callback */)
EventWhen to send
deliveredFCM delivery receipt received (onMessageReceived)
clickedUser taps the notification