# Introduction > What the Herald mobile SDK does and how it works with Herald decisions. The Herald SDK is a library for iOS and Android apps. It collects first-party data from your app, registers devices for push notifications, and shows content cards and in-app messages. | If you want to… | Start here | |---|---| | **iOS developer:** add the SDK, identify users and register for push | [Quickstart: iOS](/docs/overview/quickstart-ios) | | **Android developer:** add the SDK, identify users and register for push | [Quickstart: Android](/docs/overview/quickstart-android) | | **Backend developer:** send users and events, ask for a decision or export results | [Server API](/docs/reference/server-api) | | **Backend developer:** send a message from your backend | [Send API](/docs/reference/send-api) | | **Marketer:** write content cards and in-app messages | [Create cards](/docs/content-cards/authoring) and [Create in-app messages](/docs/in-app-messages/authoring) | | **Marketer:** see how Herald picks and checks each send | [How delivery works](/docs/concepts/how-delivery-works) | | **Admin:** verify users and handle deletion requests | [Security and identity verification](/docs/data-and-privacy/security-and-identity-verification) and [User data deletion](/docs/data-and-privacy/user-data-deletion) | | **Admin:** connect your other tools | [Integrations overview](/docs/integrations/overview) | ## How it fits with Herald Herald decides which message each user gets, on which channel and at what time, and learns from the result. The SDK is how those decisions reach your mobile app, and how your app reports back what users did. - **Data in.** The SDK sends events, user attributes and device data to Herald. That data feeds the user profile each decision is based on. - **Messages out.** When Herald picks a push notification, content card or in-app message for a user, the SDK registers the device for push, fetches the user's cards and messages, and displays them. - **Outcomes back.** Impressions, clicks and dismissals are sent to Herald and linked to the decision that produced the message, so later decisions improve. ## Architecture 1. **Your app** calls the SDK to identify users and track events. 2. **The SDK** queues that data on the device and sends it to Herald in batches. 3. **Herald** stores the data, makes decisions and records which message each user should get. 4. **Delivery** happens through Apple Push Notification service (APNs) and Firebase Cloud Messaging (FCM) for push, and through the in-app feed the SDK fetches for content cards and in-app messages. ## Next steps - [Platform support](/docs/overview/platform-support) - [Quickstart: iOS](/docs/overview/quickstart-ios) - [Quickstart: Android](/docs/overview/quickstart-android) Source: https://heraldsdk.com/docs/overview/introduction.md --- # Platform support > The operating systems, toolchains and modules each Herald SDK supports, the other platforms, and how to install them. The Herald SDK is a native library for iOS and a set of modules for Android. Both platforms expose the same calls, with the same names and the same argument order. ## Support matrix | | iOS | Android | |---|---|---| | Minimum OS | iOS 16 | Android 8.0 (API level 26) | | Language | Swift. The package builds in Swift 6 language mode; your app can use Swift 5 or 6. | Kotlin (built with Kotlin 2.0.21), Java 17 bytecode | | Build tools | Xcode 16 or later (Swift tools version 6.0) | Android Gradle Plugin 8 (built with 8.7), compileSdk 35 | | Package format | Swift Package Manager | Gradle modules (AAR) from JitPack | | Default UI views | SwiftUI | Jetpack Compose | | Push service | Apple Push Notification service (APNs) | Firebase Cloud Messaging (FCM) | | Current version | 0.6.0 | 0.6.0 | ## Modules | Platform | Module | What it does | Runtime dependencies | |---|---|---|---| | iOS | `HeraldSDK` | Identity, events, attributes, sessions, push token registration, push open handling, content card data, in-app message rules | Apple system frameworks only | | iOS | `HeraldUI` | Default content card feed and in-app message views in SwiftUI | `HeraldSDK` | | iOS | `HeraldNotificationService` | Images and action buttons in push notifications, from a Notification Service Extension | Foundation and UserNotifications only, so it links into an app extension | | iOS | `HeraldLiveActivity` | Live Activity attributes and widget, from a widget extension | Apple system frameworks only | | iOS | `HeraldGeofence` | Opt-in geofence monitoring (0.7.0, not released yet). See [Geofences](/docs/concepts/geofences). | `HeraldSDK`, CoreLocation | | iOS | `HeraldPushStory` | Push stories, from a Notification Content Extension (0.7.0+) | `HeraldNotificationService` and Apple system frameworks only | | Android | `herald-core` | The same responsibilities as `HeraldSDK` | `kotlinx-coroutines-android` 1.8.1 | | Android | `herald-ui` | Default content card feed and in-app message views in Compose | Compose BOM 2024.09.02, Material 3, `activity-compose` 1.9.2 | | Android | `herald-fcm` | FCM messaging service, token sync, notification display, Live Updates | `firebase-messaging` 24.0.3 | | Android | `herald-geofence` | Opt-in geofence monitoring (0.7.0, not released yet). Adds no permissions. See [Geofences](/docs/concepts/geofences). | `play-services-location` 21.3.0 | `herald-core` adds three permissions to your merged manifest: `INTERNET`, `ACCESS_NETWORK_STATE` and `POST_NOTIFICATIONS`. From 0.7.0, `herald-fcm` adds `POST_PROMOTED_NOTIFICATIONS` for [Live Updates](/docs/live-activities/android). ## Other platforms | Platform | Status | |---|---| | React Native | Available, installed from git: `@herald/react-native`, a wrapper over the iOS and Android SDKs. See [Quickstart: React Native](/docs/overview/quickstart-react-native). | | Flutter | Available, installed from git. The `herald_flutter` plugin wraps the native SDKs. See [Install on Flutter](/docs/overview/install-flutter). | | Unity | Available from git: the `com.herald.sdk` package wraps the iOS and Android SDKs. See [Install on Unity](/docs/overview/install-unity). | | Web | Planned. Browser push through Herald's web push script works today. | ## Install Both SDKs are open source under the Apache License 2.0. The iOS package is at `https://github.com/ender1311/herald-ios` and the Android modules are at `https://github.com/ender1311/herald-android`, published through JitPack. :::tabs ::tab ios In Xcode, choose **File > Add Package Dependencies**, enter `https://github.com/ender1311/herald-ios` and add the `HeraldSDK` and `HeraldUI` libraries to your app target. Add `HeraldNotificationService` to your Notification Service Extension target only. In a `Package.swift` manifest: ```swift dependencies: [ .package(url: "https://github.com/ender1311/herald-ios", from: "0.6.0"), ], targets: [ .target(name: "Lumen", dependencies: [ .product(name: "HeraldSDK", package: "herald-ios"), .product(name: "HeraldUI", package: "herald-ios"), ]), ] ``` ::tab android ```kotlin // settings.gradle.kts dependencyResolutionManagement { repositories { google() mavenCentral() maven { url = uri("https://jitpack.io") } } } // app/build.gradle.kts dependencies { implementation("com.github.ender1311.herald-android:herald-core:0.6.0") implementation("com.github.ender1311.herald-android:herald-ui:0.6.0") implementation("com.github.ender1311.herald-android:herald-fcm:0.6.0") } ``` ::: Version numbers follow the policy on [Versioning and support](/docs/operations/versioning-and-support). ## Next - [Quickstart: iOS](/docs/overview/quickstart-ios) - [Install on Flutter](/docs/overview/install-flutter) Source: https://heraldsdk.com/docs/overview/platform-support.md --- # Quickstart: iOS > Add the Herald SDK to an iOS app, identify a user, track an event, register for push and show content cards. This guide takes an iOS app from no SDK to a verified first event, a registered push token and the default content card feed. It takes about 30 minutes. :::prereq - An app that targets iOS 16 or later, built with Xcode 16 or later. - A Herald sending connection with an app key. In Herald, open **Settings > Sending**, open the connection and find the **Mobile SDK** card. If it has no key, click **Generate app key**. The card also shows your endpoint URL. - A backend route that returns a user token for the signed-in user, unless identity verification is **Off**. See [Users and identity](/docs/concepts/users-and-identity#user-tokens-and-verification-modes). - For push: an APNs auth key on the connection. See [iOS push setup](/docs/push-notifications/ios-setup). ::: ## 1. Add the package In Xcode, choose **File > Add Package Dependencies**, enter `https://github.com/ender1311/herald-ios`, choose version 0.6.0 or later, and add the `HeraldSDK` and `HeraldUI` libraries to your app target. For a `Package.swift` manifest, [Platform support](/docs/overview/platform-support#install) has the lines. ## 2. Configure the SDK at launch Call `Herald.configure` once, as early as possible. Debug logging helps while you integrate; remove it before release. ```swift import SwiftUI import UserNotifications import HeraldSDK import HeraldUI @main struct LumenApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { HomeView() } } } final class AppDelegate: NSObject, UIApplicationDelegate, @preconcurrency UNUserNotificationCenterDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!) { options in options.logLevel = .debug } Herald.useDefaultInAppUI() // default in-app message views UNUserNotificationCenter.current().delegate = self return true } } ``` Every SDK call returns at once and runs in the background, in the order you made it. Calls made before `configure` are kept and applied once it runs. ## 3. Identify the user After sign-in, call `identify` with your stable External ID, then `setUserToken` with the token your backend returns. Call them in that order: identifying a different user clears the previous token. ```swift func didSignIn(userId: String, userToken: String) { Herald.shared.identify(userId: userId, traits: ["plan": "free"]) Herald.shared.setUserToken(userToken) } ``` On sign-out, call `Herald.shared.reset()`. ## 4. Track an event ```swift Herald.shared.track("workout_completed", properties: ["minutes": 32, "type": "strength"]) ``` Events are queued on the device and sent in batches. [Events and attributes](/docs/concepts/events-and-attributes) lists the rules each call must follow. ## 5. Register for push Pass the APNs token to the SDK, ask for permission at a moment that makes sense to the user, and forward notification taps. ```swift extension AppDelegate { func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Herald.shared.setPushToken(deviceToken) } func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { Herald.shared.handleNotificationResponse(response) completionHandler() } } struct EnablePushButton: View { var body: some View { Button("Turn on workout reminders") { Task { _ = await Herald.shared.requestPushAuthorization() } } } } ``` `requestPushAuthorization()` shows the system prompt, registers with APNs when the user allows it, and records the push subscription. [iOS push setup](/docs/push-notifications/ios-setup) covers the APNs key, foreground display and later launches. ## 6. Show content cards `ContentCardFeed` from `HeraldUI` shows the signed-in user's cards, pinned first and then newest, and logs impressions, clicks and dismissals for you. ```swift struct HomeView: View { var body: some View { NavigationStack { ContentCardFeed() .navigationTitle("For you") } } } ``` To draw cards in your own views instead, see [Building a custom UI](/docs/content-cards/custom-ui). ## Verify it works 1. Run the app, sign in and log a workout. Send the app to the background: the SDK sends its queue as the app leaves the foreground. 2. In the Xcode console, filter for the subsystem `com.herald.sdk`. A line that starts with `Herald rejected a batch` means the request failed; anything else at debug level is normal traffic. 3. In Herald, open **Audience > Search users** and look up the External ID. The profile shows the traits you passed to `identify`, such as `plan`. 4. Have an agent send a content card to that user through the same connection. The card appears at the next session start, or right away if you call `Herald.shared.refreshContentCards()`. ## Troubleshooting - **One `Message sync needs a user token; waiting for setUserToken` debug line right after sign-in.** With verification **Required**, `identify` fetches messages before the token is set. It is harmless: `setUserToken` fetches again. Call `setUserToken` immediately after `identify`. A session-start in-app message can first show in the user's next session. A `Message sync failed with HTTP 401: Herald refused the user token` warning is different: the token the app sent is wrong. See [Error codes](/docs/reference/error-codes). - **`Herald rejected the app key: check the publishable key in configure`.** The app key is wrong, or the connection is not active. The SDK keeps the events and stops sending until the app launches again; fix the key in `configure`. - **`Herald needs a user token: call setUserToken`.** Identity verification is **Required** and the signed-in user's token is missing or wrong. The SDK keeps that user's events and sends them after the next `setUserToken`. - **The profile does not show the traits.** With verification set to **Optional**, a batch without a token is stored as anonymous and writes nothing to the profile. Call `setUserToken` after `identify`. - **`track ignored: name must not be empty`** or a similar line. The SDK checks every call against the server's limits and drops invalid calls on the device. Fix the call; nothing was sent. - **No cards.** Cards are fetched for identified users only. An agent send made before the user's device first reached Herald is suppressed, so send again after the app has run once. ## Next - [Users and identity](/docs/concepts/users-and-identity) - [iOS push setup](/docs/push-notifications/ios-setup) - [Content cards](/docs/content-cards/overview) Source: https://heraldsdk.com/docs/overview/quickstart-ios.md --- # Quickstart: Android > Add the Herald SDK to an Android app, identify a user, track an event, register for push and show content cards. This guide takes an Android app from no SDK to a verified first event, a registered push token and the default content card feed. It takes about 30 minutes. :::prereq - An app with `minSdk` 26 or higher that uses Jetpack Compose for the default views. - A Firebase project with your Android app registered, and its `google-services.json`. - A Herald sending connection with an app key. In Herald, open **Settings > Sending**, open the connection and find the **Mobile SDK** card. If it has no key, click **Generate app key**. The card also shows your endpoint URL. - A backend route that returns a user token for the signed-in user, unless identity verification is **Off**. See [Users and identity](/docs/concepts/users-and-identity#user-tokens-and-verification-modes). - For push: an FCM service account on the connection. See [Android push setup](/docs/push-notifications/android-setup). ::: ## 1. Add the modules Add the JitPack repository, then `herald-core`, `herald-ui` and `herald-fcm`, and apply the Google services plugin so Firebase starts. ```kotlin // settings.gradle.kts dependencyResolutionManagement { repositories { google() mavenCentral() maven { url = uri("https://jitpack.io") } } } // app/build.gradle.kts plugins { id("com.android.application") id("org.jetbrains.kotlin.android") id("com.google.gms.google-services") } dependencies { implementation("com.github.ender1311.herald-android:herald-core:0.6.0") implementation("com.github.ender1311.herald-android:herald-ui:0.6.0") implementation("com.github.ender1311.herald-android:herald-fcm:0.6.0") } ``` ## 2. Configure the SDK in your Application class Call `Herald.configure` once, in `Application.onCreate`. Calls made before `configure` are kept, up to 1,000, and applied in order once it runs. ```kotlin class LumenApplication : Application() { override fun onCreate() { super.onCreate() Herald.configure( this, appKey = "YOUR_APP_KEY", endpoint = "https://YOUR_HERALD_HOST", options = HeraldOptions(logLevel = LogLevel.DEBUG), ) HeraldInAppPresenter.install() // default in-app message views HeraldNotifications.createDefaultChannel(this) // channel for Herald pushes HeraldMessagingService.syncToken(this) // registers the current FCM token } } ``` Register the class in `AndroidManifest.xml` with `android:name=".LumenApplication"` on the `` element. Every SDK call is thread-safe, returns at once and runs in order on one background thread. ## 3. Identify the user After sign-in, call `identify` with your stable External ID, then `setUserToken` with the token your backend returns. Call them in that order: identifying a different user clears the previous token. ```kotlin fun didSignIn(userId: String, userToken: String) { Herald.identify(userId, mapOf("plan" to "free")) Herald.setUserToken(userToken) } ``` On sign-out, call `Herald.reset()`. ## 4. Track an event ```kotlin Herald.track("workout_completed", mapOf("minutes" to 32, "type" to "strength")) ``` Events are queued on the device and sent in batches. [Events and attributes](/docs/concepts/events-and-attributes) lists the rules each call must follow. ## 5. Register for push `herald-fcm` registers its own messaging service, so new FCM tokens reach Herald without more code. Ask for permission with `requestPushAuthorization`, which shows the Android 13 prompt when needed and records the answer, and pass notification taps to the SDK from your launcher activity. ```kotlin class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Herald.handleNotificationIntent(intent) setContent { HomeScreen(onEnablePush = { Herald.requestPushAuthorization(this) }) } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) Herald.handleNotificationIntent(intent) } } ``` [Android push setup](/docs/push-notifications/android-setup) covers the service account, background notifications and apps that already have a messaging service. ## 6. Show content cards `ContentCardFeed` from `herald-ui` shows the signed-in user's cards, pinned first and then newest, and logs impressions, clicks and dismissals for you. ```kotlin @Composable fun HomeScreen(onEnablePush: () -> Unit) { Column { Button(onClick = onEnablePush) { Text("Turn on workout reminders") } ContentCardFeed() } } ``` ## Verify it works 1. Run the app, sign in and log a workout. Send the app to the background: the SDK sends its queue as the app leaves the foreground. 2. In Logcat, filter by the tag `Herald`. With debug logging on, `Sent 3 events` (or similar) confirms a batch was accepted. `Herald rejected a batch` means it was not. 3. In Herald, open **Audience > Search users** and look up the External ID. The profile shows the traits you passed to `identify`, such as `plan`. 4. Have an agent send a content card to that user through the same connection. The card appears at the next session start, or right away if you call `Herald.refreshContentCards()`. ## Troubleshooting - **One `Message sync needs a user token; waiting for setUserToken` debug line right after sign-in.** With verification **Required**, `identify` fetches messages before the token is set. It is harmless: `setUserToken` fetches again. Call `setUserToken` immediately after `identify`. A session-start in-app message can first show in the user's next session. A `Message sync got 401: Herald refused the user token` warning is different: the token the app sent is wrong. See [Error codes](/docs/reference/error-codes). - **Nothing is sent at all.** `configure` never ran. Calls made before it are kept (up to 1,000) but only sent once it runs. Call `configure` at the top of `Application.onCreate` and check the manifest names your Application class. - **`Herald rejected the app key: check the publishable key in configure`.** The app key is wrong, or the connection is not active. The SDK keeps the events and stops sending until the app launches again; fix the key in `configure`. - **`Herald needs a user token: call setUserToken`.** Identity verification is **Required** and the signed-in user's token is missing or wrong. The SDK keeps that user's events and sends them after the next `setUserToken`. - **`Firebase is not initialized; push token not synced`.** `google-services.json` is missing or the Google services plugin is not applied. - **No cards.** Cards are fetched for identified users only. An agent send made before the user's device first reached Herald is suppressed, so send again after the app has run once. ## Next - [Users and identity](/docs/concepts/users-and-identity) - [Android push setup](/docs/push-notifications/android-setup) - [Content cards](/docs/content-cards/overview) Source: https://heraldsdk.com/docs/overview/quickstart-android.md --- # Quickstart: React Native > Add the Herald React Native package to an app, identify a user, track an event, register for push and show content cards. `@herald/react-native` is a thin wrapper over the native iOS and Android SDKs: every call goes to the native SDK, which validates, queues and sends it, and in-app messages are drawn by the native default views. This guide takes a React Native app from no SDK to a verified first event, a registered push token and a list of content cards. It takes about 30 minutes. :::prereq - React Native 0.88 or later with the New Architecture. The package is a TurboModule, built and tested with React Native 0.88; earlier versions aren't verified. - iOS: deployment target iOS 16 or later (`platform :ios, '16.0'` in your `Podfile`), Xcode 16 or later. React Native adds the `herald-ios` Swift package to your Pods project for you. - Android: `minSdkVersion` 26 or higher. A Firebase project with your Android app registered, and its `google-services.json`, for push. - A Herald sending connection with an app key. In Herald, open **Settings > Sending**, open the connection and find the **Mobile SDK** card. If it has no key, click **Generate app key**. The card also shows your endpoint URL. - A backend route that returns a user token for the signed-in user, unless identity verification is **Off**. See [Users and identity](/docs/concepts/users-and-identity#user-tokens-and-verification-modes). ::: ## 1. Install the package The package is not on npm yet. It lives in `sdks/react-native` in the Herald repository, and installing it from git needs read access to that repository. ```sh # pnpm installs a folder of a git repository directly pnpm add "github:ender1311/herald#path:/sdks/react-native" # npm or Yarn: pack it from a checkout, then install the tarball git clone https://github.com/ender1311/herald.git (cd herald/sdks/react-native && npm pack) npm install ./herald/sdks/react-native/herald-react-native-0.6.0.tgz ``` Then install the iOS pods with `cd ios && pod install`. Android needs nothing more: the package depends on `herald-core` and `herald-ui` 0.6.0 from JitPack, a repository the React Native Gradle plugin already adds. ## 2. Configure the SDK On iOS, call `Herald.configure` from JavaScript, once, before anything else. It also installs the native in-app message views. On Android, call the native `Herald.configure` in `MainApplication.onCreate` instead. The Android SDK learns about the running activity from lifecycle callbacks it registers in `configure`, and a JavaScript call comes too late for the first launch: the session start and any in-app message would wait until the app next comes to the foreground, and push taps in `MainActivity` would be missed. ```tsx // index.js or App.tsx import { Platform } from 'react-native'; import { Herald } from '@herald/react-native'; if (Platform.OS === 'ios') { Herald.configure('YOUR_APP_KEY', 'https://YOUR_HERALD_HOST', { logLevel: 'debug' }); } ``` ```kotlin // android/app/src/main/java/.../MainApplication.kt override fun onCreate() { super.onCreate() Herald.configure(this, "YOUR_APP_KEY", "https://YOUR_HERALD_HOST", HeraldOptions(logLevel = LogLevel.DEBUG)) HeraldInAppPresenter.install() // default in-app message views loadReactNative(this) } ``` The options object takes the iOS names, in seconds: `deviceDataCollection`, `flushInterval`, `flushAt`, `foregroundSessionTimeout`, `backgroundSessionTimeout`, `inAppMinimumInterval`, `maxQueuedEventAge`, `logLevel`, `trackLifecycleEvents`, `trackDeepLinks`, `trackDeepLinkQuery`, `trackExternalPushes` and `crashReports` (iOS only). On Android, session timeouts are rounded up to whole minutes and `maxQueuedEventAge` to whole days. A second `configure` is ignored with a warning, as in the native SDKs. ## 3. Identify the user After sign-in, call `identify` with your stable External ID, then `setUserToken` with the token your backend returns. Call them in that order: identifying a different user clears the previous token. ```tsx Herald.identify(userId, { plan: 'free' }); Herald.setUserToken(userToken); ``` On sign-out, call `Herald.reset()`. `Herald.heraldId` is the person's User ID for a Support ID line. ## 4. Track an event ```tsx Herald.track('workout_completed', { minutes: 32, type: 'strength' }); Herald.screen('Home'); Herald.trackPurchase('pro_monthly', 9.99, 'USD'); Herald.setAttributes({ favorite_sport: 'climbing' }); Herald.setEmail('ana@example.com'); ``` Events are queued on the device and sent in batches. [Events and attributes](/docs/concepts/events-and-attributes) lists the rules each call must follow. ## 5. Register for push `Herald.requestPushAuthorization()` shows the permission prompt (iOS, and Android 13 and later), records the answer and resolves with whether notifications are allowed. Push tokens and taps arrive in native code before JavaScript runs, so they are handled there. iOS, in `AppDelegate.swift` (the app target can `import HeraldSDK`; the package links it): ```swift import HeraldSDK func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { UNUserNotificationCenter.current().delegate = self return true } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Herald.shared.setPushToken(deviceToken) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { Herald.shared.handleNotificationResponse(response) completionHandler() } ``` Android: add `herald-fcm` and the Google services plugin as in the [Android quickstart](/docs/overview/quickstart-android#1-add-the-modules), and pass notification taps on in `MainActivity`: ```kotlin override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Herald.handleNotificationIntent(intent) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) Herald.handleNotificationIntent(intent) } ``` If another library already owns your push tokens (for example `@react-native-firebase/messaging`), pass each token on with `Herald.setPushToken(token)`: the APNs token as hex on iOS, the FCM token on Android. A push's deep link opens through the system, so React Native's `Linking` receives links to your own scheme. [iOS push setup](/docs/push-notifications/ios-setup) and [Android push setup](/docs/push-notifications/android-setup) cover the credentials. ## 6. Show content cards The package gives you the card data; you draw the cards with your own components and log what the person sees and does. ```tsx const [cards, setCards] = useState([]); useEffect(() => { Herald.getContentCards().then(setCards); const subscription = Herald.addContentCardsListener(setCards); return () => subscription.remove(); }, []); // When a card is on screen, tapped or dismissed: Herald.logImpression(card); Herald.logClick(card); Herald.logDismissal(card); ``` `Herald.refreshContentCards()` fetches cards and in-app messages now. Each card has the fields in the [iOS API](/docs/reference/ios-api#contentcard); timestamps are epoch milliseconds. ## 7. In-app messages The native default views show in-app messages with no JavaScript. To hold a message back, set a handler. It gets the message's ID, type, priority, decision ID, expiry and content, and returns (or resolves with) `display`, `later` or `discard`, as the native delegate does: ```tsx Herald.setInAppMessageHandler((message) => (isCheckingOut ? 'later' : 'display')); // When the person is free again, offer the pending message (the handler is asked again): Herald.showNext(); ``` A handler that throws lets the message show. `Herald.setInAppMessageHandler(null)` goes back to showing every message as soon as it is eligible. ## What the package does not wrap These work from the native side of your app with the native APIs ([iOS API](/docs/reference/ios-api), [Android API](/docs/reference/android-api)), but have no JavaScript call yet: Live Activities, push stories and geofences; `setLocation`, `setConsent` and `clearConsent`; `trackExternalPush`; `flush(timeout:)`; video logging; `deepLinkHandler`; custom in-app presenters and themes; and the debug preview calls. The package has no content card feed component. ## Verify it works 1. Run the app, sign in and log a workout. Send the app to the background: the SDK sends its queue as the app leaves the foreground. 2. With debug logging on, the native log shows the batch: in Xcode's console or Console.app filter by `Herald`; in Logcat filter by the tag `Herald`. `Sent 3 events` (or similar) confirms a batch was accepted. 3. In Herald, open **Audience > Search users** and look up the External ID. The profile shows the traits you passed to `identify`. 4. Have an agent send a content card to that user. Your card listener gets it at the next session start, or right away after `Herald.refreshContentCards()`. ## Troubleshooting - **`TurboModuleRegistry.getEnforcing(...): 'HeraldReactNative' could not be found`.** The native part isn't in the build: run `pod install` again for iOS, rebuild the app (not only reload JavaScript), and check that the New Architecture is on. - **Pod install fails on the deployment target.** Set `platform :ios, '16.0'` in your `Podfile` and the app target's deployment target to iOS 16. - **Android manifest merger fails on `minSdkVersion`.** Set `minSdkVersion = 26` in `android/build.gradle`. - **No in-app message on Android's first launch.** `configure` ran from JavaScript. Move it to `MainApplication.onCreate`. The sample app in `sdks/react-native/example` in the repository shows every call above. ## Next - [Users and identity](/docs/concepts/users-and-identity) - [Content cards](/docs/content-cards/overview) - [In-app messages](/docs/in-app-messages/overview) Source: https://heraldsdk.com/docs/overview/quickstart-react-native.md --- # Install on Flutter > Add the Herald Flutter plugin to a Flutter app. It wraps the native iOS and Android SDKs, installs from git, and covers identity, events, push, content cards and in-app messages. `herald_flutter` is a Flutter plugin that wraps the native Herald SDKs: `herald-ios` on iOS and `herald-android` on Android, version 0.6.0. It is a thin layer, not a separate SDK, so behavior, limits and threading are the native SDKs' ([iOS API](/docs/reference/ios-api), [Android API](/docs/reference/android-api)). Calls return once the native SDK has queued them; the few that can throw are listed under [Errors](#errors). It isn't on pub.dev yet; install it from git. :::prereq - Flutter 3.50 or later (Dart 3.14), with Swift Package Manager turned on for iOS: `flutter config --enable-swift-package-manager`. The plugin has no CocoaPods spec. - iOS 16 or later (set the Runner's deployment target to 16.0) and Android 8.0, API level 26 (`minSdk = 26`). - A Herald app key and endpoint, from the connection's **Mobile SDK** card. - For push: an APNs key on the connection for iOS, and Firebase set up in the Android app (`google-services.json`). See [iOS push setup](/docs/push-notifications/ios-setup) and [Android push setup](/docs/push-notifications/android-setup). ::: ## 1. Add the plugin ```yaml # pubspec.yaml dependencies: herald_flutter: git: url: https://github.com/ender1311/herald.git path: sdks/flutter ``` On Android, add JitPack to `android/build.gradle.kts`, where the native modules come from: ```kotlin allprojects { repositories { google() mavenCentral() maven { url = uri("https://jitpack.io") } } } ``` and make `MainActivity` extend `FlutterFragmentActivity` instead of `FlutterActivity`. The native in-app message views need a `ComponentActivity`. ## 2. Configure the SDK Call `Herald.configure` once in `main()`. It also installs the native default in-app message views. ```dart import 'package:flutter/widgets.dart'; import 'package:herald_flutter/herald_flutter.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); Herald.configure( appKey: 'YOUR_APP_KEY', endpoint: 'https://YOUR_HERALD_HOST', options: const HeraldOptions(logLevel: HeraldLogLevel.debug), ); runApp(const MyApp()); } ``` On Android, also start the SDK from your `Application` class. Dart code runs after the first activity has started, so a Dart-only start misses that first app open: the push tap that launched the app is lost (no open is logged and its deep link doesn't open), and the session and in-app messages wait until the app next comes to the foreground. **On Android the native call wins.** Once it has run, the Dart `Herald.configure` is ignored there, its options included, with one warning in the log. Pass the same options to the Kotlin call that you pass in Dart, or the two platforms behave differently (for example, Android would keep sending standard device data while iOS sends minimal): ```kotlin import com.herald.sdk.DeviceDataCollection import com.herald.sdk.Herald import com.herald.sdk.HeraldOptions import com.herald.sdk.LogLevel class MainApplication : Application() { override fun onCreate() { super.onCreate() Herald.configure( this, "YOUR_APP_KEY", "https://YOUR_HERALD_HOST", HeraldOptions( deviceDataCollection = DeviceDataCollection.MINIMAL, // Dart: DeviceDataCollection.minimal logLevel = LogLevel.DEBUG, // Dart: HeraldLogLevel.debug flushIntervalSeconds = 10, // Dart: flushInterval: Duration(seconds: 10) foregroundSessionTimeoutMinutes = 30, // Dart: foregroundSessionTimeout: Duration(minutes: 30) trackDeepLinkQuery = false, // Dart: trackDeepLinkQuery: false ), ) } } ``` Every Android option is listed on [Android API](/docs/reference/android-api). Name it in `AndroidManifest.xml` with `android:name=".MainApplication"` on ``. In Dart, `HeraldOptions` takes `deviceDataCollection`, `flushInterval`, `flushAt`, `foregroundSessionTimeout`, `backgroundSessionTimeout`, `inAppMinimumInterval`, `logLevel`, `trackLifecycleEvents`, `trackDeepLinks`, `trackDeepLinkQuery`, `trackExternalPushes` and `crashReports` (iOS only). A field left out keeps the native default. They apply on iOS, and on Android only when there is no native `configure` call. Android rounds session timeouts down to whole minutes. ## 3. Identify, track and set attributes ```dart await Herald.identify('user-123', traits: {'plan': 'free'}); await Herald.setUserToken(tokenFromYourBackend); await Herald.track('lesson_completed', properties: {'minutes': 12}); await Herald.screen('Home'); await Herald.trackPurchase(productId: 'pro_monthly', price: 9.99, currency: 'USD'); await Herald.setEmail('ada@example.com'); await Herald.setPhone('+15551234567'); final supportId = await Herald.heraldId; ``` Values are Dart strings, numbers, booleans, null, lists and maps, with the same rules as the native SDKs. `reset()` signs the user out; `flush()`, `setEnabled()`, `isEnabled` and `wipeData()` work as on [iOS](/docs/reference/ios-api#data-control). ## 4. Push ```dart final granted = await Herald.requestPushAuthorization(); // iOS: true or false. Android: null ``` What the plugin does for you: - **iOS** forwards the APNs token, push taps and sync pushes from your `FlutterAppDelegate`, and shows a Herald push that arrives while the app is open as a banner. Other notifications are left to your other plugins. Set the notification center's delegate to it in `application(_:didFinishLaunchingWithOptions:)`: `UNUserNotificationCenter.current().delegate = self`. Add the Push Notifications capability and the Remote notifications background mode. - **Android** brings in `herald-fcm`. Its messaging service registers the FCM token and shows Herald pushes, and the plugin passes notification taps to the SDK. If another plugin owns push, such as `firebase_messaging`, pass its token to `Herald.setPushToken`: the FCM token on Android, the APNs token as hex on iOS. Only one `FirebaseMessagingService` gets messages on Android; see [Android push setup](/docs/push-notifications/android-setup) for an app with its own service. Deep links from pushes, cards and messages open through the system, so your app's deep link handling receives them. ## 5. Content cards The plugin gives you the card data; draw the cards with your own widgets and log what the user does. ```dart final cards = await Herald.contentCards; Herald.contentCardsStream.listen((cards) => setState(() => _cards = cards)); Herald.logImpression(card); // once, when it is shown Herald.logClick(card); Herald.logDismissal(card); await Herald.refreshContentCards(); ``` Numbers in a card's `extras` arrive as `int` when whole and `double` otherwise, on both platforms. ## 6. In-app messages Messages are drawn by the native default views. To decide whether one shows, set a handler: ```dart Herald.setInAppMessageHandler((message) { if (_inCheckout) return InAppMessageDisplayChoice.later; return InAppMessageDisplayChoice.display; }); ``` The handler runs in Dart, so the native SDK keeps the message pending while it decides. Then `display` shows it, `later` keeps it pending (`showNext()` offers it again) and `discard` drops this occurrence. If a higher-priority message is pending too, the SDK offers that one first. `setInAppMessageHandler(null)` shows every message. ## Errors Calls throw a `PlatformException` only in these cases: | Call | Platform | When | |---|---|---| | `configure` | iOS | `endpoint` isn't a URL (`bad_args`). Android accepts any string. | | `setPushToken` | iOS | The token isn't hex (`bad_args`). Android accepts any string. | | `requestPushAuthorization` | Android | No activity is attached (`no_activity`) | `requestPushAuthorization` on iOS waits until the person answers the permission prompt. Other invalid input is logged by the native SDK and the call is skipped, as in the native SDKs. ## What the plugin doesn't wrap Live Activities, push stories, geofences, subscription states, consent, location, pushes your app sends, custom in-app presenters and themes, and the native card feed views. They work from the native side of a Flutter app: call the iOS or Android SDK from Swift or Kotlin. The Android modules are on your app's classpath through the plugin. ## Next - [Platform support](/docs/overview/platform-support) - [Content cards](/docs/content-cards/overview) - [In-app messages](/docs/in-app-messages/overview) Source: https://heraldsdk.com/docs/overview/install-flutter.md --- # Install on Unity > Add the Herald Unity package to an iOS and Android game, configure it from C#, identify a user, track events, register for push and use content cards and in-app messages. The Unity package `com.herald.sdk` is a C# API over the native iOS and Android SDKs. Each call goes to the native SDK, which queues events, runs sessions, handles push and draws in-app messages, so a Unity game behaves like a native app. In the Unity Editor, and on platforms other than iOS and Android, each call is logged to the Console and nothing is sent. :::prereq - Unity 6 (6000.0) or later, with the IL2CPP scripting backend. - iOS: **Player Settings > iOS > Target minimum iOS Version** set to 16.0 (the build stops with a message otherwise) and Xcode 16. - Android: minimum API level 26, and **Player Settings > Android > Application Entry Point** set to **GameActivity**. The native in-app message views need it; with the legacy Activity entry point, in-app messages wait and a warning is logged. - A Herald sending connection with an app key, from the **Mobile SDK** card under **Settings > Sending**. ::: ## 1. Add the package In Unity, open **Window > Package Manager**, click **+**, choose **Add package from git URL** and enter: ``` https://github.com/ender1311/herald.git?path=sdks/unity ``` Or add it to `Packages/manifest.json`, with `#` on the end to pin a version: ```json "com.herald.sdk": "https://github.com/ender1311/herald.git?path=sdks/unity" ``` The repository holding the package is private for now, so the URL works only for accounts with access to it. A public package will replace it; this page will change to that URL. The package needs no External Dependency Manager and no custom Gradle templates. When you build: - **iOS**: it adds the `herald-ios` Swift package (`HeraldSDK` and `HeraldUI`) to the UnityFramework target of the generated Xcode project and turns on Unity's push token forwarding. - **Android**: it adds JitPack to `settings.gradle` and the `herald-core`, `herald-ui` and `herald-fcm` modules to the generated Gradle project. ## 2. Configure at launch Call `Herald.Configure` once, as early as you can, from Unity's main thread: ```csharp using HeraldSDK; using UnityEngine; public static class HeraldSetup { [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] static void Start() { Herald.Configure("YOUR_APP_KEY", "https://YOUR_HERALD_HOST", new HeraldOptions { LogLevel = HeraldLogLevel.Debug, // remove before release }); } } ``` `HeraldOptions` has `DeviceDataCollection`, `LogLevel`, `FlushIntervalSeconds`, `FlushAt`, `InAppMinimumIntervalSeconds`, `TrackLifecycleEvents` and `TrackDeepLinks`, with the native defaults. See [iOS API](/docs/reference/ios-api#setup) for what each does. ## 3. Identify the player and track events ```csharp using System.Collections.Generic; Herald.Identify("user-123", new Dictionary { { "plan", "free" } }); Herald.SetUserToken(tokenFromYourBackend); // unless identity verification is Off Herald.SetEmail("player@example.com"); Herald.Track("level_completed", new Dictionary { { "level", 3 }, { "stars", 2 } }); Herald.Screen("shop"); Herald.TrackPurchase("gem_pack", 4.99, "USD"); ``` Values can be strings, numbers, booleans, null, lists and dictionaries; attributes take strings, numbers, booleans, null or a list of strings. Call `Herald.Reset()` when the player signs out. `Herald.HeraldId` is the player's User ID for a Support ID line. See [Users and identity](/docs/concepts/users-and-identity). ## 4. Push Call `Herald.RequestPushAuthorization()` at a moment that makes sense to the player. It shows the permission prompt (iOS, and Android 13 and later) and registers the device. The package handles taps itself: it logs the open and opens the push's deep link. Links with your app's own scheme arrive in Unity's `Application.deepLinkActivated`. - **iOS**: in Xcode, add the **Push Notifications** capability to the Unity-iPhone target, and upload an APNs key to the connection. See [iOS push setup](/docs/push-notifications/ios-setup). The package installs a notification center delegate as the app launches; notifications that aren't from Herald, and how a notification shows while the game is open, are passed to any delegate that was set before it (another plugin's). With none, a notification shows as a banner while the game is open. Another plugin that sets the notification center delegate after launch, such as Unity Mobile Notifications, replaces the package's, and Herald push taps are then neither logged nor opened: forward each response from that delegate to `Herald.shared.handleNotificationResponse(response)` in native code (it returns `false` for notifications that aren't from Herald). - **Android**: Firebase must be set up in the game. Add the Firebase Unity SDK's **FirebaseApp** package with your `google-services.json`, but not its **Firebase Messaging** package: `herald-fcm` brings its own messaging service, and only one service receives each push. See [Android push setup](/docs/push-notifications/android-setup) for the Firebase project and server key. Silent sync pushes don't refresh messages in the background in a Unity game; new cards and messages arrive at the next session or `Herald.RefreshContentCards()`. ## 5. Content cards The package keeps the current cards in `Herald.ContentCards` and raises `Herald.ContentCardsChanged` on Unity's main thread when they change. Draw them in your own UI and report what the player does: ```csharp Herald.ContentCardsChanged += cards => { foreach (var card in cards) { // card.Title, card.Body, card.ImageUrl, card.Url, card.Extras ... Herald.LogImpression(card); // when it is on screen } }; // Herald.LogClick(card) when tapped (then open card.Url), Herald.LogDismissal(card) when dismissed ``` ## 6. In-app messages The native SDK draws in-app messages over the game with its default views. To hold them during gameplay, set a delegate: ```csharp class MessageGate : IInAppMessageDelegate { public static volatile bool InLevel; public InAppMessageDisplayChoice ShouldDisplay(InAppMessage message) => InLevel ? InAppMessageDisplayChoice.Later : InAppMessageDisplayChoice.Display; } Herald.InAppMessageDelegate = new MessageGate(); // when the level ends: MessageGate.InLevel = false; Herald.ShowNext(); ``` On Android, `ShouldDisplay` runs on the Android UI thread, not Unity's main thread: read a flag, don't call Unity APIs, and return quickly. `Later` keeps the message pending; `Discard` drops this showing. See [In-app messages](/docs/in-app-messages/overview). ## What the package covers | C# | Native | |---|---| | `Configure` | `configure`, plus the default in-app presenter | | `Identify`, `SetUserToken`, `Reset`, `HeraldId` | same names | | `Track`, `Screen`, `TrackPurchase` | same names | | `SetAttribute`, `SetAttributes`, `SetEmail`, `SetPhone` | same names | | `RequestPushAuthorization` | same name; taps handled for you | | `Flush`, `SetEnabled`, `IsEnabled`, `WipeData` | same names | | `ContentCards`, `ContentCardsChanged`, `RefreshContentCards`, `LogImpression`, `LogClick`, `LogDismissal` | content card store and logging | | `InAppMessageDelegate`, `ShowNext` | same names | Not in the Unity package yet: `setSubscription`, `setLocation`, consent, `trackExternalPush`, custom in-app message views, a deep link handler, Live Activities, push stories and geofences. They work from native code in the generated Xcode or Gradle project. ## Related - [Platform support](/docs/overview/platform-support) - [iOS API](/docs/reference/ios-api) - [Android API](/docs/reference/android-api) Source: https://heraldsdk.com/docs/overview/install-unity.md --- # Users and identity > Device IDs, anonymous and identified users, user tokens and the three identity verification modes, sign-out and user switching. Every install of your app has a device ID, and at any moment the device is either anonymous or identified as one of your users. Identity decides what Herald stores for a user and which messages the device can receive. ## Device ID The SDK generates a random UUID the first time it runs and stores it in the app's private storage. It is not the IDFA, the IDFV, the Android ID or the advertising ID. - It stays the same across sign-ins, sign-outs and app updates. - `wipeData()` replaces it with a new one. - On iOS it lives in Application Support, excluded from backups, and is removed with the app. On Android it lives in the app's no-backup files directory, which Android Auto Backup never copies. SDK 0.4.0 and earlier keep it in the app's files directory, which Auto Backup includes unless your backup rules exclude it. ## Anonymous and identified | | Anonymous device | Identified and verified user | |---|---|---| | Events | Stored with the device ID | Stored with the device ID and the External ID | | Traits and attributes | Not written to any profile | Merged into the user's profile | | Push token | Not stored, so no push | Stored as the user's push contact | | Content cards and in-app messages | None (the sync returns empty lists) | The user's cards and messages | | Message outcomes | Not credited | Credited to the Herald decision | A device is identified from the `identify` call until `reset()`. Events recorded before `identify` are linked to the user when they sign in on that device: see [Guests and signed-in users](#guests-and-signed-in-users). Whether Herald trusts that identity depends on the verification mode below. ## Guests and signed-in users **Before sign-in.** A guest has no profile. Their events are stored with the device ID only: no profile, no push, no messages and no goal credit yet. **At sign-in.** When a device is first bound to a verified user, Herald links that device's guest events from the last 30 days to the user (at most the 5,000 most recent). That includes events from the same batch as the `identify`. The linked events then count as the user's: - The user's first seen time moves back to the earliest linked event, and the events count toward their activity and send-time stats. - A goal event from before sign-in credits the user's earlier Herald message, within that goal's attribution window, as if it had been sent signed in. A first-time-only goal counts the linked events too. - The person's activity timeline marks them **before sign-in**. Only a verified identity links events. An unverified claim (no valid user token under **Optional**) links nothing, and its events stay anonymous. **Shared devices.** Guest events are linked only if they come after everyone else's use of the device: after the last sign-out (`reset()`), and after the latest event of any other person on that device, signed in or claimed without a valid user token. When person A signs out, a guest browses and person B signs in, the guest's events go to B, never to A, and nothing from before A's time on the device does. Events stored for a signed-in user never move. **Several devices.** Each device's guest history is linked to the person when they first sign in on that device. Signing in again after a sign-out links only the guest events since that sign-out. **Reinstall.** Reinstalling the app or calling `wipeData()` gives the device a new device ID, so nothing recorded under the old ID is linked. ## Identify Call `identify` after sign-in, with the same stable ID your other systems use for that person (for example the ID your warehouse syncs to Herald). Herald calls it the **External ID**. Do not use an email address: it changes, and it is personal data. :::tabs ::tab ios ```swift Herald.shared.identify(userId: "u_123", traits: ["plan": "free"]) Herald.shared.setUserToken(tokenFromYourBackend) ``` ::tab android ```kotlin Herald.identify("u_123", mapOf("plan" to "free")) Herald.setUserToken(tokenFromYourBackend) ``` ::: - The External ID is 1 to 200 characters. Traits follow the attribute rules on [Events and attributes](/docs/concepts/events-and-attributes). - Calling `identify` again with the same ID sends the new traits and changes nothing else. - After identifying, the SDK fetches the user's cards and messages, and sends the device's push token again so it is stored for this user. ## User tokens and verification modes A user token proves your backend vouches for the External ID. It is the hex HMAC-SHA256 of the External ID, keyed with the SHA-256 hex digest of the connection's ingest token. Mint it on your backend after sign-in and pass it to `setUserToken`. Never put the ingest token in the app. ```javascript // Node.js, on your backend. HERALD_INGEST_TOKEN is the connection's ingest token. import { createHash, createHmac } from "node:crypto"; const key = createHash("sha256").update(process.env.HERALD_INGEST_TOKEN).digest("hex"); const userToken = createHmac("sha256", key).update(userId).digest("hex"); ``` The token does not expire. It changes only when someone rotates the connection's ingest token, which invalidates every user token at once. Set the mode on the connection's **Mobile SDK** card. New connections start at **Required**. | Mode | Valid token | No token | Wrong token | Content cards and in-app messages | |---|---|---|---|---| | Required (default) | User verified | Request rejected (401) | Request rejected (401) | Only with a valid token | | Optional | User verified | Events stored as anonymous; nothing written for the user | Request rejected (401) | Empty without a token; 401 with a wrong one | | Off | User trusted as sent | User trusted as sent | Not checked | Returned for any External ID | A request that names no user (an anonymous device) never needs a token in any mode. :::warning Off is for development only With verification **Off**, anyone who has your app key can send events as any user and read any user's content cards and in-app messages. App keys ship inside your app, so treat them as public. Use **Off** only with test data, never in production. ::: Events recorded between `identify` and `setUserToken` are not lost. If a flush runs first and the server answers 401, the SDK keeps the batch, logs `Herald needs a user token: call setUserToken` and sends the user's events once `setUserToken` is called. Anonymous events keep flowing meanwhile. Call `setUserToken` as soon as your app has the token. `identify` starts a fetch of the user's cards and messages before your app can call `setUserToken`. Under **Required**, the first such fetch on a device gets a 401, logged at debug level; it is harmless. The SDK remembers that the connection needs a token, so later sign-ins wait for `setUserToken` instead of fetching without it. `setUserToken` then fetches with the token, so cards appear in the same session. A session-start in-app message for that user can first show in their next session, because the session-start trigger already ran. ## Sign-out Call `reset()` when the user signs out. The device becomes anonymous and keeps its device ID. :::tabs ::tab ios ```swift Herald.shared.reset() ``` ::tab android ```kotlin Herald.reset() ``` ::: - The SDK clears the External ID, the user token, the User ID, the cards and the in-app messages on the device. - Events the previous user queued before sign-out are still sent under that user, with that user's token. - The next batch the device sends is anonymous. Herald then unbinds the device from the previous user and deletes that user's push tokens for the device, so a signed-out phone stops getting their notifications. - In-app message history (which messages the user has seen) is kept per user and comes back if the same user signs in again. ## Support ID Every identified person gets a **User ID** from Herald: eight letters and digits shown as `XXXX-XXXX`, such as `7K3M-9QXA`. It is short enough to read out loud and never changes. It is separate from the **External ID**: External ID is the id your app passes to identify(). Anonymous devices have no User ID. - It shows at the top of the person's page in Herald. - Support can search for it on **People**, with or without the dash and in any case. Every console role can search by it. - The SDK receives it in the response to the first accepted batch for the user the batch is verified as: with a valid user token under Required or Optional, and for any claimed user under Off. Under Optional without a token it never arrives. It is nil until then, and again after `reset()` or a switch to another user. The SDK caches it, so it is there on the next launch. :::tabs ::tab ios ```swift let supportId = Herald.shared.heraldId // "7K3M-9QXA" or nil ``` ::tab android ```kotlin val supportId = Herald.heraldId // "7K3M-9QXA" or null ``` ::: Show it in your app's settings or help screen labeled "Support ID", so people can read it out when they contact you. It isn't secret, but it's only useful to someone with access to your Herald console. ## Random samples Every person also has a **random number**: a whole number from 0 to 9,999. Herald assigns it when it first sees the person and never changes it. People who existed before this shipped got one then. It shows on the person's page under **Attributes**, for every console role. Use it in a segment to aim a campaign or agent at a random share of people. Each number covers 0.01% of people, so: - **1% pilot:** Random number is less than 100. - **10%:** Random number is less than 1000. - **Two samples that never overlap:** Random number is less than 100 for one, and greater than or equal to 100 and less than 200 for the other. A person's number stays the same, so they stay in the same sample every time the segment is rebuilt. ## Switching users Calling `identify` with a different ID while a user is identified switches users. The SDK clears the previous user's token, cards and messages, then identifies the new user and sends the device's push token for them. Call `setUserToken` with the new user's token straight after. A switch and `reset()` both end the current session and start a new one. ## Edge cases - **Calls before `configure`.** The SDK keeps up to 1,000 of them, in order, and applies them once `configure` runs. Later calls are dropped with a warning. - **Verification set to Optional, no token sent.** Events are stored, but no profile, push token or outcome is written for the user. This is the most common reason a profile stays empty. - **Rotating the ingest token.** Every existing user token stops working. Under **Required**, identified traffic is rejected until apps get new tokens from your backend. ## Related - [Quickstart: iOS](/docs/overview/quickstart-ios) - [Quickstart: Android](/docs/overview/quickstart-android) - [Security and identity verification](/docs/data-and-privacy/security-and-identity-verification) Source: https://heraldsdk.com/docs/concepts/users-and-identity.md --- # Sessions > When the SDK starts and ends a session (separate foreground and background timeouts, continued across restarts), what it records for each one, and what a new session triggers. A session is one continuous period of use of your app, from the first activity until 30 minutes pass without any. The SDK tracks sessions on its own; you do not call anything to start or end them. ## How sessions behave | Rule | Behavior | |---|---| | Start | The first SDK activity on a device, or the first activity after the timeout has passed | | Timeout | 30 minutes without activity in the foreground, or 30 minutes in the background (each configurable) | | Session ID | The start time in epoch milliseconds, sent as `sessionId` on every event | | `session_start` event | Queued when the session starts, with `session_index` (sessions on this install, from 1) and `previous_session_id` (null for the first). SDK 0.6.0 and later. | | `session_end` event | Queued when the next session starts, with `durationSeconds` (last activity minus start) and a timestamp at the last activity | | On start | The SDK fetches the user's content cards and in-app messages, then evaluates in-app messages with a session start trigger | Activity means any recorded SDK call (an event, an attribute, an interaction) and the app coming to the foreground. When the app goes to the background, the SDK saves the time as the last activity and flushes the queue. ## Sign-out and user switch `reset()` and identifying a different user both end the current session and start a new one. The `session_end` is still attributed to the previous user. The same rules apply on iOS and Android. The foreground timeout counts from the last activity while the app is in the foreground: a foreground app left idle for 30 minutes starts a new session at its next activity. Once the app goes to the background, the background timeout counts instead, from the moment it went there: coming back after it starts a new session. A cold start within the foreground timeout of the last activity continues the same session, with the same session ID (when the app was last in the background, for example killed there, the background timeout decides instead); the SDK keeps the session ID, its last activity and the session index on the device. `session_index` counts from SDK 0.6.0: an app updated from an earlier SDK starts at 1. ## Change the timeout :::tabs ::tab ios ```swift Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!) { options in options.foregroundSessionTimeout = 15 * 60 // seconds options.backgroundSessionTimeout = 5 * 60 } ``` ::tab android ```kotlin Herald.configure( this, appKey = "YOUR_APP_KEY", endpoint = "https://YOUR_HERALD_HOST", options = HeraldOptions(foregroundSessionTimeoutMinutes = 15, backgroundSessionTimeoutMinutes = 5), ) ``` ::: The older single setting (`sessionTimeout` on iOS, `sessionTimeoutMinutes` on Android) still works and sets both; it is deprecated. ## Edge cases - **The app is killed.** The last activity is saved to disk whenever the app moves to the background, and at least once a minute while it runs. The `session_end` for that session is sent when the next one starts, with the duration up to the last saved activity. - **A session starts in the background,** for example when a notification tap records an event before the app is visible. The session start trigger for in-app messages waits until the app is in the foreground. - **The SDK is disabled** with `setEnabled(false)`. No sessions start and no events are recorded until it is enabled again. ## Related - [Events and attributes](/docs/concepts/events-and-attributes) - [In-app message triggers](/docs/in-app-messages/triggers-and-delivery) - [Data batching and offline behavior](/docs/concepts/batching-and-offline) Source: https://heraldsdk.com/docs/concepts/sessions.md --- # Events and attributes > Custom events, screens, purchases, user attributes and subscriptions, with the value types, reserved keys and limits each call follows. Events record what a user did, and attributes record what is true about them. Herald uses both to build the profile each decision is based on, and in-app messages can trigger on events. ## The calls | Call | Records | Example | |---|---|---| | `track` | A custom event with properties | `workout_completed` with `minutes` | | `screen` | A screen view with properties | `Plan` | | `trackPurchase` | A purchase: product, price, currency, quantity, properties | `plus_annual` at 59.99 USD | | `setAttribute`, `setAttributes` | User attributes, merged into the profile | `favorite_workout` | | `setEmail`, `setPhone` | The user's email address and phone number | `maya@example.com` | | `setSubscription` | Opt-in state for push, email or SMS | email subscribed | | `identify` traits | Attributes sent with the identify call | `plan` | :::tabs ::tab ios ```swift Herald.shared.track("workout_completed", properties: ["minutes": 32, "type": "strength"]) Herald.shared.screen("Plan") Herald.shared.trackPurchase(productId: "plus_annual", price: 59.99, currency: "USD") Herald.shared.setAttributes(["plan": "plus", "favorite_workout": "strength", "goals": ["sleep", "strength"]]) Herald.shared.setEmail("maya@example.com") Herald.shared.setPhone("+15551234567") Herald.shared.setSubscription(.email, .subscribed) ``` ::tab android ```kotlin Herald.track("workout_completed", mapOf("minutes" to 32, "type" to "strength")) Herald.screen("Plan") Herald.trackPurchase(productId = "plus_annual", price = 59.99, currency = "USD") Herald.setAttributes(mapOf("plan" to "plus", "favorite_workout" to "strength", "goals" to listOf("sleep", "strength"))) Herald.setEmail("maya@example.com") Herald.setPhone("+15551234567") Herald.setSubscription(SubscriptionChannel.EMAIL, SubscriptionState.SUBSCRIBED) ``` ::: `trackPurchase` has a default `quantity` of 1. Properties default to empty on every call. ## Events and agent goals A `track` or `trackPurchase` call from an identified, verified user counts toward agent goals. Herald credits it to the most recent message it sent that user, among agents with a goal for that event name. | Rule | Behavior | |---|---| | Event name a goal matches | `track`: the name you pass. `trackPurchase`: `purchase`. | | Purchase properties | Your properties plus `productId`, `price`, `currency` and `quantity`, so a goal can weight its reward by `price` | | Which message is credited | The most recent unconverted message sent to the user, from an agent with a goal for the event | | Attribution window | 48 hours after the send; 30 days for `plan_completed`, `plan_read_day_3` and `plan_read_day_7` | | Who counts | Identified, verified users only. Anonymous and unverified events are stored but never credited. | | Retries | An event ID is credited once, however often the SDK resends its batch | | `screen` calls | Never counted | Each message is credited for one conversion. Send each goal event from one source: if the server API and the SDK both send it, a second open message can get the credit. ## Value types | | Event and screen properties | Attributes and traits | |---|---|---| | Allowed values | Any JSON value: string, number, boolean, null, array, nested object | String, number, boolean, null, or an array of strings | | Numbers | Must be finite (no NaN or infinity) | Must be finite | | iOS type | `HeraldValue`, written as Swift literals | `HeraldValue`, written as Swift literals | | Android type | `Map` of strings, numbers, booleans, null, lists and maps | `Map` of strings, numbers, booleans, null and lists of strings | ## How attributes merge Each attribute call merges into the user's profile: a key you send replaces the stored value for that key, and keys you do not send stay as they are. Sending `null` removes the key from the profile, so it no longer counts as set in segments (an "exists" condition stops matching). Attributes are written only for an identified, verified user; see [Users and identity](/docs/concepts/users-and-identity). ## Reserved keys | Key | Set by | Where it goes | |---|---|---| | `$email` | `setEmail` | The user's email contact, not the attribute map. Must be a valid address. | | `$phone` | `setPhone` | The user's SMS contact, not the attribute map. Must be in E.164 format, such as `+15551234567`. | | `$latitude`, `$longitude` | `setLocation(latitude:longitude:)` | The device record, not the user profile. Only sent when your app calls it. | | `computed_…` | Herald only | [Computed attributes](/docs/concepts/computed-attributes). Your app can't set these: the event is rejected with `invalid_field`. | Do not start your own attribute keys with `$`. Passing `nil` or `null` to `setEmail` or `setPhone` sends a null value. ## Limits These are the server's limits. The SDK checks every call against them before queuing it. | Field | Rule | |---|---| | Event and screen name | 1 to 255 characters | | Property key | Up to 255 characters | | Attribute and trait key | 1 to 255 characters | | External ID (`userId`) | 1 to 200 characters | | Product ID | 1 to 255 characters | | Currency | A 3-letter ISO 4217 code, such as `USD` (the SDK converts it to upper case) | | Quantity | A whole number, 1 or more | | Price | A finite number | | Email | A valid address | | Phone | E.164: a plus sign, then 7 to 15 digits, not starting with 0 | Lengths count UTF-16 code units, as the server does. ## Invalid calls are rejected on the device The server rejects a whole batch of up to 100 events if one event breaks a rule. To keep one bad call from costing the rest, the SDK validates each call first. A call that fails is dropped on the device, never queued, and logged: ```text track ignored: name must not be empty ``` The example is from iOS. The log is at error level on iOS and warning level on Android, so it shows at the default log level on both. Email and phone values are handled per key. Herald skips an invalid `$email` or `$phone` and keeps the rest of the event. The SDK also checks both on the device: inside `setAttributes`, `setEmail` and `setPhone` it drops only the invalid key, with a warning; inside `identify` traits it rejects the whole call. ## Subscriptions `setSubscription` records a user's opt-in state for one channel. Herald applies it for identified, verified users. | State | Effect in Herald | |---|---| | `subscribed` / `SUBSCRIBED` | Lifts an earlier unsubscribe for the channel | | `optedIn` / `OPTED_IN` | Lifts an earlier unsubscribe for the channel | | `unsubscribed` / `UNSUBSCRIBED` | Suppresses the channel: for push, this device's tokens; for email and SMS, the user's addresses | A subscribe never lifts a suppression caused by a bounce or a spam complaint. Push permission has its own guide: [Permission prompts](/docs/push-notifications/permission-prompts). ## Related - [Sessions](/docs/concepts/sessions) - [Device data collected](/docs/concepts/device-data) - [Event payload reference](/docs/reference/event-payload) - [Limits](/docs/reference/limits) Source: https://heraldsdk.com/docs/concepts/events-and-attributes.md --- # Device data collected > Exactly what device data the SDK sends, which part you can turn off with minimal mode, what it never collects, and how Herald derives country. Device data is the information about the app, the operating system and the device that the SDK attaches to every batch it sends. It comes in two tiers: data the SDK always sends, and data it sends by default that you can turn off. ## Always sent | Data | Wire field | Example | |---|---|---| | Device ID (a random UUID the SDK creates) | `deviceId` | `6c1f2a90-…` | | App name, version, build and bundle ID or package name | `context.app` | `Lumen`, `4.2.0`, `812`, `com.lumen.app` | | Build kind (iOS 0.5.0+): Xcode or development build, TestFlight or App Store; left out until the SDK knows it | `context.app.distribution` | `development`, `testflight`, `appstore` | | OS name and version | `context.os` | `iOS`, `18.1` | | Region setting (the device's locale region code) | `context.region` | `US` | | SDK name and version | `sdk` | `herald-ios`, `0.4.0` | | Session start and end, with duration | `session_start`, `session_end` events | `durationSeconds: 412` | | Message interactions: impressions, clicks, dismissals, push opens | `interaction` events | `content_card`, `click` | ## Sent by default, off in minimal mode | Data | Wire field | Values | |---|---|---| | Device manufacturer, model and type | `context.device` | `Apple`, `iPhone16,1`, `phone` (also `tablet`; iOS can report `desktop`, `tv`, `car`, `headset`) | | Screen width, height and density | `context.screen` | Points on iOS, dp on Android, plus the scale factor | | Locale | `context.locale` | `en-US` | | Language | `context.language` | `en` | | Time zone (IANA name) | `context.timezone` | `America/Chicago` | | Network type | `context.network.type` | `wifi`, `cellular`, `ethernet`, `other`, `none` | | Notification permission | `context.push.authorization` | iOS: `authorized`, `denied`, `provisional`, `ephemeral`, `not_determined`. Android: `authorized`, `denied`, and on Android 13 and later `not_determined` until the app has asked through `requestPushAuthorization` | In minimal mode these keys are left out of the batch entirely, not sent as empty values. ## Sent only when your app calls the SDK - Events, screens, purchases and attributes you record. - Email and phone number (`setEmail`, `setPhone`). - Crash and hang reports on iOS, only when you set `crashReports` to `true`. They carry no user id and no device id. See [iOS API](/docs/reference/ios-api). - The push token: when you pass it to `setPushToken` on iOS, or automatically from `herald-fcm` on Android. - Location: only the coordinates you pass to `setLocation(latitude:longitude:)`. The SDK never reads location itself. - Geofence crossings (SDK 0.7.0+): `$geofence_enter` and `$geofence_exit` with the geofence's id and name, only after your app adds the geofence module and calls `enableGeofences()`. No coordinates. See [Geofences](/docs/concepts/geofences). ## Never collected - Advertising identifiers: IDFA on iOS, the advertising ID (GAID) on Android. - Vendor and hardware identifiers: IDFV, Android ID. - Precise or coarse location from the operating system. With geofences on, the operating system watches the geofences on the device; the SDK sends only crossings. - Contacts, photos or other personal content. - Mobile carrier. ## Turn on minimal mode :::tabs ::tab ios ```swift Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!) { options in options.deviceDataCollection = .minimal } ``` ::tab android ```kotlin Herald.configure( this, appKey = "YOUR_APP_KEY", endpoint = "https://YOUR_HERALD_HOST", options = HeraldOptions(deviceDataCollection = DeviceDataCollection.MINIMAL), ) ``` ::: Herald keeps only the latest device data for each device and replaces it with every batch. Switching an app to minimal mode removes the stored second-tier data the next time the device sends a batch. ## How Herald uses device data - **Country.** Herald takes the country of the request from its hosting edge when it is a two-letter code. When it is not available, it uses the device's region setting. The region setting is a user preference, not a location, so treat country as approximate. Herald stores the country on the device record; it does not store the request's IP address with SDK data. - **Time zone.** For an identified, verified user, Herald fills the profile's time zone from the device only when the profile has none. A time zone synced from your warehouse always wins. - **Notification permission.** The latest value is stored on the device record with the rest of the context. ## Related - [Data collection controls](/docs/data-and-privacy/data-collection-controls) - [App store disclosures](/docs/data-and-privacy/app-store-disclosures) - [Users and identity](/docs/concepts/users-and-identity) Source: https://heraldsdk.com/docs/concepts/device-data.md --- # How delivery works > How a Herald decision becomes a push notification, content card or in-app message, and how the outcome flows back to the decision. Delivery is the path from a Herald decision to a message on the user's device, and back. Herald decides; push goes out through Apple and Google; content cards and in-app messages wait on Herald until the SDK fetches them. ## The path, step by step 1. **Herald decides.** An agent picks a message, a channel and a time for a user, and sends it through a sending connection. 2. **Push goes to the push service.** The send is queued and delivered by Herald's dispatcher to APNs (iOS) or FCM (Android), addressed to the push tokens the SDK registered for that user. 3. **Cards and in-app messages wait for the app.** Herald writes a message record for the user. The SDK fetches the user's records at session start, after sign-in, and when you call `refreshContentCards()`. 4. **The device shows the message.** The operating system shows push. The SDK publishes cards to your feed, and evaluates in-app messages on the device each time a trigger fires. 5. **The outcome comes back.** Impressions, clicks, dismissals and push opens are sent as interaction events that carry the decision ID, so Herald credits the result to the decision that produced the message. ## Channels compared | | Push | Content card | In-app message | |---|---|---|---| | How it reaches the device | APNs or FCM | Fetched by the SDK | Fetched by the SDK, shown on a trigger | | When the user sees it | When the push service delivers it | At the next fetch | When its trigger fires after a fetch | | Scheduled send time | Honored | Ignored: visible at the next fetch | Ignored: eligible at the next fetch | | Works offline | No | Yes, from the on-device cache | Yes, from the on-device cache | | Requires | A push token for the identified user, and APNs or FCM credentials on the connection | An identified user with the SDK installed | An identified user with the SDK installed | A fetch returns up to 100 content cards and 50 in-app messages. Dismissed, expired and archived messages are left out. ## When a message is suppressed A content card or in-app message for a user who has no SDK device on that connection is suppressed: Herald writes nothing and records the send as suppressed. This keeps messages from piling up for users who have not installed or opened the app. A push needs a push token. Tokens are stored only for identified, verified users, so an anonymous device never receives push from Herald. ## How outcomes are credited | Interaction | Sent when | Effect on the decision | |---|---|---| | Impression | A card or in-app message is shown | Counted as delivered | | Click, or button tap | The user taps the card, the message or one of its buttons | Counted as a click, which rewards the decision | | Dismiss | The user dismisses the card or message | Counted as a dismissal | | Push open | The user opens a push notification | Counted as an open | | Push action button | The user taps a button on a push | Logged as an open, then a button tap, so it counts as an open and a click | Herald credits an outcome only when the user is verified and the decision belongs to that user. Outcomes from anonymous devices, or for someone else's decision, are stored as events and change nothing. ## Send-time checks Agents and campaigns choose who gets a message ahead of time. For messages Herald delivers itself, it checks again right before each one goes out: - **Agents:** the person still matches the agent's audience, hasn't already completed its main goal, and the agent is still running. You can also skip people who used the app since the message was queued, or today in their time zone. - **Campaigns:** with **Check again at send time** on (the default for new campaigns), people who no longer match the audience or already completed the goal are skipped. The **If they've used the app** setting works the same way as for agents. - **Messaging limits:** in Enforce mode, a message is held when the person's attention budget for the channel or the message's category cap is full, counting pushes your app sends itself. Campaign messages wait for a free slot and are dropped after the category's "useful for" time; agent messages are skipped. In Observe mode, the old push limit (on by default at 3 pushes in 24 hours) skips agent and campaign pushes instead, whatever the campaign's other send-time settings. Send API messages without a category are never held, but they count. See [Message priority and attention budget](/docs/concepts/message-priority). Skipped messages count as never sent. Audience segments refresh hourly, so a change in someone's data can take up to an hour to show here. If the check can't run, nothing is sent and Herald tries again a minute later. Messages sent through another provider are scheduled by that provider, so they aren't checked. Most apps already send transactional messages (receipts, sign-in codes, password resets, order and account updates) from their own backend. Keep doing that, and report each push to Herald with the $external_push event so it can count every push a person gets. If you'd rather Herald send them, use the Send API: those messages go out right away and skip the send-time checks. Use agents and campaigns for marketing and lifecycle messages. Send API messages still skip unsubscribed and bounced addresses, follow the quiet hours you ask for, and skip campaign frequency caps when you name the recipients. ## Sync push When Herald writes a new content card or in-app message for a user who has a push token, it also sends a silent push that tells the SDK to fetch now, instead of waiting for the next session. It never shows a notification. Herald sends at most one per user every five minutes. Apps that do not handle it still get the message at the next session. See [Silent push](/docs/push-notifications/silent-push). ## Push dispatch timing Push sends wait in an outbox until Herald's dispatcher delivers them. The dispatcher runs on a schedule your Herald operator sets up; the setup guide runs it every minute. With that schedule, a push leaves Herald within about a minute of its send time, and APNs or FCM add their own delivery time. ## Related - [Message priority and attention budget](/docs/concepts/message-priority) - [Sessions](/docs/concepts/sessions) - [Content cards](/docs/content-cards/overview) - [In-app message triggers](/docs/in-app-messages/triggers-and-delivery) - [iOS push setup](/docs/push-notifications/ios-setup) - [Android push setup](/docs/push-notifications/android-setup) Source: https://heraldsdk.com/docs/concepts/how-delivery-works.md --- # Data batching and offline behavior > How the SDK queues events on disk, when it sends them, how it retries, what it drops, and how it behaves without a network. The SDK never sends an event the moment you record it. It writes each event to a queue on disk and sends the queue in batches, so data survives app restarts, poor networks and airplane mode. ## When the SDK sends | Trigger | Default | Setting | |---|---|---| | Timer, while the app is in the foreground | Every 10 seconds | iOS `flushInterval` (seconds), Android `flushIntervalSeconds` | | Queue size | 20 queued events | iOS and Android `flushAt` | | App moves to the background | Always | None | | Your app asks | When you call `flush()` | None | On iOS, the SDK asks the system for background time when the app leaves the foreground, and holds it until the upload finishes. :::tabs ::tab ios ```swift Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!) { options in options.flushInterval = 30 options.flushAt = 50 } ``` ::tab android ```kotlin Herald.configure( this, appKey = "YOUR_APP_KEY", endpoint = "https://YOUR_HERALD_HOST", options = HeraldOptions(flushIntervalSeconds = 30, flushAt = 50), ) ``` ::: ## Confirm delivery before turning the SDK off `flush()` starts a send and returns at once. When a last change must reach Herald before you call `setEnabled(false)`, for example clearing the email at sign-out, use the iOS SDK's (0.5.0+) `flush(timeout:)` and wait for it: ```swift Herald.shared.setAttributes(["email": .null]) let delivered = await Herald.shared.flush(timeout: .seconds(10)) Herald.shared.setEnabled(false) ``` `true` means everything recorded before the call is on the server, so turning the SDK off afterwards can't lose it. On `false`, the events still queued stay on the device unsent while the SDK is off, and go out after `setEnabled(true)`; `wipeData()` deletes them. ## How batches are built - A batch holds up to 100 events and stays under the server's 512 KB request limit. When events do not fit, the SDK halves the batch until they do; the rest wait for the next batch. - A batch belongs to one user, or to no user. The SDK starts a new batch whenever the user changes, and `identify` goes out in the new user's batch. Events recorded before sign-in go out as an anonymous batch. When the user then signs in on that device, Herald links that device's recent guest events to them: see [Guests and signed-in users](/docs/concepts/users-and-identity#guests-and-signed-in-users). - Events go out in the order you recorded them. One exception: a push token moves ahead of a push subscription in the same batch, so Herald has the token when it applies the opt-in. - Each batch carries the current device data. See [Device data collected](/docs/concepts/device-data). ## Persistence and the queue cap | Rule | Behavior | |---|---| | Storage | iOS: a file in Application Support, excluded from backups. Android: a file in the app's no-backup files directory, excluded from backups (the files directory in SDK 0.4.0 and earlier). | | Survives | App restarts, crashes, updates and reboots | | Cap | 1,000 events | | When full | The oldest events are dropped to make room | | Max age | SDK 0.6.0 and later drop queued events more than 30 days old before building a batch, since Herald would reject them as `too_old` (`maxQueuedEventAge` on iOS, `maxQueuedEventAgeDays` on Android) | | Dropped count | Saved, and sent as `dropped` on the next batch; cleared once a batch that reported it is accepted. Counts events dropped for the cap, for size and for age. | Cards and in-app messages are cached on disk too, so they show without a network after a restart. ## Retries and backoff | Response | What the SDK does | |---|---| | 2xx | Removes the batch from the queue and sends the next one. Events Herald couldn't accept are listed in the response's `rejected` and logged at debug level; they are never retried, and the rest of the batch was kept. See [Rejected events](/docs/reference/error-codes#rejected-events). | | 408, 429, 5xx, or no network | Keeps the batch and retries later, with exponential backoff and jitter | | 401 with the error `Invalid app key` | Keeps every queued event, logs `Herald rejected the app key: check the publishable key in configure`, and sends nothing more until the app launches again (with the key fixed). The queue limit still applies. | | 401 for a signed-in user's batch (missing or wrong user token) | Keeps the batch, logs `Herald needs a user token: call setUserToken` once, and holds that user's events until the app calls `setUserToken`, which sends them. Anonymous events keep flowing. The queue limit still applies, so the oldest events are dropped if the token never comes. | | Any other 4xx (400, 403, 404, 413) | Drops the batch and logs an error; retrying would not help | Backoff starts at about 1 second, doubles after each failure, and stops growing at 5 minutes. Each wait is a random time between half and all of the computed delay, so many devices do not retry at the same moment. A `Retry-After` header from the server takes precedence, in seconds or as an HTTP date, and so does a `retryAfterSeconds` field in the response body. Either is capped at one hour. SDK calls still return at once during a backoff, and the events they record join the queue. ## Idempotency Every event has a unique ID that the SDK creates. Herald stores each event ID once per connection and reports repeats as duplicates. The SDK removes events from its queue only after a response, so if the app is killed mid-upload, the next attempt re-sends the same IDs and nothing is counted twice. ## Clock correction Phone clocks are sometimes wrong by minutes or hours. Each batch carries `sentAt`, the device's time when it was sent, from the same clock as the event timestamps. Herald notes when the batch arrived and moves every event by the difference: the stored event time is arrival time minus (`sentAt` minus the event's `timestamp`), and never later than arrival. An event recorded 10 minutes before the send lands 10 minutes before arrival, whatever the phone's clock said, and so do events that waited offline for days. Activity, the preferred send time, goal attribution and every other use of event time read the corrected time. The device's own `timestamp` is kept too. Events whose corrected time is more than 30 days old are rejected as `too_old`. Server events (`POST /api/v1/events`) are not corrected and have no age limit: Herald trusts your server's clock, so historical imports are kept, and rejects only events more than 5 minutes ahead of arrival as `in_future`. ## Offline behavior - Recording keeps working: events go to the disk queue, up to the cap. - Uploads wait: each attempt fails and backs off until the network returns. - Events queued for more than 30 days are dropped on the device (SDK 0.6.0 and later) and counted in `dropped`; from an earlier SDK, Herald rejects them as `too_old` when they finally arrive. - Cards and in-app messages come from the last successful fetch. In-app triggers are evaluated on the device, so they fire offline. - Interactions with cached messages are queued like any other event and credited once they reach Herald. ## Related - [Sessions](/docs/concepts/sessions) - [Events and attributes](/docs/concepts/events-and-attributes) - [Error codes](/docs/reference/error-codes) - [Limits](/docs/reference/limits) Source: https://heraldsdk.com/docs/concepts/batching-and-offline.md --- # Event schemas > Optional, versioned definitions of a custom event's properties. Herald checks every track event with that name, and either rejects or flags the ones that don't match. Custom `track` events take any properties. That is flexible, but a typo or a type change in one app release can quietly break the goals, segments and personalization built on that event. An event schema states which properties an event should have, so Herald can catch that. Schemas are optional. You define them only for the events you care about; every other event is accepted as it is. ## What a schema holds A schema belongs to one app and one event name. Set it up in the console under **Settings → Event schemas** (admins). Names starting with `$` are reserved for the SDK's own events and can't have a schema. Each property has: | Field | Values | |---|---| | Name | The property key | | Type | `string`, `number`, `integer`, `boolean`, `object` or `array` | | Required | Whether the event must have it. A `null` value counts as missing | | Allowed values | Strings only: the values it may take | | Max length | Strings only: the most characters it may have | | Min and max | Numbers only: the range it must be in | Properties the schema doesn't list are allowed and kept. An app can have up to 100 event schemas, each with up to 50 properties and 50 versions (see [Limits](/docs/reference/limits)). ## Versions Every save creates a new version; a saved version never changes. Versions use SchemaVer, `MODEL-REVISION-ADDITION`, starting at `1-0-0`. The console shows the next version before you save, with the reason: | Change from the latest version | Next version | Console reason | |---|---|---| | Only new optional properties, or anything else that keeps earlier events valid (more allowed values, a looser rule, a property made optional) | ADDITION: `1-0-0` → `1-0-1` | New optional properties only | | Only the mode | ADDITION: `1-0-1` → `1-0-2` | Mode change only | | A new required property, a removed property, a type change, fewer allowed values, a stricter max length, min or max, or an optional property made required | MODEL: `1-0-1` → `2-0-0` | Breaking change | REVISION is reserved: Herald doesn't produce it. A save with no changes is refused (**No changes to save**). If someone else saved a newer version after you opened the form, your save is refused and you reload to see it. Each schema's version history is shown read-only in the console. ## Modes | Mode | An event that doesn't match | |---|---| | **Reject invalid events** | Is rejected with reason `schema_violation` and left out of the batch; the rest of the batch is kept | | **Accept and warn** | Is kept as usual, and recorded as a warning | Mode belongs to each version. An event checked against a version, the latest or a pinned one, uses that version's mode, so saving a new version in **Accept and warn** doesn't change how events that pin an older version are checked. Use **Accept and warn** while you roll out a change: save the new version in that mode, watch the warnings while app versions update, then save it again with **Reject invalid events**. Each mode switch saves a new ADDITION version. ## Pinning a version from the app By default an event is checked against the latest version of its schema. An app release built for an older version can name it, so a breaking change for newer releases doesn't reject its events: ```swift Herald.shared.track("signup", properties: ["plan": "pro"], schemaVersion: "1-0-0") ``` ```kotlin Herald.track("signup", mapOf("plan" to "pro"), schemaVersion = "1-0-0") ``` `schemaVersion` is optional, in SDK 0.6.0 and later; existing `track` calls are unchanged. It is sent as the event's `schemaVersion` field ([Event payload](/docs/reference/event-payload#track)). A version the schema doesn't have rejects the event with `unknown_schema_version`. For an event name with no schema, `schemaVersion` is ignored. The SDKs leave off a value that isn't a version like `1-0-0`, with a debug log, and still send the event. Events your backend sends with [`POST /api/v1/events`](/docs/reference/server-api#post-api-v1-events) are checked the same way, and take the same optional `schemaVersion` field. ## How failures show up Rejected events and warnings, from the SDK or your backend, are listed under **Rejected events** on the SDK connection's page in the console (**Settings → Sending & SDK**, then the connection), kept for 30 days. A warning shows as **Schema warning (accepted)**. Up to 200 warnings are stored per app a day, apart from the 1,000 rejected events, so a busy event in **Accept and warn** mode never hides real rejects. The detail names the first failing property and rule, and the version checked, such as `properties.plan: must be one of free, pro (schema signup 1-0-0)`. A rejected event is also listed in the response's `rejected`, which the SDKs log at debug level and never retry. A warning isn't. See [Rejected events](/docs/reference/error-codes#rejected-events) for every reason code. Source: https://heraldsdk.com/docs/concepts/event-schemas.md --- # Computed attributes > Per-person values Herald computes from each person's events, such as how often they opened the app this week or when they last bought something, kept up to date as events arrive. Some of the most useful facts about a person come from what they do, not from what your app sets: "opened the app 3 times this week", "spent $40 in the last 30 days", "last purchase 2 days ago". A computed attribute is a value Herald works out for each person from their events and stores on their profile as `computed_`, next to the attributes your app sends. Set them up in the console under **Settings → Computed attributes** (admins). Each belongs to one app. ## Kinds | What to compute | Value | Window | |---|---|---| | Count of an event | How many times the event happened, as a whole number | Yes | | Sum of a property | The total of one numeric property on the event, rounded to 6 decimal places. Values that aren't numbers are ignored | Yes | | Last time an event happened | The time of the latest one, as an ISO-8601 UTC string such as `2026-11-20T10:00:00.000Z` | No: all history | | First time an event happened | The time of the earliest one, in the same format | No: all history | The event is a `track` event name, including the SDK's own [lifecycle events](/docs/reference/event-payload#lifecycle-events) such as `$app_opened`. `purchase` also matches purchase events, and a sum over purchases can read `price` and `quantity`. Events your backend sends with `POST /api/v1/events` count the same as SDK events. ## Windows A count or sum covers a trailing window: the last N hours or days from now, by the time each event happened, up to 90 days. As events age out of the window the value goes down, and when none are left it is `0`. The value stays `0` rather than disappearing, until you delete the computed attribute. A person who has never had a matching event has no value. To find them in a segment, use "does not exist". ## Which events count - Only accepted events: an event rejected by validation or an [event schema](/docs/concepts/event-schemas) never counts. - Only identified people. Events from before someone signed in count once Herald [links them at sign-in](/docs/concepts/users-and-identity). - Event times are the [corrected times](/docs/concepts/batching-and-offline#clock-correction) Herald stores. ## Freshness Values update on each event: when a batch, a server event or a server user import arrives for a person, their computed attributes for those events are worked out again right away, after the attributes the same request sets. Agent targeting reads the new value at once. Windows are re-checked hourly, so a count can take up to an hour to go down after an event ages out. Segments are rebuilt hourly too, so **a segment that uses a computed value can lag by up to an hour**. A new computed attribute, or one you edit, is filled in for everyone in the hour after you save it, in steps for larger apps. The list shows **Filling in… N%** until it is **Ready**. Deleting one removes `computed_` from every person the same way. ## Using values The value is an ordinary attribute named `computed_`; the console shows the name with a copy button. - **Segments:** an attribute condition on `computed_`, such as greater than 2 for a count. - **Agent targeting:** a target filter key, such as `computed_app_opens_7d__gte: 3`. - **The person's page:** values appear with the other attributes, under **Computed**. - **Message personalization:** `{{key}}` placeholders are filled from the data sent with each message, not from the profile, so include the computed value in that data when you want it in a message. ## Use as model signals Switch on **Use in personas and decisions** for a computed attribute to make it a model signal: Herald adds it to each person's profile numbers, so [personas and decisions](/docs/concepts/app-signals) reflect what people do in your app. Admins can do this on each row, or start from a template for your kind of app. - **Limit:** 6 per account, across its apps. The counter on the page reads "3 of 6 in use". At 6, the other switches can't be turned on until you turn one off; the API answers 400 with `An account can use at most 6 model signals`. - **Scaling:** each signal is put on a 0 to 1 scale from the values of your account's people. For last and first times, 1 means recent. - **Readiness:** the list shows **Ready**, **Scaling, ready within the hour** (the scale isn't computed yet, so the signal counts as 0 for everyone) or **Needs 30 people with a value** (it stays inactive until 30 people have one). - **Editing:** changing a computed attribute's definition clears its scale. It is worked out again within the hour. - **Changing the set:** turning a signal on or off, deleting one, or editing its definition makes LinUCB for the account relearn. Personas refresh at the next nightly discovery and match on the core numbers until then. Later signals move up one place when one is removed. See [App signals](/docs/concepts/app-signals). ## Reserved prefix Attribute keys starting with `computed_` belong to computed attributes. Your app and backend can't set them: in an SDK batch the event is rejected with `invalid_field`, and `POST /api/v1/users` answers 400. ## Limits Up to 20 computed attributes per app and 6 model signals per account, with windows of up to 90 days (2,160 hours). Names are lowercase letters, digits and `_`, start with a letter, are at most 40 characters, and are unique across the apps in your account. See [Limits](/docs/reference/limits). Source: https://heraldsdk.com/docs/concepts/computed-attributes.md --- # App signals > How Herald builds personas and decisions from ten core numbers plus up to six numbers from your own app, such as workouts this week, and how to start from a template for your kind of app. Herald describes each person with a short list of numbers. Personas group people with similar numbers, and decisions use them to pick the message most likely to work for that person. Out of the box the list says how someone responds to messages. **App signals** add what they do in your app. ## The core numbers Every person gets ten numbers, the same in every app: - Push response rate, email response rate and overall response rate. - The share of their activity in the morning, in the evening and on weekends. - How recently they were active. - How long they have been around (tenure). - Active days in the last 30. - Messages per week. These work with no setup. They describe when and how people respond, not what they use your app for. ## What signals add A signal is a [computed attribute](/docs/concepts/computed-attributes) you mark as **Use in personas and decisions**. Each account can use up to 6. A person's list becomes the ten core numbers followed by your signals, in the order you turned them on. A fitness app might add workouts this week, minutes this month and days since the last workout. Personas can then tell regulars from people who are drifting, and decisions can learn which message suits each. The core numbers stay for everyone, so an account with no signals works as before. ## Start from a template In the console, open **Settings → Computed attributes** and choose a category under **Start from a template**. Each suggestion is a ready computed attribute with a line on why it helps. Type or pick the event your app sends (the suggestions are the events Herald has seen; an event it hasn't seen yet is marked "Not seen in your events yet" and can still be added), then **Add** or **Add and use in model**. The event and property names below are suggestions only. | Category | Suggestions | |---|---| | Fitness | `workouts_7d` (count of `workout_completed`, 7 days); `workout_minutes_30d` (sum of `duration_minutes`, 30 days); `last_workout`; `programs_started_30d`; `personal_records_30d` | | Meditation and wellness | `sessions_7d` (count of `session_completed`, 7 days); `mindful_minutes_30d` (sum of `duration_minutes`, 30 days); `last_session`; `journal_entries_30d` | | Learning | `lessons_7d` (count of `lesson_completed`, 7 days); `quizzes_30d`; `last_lesson`; `courses_started_30d` | | Shopping | `purchases_90d` (count of `purchase`, 90 days); `revenue_90d` (sum of `value`, 90 days); `cart_adds_7d`; `last_purchase` | | Media and content | `items_viewed_7d` (count of `content_viewed`, 7 days); `watch_minutes_30d` (sum of `duration_minutes`, 30 days); `shares_30d`; `last_view` | | Finance | `transactions_30d` (count of `transaction`, 30 days); `transfers_30d`; `last_transaction`; `goals_set_90d` | | Games | `levels_7d` (count of `level_completed`, 7 days); `purchases_90d`; `last_level`; `matches_7d` | | Community | `posts_7d` (count of `post_created`, 7 days); `comments_7d`; `follows_30d`; `last_post` | Names starting with `last_` are "last time an event happened" attributes. The rest count an event, or sum a property, over the window in the name. ## Scaling and readiness Counts of 40 and sums of 3,000 minutes can't sit beside rates between 0 and 1, so Herald rescales each signal to 0 to 1. A person's number is where their value falls among everyone in your account who has one: 0 is the lowest, 1 the highest, 0.5 the middle. Someone with no value for a count or a sum counts as zero. The scale is checked hourly and refreshed daily, and again before each nightly persona discovery. A signal shows one of these statuses: - **Ready**: the scale exists and the signal is in use. - **Scaling, ready within the hour**: the scale isn't computed yet. Until it is, the signal counts as 0 for everyone, so it changes nothing. - **Needs 30 people with a value**: fewer than 30 people have a value. The signal stays inactive until they do. It is tried again within a day. ## Recent is high For "last time" and "first time" signals, the number is how recent the time is: 1 is very recent and 0 is the stalest, or no value at all. A person who worked out today scores near 1 on `last_workout`. Persona traits say "recent", "a while ago" or "long ago" for these, and "high", "mid" or "low" for the others. ## How personas use signals Nightly persona discovery groups people by the whole list, so signals shape the groups. Each discovered persona then shows its signals as small chips on its page, such as "Workouts 7d · high", under its other traits. Personas found before you added signals show no chips. Chips update at the next nightly discovery, so a signal you have just turned off or edited can still show until then. ## How decisions use signals Agents that use **LinUCB** read each person's whole list when they choose a message and learn from the result. With signals, it can learn that people with many workouts and a recent last workout respond to one message while drifting people respond to another. ## Thompson Sampling or LinUCB with many personas Both choose between your message variants, but they share learning differently. - **Thompson Sampling** keeps separate results for each persona and learns a winner per persona. Each persona needs enough sends and responses of its own, so with many personas it learns slowly, and small personas stay uncertain longer. - **LinUCB** uses each person's numbers directly and shares what it learns across everyone. A response from one person teaches it about people who look like them. It suits accounts with many personas, or with signals. ## Changing the signal set Turning a signal on or off, deleting it, or editing its computed attribute's definition changes what every person's list means. - **LinUCB** relearns for your account. Its earlier results were for a different list, so Herald starts fresh rather than mixing them. Results for decisions made before the change are not applied to the new learning. - **Personas** refresh at the next nightly discovery. Until then, people are matched to personas found on a different set of signals using the ten core numbers only, so persona-targeted agents keep sending. - **Thompson Sampling** is unaffected: it doesn't use the list. Turning a signal off, or deleting its computed attribute, takes it out at once and moves later signals up one place. ## Limits 6 signals per account, across all its apps. A signal can't be turned on once 6 are in use; turn one off first. Moving an app into an account can leave more than 6 on: then only 6 are used, the counter reads, for example, "7 of 6 in use — turn one off", and the others show **Not used: over the limit of 6**. See [Limits](/docs/reference/limits). Source: https://heraldsdk.com/docs/concepts/app-signals.md --- # Media library > Pick, upload and reuse images and videos in Herald, search free photos and videos from Unsplash and Pexels, and where each channel shows a video. The media library is where you choose the image or video for a push, an in-app message, a content card or an email. Every image field in Herald's message editors has a **Choose media** button that opens it. You can still use **Paste URL** to type an image address yourself. ## Choose media The picker has these tabs: | Tab | What it holds | |---|---| | Library | Everything your account used or uploaded before: uploads, stock items and generated images. Filter by images or videos. Library items are shared across your apps. | | Unsplash | Free photos. The tab says "Photos from Unsplash". | | Pexels | Free photos and videos. The tab says "Photos and videos provided by Pexels". | | Generate | AI image generation, shown only where it is turned on for your account. | Search either provider, narrow by orientation (landscape, portrait or square) and choose **Load more** for further results. When you choose **Use this image** or **Use this video**, Herald saves the item to your library and sizes the picture for the channel you are editing. If a provider is not set up for your deployment, its tab is hidden. If you search a lot in a short time you may see "Too many searches. Try again in a few minutes." or " is busy. Try again soon." Searches you have made recently are served from a cache and don't count against these limits. ## Upload your own Choose **Upload** on the Library tab. - Images: JPEG, PNG, GIF or WebP, up to 10 MB. - Videos: MP4, up to 50 MB. Herald takes a poster image from the first frame of the video in your browser. Where uploads aren't set up for your deployment, the Library tab says "Uploads aren't set up". Deleting a file asks "Delete this file?" and adds "It stays in messages that already use it." Messages keep the address they saved, so a file you deleted may stop loading later; delete a file only when no message needs it. ## Image sizes Herald sizes a stock photo for the channel it is going to. Your own uploads and generated images are used as they are, so upload them at a size that suits the channel. | Channel | Size | |---|---| | Push, iOS and Android | 1,024 by 512 pixels, JPEG | | In-app message | 1,080 by 1,080 pixels | | Content card | 1,200 by 800 pixels | | Email | 1,200 pixels wide | The editor warns you when an uploaded image's shape doesn't match the channel ("It will be cropped"), when a push image is over 1 MB ("may not show on Android push") or WebP ("may not show on iOS push"). ## Video A video always comes with a poster image, and the message's image is that poster. That keeps every older app, and every channel without video support, showing a picture. | Channel | What people see | |---|---| | iOS push | The video, when the app has the Notification Service Extension and the video is MP4 or QuickTime and at most 10 MB. Otherwise the poster, then the text. | | Android push | The poster. | | In-app message | The poster with a play button in modal and full-screen messages. A tap plays it with sound. Slideup and HTML messages show no video. | | Content card | The poster with a play button in captioned-image cards. A tap plays it with sound. | | Email | The poster, linked to the video, with a "Watch the video" link. | Video needs SDK 0.6.0 or later in the app. Older SDKs show the poster. See [Rich push](/docs/push-notifications/rich-push#video), [In-app messages](/docs/in-app-messages/authoring#video) and [Content cards](/docs/content-cards/authoring#video). When you choose a Pexels video for a push, Herald picks a version of at most 720p and prefers one that is 10 MB or less. If none is that small, the editor warns "This video is too large for iOS push. iOS will show the poster." ## Credits Photos and videos from Unsplash and Pexels carry the creator's name and links. In email, Herald can add a line such as "Photo by Ada on Unsplash" or "Video by Jo on Pexels" that links to the creator and the provider. In-app messages and content cards carry the credit in `credit` for apps that want to show it (see the [event payload](/docs/reference/event-payload#interaction) and the SDK references). Unsplash and Pexels ask that you credit creators where it is practical. ## Allowed sources A message that carries media can only use pictures and videos from Unsplash, Pexels or your Herald uploads. Herald refuses any other address with "Media URLs must use a supported host." A message with a plain pasted image URL has no such rule. See [Limits](/docs/reference/limits#media) for every size and search limit. Source: https://heraldsdk.com/docs/concepts/media-library.md --- # Geofences > Add places in the console and get an event when someone with your app enters or leaves one, with the opt-in geofence module for iOS and Android. The SDK never asks for location permission and never sends the device's location. SDK 0.7.0 and later. Not released yet. A geofence is a circle around a place, such as a store. When someone with your app enters or leaves one, the SDK sends a `track` event, `$geofence_enter` or `$geofence_exit`. You use those events like any other: in [segments](/docs/concepts/events-and-attributes), as an [in-app message trigger](/docs/in-app-messages/triggers-and-delivery), and in agent goals and targeting. There is no separate geofence campaign type. ## How it protects privacy - The SDK never asks for location permission. Your app asks, with its own explanation, before it turns geofences on. - The SDK reads no location until your app calls `enableGeofences()`. - The SDK downloads the app's whole geofence list. It never sends the device's location to Herald to find nearby places. - What reaches Herald is only the crossing: the geofence's id and name, as an event. The SDK sends no coordinates. - Geofences are a separate module. An app that doesn't add it never links CoreLocation (iOS) or Play Services location (Android). ## 1. Add geofences in the console Open Settings, **Geofences**, with the app in view. Each geofence has a name, a latitude and longitude, and a radius from 100 meters to 10 kilometers. An app can have up to 100. Type the coordinates (copy them from any map app) and use **Open in map** to check the point. Only admins can add, change or delete geofences. ## 2. Add the module :::tabs ::tab ios Add the `HeraldGeofence` library product from the Herald Swift package to your app target, next to `HeraldSDK`. ```swift .product(name: "HeraldGeofence", package: "herald-ios"), ``` ::tab android ```kotlin // app/build.gradle.kts dependencies { implementation("com.github.ender1311.herald-android:herald-geofence:0.7.0") } ``` `herald-geofence` depends on Play Services location (`play-services-location` 21.3.0) and adds no permissions to your manifest. Your app declares `ACCESS_FINE_LOCATION` and `ACCESS_BACKGROUND_LOCATION` itself. ::: ## 3. Get permission, then turn it on Ask for background location in your app's own flow: "Always" on iOS (with `NSLocationAlwaysAndWhenInUseUsageDescription` and `NSLocationWhenInUseUsageDescription` in Info.plist), and fine plus background location on Android 10 and later. Then call `enableGeofences()` after `configure`, at every launch, including when the system starts the app in the background for a crossing. On Android this is also what registers the geofences again after the phone restarts. Without the permission it logs a warning and does nothing. :::tabs ::tab ios ```swift import HeraldGeofence // In application(_:didFinishLaunchingWithOptions:), after Herald.configure, once the person granted Always: Herald.shared.enableGeofences() ``` ::tab android ```kotlin import com.herald.geofence.enableGeofences // In Application.onCreate, after Herald.configure, once the person granted fine and background location: Herald.enableGeofences() ``` ::: `disableGeofences()` stops monitoring until the next `enableGeofences()`. Call it when the person turns location features off in your app. ## What the SDK monitors | | iOS | Android | |---|---|---| | How | Core Location region monitoring | Play Services `GeofencingClient` | | How many | The 20 nearest (Apple's limit, minus regions your app monitors itself) | All of them: an app has at most 100, which is Google's limit | | Picking the nearest | By distance to the edge, from the last known location, re-picked on significant location change when the app has more than fit | Not needed | | Already inside when it starts | No event until the person leaves and comes back | Same | | After a restart, or Location turned off and on | Keeps monitoring: iOS keeps the regions | Stops until the app next opens, which registers them again. Android drops an app's geofences on restart and when Location is turned off. | The SDK fetches the list at each `enableGeofences()` and keeps the last one on the device, so a launch without a network uses it. Changes in the console reach a device the next time the app starts. ## The events | Name | Properties | |---|---| | `$geofence_enter` | `geofence_id`, `geofence_name` (strings) | | `$geofence_exit` | `geofence_id`, `geofence_name` (strings) | The SDK sends at most one event per geofence and direction every 5 minutes, so a person walking along the edge doesn't send a burst. Crossings happen in the background, so they don't count as app activity (last active, active days or send-time checks). While the SDK is off (`setEnabled(false)` or `wipeData()`), crossings send nothing. At the next `enableGeofences()` or crossing, the SDK also stops monitoring and deletes the geofence data it kept on the device (the cached list and the last crossing times). ## Turn it off for every device Settings, **SDK settings**, **Geofences**: set it to **Off** and the SDK stops monitoring on every device the next time the app starts, even in apps that call `enableGeofences()`. **Use app's value** and **On** both leave it to the app. ## Limits - Up to 100 geofences per app, each with a radius of 100 to 10,000 meters and a name of up to 100 characters. - Android: after the phone restarts, or Location is turned off and back on, geofences resume the next time the app opens. iOS keeps them. - iOS and Android decide when to report a crossing. It can take a few minutes, and small circles in places with few Wi-Fi networks or cell towers are less reliable. Apple and Google recommend a radius of at least 100 to 150 meters. - React Native, Flutter and Unity apps can use geofences from the native side of the app; the wrappers don't include them yet. ## Related - [Data collection controls](/docs/data-and-privacy/data-collection-controls) - [App store disclosures](/docs/data-and-privacy/app-store-disclosures) - [Event payload](/docs/reference/event-payload#geofence-events) - [GET /api/v1/sdk/geofences](/docs/reference/rest-endpoints#get-api-v1-sdk-geofences) Source: https://heraldsdk.com/docs/concepts/geofences.md --- # Journeys > Multi-step flows that follow each person over days or weeks. Which events start them, how steps work, what counts as converted, and the events your app needs to send. A journey follows each person through a series of steps: a welcome series, a nudge when someone stalls, a win-back when they go quiet. You build it in the Herald console under **Messaging → Journeys**. Your app's part is sending the events that start a journey, move people along it and count as its goal. :::prereq - The SDK installed, with people identified by their External ID (see [Users and identity](/docs/concepts/users-and-identity)). - The events you want to use sent with `track()` (see [Events and attributes](/docs/concepts/events-and-attributes)). - At least one channel set up for the app: push, email, in-app messages or content cards. ::: ## Simple by default The builder starts with the basics: entry by event, Send a message, Wait, Wait for an action, Split by audience and End, plus the goal and analytics. Everything else is a switch under **Settings → General → Journey features**: versions, smarter sending, the extra steps, entry by audience or API, test runs, holdout and re-entry. Each person chooses for themselves; an account admin sets what the team starts with under **Settings → Members**. Hiding a feature only removes it from the menus. A journey that already uses it always shows it, so nobody loses sight of a teammate's work. ## How a journey runs 1. **People enter.** Choose one of three ways on the entry step: - **When they do an action:** each identified person who does the entry event after the journey is published. People who did it before don't enter. - **When they're in an audience:** everyone in the audience when you publish, and anyone who joins it later. - **When your server adds them (API):** your backend calls [`POST /api/v1/journeys/{id}/enter`](/docs/reference/server-api#post-api-v1-journeys-id-enter). With an action or the API, you can also limit entry to an audience. 2. **They move through the steps.** Each step either sends a message, waits, or picks a path. People move as soon as a step allows it. 3. **They finish.** A path ends at an End step or where nothing follows. People who do the goal event leave early and count as converted. A person is never in the same journey twice at once. Whether they can enter again later is a journey setting: once only, or again after a number of days. ## Steps | Step | What it does | |---|---| | Send a message | Sends push, email, an in-app message or a content card. Each person gets every channel they can receive. | | Wait | Holds people for a set time, from 1 minute to 365 days. | | Wait for an action | Waits until the person does an event, or opens or taps a message sent earlier in the journey, up to a time limit. They take **Did it** as soon as they do it, or **Timed out** when the limit passes. | | Split by audience | Sends people down the first path whose audience they're in, checked top to bottom. Everyone else takes the last path. | | End | Finishes the path. The step's name shows in analytics as how people finished. | More steps, listed after the basics: | Step | What it does | |---|---| | Random split | Places each person on a path at random by share (for example 50% and 50%), and keeps them there. Use it to compare two paths. | | Update profile | Sets attributes on the person's profile, as if your app had sent them with `identify()`. Contact fields (`$email`, `$phone`) can't be set here. | | Add to an audience | Adds the person to an audience, or takes out people a journey added. Audiences built from rules keep updating on their own. | | Send a webhook | Sends a `POST` to your https address with the journey, the step and the External ID of everyone who reached it, about once a minute. | ### Webhook body ```json { "journey": { "id": "j_123", "name": "First-week welcome" }, "step": { "id": "s4k2p1", "name": "Tell the CRM" }, "people": [{ "externalId": "user_42" }], "sentAt": "2026-11-26T09:00:00Z" } ``` Answer with any 2xx status. Redirects aren't followed. If the call fails, it's tried again for an hour; after that, the people at the step move on and count as dropped with the reason **Error**. ## What a wait can wait for Pick from a list, or type an event name: - **This journey's messages:** **Opened** counts a push tap, an email open, or an in-app message or card that was shown. **Tapped or clicked** counts a push tap, a link click in the email, or a tap on the in-app message or card. Only messages earlier on the same path are offered, and engagement counts from when the person entered the journey. Email opens can be counted early by mail apps that load images on their own, so prefer **Tapped or clicked** for email. - **Your events:** the custom events your app sent in the last 30 days, plus events with a schema that haven't arrived yet. - **App activity:** the events the SDK sends on its own (SDK 0.6.0 and later): `session_start`, `$app_opened`, `$app_foreground`, `$app_background`, `$app_installed`, `$app_updated`, `$deep_link_opened`, and `purchase`. - **Screens:** screen names your app sent with `screen()`. Event names must match exactly. If no one has sent the name you type in the last 30 days, the builder says so, so a typo doesn't quietly send everyone down **Timed out**. The entry event and the goal use the same list. ## Versions and smarter sending A message step can do more than send one message: - **Versions (A/B):** add up to three more versions of the message (B, C, D), each starting as a copy of A. Split people evenly, or let the engine pick: each person gets a version chosen by how well each has led to the journey's goal so far, so more people get the winner while the others keep being tried. The engine needs a goal. With **Let Herald choose per person**, each person gets the version most likely to add [long-term value](/docs/concepts/long-term-value#journeys) for them, with no goal needed. Analytics shows each version's conversion rate. - **When to send:** right away, or at each person's usual time, the hour they're most often active, within the next day. People Herald doesn't know yet get it right away. - **Channels:** every channel they can receive, or just the channel each person has responded to most. People with no history get every channel. Each person's path shows which version they got, by which channel and when, so no choice is hidden. ## Messages follow your guardrails Journey messages go through the same delivery as campaigns, so: - the app's push limit across every source applies, - quiet hours hold a message until the person's morning, - send-time checks skip people who no longer qualify. ## Goal and holdout - **Goal:** an event that counts as success, within 1 to 30 days of entering. People who do it leave the journey and count as converted. - **Holdout:** a share of the people who enter (10% by default, up to 50%) who get no messages. They're watched for the goal over the same window, so **Lift vs holdout** shows what the journey adds. ## Analytics The Analytics tab shows how many people are in the journey now, how many entered and converted, and lift vs holdout, then the same counts on every step. Pick **All time** or the last 7, 30 or 90 days: a range counts the people who entered in it and what happened at each step in it, while **In journey now** is always live. Click any number to see the people behind it, then one person's path. ## Test a journey Before publishing, select **Test** and enter someone's External ID. The builder shows the path they would take through the draft, using the audiences they're in now, and highlights it on the canvas. Waits are skipped, and you choose whether they do each action the journey waits for. Nothing is sent. ## Drafts and publishing The builder saves your draft as you work, and **Save draft** saves it right away. Nothing goes live until you publish. Changes to a live journey are a draft until you publish them. The review shows what changes and, if you remove a step people are waiting at, lets you move them to the next step or take them out. Each publish saves a version you can restore as the draft. ## Events your app sends A journey only sees what your app sends. Use the same event names in your app and the journey: ```swift Herald.shared.track("onboarding_complete") ``` ```kotlin Herald.track("onboarding_complete") ``` Events count from when Herald receives them, so an event sent from an offline device starts a journey when the device comes back online. ## Limits | Limit | Value | |---|---| | Steps per journey | 100 | | Paths per split | 8, plus everyone else | | Paths per random split | 2 to 8, shares in whole percent adding up to 100 | | Attributes per Update profile step | 20 | | Wait and time limit | 1 minute to 365 days | | Goal window | 1 to 30 days | | Holdout | 0% to 50% | | How often people move along | about every minute; **Wait for an action** checks every 5 minutes | Source: https://heraldsdk.com/docs/concepts/journeys.md --- # How Herald learns with small audiences > How Herald starts a new agent from public benchmarks and your app's own history, lets small personas borrow from the whole agent, and tells you when your traffic is too thin for your setup. An agent picks the best message by trying variants and watching what people do. With a large audience that works quickly. With a small one, a variant may see only a handful of conversions a month, and splitting that across several personas leaves each choice close to a coin flip. Herald has four things that help. ## Where a new agent starts A new agent does not start from zero. It starts from realistic numbers, built up in layers: 1. **Public benchmarks.** For each channel (push, email, SMS, in-app, content cards, web push) Herald uses published engagement rates as a first guess, adjusted for triggered messages, which beat broadcasts, and for your app's category if you set one under Settings, General, **App category**. 2. **Your app's history.** The agent's guess then moves toward what your own app's messages have earned over the last 180 days. 3. **The whole agent.** A variant's result is pooled across all the agent's personas. 4. **The persona, then the person.** Each persona starts from the pooled result for the variant and adds its own results. A person's own history is added last. Each layer is only a starting point. Your own results take over within weeks, and a new variant can still prove itself quickly. A few headline figures that set the first guess, all from public reports: - Median push direct open rate of about 3% of sends: [Airship push benchmarks](https://www.airship.com/mobile-app-push-notification-benchmarks-for-2026/). - Email click rates of about 1.7% for campaigns against about 5.6% for automated flows: [Klaviyo email benchmarks](https://www.klaviyo.com/products/email-marketing/benchmarks). - Messages within one app differ only a little on average, which is why Herald keeps these starting guesses weak and lets your data lead: [Yancey and Settles, Duolingo, KDD 2020](https://research.duolingo.com/papers/yancey.kdd20.pdf). These are published rates of engagement, not promises about your results. ## Learn faster with small audiences On a Thompson Sampling agent, the agent's **Settings** has a toggle, **Learn faster with small audiences**: "Starts from benchmarks for apps like yours and lets small personas borrow from the whole agent. Recommended." - New Thompson Sampling agents have it on. - Agents you made earlier keep their current learning method until you turn it on. - Turning it off goes back to the earlier behavior. Your settings, such as how fast old results fade, stay as they were. With it on, a persona with little data borrows from the whole agent. A persona with a lot of data, and clearly different results from the others, relies on its own. Herald works out how much to borrow from the data itself. ## Learning fit The agent's **Performance** tab shows a **Learning fit** card with a colored dot. It compares your traffic with your setup, counting conversions per variant per week: | Dot | Conversions per variant per week | Meaning | |---|---|---| | Green | 50 or more | Traffic is enough for this setup. | | Amber | 5 to 50 | Learning is slow. | | Red | Under 5 | Too little to learn from reliably. | Below green, the card says what to change: keep two or three variants until one pulls ahead, keep your personas (small ones borrow from the whole agent) or turn on the toggle above, or use Thompson Sampling instead of LinUCB. ## LinUCB needs more traffic LinUCB uses each person's profile and needs about 50 conversions per variant each week to learn well. If you pick it with less, the algorithm picker shows a warning. You can still choose it. Herald never switches your algorithm for you. ## Old results fade toward the starting guess Old results lose weight over time, so an agent can follow changes in what people like. They now fade back to the arm's starting point, not past it, so a quiet variant does not drift into random picking. This applies to every agent. Source: https://heraldsdk.com/docs/concepts/learning-with-small-audiences.md --- # Message priority and attention budget > How Herald ranks messages into categories and gives each person an attention budget that adapts to how they respond, what happens to a message held back, and how the Send API takes part. People stop reading when they get too much. Herald keeps each person's messages under a budget that rests on two ideas: every message belongs to a **category**, and every person has an **attention budget** per channel. When someone's budget is full, the higher-ranked message goes first. Set both under **Settings → Messaging limits** (admins). Each app has its own. ## Categories A category ranks a kind of message and can cap how many of it one person gets. Every campaign and agent has a **Category** select ("Higher categories win when someone's budget is full."). These are the defaults: | Category | Rank | Cap per person per channel | Useful for | |---|---|---|---| | Transactional | 0 | Never limited, never held, doesn't count toward the budget | n/a | | Lifecycle | 1 | No cap | 72 hours | | Engagement | 2 | 2 a day | 48 hours | | Promotions | 3 | 1 a day, 3 a week | 24 hours | A lower rank wins. Admins can rename categories, add new ones (rank 1 or higher), reorder them, and change each cap and its "useful for" time. Engagement and Transactional can't be deleted. Deleting another category moves its campaigns and agents to Engagement. Only admins can give a message the Transactional category in the console; any API key can send it through the [Send API](/docs/reference/send-api). A category cap applies per person per channel, and can't go past the channel's own limit: the cap in force is the lower of the two. ## Channel limits Each channel has a budget range per person, counted over the trailing 24 hours and the trailing 7 days. An empty maximum means no limit. | Channel | Max a day | Max a week | Min a week | |---|---|---|---| | Push | 3 | 8 | 1 | | Web push | 3 | 8 | 1 | | Email | 1 | 4 | 1 | | SMS | 1 | 2 | 1 | The same page sets a weekly message aim for long-term value agents and which agent gets a person when several want them. See [Attention as a budget](/docs/concepts/long-term-value#attention-as-a-budget). ## The adaptive budget Within its range, each person's weekly allowance follows a score from 0 to 1, starting at 0.7: allowance = min + round((max − min) × score) A new person on push therefore gets 1 + round(7 × 0.7) = 6 pushes a week. The score moves each night: | What happened | Score | |---|---| | The person opened a message | +0.05 | | The person clicked | +0.10 | | From the 3rd send in a row that was ignored | −0.10 for each | | Opt-out, unsubscribe or complaint on another channel | −0.30 | | Uninstall, or 14 days inactive | −0.20, at most once per 14 days | | 7 quiet days | Drifts 0.02 a day back toward 0.7 | The daily limit is never adaptive. Turn the adaptive weekly budget off and the weekly allowance is the channel's maximum. ### Which sends can show engagement A send counts as ignored only where Herald records opens, which is email and agent pushes. Campaign and Send API pushes, web push and SMS don't report opens, so on those channels the score changes only on opt-outs, uninstalls and inactivity. ## Observe and Enforce | Mode | What it does | |---|---| | Observe | The default for apps that existed before this feature. Herald records what it would have held back and shows it, but holds nothing new. The old push limit and campaign spacing keep working. | | Enforce | The default for new apps. The budget replaces the push limit and the 72-hour and 24-hour campaign spacing. | Switching back to Observe is the kill switch: it stops all budget holds at once. ## When a message is held - **Campaign messages** (including scheduled ones) wait for the person's next free slot, moved out of quiet hours. If no slot opens within the category's "useful for" time, the message is dropped. - **AI agent messages** are skipped. The agent decides again on its next run. - A message queued within the next 24 hours with a higher priority reserves the last slot, so a lower one doesn't take it. A held message is recorded as suppressed with a reason, shown in the console as "Held back" with one of: | Console label | Reason | |---|---| | person's budget was full | `budget:budget_full` | | category limit reached | `budget:category_cap` | | held for a higher-priority message | `budget:reserved` | | waited, but no slot opened in time | `budget:expired` | Campaign results show "Delayed by the budget: N, avg wait X h". An agent's performance page has a "Held back" card. ## The Send API `POST /api/v1/messages/send` takes an optional `category`, one of your app's category keys. An unknown key returns 400 with `category must be one of: `. - **With a category:** the normal rules apply. Transactional is exempt. In Enforce mode, any other category is held or deferred like a campaign message. - **Without one:** nothing changes. The message is never held, and counts toward the channel limit but not toward any category cap. Pass a category on every send. See the [Send API reference](/docs/reference/send-api). ## Pushes your app sends A `$external_push` event with `category: "transactional"` doesn't count toward the budget. Other `$external_push` events count toward the push channel only. See [Pushes your app sends](/docs/push-notifications/pushes-your-app-sends). ## Related - [How delivery works](/docs/concepts/how-delivery-works) - [Limits](/docs/reference/limits) Source: https://heraldsdk.com/docs/concepts/message-priority.md --- # Long-term value > How a Thompson Sampling agent can learn which messages make people use your app more over the next 90 days, compared with people who got nothing, and skip a send when no message is likely to help. By default an agent learns from a goal soon after each send. A message can win that way and still hurt: a pushy message gets clicks today and uninstalls next week. On a Thompson Sampling agent you can switch the agent's **Settings**, **What Herald learns from**, to **Long-term value** instead. ## What counts as value Value is counted in one unit: active days over the next 90 days. Each day someone uses your app counts once, however many sessions they have. On top of that: - **Shares.** Each event named `share` is worth 7 active days. - **Referrals.** Each event named `referral_signup`, sent when a friend someone invited signs up, is worth 30 active days. - **Purchases.** Revenue is turned into active days at your app's average revenue per active day over the last 90 days. Annoyance costs value too. An unsubscribe costs 1, turning off push 2, an uninstall 3 and a spam complaint 3, where 1 is an average person's next 90 days. ## How a message gets credit Herald compares each person who got a message with people who got nothing: the agent's holdout group, and people it chose not to message. It looks at how active the person was in the 28 days before the send and estimates their next 90 days from what they do after it. A message gets credit only for value above what similar people did without one, minus any annoyance beyond the holdout group's rate. Results start after a day, are corrected after three days and settle after a week, when annoyance is checked. ## No repeated messages A long-term value agent doesn't send someone a message they got from it in the last 7 days, even if it's the strongest one. When the person has had every message in that time, the agent sends the one they got longest ago, so messages take turns. ## Skipping a send With long-term value on, a second option appears: **Skip a send when it's unlikely to help**. Sending nothing is then one of the choices, with a value of exactly zero. If no message is likely to beat that for a person, Herald sends nothing and tries again on a later day. A small share of picks still tries every option, so the agent keeps learning. ## Small apps and big apps A small app starts with a simple estimate: a person's activity rate over the days measured, times 90 days, allowing for some drop-off. Once 2,000 of your app's messages, skips and holdout picks have a full 90 days measured, Herald fits its own estimate each week and uses it only while it predicts better than the simple one. It fits a second one the same way from the 28 days before a message alone, which is what each person's next 90 days would likely have been without it; a message's credit is measured from there. Personas with little data borrow from the whole agent, as with [learning with small audiences](/docs/concepts/learning-with-small-audiences). The agent's results show a **Long-term value lift** card: extra active days per person over 90 days compared with people who got nothing, with a 95% range. It needs 200 people who got a message and 200 who didn't, each at least a week ago. ## Message features Every message variant can carry a few features: its **Tone** (practical, warm, curious, urgent, playful or celebratory), **Approach** (progress, social proof, fear of missing out, curiosity, reward, reminder, news or personal), **Offer** (none, discount, free trial, content or feature), **Call to action** (open the app, buy, read, watch, share, invite, update or none), **Length** (short, medium or long), and whether it's **Personalized** and **Uses emoji**. Set them under **Message features** when you edit a variant. You don't have to fill them in by hand. When someone adds a message or changes its copy, Herald asks AI to fill the features of any variant that has none. People who can edit the message library can press **Fill with AI** on a variant to get a suggestion to check before saving, and admins can press **Tag messages** on an agent's Messages page to fill up to 20 messages at a time that don't have features yet. Each variant AI fills counts as one AI copy request against your daily limit, and filling stops when the limit is used up. Features you save yourself replace what AI filled. With features, an agent can learn **by message features** instead of by persona: which kinds of message work for which kinds of person. It looks at how engaged someone has been (active fewer than 3 of the last 30 days, 3 to 14, or more than 14), their lifecycle stage and how recently they were active. A brand-new message then starts from what similar messages did for similar people, instead of from scratch. Learning by features needs more traffic than learning by persona, and it doesn't forget old results, so a big change in what your audience likes takes longer to show. ## Testing a new approach Each agent has a **Learning** tab. On a long-term value agent it shows the agent's **Current approach**, **Long-term value, by persona** or **Long-term value, by message features**, and a suggestion. The suggestion counts the decisions the agent made per message per week over the last four weeks: under 200 is too few to compare approaches, so it suggests keeping the current one; otherwise it suggests learning by message features when at least half the agent's messages have features, and by persona when they don't. Admins can test the other approach in one of two ways, with at most two tests running per agent: - **Try in shadow.** The new approach scores every decision and records what it would have done, without sending anything. **Check on past decisions** estimates how it would have done on the last 60 days of decisions it saw, once at least 1,000 of them have a full week of results. - **Give it 10% of people.** The new approach decides for a fixed 10% of people. Once 200 decisions on each side have a full week of results, the page compares the two. Either way the result is the extra active days per person over 90 days compared with the current approach, with a 95% range. **Make it the current approach** is available only once the whole 95% range is above zero; it stops any other test. A test given 10% of people is stopped automatically, checked once a day, if its unsubscribes, push opt-outs, uninstalls and spam complaints per message are more than 50% higher than the current approach's over the last 30 days, once it has at least 30 of them. ## Learning from other apps Admins can turn on **Share and learn across accounts** under Settings, General, **Learn from other apps**. It's off by default. Every night, Herald combines what has been learned in the accounts that have it on, weighting each by how much it has learned: what each kind of message feature is worth with each kind of person, from agents with at least 200 results, and each app's fitted estimate of the next 90 days. Only these learned numbers are shared, never your data or your users, and only between accounts that share. Your account then gets a head start: a new agent learning by message features starts from the shared numbers instead of from zero, and until your app fits its own estimate of the next 90 days, it uses the shared one. The shared numbers exist only once at least two accounts contribute. While only a few accounts share, the one that has learned the most counts for most of the result. Turn sharing off and you stop getting the head start too. ## Time and channel An agent's messages can go out on different channels, so the agent already chooses the channel when it chooses a message. An agent that learns by message features also learns which channel works for which kind of person. Such an agent can also choose the time of day: tick **Choose the time of day too** under what the agent learns from. When it's on, the agent decides for each person about once a day: it picks a message and a three-hour block in the person's local time (6-9, 9-12, 12-15, 15-18 or 18-21) that starts within the next 24 hours, outside the agent's quiet hours and blackout dates. Pushes never get the 6-9 block. The message goes out at the person's usual time if it falls inside that block, otherwise when the block starts, and the messaging limits are checked again right before it goes out. Content cards, modal in-app messages and in-app messages without a title still go at once. Value is measured from when the message was due to go out. This works only for messages Herald delivers itself; with any other sending connection the agent chooses only the message. ## Journeys A journey's message step with versions can **Let Herald choose per person**: each person gets the version most likely to add long-term value for them. Turn it on under Settings, General, **Journey features**. Each step learns on its own, from people who got a version compared with the journey's holdout group, counted when they enter the journey. It doesn't need a journey goal. Give it a few weeks before it learns. Tick **Allow skipping this message** and sending nothing becomes one of the choices: a person it's unlikely to help moves on to the next step without the message. A version with no valid content isn't a choice. ## Attention as a budget Each message uses some of a person's attention. Under Settings, **Messaging limits**, admins can set **Messages per person per week, aim**. Every day Herald counts the messages your long-term value agents sent over the last 7 days per person who was active in that time, and moves a price toward your aim: up when they sent more, down when they sent less, never below zero. Long-term value agents then send only a message they estimate is worth more than the price, even when **Skip a send when it's unlikely to help** is off, so volume lands near your aim. Leave it empty and there's no price. Agents that learn from goals ignore it. **When several agents want the same person** decides who gets them on a run: - **Highest priority agent first** (the default): the agent highest in your priority order, as before. - **Agent whose message adds the most value**: among the long-term value agents that want the person, the one whose best message is estimated to add the most value gets them, if it's worth more than the price; if none is, nobody messages them on that run. Message categories still come first: only agents in the person's highest category compete, and agents in that category that don't learn long-term value get first pick, in priority order. A long-term value agent's results show a **Sending less** card when messages make some of its personas less active than people who got nothing. A persona counts once at least 200 of its people got a message and 200 didn't over the last 90 days, and the whole 95% range is below zero. The card reads "Sending less to these N people would add an estimated X active days per person over 90 days", with a 95% range. ## New messages On a long-term value agent's **Learning** tab, admins can turn on **Write new messages each week**. Every Monday, Herald asks AI for up to the number you choose (1 to 5, 2 by default) of new messages, based on what's working: the message features worth the most to the agent, or its best messages. They're added to the message of the agent's best variant, with their features filled. For email, the new versions try new subject lines. Under **New messages**, choose **Wait for my approval** and each one shows on the agent's messages as **Suggested by Herald**, never sent until someone who can edit the message library presses **Approve** (or **Discard**). Choose **Start sending them** and they go live at once with a week's warm-up. No new messages are written while that many suggestions are still waiting. Writing them counts against your daily AI copy limit: one request for the drafts and one per new message to fill its features. If today's limit can't cover that, the agent waits for next week. **Pause messages that can't win** pauses a message once it has been sent 500 times and has less than a 1% chance of being the best. It never leaves an agent with fewer than 2 active messages. ## Sequence learning for very large apps The other approaches judge each message on its own. **Long-term value, sequence learning** learns which series of messages works best over time: it knows how many messages someone got in the last day and week, how long ago the last one was, what it was like, and how engaged the person is, so it can learn that a message that works today makes the next one work less, or that waiting a day pays off. Every night it refits from the agent's most recent decisions, up to 200,000, and it's cautious with choices the agent has rarely made. It follows the price too. It needs a lot of traffic: about 50,000 decisions a month. The Learning tab suggests it once an agent records that many, and it can only be tested, in shadow or on 10% of people, never switched on directly. Until its first nightly fit it decides like learning by persona. Making it the current approach takes two checks. One is the usual check on past decisions, or the comparison on 10% of people. The other is a simulation: Herald builds a model of your app from the agent's last 90 days of decisions, then runs the current approach and sequence learning for 90 simulated days on the same simulated people, up to 5,000 of them. The result reads "In a simulation of your app over 90 days: +X active days per person compared with the current approach", with a 95% range. Admins run it with **Check on past decisions**; a run stops after about 3 minutes, and a result from the last 24 hours that's newer than the model is reused. **Make it the current approach** is available once the whole 95% range is above zero in both checks. ## Settings Admins can change what counts under Settings, General, **How long-term value is counted**, for each app: what a share and a referral signup are worth, whether purchases count, and what each kind of annoyance costs. Agents that learn from goals ignore them. Source: https://heraldsdk.com/docs/concepts/long-term-value.md --- # iOS setup > Connect Herald to Apple Push Notification service with an APNs auth key, register device tokens and handle notification taps. This guide connects Herald to Apple Push Notification service (APNs) and wires your app to register for push and report opens. ## Before you start - An Apple Developer Program membership with access to **Certificates, Identifiers & Profiles**. - The SDK installed and configured. See [Quickstart: iOS](/docs/overview/quickstart-ios). - Admin access to the Herald sending connection your agents use. ## 1. Create an APNs auth key 1. In your Apple Developer account, open **Certificates, Identifiers & Profiles > Keys** and add a key with **Apple Push Notifications service (APNs)** enabled. 2. Download the `.p8` file. Apple lets you download it once, so store it in your secrets manager. 3. Note the **Key ID** (10 characters) and your **Team ID** (10 characters, under **Membership details**). One auth key works for every app on your team and for both the sandbox and production APNs environments. ## 2. Add the key to Herald In Herald, open **Settings > Sending**, open the connection and fill the APNs section: | Field | Value | |---|---| | Key (`.p8`) | The file from step 1 | | Key ID | 10 characters | | Team ID | 10 characters | | Bundle ID | Your app's bundle identifier, such as `com.lumen.app` | Herald stores the key encrypted and uses it to sign short-lived tokens for APNs. ## 3. Turn on the capability In Xcode, select your app target, open **Signing & Capabilities** and add **Push Notifications**. Visible alerts do not need the **Remote notifications** background mode. Herald also sends silent sync pushes that refresh content cards and in-app messages, and those need it; see [Silent push](/docs/push-notifications/silent-push). ## 4. Register the device token Set the notification delegate at launch, register with APNs on every launch once the user has allowed notifications, and pass the token to the SDK. Device tokens can change, so registering each launch keeps Herald current. ```swift final class AppDelegate: NSObject, UIApplicationDelegate, @preconcurrency UNUserNotificationCenterDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!) UNUserNotificationCenter.current().delegate = self Task { let settings = await UNUserNotificationCenter.current().notificationSettings() if settings.authorizationStatus == .authorized { application.registerForRemoteNotifications() } } return true } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Herald.shared.setPushToken(deviceToken) } } ``` The first time, ask with `requestPushAuthorization()`. It shows the system prompt and registers with APNs when the user allows notifications. See [Permission prompts](/docs/push-notifications/permission-prompts) for when to ask. The SDK picks the APNs environment for each token: `sandbox` on the simulator and in development-signed builds, `production` for App Store and TestFlight builds. Herald sends to the matching APNs host. ## 5. Handle taps and foreground display Forward notification responses to the SDK. It logs the open, evaluates in-app messages with a push open trigger, and opens the push's deep link. It returns `false` for notifications that did not come from Herald, so you can handle your own. iOS does not show a banner while your app is in the foreground unless you return presentation options. ```swift extension AppDelegate { func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { if !Herald.shared.handleNotificationResponse(response) { // Not a Herald push: handle your other notifications here. } completionHandler() } func userNotificationCenter( _ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void ) { completionHandler([.banner, .list, .sound]) } } ``` The SDK counts each push open once, even if iOS delivers the same response again. ## What Herald sends Each message push is a visible alert with high priority that expires after 24 hours. The payload carries: | Key | Contents | |---|---| | `aps.alert` | The title (optional) and body | | `aps.sound` | `default` | | `aps.mutable-content` | `1`, only when the message has an image or buttons | | `nexus_decision_id` | The Herald decision ID. The SDK uses it to recognize Herald pushes and credit the open. | | `deeplink` | The message's deep link, when it has one | | `image_url` | The message's iOS image, when it has one. See [Rich push](/docs/push-notifications/rich-push). | | `herald_message_id` | The message ID, when the push comes from a campaign message | | `herald_actions` | The buttons, when the message has them: each with an `id`, a `title` and an optional `deeplink` | | `herald_test` | `"1"` on a test send | Repeated sends for the same decision collapse into one notification on the device. ## Verify it works 1. Run the app on a device, sign in so the user is identified, and allow notifications. 2. With `options.logLevel = .debug`, confirm the console shows no `Herald rejected a batch` line after the token is sent. 3. Send a test push. See [Testing push](/docs/push-notifications/testing). ## Troubleshooting - **APNs returns `BadDeviceToken`.** The token belongs to the other APNs environment than the one used. Rebuild with the signing you intend to test (development or distribution); the SDK sends the environment with each new token. - **APNs returns `DeviceTokenNotForTopic`.** The bundle ID on the connection does not match the app that produced the token. - **APNs returns `InvalidProviderToken`.** The Key ID or Team ID does not match the `.p8` key. - **No pushes, no APNs errors.** Herald stores tokens only for identified, verified users. Check that the app calls `identify` and `setUserToken`, and that verification is not **Optional** with a missing token. ## Next - [Permission prompts](/docs/push-notifications/permission-prompts) - [Deep links](/docs/push-notifications/deep-links) - [Rich push](/docs/push-notifications/rich-push) Source: https://heraldsdk.com/docs/push-notifications/ios-setup.md --- # Android setup > Connect Herald to Firebase Cloud Messaging with a service account, add the FCM module and handle notification taps. This guide connects Herald to Firebase Cloud Messaging (FCM) and wires your app to register for push, show notifications and report opens. ## Before you start - A Firebase project with your Android app registered under its package name. - The SDK installed and configured. See [Quickstart: Android](/docs/overview/quickstart-android). - Admin access to the Herald sending connection your agents use. ## 1. Create a service account key 1. In the Firebase console, open **Project settings > Service accounts** and click **Generate new private key**. This downloads a JSON file for the project's Firebase Admin SDK service account, which can send through the FCM HTTP v1 API. 2. Make sure the **Firebase Cloud Messaging API (V1)** is enabled for the project (Project settings > Cloud Messaging). ## 2. Add it to Herald In Herald, open **Settings > Sending**, open the connection and paste the JSON into the FCM section. Herald reads the project ID from the file and stores the key encrypted. Delete the downloaded copy afterwards. ## 3. Add Firebase and the FCM module Add `google-services.json` to your app module, apply the Google services plugin and add `herald-fcm`. If your own code uses Firebase Messaging classes (for example your own messaging service), add `com.google.firebase:firebase-messaging` too: `herald-fcm` does not expose it. ```kotlin // app/build.gradle.kts plugins { id("com.android.application") id("org.jetbrains.kotlin.android") id("com.google.gms.google-services") } dependencies { implementation("com.github.ender1311.herald-android:herald-fcm:0.6.0") } ``` `herald-fcm` registers `HeraldMessagingService` in its manifest. The service passes every new FCM token to `Herald.setPushToken` and shows Herald pushes that reach your app while it is in the foreground. ## 4. Start push in your Application class ```kotlin class LumenApplication : Application() { override fun onCreate() { super.onCreate() Herald.configure(this, appKey = "YOUR_APP_KEY", endpoint = "https://YOUR_HERALD_HOST") HeraldNotifications.createDefaultChannel(this) HeraldMessagingService.syncToken(this) } } ``` `syncToken` fetches the current FCM token, so a device that got its token before you added the SDK is registered too. It does nothing when Firebase is not initialized. ## 5. Show notifications in the background When your app is in the background, Android displays Herald pushes itself, without calling your code. Point Firebase's defaults at the Herald channel and at your notification icon so both paths look the same: ```xml ``` `herald-fcm` uses the same icon setting for foreground notifications and falls back to your app icon. Use a white, transparent icon: Android draws the small icon as a silhouette. ## 6. Handle taps A tap opens your launch activity with the Herald extras on the intent. Pass the intent to the SDK from `onCreate` and `onNewIntent`. It logs the open, evaluates in-app messages with a push open trigger, opens the deep link, and removes the extras so a recreated activity does not count the open twice. ```kotlin class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Herald.handleNotificationIntent(intent) setContent { HomeScreen() } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) Herald.handleNotificationIntent(intent) } } ``` Declare the launch activity with `android:launchMode="singleTop"` so a tap while the app is open reaches `onNewIntent` instead of stacking a second copy. ## If your app has its own messaging service Android delivers FCM messages to one service. If you already have one, remove the Herald service from the merged manifest and call the SDK from yours: ```xml ``` ```kotlin class LumenMessagingService : FirebaseMessagingService() { override fun onNewToken(token: String) { Herald.setPushToken(token) } override fun onMessageReceived(message: RemoteMessage) { if (HeraldNotifications.handleRemoteMessage(this, message)) return // Handle your other pushes here. } } ``` You can instead subclass `HeraldMessagingService`, override `onNonHeraldMessage`, and register your subclass in place of the original. ## What Herald sends Each push is an FCM notification message with high Android priority: | Field | Contents | |---|---| | `notification.title`, `notification.body` | The title (optional) and body | | `notification.image` | The message's Android image, when it has one | | `data.nexus_decision_id` | The Herald decision ID. The SDK uses it to recognize Herald pushes and credit the open. | | `data.deeplink` | The message's deep link, when it has one | ## Verify it works 1. Run the app on a device or an emulator with Google Play services, sign in so the user is identified, and allow notifications. 2. With `LogLevel.DEBUG`, Logcat (tag `Herald`) shows `Sent N events` after the token is registered. A `Firebase is not initialized` warning means step 3 is incomplete. 3. Send a test push. See [Testing push](/docs/push-notifications/testing). ## Troubleshooting - **FCM returns `SENDER_ID_MISMATCH`.** The service account belongs to a different Firebase project than the app's `google-services.json`. - **FCM returns `UNREGISTERED`.** The app was uninstalled or the token was replaced. The SDK sends new tokens as FCM issues them. - **Foreground pushes do not show.** Another messaging service receives the messages. Remove one of them, or call `HeraldNotifications.handleRemoteMessage` from yours. - **Taps are not counted.** `Herald.handleNotificationIntent` is missing from `onCreate` or `onNewIntent` of the launch activity. ## Next - [Permission prompts](/docs/push-notifications/permission-prompts) - [Android notification channels](/docs/push-notifications/android-notification-channels) - [Deep links](/docs/push-notifications/deep-links) Source: https://heraldsdk.com/docs/push-notifications/android-setup.md --- # Permission prompts > When to ask for notification permission, how to ask on iOS and on Android 13 and later, provisional authorization, and how the SDK records the answer. Both iOS and Android 13 and later require the user's permission before an app can show notifications. You usually get one chance at the system prompt, so the moment you ask matters more than the code. ## When to ask - **Ask after the user sees the value.** For Lumen, that is after the first `workout_completed`, with a line like "Want a reminder before tomorrow's session?". A prompt at first launch, before the user knows the app, is easy to refuse. - **Explain first, in your own UI.** Show a short screen or sheet that says what you will send and how often, with buttons for yes and not now. Show the system prompt only after yes. Saying not now to your screen costs nothing; refusing the system prompt is hard to undo. - **Use an in-app message as the explanation.** An in-app message with a button that deep links to your own route (for example `lumen://enable-reminders`) can trigger on an event and lead into the system prompt. See [In-app messages](/docs/in-app-messages/overview). ## Ask on iOS `requestPushAuthorization()` asks for alerts, sounds and badges. When the user allows it, the SDK registers with APNs and records the push subscription as opted in once the token arrives. When the user declines, it records the subscription as unsubscribed. It returns whether permission was granted. ```swift struct ReminderPrompt: View { var body: some View { Button("Remind me before workouts") { Task { let granted = await Herald.shared.requestPushAuthorization() if !granted { /* show how to turn notifications on in Settings */ } } } } } ``` iOS shows the system prompt once. Later calls return the user's earlier answer without a prompt. To send a user who declined to your app's notification settings: ```swift if let url = URL(string: UIApplication.openNotificationSettingsURLString) { UIApplication.shared.open(url) } ``` ### Provisional authorization Provisional authorization delivers notifications quietly to Notification Center without a prompt, and lets the user keep or turn them off from there. `requestPushAuthorization()` does not request it. To use it, ask the system yourself and record the result: ```swift @MainActor func requestQuietNotifications() async { let center = UNUserNotificationCenter.current() let granted = (try? await center.requestAuthorization(options: [.alert, .sound, .badge, .provisional])) ?? false if granted { UIApplication.shared.registerForRemoteNotifications() } Herald.shared.setSubscription(.push, granted ? .optedIn : .unsubscribed) } ``` The device data then reports `provisional` as the notification permission. ## Ask on Android 13 and later Android 13 (API level 33) added the `POST_NOTIFICATIONS` runtime permission. `herald-core` declares it in its manifest, so you do not add it yourself. On Android 12 and earlier, notifications are allowed by default and there is no prompt. `Herald.requestPushAuthorization(activity)` shows the prompt on Android 13 and later when the permission is not granted yet, and records the answer as the push subscription: opted in when the user allows it, unsubscribed when they decline. It reads the answer when your activity resumes after the prompt closes, so you do not forward `onRequestPermissionsResult`. On Android 12 and earlier, or when the permission is already granted, it records whether notifications are enabled for the app, without a prompt. Call it from the main thread. ```kotlin class SettingsActivity : ComponentActivity() { fun onEnableRemindersTapped() { Herald.requestPushAuthorization(this) } } ``` An opt-in is held on the device until the FCM token exists, so Herald receives the token before the opt-in. An opt-out is sent at once. If you prefer the Activity Result API, request the permission yourself and record the answer with `setSubscription`: ```kotlin class SettingsActivity : ComponentActivity() { private val askNotifications = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> Herald.setSubscription( SubscriptionChannel.PUSH, if (granted) SubscriptionState.OPTED_IN else SubscriptionState.UNSUBSCRIBED, ) } fun onEnableRemindersTapped() { if (Build.VERSION.SDK_INT >= 33) askNotifications.launch(Manifest.permission.POST_NOTIFICATIONS) } } ``` The SDK only knows the prompt was shown when `requestPushAuthorization` showed it. If you ask yourself and the user declines, the notification permission in device data stays `not_determined` rather than `denied`; the push subscription you record is what Herald acts on. ## Subscription state Herald tracks push consent in two places: | Signal | Source | What it means | |---|---|---| | Push subscription | `setSubscription(.push, …)`, or `requestPushAuthorization` | Unsubscribed suppresses push to this device's tokens. Subscribed or opted in lifts that suppression. | | Notification permission | Device data, `context.push.authorization`, sent with every batch | What the operating system currently allows: `authorized`, `denied` or `not_determined` on both platforms, plus `provisional` and `ephemeral` on iOS. Android 13 and later reports `not_determined` until the app has asked through `requestPushAuthorization`; Android 12 and earlier report `authorized` unless notifications are turned off. | A device with a registered token can receive push without any subscription event. Users can also turn notifications off in system settings at any time, which no SDK call reports as it happens; the notification permission in the next batch reflects it. Notification permission is second-tier device data, so it is not sent in minimal mode. ## Verify it works 1. Install the app fresh, trigger your prompt and allow notifications. 2. With debug logging on, confirm the subscription and push token batch is accepted (no `Herald rejected a batch` line). 3. Decline on a second fresh install and confirm the app shows your path to Settings. ## Troubleshooting - **The iOS prompt never appears.** The user already answered. Delete the app to reset the answer on a test device. - **The Android prompt never appears.** The device runs Android 12 or earlier, or the app targets an SDK level below 33, in which case Android shows the prompt on its own when you create the first channel. - **Push still arrives after the user opted out in your app.** Call `setSubscription(.push, .unsubscribed)` (iOS) or `setSubscription(SubscriptionChannel.PUSH, SubscriptionState.UNSUBSCRIBED)` (Android) when the user turns off notifications in your own settings screen. ## Next - [Rich push](/docs/push-notifications/rich-push) - [Consent and opt-out](/docs/data-and-privacy/consent-and-opt-out) Source: https://heraldsdk.com/docs/push-notifications/permission-prompts.md --- # Rich push > Show images in push notifications on iOS with a Notification Service Extension and on Android with a big picture style, and add action buttons from Herald. A push message in Herald can carry an image for iOS and an image for Android. This page shows what each platform needs to display it, and how action buttons work on the device. ## Before you start - Push set up on the platform: [iOS setup](/docs/push-notifications/ios-setup) or [Android setup](/docs/push-notifications/android-setup). - Image URLs served over HTTPS. iOS blocks plain HTTP downloads in extensions by default. ## Images on iOS When a message has an iOS image, Herald adds `mutable-content: 1` and an `image_url` key to the APNs payload. iOS then hands the notification to your Notification Service Extension, which has about 30 seconds to download the image and attach it. Without an extension, the notification shows as text. 1. In Xcode, choose **File > New > Target > Notification Service Extension**, name it (for example `LumenNotificationService`) and embed it in your app. 2. Add the `HeraldNotificationService` library to the extension target only. It depends on Foundation and UserNotifications, not on `HeraldSDK`, so it is safe to link into an app extension. 3. Replace the generated `NotificationService.swift` with the code below. 4. Set the extension's deployment target to iOS 16 or later. ```swift import HeraldNotificationService final class NotificationService: HeraldNotificationService, @unchecked Sendable {} ``` The class reads `image_url` (and `image`, if a sender uses that key), downloads the image over HTTPS within 20 seconds, and attaches it. It skips the image and shows the text notification when the URL is not HTTPS, the server answers with an error, the file is larger than 10 MB, the download runs out of time, or the file is not JPEG, PNG, GIF or HEIC. To wait a different time, override `imageTimeout`. If you already have a service extension, call the same logic from it: ```swift import HeraldNotificationService import UserNotifications final class NotificationService: UNNotificationServiceExtension { override func didReceive( _ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void ) { nonisolated(unsafe) let content = request.content nonisolated(unsafe) let handler = contentHandler Task { let prepared = await HeraldRichPush.prepare(content) handler(prepared) } } } ``` `HeraldRichPush.prepare` returns the content unchanged when the push has no image and no buttons. With this form, handle `serviceExtensionTimeWillExpire` yourself; the `HeraldNotificationService` class already does. ## Images on Android When a message has an Android image, Herald sets `notification.image` in the FCM message. You do not need extra code: - **App in the background.** Android and Firebase display the notification, and expanding it shows the image. - **App in the foreground.** `herald-fcm` downloads the image (5-second connect and read timeouts, 8 seconds in total, up to 5 MB, scaled down to fit 1,024 by 1,024 pixels) and shows it with a big picture style, with the image as the large icon too. If the download fails, the notification shows its full text instead. ## Video A push can carry a video as well as its image. The image stays the poster, so the push looks right everywhere a video can't play. Pick a video in the [media library](/docs/concepts/media-library); you need SDK 0.6.0. - **iOS.** Herald adds a `video_url` key beside `image_url` to the APNs payload. The Notification Service Extension from [Images on iOS](#images-on-ios) attaches the video when the URL is HTTPS, the server says it is `video/mp4` or `video/quicktime`, and the file is at most 10 MB (both the `Content-Length` and the bytes received are checked). It gets 60% of a 25-second budget. If the video fails (an error, too slow, too big or the wrong type), the extension attaches the poster in `image_url` instead, and if that fails too the notification shows its text. The notification is always delivered. Without the extension the push shows as text. - **Android.** Android shows the poster. `herald-fcm` ignores `video_url`. - **Payload size.** APNs allows 4,096 bytes. If a long video URL and a long body don't fit, Herald shortens the body first, then drops `video_url`. The poster is never dropped. When you pick a video for a push, the editor warns "This video is too large for iOS push. iOS will show the poster." if it is over 10 MB. ## Action buttons Both SDKs can show up to three action buttons on a push and report which one the user tapped. You author the buttons in Herald, and the SDKs draw them. ### Author buttons in Herald 1. Open a push variant with **Edit**, then open **Delivery options (mobile SDK)**. 2. Under **Action buttons**, choose **Add button** and fill in **Button 1 title** (up to 30 characters) and **Deep link (optional)**. Add up to three buttons. A button with no deep link opens the push's own deep link. 3. Choose **Save delivery options**. The variant's own **Save** does not store them. Buttons apply to pushes sent after you save. ### How buttons reach each platform | Platform | What Herald sends | What the app needs | |---|---|---| | iOS (APNs) | A `herald_actions` key with the buttons, and `mutable-content: 1`. Herald sets no `aps.category`. | The Notification Service Extension from [Images on iOS](#images-on-ios). It adds the buttons before the notification shows. Without it, the push shows with no buttons. | | Android (FCM) | A data message that carries the title, body and `herald_actions`, with no notification block. | `herald-fcm`, which builds the notification with its buttons whether the app is in the foreground or the background. | | iOS device through FCM | The normal notification, without buttons. | None. Send iOS pushes through APNs to get buttons. | On iOS, a category your app registered with `registerPushCategories` is kept. A category whose id starts with `herald.` is the one the extension created for earlier buttons, and the extension replaces it with the buttons in the push. ### What the SDKs read - **Android.** `herald-fcm` reads a `herald_actions` data key, a JSON array such as `[{"id":"start","title":"Start workout","deeplink":"lumen://workout"}]`. Malformed entries are skipped and only the first three are kept. - **iOS.** `HeraldNotificationService` turns the same `herald_actions` key into a notification category. A button tap opens the app. The SDK logs a push open, then a `button` interaction with the button's ID, both linked to the decision. It then opens the button's own deep link, or the push's deep link when the button has none. For buttons you define in the app instead, register a category and send its id in `aps.category` yourself: ```swift Herald.shared.registerPushCategories([ HeraldPushCategory(id: "workout_reminder", buttons: [ .init(id: "start", title: "Start workout"), .init(id: "snooze", title: "Remind me later"), ]), ]) ``` ## Verify it works 1. Create a push message in Herald with an iOS image and an Android image, both HTTPS. 2. Send it to a test user (see [Testing push](/docs/push-notifications/testing)). 3. On iOS, long-press or expand the notification to see the image. On Android, expand the notification, once with the app in the background and once in the foreground. ## Troubleshooting - **No buttons on iOS.** The extension is missing or not embedded, or the push went through FCM instead of APNs. - **No buttons on Android.** `herald-fcm` is not in the app, or another messaging service receives FCM messages. See [Android setup](/docs/push-notifications/android-setup). - **iOS shows text only.** The extension target is missing, not embedded in the app, its principal class is not your `HeraldNotificationService` subclass, or its deployment target is above the device's iOS version. Run the extension scheme and attach the debugger to check `didReceive` is called. - **iOS shows text only for some images.** The URL is plain HTTP, the file is larger than 10 MB, or it is WebP or another type iOS does not accept as an attachment. Serve compressed JPEG or PNG images over HTTPS. - **Android shows text only in the foreground.** The image did not download within 8 seconds, the server returned an error, or the file is larger than 5 MB. ## Next - [Push stories](/docs/push-notifications/push-stories) - [Deep links](/docs/push-notifications/deep-links) - [Testing push](/docs/push-notifications/testing) Source: https://heraldsdk.com/docs/push-notifications/rich-push.md --- # Deep links > Open a specific screen in your app when a user taps a push notification, a content card or an in-app message button. A deep link is a URL that opens a specific screen in your app, such as `lumen://plan/today`. Every Herald push, content card and in-app button can carry one; the SDK opens it when the user taps. ## Before you start - A URL scheme or universal link (iOS) or App Link (Android) your app already handles, or will handle after this guide. - Notification taps wired to the SDK: [iOS setup](/docs/push-notifications/ios-setup#5-handle-taps-and-foreground-display) or [Android setup](/docs/push-notifications/android-setup#6-handle-taps). ## How the SDK opens links | Source | iOS | Android | |---|---|---| | Push tap | `handleNotificationResponse` opens the push's `deeplink` (a tapped action button's own link first) | `handleNotificationIntent` opens the push's `deeplink` (a tapped action button's own link first) | | Content card or in-app message tap | The `HeraldUI` views call `openDeepLink(_:)` for the card or button URL; custom views call it themselves | The `herald-ui` views open the card or button URL; custom views call `Herald.openUrl` | | How it opens | Your `deepLinkHandler`, or the system when the handler is not set or returns `false` | Your `Herald.deepLinkHandler`, or an `ACTION_VIEW` intent for the URL when the handler is not set or returns `false` | Push dismissals never open a link. ## 1. Route links in your app :::tabs ::tab ios Set `deepLinkHandler` once at launch. Return `true` when your app handled the URL; return `false` to let the SDK pass it to the system (for example a web URL that should open in Safari). ```swift @MainActor func installDeepLinkHandler() { Herald.shared.deepLinkHandler = { url in guard url.scheme == "lumen" else { return false } Router.shared.open(url) // your app's navigation return true } } ``` Handle your own universal links (`https://` URLs on your domain) in the handler too, and return `true`. Handing them to the system from inside your app is not a reliable way to open your own screens. To open a link from your own UI the same way, for example from a custom card list, call `Herald.shared.openDeepLink(url)`. From SDK 0.6.0 every link that goes through the SDK (both platforms) is recorded as a `$deep_link_opened` event, without its query unless you turn on `trackDeepLinkQuery`. See [Lifecycle events](/docs/reference/event-payload#lifecycle-events). ::tab android Set `Herald.deepLinkHandler` once, in `Application.onCreate`. Return `true` when your app handled the URL; return `false` to let the SDK open it with `Intent.ACTION_VIEW` (for example a web URL that should open in the browser). Taps and clicks call it on the main thread. ```kotlin Herald.deepLinkHandler = { url -> if (url.startsWith("lumen://")) { Router.open(url) // your app's navigation, inside the current task true } else { false } } ``` With a handler, in-app buttons and card clicks navigate inside your running activity instead of starting a new task. A push tap still arrives through `handleNotificationIntent` in your launch activity, which passes the link to the handler. Without a handler, or for links it returns `false` for, declare an intent filter for your scheme on the activity that shows the screen. The SDK opens those links with `Intent.ACTION_VIEW` in a new task, so any activity that matches receives them. ```xml ``` Read the link in `onCreate` and `onNewIntent` from `intent.data`. With `singleTop`, a link that arrives while the activity is on top reaches `onNewIntent`. For `https://` links on your domain, handle them in `deepLinkHandler` and return `true`, or set up Android App Links so they open your app instead of the browser. To open a link from your own UI the same way, call `Herald.openUrl(url)`. ::: ## 2. Add the link to the message In Herald, set the deep link on the push message, on the content card, or on each in-app message button. Use the full URL, including the scheme. ## Verify it works :::tabs ::tab ios Open the link in the simulator to test your routing on its own: ```bash xcrun simctl openurl booted "lumen://plan/today" ``` ::tab android Open the link on a connected device or emulator to test your routing on its own: ```bash adb shell am start -a android.intent.action.VIEW -d "lumen://plan/today" ``` ::: Then send a test push with the same deep link and tap it. See [Testing push](/docs/push-notifications/testing). ## Troubleshooting - **iOS opens Safari instead of the app.** The handler returned `false` for a URL your app owns, or no handler is set. Return `true` for your scheme and your domains. - **Nothing happens on Android.** No `deepLinkHandler` took the link and no activity declares an intent filter for the scheme. Logcat shows `openUrl failed` under the tag `Herald`. - **Android opens a second copy of your screen.** The link went to `ACTION_VIEW`, which starts a new task. Set `Herald.deepLinkHandler` and navigate inside your app. - **The link opens, but on the wrong screen.** Your routing reads the URL before the app finishes launching. Store the URL and navigate once your root view is ready. - **A web link opens in the app instead of the browser.** Your universal link or App Link configuration claims that path. Narrow the paths your app claims. ## Next - [Silent push](/docs/push-notifications/silent-push) - [Testing push](/docs/push-notifications/testing) Source: https://heraldsdk.com/docs/push-notifications/deep-links.md --- # Silent push > The sync push Herald sends so content cards and in-app messages arrive without waiting for the next session, and how to wire it on iOS and Android. A silent push wakes your app in the background without showing a notification. Herald sends one kind, the sync push, so new content cards and in-app messages reach the device without waiting for the next session. ## What a sync push is A sync push is a data-only push with the key `herald_sync` set to `"1"`. On iOS it is an APNs background push (`content-available: 1`, no alert, sound or badge). On Android it is an FCM data message. When the SDK receives one, it fetches cards and in-app messages with the usual ETag check, so an unchanged list costs a `304`. A sync push never shows a notification, is never logged as a push open, and does nothing while the SDK is disabled. ## When Herald sends one - An agent sends a content card or in-app message to a user who has an SDK device, and the user also has an active, unsuppressed push token on the connection. Herald sends one sync push per token, whatever the number of messages. - Herald sends at most one sync push per user every five minutes. A message written inside that window waits for the next session or the next sync push. - An admin test of a card or modal sends a sync push and skips the five-minute limit. See [Testing push](/docs/push-notifications/testing). The push is queued in the same outbox as other pushes and delivered at once. If it cannot be sent, the message is still stored and the SDK fetches it at the next session. The SDK also skips a sync push that arrives within 30 seconds of the last one it handled. iOS may delay or drop background pushes, for example when Background App Refresh is off. Treat a sync push as a faster path, not a guarantee. ## Before you start - Push set up: [iOS setup](/docs/push-notifications/ios-setup) or [Android setup](/docs/push-notifications/android-setup). - SDK version 0.2.0 or later. ## Wire it up :::tabs ::tab ios 1. In your app target, open **Signing & Capabilities**, add **Background Modes** and turn on **Remote notifications**. In `Info.plist` this adds `remote-notification` to `UIBackgroundModes`. 2. Forward the push from your app delegate: ```swift func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void ) { Task { let synced = await Herald.shared.handleRemoteNotification(userInfo) completionHandler(synced ? .newData : .noData) } } ``` `handleRemoteNotification` runs on the main actor and returns `true` when the push was a Herald sync push, once the refresh has finished or after 25 seconds at most (iOS allows about 30 for the completion handler); if `configure` has not run yet, it starts the refresh and returns at once. It returns `false` for any other notification, so you can handle your own pushes after it. Without the Remote notifications background mode, iOS does not wake the app, and new messages arrive at the next session. ::tab android Nothing to add. `herald-fcm`'s `HeraldMessagingService` receives sync pushes and calls the SDK for you. If your app has its own `FirebaseMessagingService`, call one line from `onMessageReceived`: ```kotlin override fun onMessageReceived(message: RemoteMessage) { if (Herald.handleRemoteMessage(message.data)) return // Your own handling. } ``` `handleRemoteMessage` returns `true` for a sync push and `false` for any other message. It waits for the refresh to finish (8 seconds at most) before it returns, so FCM keeps the process alive until then. ::: ## Verify it works 1. Sign in as a test user on a device with push allowed, and put the app in the background. 2. Use [Send a test from Herald](/docs/push-notifications/testing#send-a-test-from-the-mobile-sdk-card) with the **Content card** channel. 3. Open the app. The card is already in the feed, without a session start having fetched it. ## Troubleshooting - **iOS never receives it.** The Remote notifications background mode is off, or the delegate method is not implemented. Background pushes also do not arrive when the user force-quits the app. - **Android never receives it.** Another messaging service receives FCM messages. Remove it, or call `Herald.handleRemoteMessage` from it. - **A second test does nothing within 30 seconds.** The SDK skips a sync push that follows another within 30 seconds. - **Cards still wait for the next session.** The user has no active push token, or Herald already sent a sync push in the last five minutes. ## Keep your own silent pushes If your app already uses silent pushes from another service, keep them. Herald sync pushes carry `herald_sync`; on iOS `handleRemoteNotification` returns `false` for other notifications, and on Android `Herald.handleRemoteMessage` returns `false`. To refresh at a moment you choose, call `refreshContentCards()`. It fetches cards and in-app messages together. :::tabs ::tab ios ```swift Herald.shared.refreshContentCards() ``` ::tab android ```kotlin Herald.refreshContentCards() ``` ::: ## Related - [How delivery works](/docs/concepts/how-delivery-works) - [Android setup](/docs/push-notifications/android-setup) Source: https://heraldsdk.com/docs/push-notifications/silent-push.md --- # Android notification channels > The default channel Herald pushes use on Android, how to name and translate it, and how channels are chosen in the foreground and background. On Android 8.0 and later, every notification belongs to a channel, and users control sound, vibration and visibility per channel in system settings. Herald pushes use the default channel unless a push variant names another. ## The default channel | Property | Value | |---|---| | Channel ID | `herald_default` (`HeraldNotifications.DEFAULT_CHANNEL_ID`) | | Name | The string resource `herald_default_channel_name`, "Notifications" by default | | Importance | `NotificationManager.IMPORTANCE_DEFAULT`: makes a sound, shows in the status bar, no heads-up banner | | Created | When you call `HeraldNotifications.createDefaultChannel`, or the first time `herald-fcm` shows a push | Create it at startup, as the quickstart does, so the channel exists before the first push and users can adjust it in settings early. ## How a channel is chosen | App state | Who shows the notification | Channel | |---|---|---| | Foreground | `herald-fcm` | The channel named in the push's `herald_channel_id` data key or FCM `channel_id`, if it exists on the device; otherwise `herald_default` | | Background | Android and Firebase | The channel named in the push, otherwise the `default_notification_channel_id` in your manifest, otherwise Firebase's own fallback channel | A Herald push uses the default channel unless its variant names a channel (see [The Android channel option](#the-android-channel-option)). Set the manifest default to `herald_default` so background and foreground pushes land in the same channel: ```xml ``` ## The Android channel option To send a push on one of your own channels, open the push variant with **Edit**, open **Delivery options (mobile SDK)** and enter the channel's ID in **Android channel ID** (up to 100 characters). Leave it empty to use the app's default channel. Choose **Save delivery options** to store it. Herald sends the ID in the `herald_channel_id` data key and as the FCM `channel_id`. Create the channel in your app before the first push arrives, with `NotificationManager.createNotificationChannel`. If the channel does not exist on the device, the foreground rule above applies and the push lands in `herald_default`. The option applies to Android only and has no effect on iOS. ## Name, translate or change importance Android fixes a channel's importance when it is created, and only the user can change it afterwards. Set the name and importance before the channel first exists. To rename or translate the channel, override the string resource in your app: ```xml Workout reminders ``` To set a different importance, pass it when you create the channel: ```kotlin HeraldNotifications.createDefaultChannel( this, name = getString(R.string.herald_default_channel_name), importance = NotificationManager.IMPORTANCE_HIGH, ) ``` The call does nothing if the channel already exists. To change importance for existing installs, users have to change it in system settings. ## Edge cases - **The user turns the channel off.** Android drops Herald pushes on that channel without showing them. The notification permission in device data still reports `authorized`, because the app-level switch is on. - **The user turns all app notifications off.** `herald-fcm` shows nothing, and the next batch reports the notification permission as `denied`. ## Related - [Android setup](/docs/push-notifications/android-setup) - [Permission prompts](/docs/push-notifications/permission-prompts) Source: https://heraldsdk.com/docs/push-notifications/android-notification-channels.md --- # Testing push > Turn on verbose logging, send a test notification to one device, and fix the most common push failures. This guide gets one test device receiving Herald pushes, with enough logging to see each step. Test on a physical device or an emulator with Google Play services; check the push path end to end before you test content. ## Before you start - Push set up: [iOS setup](/docs/push-notifications/ios-setup) or [Android setup](/docs/push-notifications/android-setup). - A test External ID your app can sign in as. ## 1. Turn on verbose logging :::tabs ::tab ios ```swift Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!) { options in options.logLevel = .debug } ``` Logs use the subsystem `com.herald.sdk` and the category `Herald`. Read them in the Xcode console, or in the Console app with the device connected. ::tab android ```kotlin Herald.configure( this, appKey = "YOUR_APP_KEY", endpoint = "https://YOUR_HERALD_HOST", options = HeraldOptions(logLevel = LogLevel.DEBUG), ) ``` Logs use the tag `Herald`. Filter Logcat with `tag:Herald`. ::: Set the level back to the default (warning) for release builds. ## 2. Register the test device 1. Install the app, sign in as the test user, and allow notifications. 2. Confirm no `Herald rejected a batch` line appears after the push token is sent. `Herald needs a user token: call setUserToken` means the user token is missing or wrong, and Herald has not stored the push token yet. 3. Note the device token if you want to use a provider console. On iOS, log the hex form in `didRegisterForRemoteNotificationsWithDeviceToken`; on Android, read it from `FirebaseMessaging.getInstance().token`. ## 3. Send a test push **From the provider console.** This checks the device, the credentials and the SDK's handling, without Herald's decisioning. Include `nexus_decision_id` so the SDK treats the push as a Herald push; a made-up value is fine, because Herald credits only real decisions that belong to the user. :::tabs ::tab ios Use Apple's Push Notifications Console (in your developer account, under CloudKit Console) with your device token, your bundle ID as the topic and the environment that matches your build. Payload: ```json { "aps": { "alert": { "title": "Test", "body": "Tap to open today's plan" }, "sound": "default" }, "nexus_decision_id": "test_1", "deeplink": "lumen://plan/today" } ``` ::tab android In the Firebase console, create a notification under **Messaging**, choose **Send test message** and paste the FCM token. Under **Additional options > Custom data**, add: | Key | Value | |---|---| | `nexus_decision_id` | `test_1` | | `deeplink` | `lumen://plan/today` | ::: **From Herald.** This checks the full path, including the credentials on the connection. Use [Send a test from Herald](#send-a-test-from-the-mobile-sdk-card) below. A send from an agent waits for Herald's dispatcher, which your operator runs on a schedule, so allow a minute or two. ## Send a test from the Mobile SDK card The **Mobile SDK** card on the connection's page has a **Send a test** form. It sends one message to one user now. Only admins can use it, and the **Send test** button stays disabled until the connection has an app key. | Field | Rules | |---|---| | External ID | The ID the user signed in with, up to 200 characters | | Channel | **Push**, **Content card** or **In-app modal** | | Title | Required, up to 200 characters | | Body | Required, up to 2,000 characters | | Deep link (optional) | A link your app opens when the user taps | What each channel does: - **Push** goes to every active push token the user has, without waiting for the dispatcher. It carries a `herald_test` key so you can tell it from a real send. - **Content card** and **In-app modal** create a message for the user, with a `test` extra set to `true`. It expires after 24 hours so it does not stay in a real user's feed. Herald then sends a sync push so the app refreshes at once. See [Silent push](/docs/push-notifications/silent-push). A test does not create a decision, so it does not count toward send caps or an agent's results. It uses the defaults for the channel, not a variant's delivery options. The form shows one result: | Result | Meaning | |---|---| | Sent. | The push was accepted by APNs or FCM, or the card or modal was created. | | Queued. Delivery is being retried. | The push service did not accept it yet. Herald retries it. | | Not sent: this user has no push token. | The user has no active push token, or every token is suppressed. Check the user is identified and verified. | | Not sent: this user has no device registered with the SDK. | A card or modal needs a device that has opened the app as this user. | | Failed: *reason* | Herald could not build or deliver the push, for example a missing credential on the connection. | ## Verify it works 1. The notification appears, with the app in the background and again in the foreground. 2. Tapping it opens the app and the deep link's screen. 3. With debug logging on, the next batch after the tap is accepted. It carries a push `open` interaction. ## Common failures | Symptom | Likely cause | Fix | |---|---|---| | No notification, no errors in the app | The user is anonymous, or verification is **Optional** and no token was sent, so Herald stored no push token | Call `identify` and `setUserToken` before testing | | `Herald rejected the app key: check the publishable key in configure` | Wrong app key, or the connection is not active | Check the key on the **Mobile SDK** card | | `Herald needs a user token: call setUserToken` | A missing or wrong user token under **Required** | Check your token minting and call `setUserToken` after `identify` | | APNs `BadDeviceToken` | Token and APNs environment do not match | Test a development build against sandbox, or a TestFlight build against production | | APNs `DeviceTokenNotForTopic` | Bundle ID on the connection differs from the app's | Fix the bundle ID on the connection | | APNs `InvalidProviderToken` | Key ID or Team ID does not match the `.p8` key | Re-enter the key details | | FCM `SENDER_ID_MISMATCH` | Service account from another Firebase project | Use the project in the app's `google-services.json` | | iOS: no banner in the foreground | `willPresent` is not implemented | Return `.banner` from `willPresent` | | Android: no notification in the foreground | Another messaging service receives FCM messages | Remove one, or call `HeraldNotifications.handleRemoteMessage` from yours | | Taps open the app but are not counted | Taps are not forwarded to the SDK | Call `handleNotificationResponse` (iOS) or `handleNotificationIntent` in `onCreate` and `onNewIntent` (Android) | | Push arrives late | The dispatcher runs less often than every minute | Ask your Herald operator to schedule it every minute | ## Next - [Logging and debugging](/docs/operations/logging-and-debugging) - [Troubleshooting](/docs/operations/troubleshooting) Source: https://heraldsdk.com/docs/push-notifications/testing.md --- # Pushes your app sends > Keep transactional pushes in your own backend and report each one with the $external_push event, so the per-app push limit counts every push a person gets. Most apps already send transactional messages (receipts, sign-in codes, password resets, order and account updates) from their own backend. Keep doing that, and report each push to Herald with the $external_push event so it can count every push a person gets. If you'd rather Herald send them, use the Send API: those messages go out right away and skip the send-time checks. Use agents and campaigns for marketing and lifecycle messages. ## What to keep in your backend - Sign-in codes, password resets and other security messages. - Chat messages and other pushes that must arrive the moment something happens. - Silent and data-only pushes your app uses to refresh itself. - Pushes with sensitive content you'd rather not send through another service. ## What can move to Herald Marketing and lifecycle pushes: onboarding, re-engagement, feature announcements, reminders and offers. Agents pick the message and time for each person, and campaigns send to an audience at a set time. ## Report each push Send `$external_push` from your backend right after it sends a push, with the same ingest token you use for other server events: ```shell curl -X POST "https://YOUR_HERALD_HOST/api/v1/events" \ -H "Authorization: Bearer $HERALD_INGEST_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "events": [ { "id": "evt_123", "userId": "u_123", "name": "$external_push", "timestamp": "2026-11-21T08:00:00Z", "properties": { "category": "transactional", "message_id": "order-42-shipped", "source": "orders" } } ] }' ``` | Property | Rules | |---|---| | `category` | `transactional`, `marketing` or `other`. Optional; defaults to `other`. Any other value is refused. | | `message_id` | Optional, 1 to 200 characters. A push with the same `message_id` for the same user counts once. | | `source` | Optional, 1 to 100 characters, such as `orders`. | Don't send the push's title or body: Herald drops every other property. The person's profile shows each one as "Push sent by your app", with its category and source. ## SDK auto-capture From SDK 0.6.0, the SDKs also record pushes they see, with `trackExternalPushes` on (the default): - **iOS:** a push that isn't from Herald, when the person taps it and your app forwards the tap to `handleNotificationResponse`. - **Android:** a non-Herald FCM message with a notification, when it reaches `HeraldMessagingService` (`herald-fcm`). In your own FirebaseMessagingService, call `Herald.handleExternalPush(message.data, message.notification != null, message.messageId)`. The SDKs also record some of these pushes on their own: on iOS when someone taps one, and on Android when one arrives. To count every push, report them from your backend. They never record silent or data-only pushes. You can also report a push from the app: `trackExternalPush(messageId:category:source:)` on iOS, `Herald.trackExternalPush(messageId, category, source)` on Android. Turn auto-capture off with `trackExternalPushes = false` in `HeraldConfiguration` (iOS) or `HeraldOptions` (Android), or without an app update with **Track pushes your app sends** under Settings, [SDK settings](/docs/data-and-privacy/data-collection-controls#remote-sdk-settings) (0.6.0 and later). ## Count each push once When both your backend and the SDK report the same push, give them the same ID. Put the `message_id` your backend reports in the push payload under `herald_external_id`, and the category under `herald_category`: ```json { "aps": { "alert": { "title": "Order shipped", "body": "…" } }, "herald_external_id": "order-42-shipped", "herald_category": "transactional" } ``` On Android, put them in the FCM `data` block. Without `herald_external_id`, the SDK uses the notification's own ID (the iOS request identifier, the FCM message ID), so one push seen twice on a device still counts once, but it won't match your backend's report. ## The push limit In Enforce mode the push limit is replaced by the app's messaging limits and attention budget: a `$external_push` event with `category: "transactional"` doesn't count toward the budget, and any other one counts toward the push channel only. See [Message priority and attention budget](/docs/concepts/message-priority). The rest of this section describes the push limit used in Observe mode. Each app has a push limit across all sources, on by default at 3 pushes per person in the last 24 hours. It counts every mobile push the person got from the app: Herald agent, campaign and Send API pushes, plus the pushes your app reports. When someone has reached it, Herald makes no new push decisions for them (an agent with other channels can still pick one of those) and skips agent and campaign pushes due for them; Send API messages are never skipped, but they count. Campaigns sent through Braze aren't limited; Braze schedules those itself. Web push and other channels don't count. A push counts once however many of the person's devices it reached. Change it in **Settings > General > Push limit across all sources**: turn **Limit pushes per person** off, or set **Pushes per 24 hours** from 1 to 20. A skipped push shows in campaign results under "Skipped at send time" as "push limit". ## Related - [How delivery works](/docs/concepts/how-delivery-works) - [Event payload spec](/docs/reference/event-payload) - [Server API](/docs/reference/server-api) - [Limits](/docs/reference/limits) Source: https://heraldsdk.com/docs/push-notifications/pushes-your-app-sends.md --- # Push stories > Send a push with 2 to 10 pages people flip through, each with an image, title, subtitle and deep link, shown by a Notification Content Extension on iOS and by the FCM module on Android. A push story is a push with 2 to 10 pages. Each page has an image, a title, a subtitle and an optional deep link. People move between pages from the expanded notification and open the page they're on. It is the Herald version of Braze push stories. Push stories need SDK 0.7.0 (not released yet). A device on an older SDK, or an iPhone app without the extensions below, shows the first page as a normal [rich push](/docs/push-notifications/rich-push): its image, its title, its subtitle as the body, and its deep link. ## Before you start - Push set up on the platform: [iOS setup](/docs/push-notifications/ios-setup) or [Android setup](/docs/push-notifications/android-setup). - Images served over HTTPS. - On iOS, the Notification Service Extension from [Rich push](/docs/push-notifications/rich-push#images-on-ios). It downloads every page's image before the notification shows. ## Create a story In a campaign, open the **Push** channel and turn on **Story**. The push's title, body, image and deep link become the first page, and an empty second page is added. 1. For each page, choose an image from the [media library](/docs/concepts/media-library) (or paste an HTTPS URL), then fill in **Title** (up to 60 characters in the editor), **Subtitle** (up to 178) and an optional **Deep link**. A page without a deep link opens the app. 2. Use **Add page** for up to 10 pages. The arrows move a page up or down, and the cross removes it (a story keeps at least 2). 3. The preview shows the first page, which is what the collapsed notification and older apps show. All pages together, plus the first page's text, image and link (sent a second time for older apps), must fit in about 3.4 KB of the push (Apple and Google cap a push at 4 KB). If they don't, the campaign can't be saved: shorten the text or links, or remove a page. Agents don't send stories. From your backend, send a story with the [Send API](/docs/reference/send-api#push-stories). ## iOS: add a Notification Content Extension iOS shows the pages in a Notification Content Extension, a second app extension beside the service extension. 1. In Xcode, choose **File > New > Target > Notification Content Extension**, name it (for example `LumenPushStory`) and embed it in your app. Set its deployment target to iOS 16 or later. 2. Add the `HeraldPushStory` library to the new target only. Like `HeraldNotificationService`, it doesn't depend on `HeraldSDK`. 3. Delete the generated `MainInterface.storyboard` and replace `NotificationViewController.swift` with: ```swift import HeraldPushStory final class NotificationViewController: HeraldStoryViewController {} ``` 4. In the extension's `Info.plist`, under `NSExtension`, remove `NSExtensionMainStoryboard`, add `NSExtensionPrincipalClass` with the value `$(PRODUCT_MODULE_NAME).NotificationViewController`, and set these keys under `NSExtensionAttributes`: | Key | Value | |---|---| | `UNNotificationExtensionCategory` | `HERALD_STORY` | | `UNNotificationExtensionDefaultContentHidden` | `YES` (the extension shows the title and subtitle itself) | | `UNNotificationExtensionInitialContentSizeRatio` | `1` | 5. Keep forwarding notification taps to `Herald.shared.handleNotificationResponse(_:)` from your `UNUserNotificationCenterDelegate`, as in [iOS setup](/docs/push-notifications/ios-setup). When a person long-presses or expands a story, the extension shows the current page's image, title and subtitle, with **Previous**, **Next** and **Open** under it. **Open** opens the app at that page's deep link, or just opens the app when the page has none. Tapping the notification itself opens the first page, as it does on a device without the extension. To rename the buttons, override `previousTitle`, `nextTitle` and `openTitle` in your subclass. The service extension registers the `HERALD_STORY` category with a single **Open** button the first time a story arrives, so an app with the service extension but no content extension still gets a working button. If a page's image didn't download in time, the content extension downloads it when the page is shown. ## Android: nothing to add `herald-fcm` shows stories. A story arrives as an FCM data message, and `herald-fcm` builds the notification with the page's image, title and subtitle and **Previous** and **Next** buttons. A button redraws the same notification with the other page, without sound or vibration. A tap opens the app at the page shown (just the app when the page has no deep link). The collapsed notification shows the page's title and subtitle. To rename the buttons, override the string resources `herald_story_previous` and `herald_story_next` in your app. ## What gets tracked Opening a page logs a push open and a `button` interaction whose button ID is `herald_story_page_`, counting from 0 (`herald_story_page_1` is the second page). Moving between pages logs nothing. A tap on the iOS notification itself logs an open of the first page with no button. ## What Herald sends | Platform | Payload | |---|---| | iOS (APNs) | `aps.category: HERALD_STORY`, `mutable-content: 1`, and `herald_story`: the pages as `[{"image_url", "title", "subtitle", "deeplink"?}]`. The alert, `image_url` and `deeplink` are the first page's. | | Android (FCM) | A data message with no notification block: `title`, `body` and `image` from the first page, and `herald_story` with the same array as a JSON string. | ## Troubleshooting - **iOS shows a normal push.** The content extension is missing, not embedded, its `UNNotificationExtensionCategory` isn't `HERALD_STORY`, or the app is on an SDK before 0.7.0. - **iOS shows a normal push with the service extension missing.** The service extension registers the `HERALD_STORY` category the first time a story arrives; without it, register a category with that id in your app (for example with `registerPushCategories`), or iOS won't use the content extension. - **iOS pages have no image.** The images are not HTTPS, don't load from the device, or aren't a type iOS can show (JPEG, PNG, GIF or HEIC). The content extension downloads any image the service extension didn't attach. - **Android shows a normal push.** The app's `herald-fcm` is older than 0.7.0, or another messaging service receives FCM messages. See [Android setup](/docs/push-notifications/android-setup). ## Next - [Rich push](/docs/push-notifications/rich-push) - [Testing push](/docs/push-notifications/testing) Source: https://heraldsdk.com/docs/push-notifications/push-stories.md --- # Live Activities setup > Add the Live Activity widget to your iPhone app, turn on Apple's Broadcast Capability, and learn what a Live Activity campaign can and cannot do. A Live Activity is a card on the iPhone lock screen and in the Dynamic Island that stays up until an end time, with a progress bar or a countdown. Herald starts one from a campaign and ends it at the end time you set. On iPhone, Live Activities need iOS 18 or later; older versions do not receive them. The same campaign reaches Android phones as a Live Update; see [Live Activities on Android](/docs/live-activities/android). This page sets up the iPhone side. ## 1. Add a Widget Extension In Xcode choose File › New › Target › Widget Extension. You can leave "Include Live Activity" off; Herald supplies the view. ## 2. Add the `HeraldLiveActivity` product Add the `HeraldLiveActivity` library product from the Herald Swift package to the widget extension. It has no dependency on `HeraldSDK`, so it is safe to link from an extension. The app target links `HeraldSDK`, which depends on it, so the app sees the same `HeraldActivityAttributes` type. ## 3. Add the widget to your WidgetBundle ```swift import WidgetKit import HeraldLiveActivity @main struct MyWidgets: WidgetBundle { var body: some Widget { HeraldLiveActivityWidget() } } ``` The widget shows the title, the body and either a progress bar or a countdown, on the lock screen and in the Dynamic Island. A tap opens the campaign's deep link. ## 4. Set NSSupportsLiveActivities In the app's Info.plist (not the extension's), set `NSSupportsLiveActivities` to YES. ## 5. Turn on Broadcast Capability Herald starts and updates activities with Apple's broadcast push. Enable it for your App ID at developer.apple.com › Certificates, IDs & Profiles › Identifiers › your App ID › Push Notifications › Broadcast Capability. It cannot be turned on from Xcode. ## 6. Nothing else to call After `configure`, the SDK sends the Live Activity push-to-start token to Herald on iOS 18 and later. Like the push token, it is not sent while the SDK is disabled. See [Consent and opt-out](/docs/data-and-privacy/consent-and-opt-out). ## What a campaign can do - A start alert is required: the notification that appears when the activity starts. - Title up to 40 characters, body up to 80. - A progress bar or a countdown. - It ends at most 8 hours after it starts. Herald ends it at that time. - The campaign page has **Update Live Activity** (title, body, progress, end time) and **End now**. - Delivery is not in local time, and it respects quiet hours. - One Live Activity start per person per 72 hours, counted apart from push. - It needs Herald's own APNs delivery (iPhone) or FCM delivery (Android), not Braze. - Results show "—" for delivered and opened, because Apple does not report them for broadcast. To check your setup, send a test from the campaign. See [Testing push](/docs/push-notifications/testing). Source: https://heraldsdk.com/docs/live-activities/setup.md --- # Live Activities on Android > How a Live Activity campaign reaches Android phones as a Live Update through FCM, what the Android SDK shows on each version, and Google's rules for promoted notifications. A Live Activity campaign also reaches Android phones. There it is a Live Update: an ongoing notification with the same title, body and progress bar or countdown, which Android 16 can promote to a chip in the status bar and a place at the top of the lock screen. The campaign is the same one you send to iPhones; nothing changes in the console. ## What you need - `herald-fcm` 0.7.0 or later, set up as in [Android setup](/docs/push-notifications/android-setup). There is no separate module or widget. - FCM on the app's connection. A connection with FCM and no APNs can send Live Activity campaigns to Android only. `herald-fcm` adds the `POST_PROMOTED_NOTIFICATIONS` permission to your merged manifest. It is a normal permission: there is no prompt, but the person can turn promotion off for your app in system settings. ## How it is delivered Android has no broadcast push, so Herald sends one FCM data message to each Android push token in the audience: | Moment | What Herald sends | |---|---| | The campaign starts | A start, at the person's send time. Quiet hours and the 72-hour Live Activity cap apply, and a push unsubscribe or suppressed token stops it, as with push. | | **Update Live Activity** | An update to every Android device it started on, queued at once and delivered within about a minute. Quiet hours do not apply mid-activity. | | **End now**, a cancel, or the end time | An end to every Android device it started on. | A start still waiting for the person's send time picks up the latest update. Live Updates don't count toward the push limit. ## What the notification looks like | Android version | What the person sees | |---|---| | 16 (API 36) and later | An ongoing notification that asks to be promoted. A progress bar uses `Notification.ProgressStyle` and shows the percentage in the status bar chip; a countdown counts down to the end time. | | 8.0 to 15 | The same ongoing notification with a standard progress bar or countdown, never promoted. | On every version the notification uses the `herald_default` channel, does not alert again on an update, and disappears at the end time even if the end message never arrives. A tap opens the campaign's deep link in your app, or the app when there is none. If the person dismisses it, later updates do not bring it back. `Herald.canPostLiveUpdates()` tells you whether Android will promote it: `false` below Android 16, before `configure`, or when the person turned promotion off. See [Android API](/docs/reference/android-api#canpostliveupdates). ## Google's rules for promotion Android promotes a notification only when it is ongoing, has a title, has no custom views, is not colorized and is not on a channel with `IMPORTANCE_MIN`. `herald-fcm` meets all of these as long as you leave `herald_default` at its default importance. Google limits Live Updates to activities the person started or is waiting on, such as a ride, a delivery, a game in progress or a timer. Promotions, ads and other marketing don't qualify: Android may show them as ordinary notifications instead, and Google may stop promoting your app's notifications. Use Live Activity campaigns for something the person is following, and push for everything else. ## Limits - The same content limits as on iPhone: title up to 40 characters, body up to 80, at most 8 hours. See [What a campaign can do](/docs/live-activities/setup#what-a-campaign-can-do). - The start alert is the notification itself; Android does not show the separate start alert text. - An Android device on an older `herald-fcm` ignores Live Updates. - Test sends from the campaign go to iPhones only. Source: https://heraldsdk.com/docs/live-activities/android.md --- # Content cards overview > What content cards are, how they reach the device, the three card types and every field in the card data model. Content cards are persistent messages that live inside your app, in a feed or any other place you choose, until they expire or the user dismisses them. Unlike a push notification, a card waits for the user: it is there the next time they open the screen. ## Who it's for - **Lifecycle teams** who want a message channel that does not depend on push permission and does not interrupt the user. - **Mobile engineers** who need a list of cards to render, either with the ready-made feed or in their own views. ## How it works 1. A Herald agent decides to send a user a message on the **content card** channel of a Herald sending connection. 2. Herald stores the card for that user. Nothing is sent to the device yet. 3. The SDK fetches the user's cards at the start of each session, when a user is first identified, and whenever you call `refreshContentCards()`. The request carries an ETag, so an unchanged list costs one small response. 4. Your app shows the cards with the default feed or your own UI. 5. Impressions, clicks and dismissals go back to Herald and are credited to the decision that produced the card, so the agent learns which messages work. Cards are fetched for identified users only. An anonymous device gets an empty list. With identity verification set to **Required** or **Optional**, the user also needs a valid user token; see [Users and identity](/docs/concepts/users-and-identity#user-tokens-and-verification-modes). ## Card types | Type | Wire value | What it shows | |---|---|---| | Classic | `classic` | Title, body and an optional call to action | | Captioned image | `captioned_image` | An image (16:9 in the default feed) above the title, body and call to action | | Image only | `image_only` | An image (2:1 in the default feed), with no text. Screen readers read the title, or `extras["alt"]` when the card has no title | A card whose type the SDK does not recognize is skipped, and the rest of the list still loads. ## Card data model `ContentCard` has the same fields on both platforms. Swift types are on the left, Kotlin types on the right. | Field | iOS | Android | Meaning | |---|---|---|---| | `id` | `String` | `String` | Unique card ID. Interactions are logged under it. | | `type` | `ContentCard.CardType` | `ContentCardType` | `classic`, `captionedImage` / `CAPTIONED_IMAGE`, `imageOnly` / `IMAGE_ONLY` | | `title` | `String?` | `String?` | Headline | | `body` | `String?` | `String?` | Body text | | `imageUrl` | `URL?` | `String?` | Image for captioned and image-only cards. For a video, its poster. | | `videoUrl`, `videoPosterUrl` | `URL?` | `String?` | A video for captioned-image cards (0.6.0), and its poster, the same as `imageUrl`. See [Video](/docs/content-cards/authoring#video). | | `videoAutoplay` | `Bool` | `Boolean` | Play muted and looped in the default feed while half visible (0.6.0). `false` by default. | | `credit` | `MediaCredit?` | `MediaCredit?` | `name`, `profileUrl` and `sourceUrl` of a stock photo or video's creator (0.6.0) | | `cta` | `String?` | `String?` | Call-to-action label, such as "Try Plus" | | `url` | `URL?` | `String?` | Deep link or web URL opened on click. A card without a URL is not tappable in the default feed. | | `extras` | `[String: HeraldValue]` | `Map` | Free-form key-value data for your own UI | | `pinned` | `Bool` | `Boolean` | Pinned cards sort first in the default feed | | `dismissible` | `Bool` | `Boolean` | Whether the user may dismiss the card | | `categories` | `[String]` | `List` | Labels you can filter on | | `createdAt` | `Date` | `Long` (epoch ms) | When Herald created the card | | `expiresAt` | `Date?` | `Long?` (epoch ms) | After this time the card is no longer shown. Null means no expiry. | | `viewed` | `Bool` | `Boolean` | An impression was logged for this card | | `clicked` | `Bool` | `Boolean` | A click was logged for this card | | `dismissed` | `Bool` | `Boolean` | The card was dismissed | | `decisionId` | `String?` | `String?` | The Herald decision the card came from. The SDK sends it back with each interaction. | `viewed` and `clicked` come from Herald on every sync and are updated on the device as soon as you log an impression or click, so you can use them for an unread badge. ## What the SDK keeps on the device - The card list is stored with the rest of the SDK state, so cards show offline and at launch, before the first sync finishes. - The list you read contains only cards that are unexpired and not dismissed, in the order Herald returns them: newest first. - Herald returns at most the 100 newest active cards for a user. - `reset()` and switching users clear the list. The next user's cards arrive with their first sync. ## What an agent sends A card sent by a Herald agent carries the variant's title, body, call to action and deep link. By default it is a `captioned_image` card when the message variant has an image and a `classic` card otherwise, dismissible, not pinned, with no categories, no extras and no expiry. You change the card type, pinning, dismissal, categories, extras and expiry per variant in **Delivery options (mobile SDK)**. See [Create cards in Herald](/docs/content-cards/authoring). ## Next - [Create cards in Herald](/docs/content-cards/authoring): set the options per message variant. - [Default feed](/docs/content-cards/default-feed): show cards with the built-in view. - [Building a custom UI](/docs/content-cards/custom-ui): render cards in your own views. Source: https://heraldsdk.com/docs/content-cards/overview.md --- # Create cards in Herald > Where to set card type, pinning, dismissal, categories, extras and expiry on a message variant in Herald, with the default and limit of each option and a worked example. You set how a content card looks and how long it lives on the message variant, in a section called **Delivery options (mobile SDK)**. Agents read these options at send time, so every card an agent sends from that variant carries them. ## Before you start - A message variant on the **content card** channel, in an agent's message manager or in a content library. - The SDK installed in your app. See the [quickstart](/docs/overview/quickstart-ios). The SDK already reads every option on this page, so no app update is needed. ## Find the options 1. Open the variant with **Edit**. The section appears when you edit an existing variant, not while you create one. 2. Open **Delivery options (mobile SDK)**. It is collapsed by default, with a one-line summary of the choices that differ from the defaults. 3. Change the options, then choose **Save delivery options**. The variant's own **Save** does not store them. **Reset to defaults** restores every option below. Options apply to cards sent after you save. Cards already sent keep the options they were sent with. A variant with no saved options behaves as the defaults below, so variants you wrote before 0.2 send the same cards as before. ## Options | Option | Default | Limit | What it does | |---|---|---|---| | Card type | Automatic | Automatic, Classic, Captioned image or Image only | Automatic sends a captioned image card when the variant has an image, and a classic card otherwise. | | Pinned | Off | | The default feed lists pinned cards first. See [Pinning, expiry and categories](/docs/content-cards/pinning-expiry-categories). | | Dismissible | On | | When off, the default feed does not let the user swipe the card away. | | Categories | None | Up to 10, each 1 to 50 characters | Labels your app can filter on. Press Enter to add one. | | Extras | None | Up to 20 pairs; key up to 100 characters, value up to 1,000 | Key and value pairs your app reads from the card, for example to choose a layout. | | Expires after (hours) | Never | 1 to 8,760 (one year) | The card disappears from the feed this long after it is sent. Leave it empty to never expire. | An image-only card shows the image and nothing else, so it needs a variant with an image. ## Video A card can show a video in place of its image. Pick one with **Choose media** (see the [media library](/docs/concepts/media-library)); the card's image is then the video's poster. Video needs SDK 0.6.0. - **Where it plays.** Captioned-image cards show the poster with a play button ("Play video" for VoiceOver and TalkBack). A tap plays the video inline, with sound, in the platform's standard player. Classic and image-only cards show no video. - **Autoplay.** A card sent with `videoAutoplay: true` (through the [Send API](/docs/reference/rest-endpoints) or a campaign; the editor has no switch) plays muted and looped in the SDK's `ContentCardFeed` while at least half of it is visible, and pauses when it isn't. It never autoplays when the device has Reduce Motion (iOS) or "remove animations" (Android) on. On Android an autoplaying video has no controls, and a tap opens the card's URL like any other tap on the card. On iOS autoplay only happens inside the `ContentCardFeed`; a custom UI plays nothing on its own. - **What Herald sends.** The card gets `videoUrl`, `videoPosterUrl` (the same as `imageUrl`), `videoAutoplay` (`false` unless set) and, for a stock photo or video, `credit`. - **Events.** `video_play` when the video starts and `video_complete` when it ends, once per play. A loop of an autoplaying video is not a new play. See [Event payload](/docs/reference/event-payload#interaction). ## Worked example Lumen, a fitness app, wants a card that stays at the top of the feed when a user's 6-week strength plan is ready, and goes away after three days. 1. Open the variant, set the title to "Your 6-week strength plan is ready", add the plan image, and save. 2. Open **Delivery options (mobile SDK)** and set: | Option | Value | |---|---| | Card type | Captioned image | | Pinned | On | | Dismissible | On (default) | | Categories | `programs` | | Expires after (hours) | 72 | 3. Choose **Save delivery options**. An agent that sends this variant on Monday at 9:00 creates a pinned captioned image card tagged `programs`. It leaves every user's feed on Thursday at 9:00. A custom UI can show only the program cards by filtering on the `programs` category. See [Building a custom UI](/docs/content-cards/custom-ui). ## Verify it works 1. Send the variant to a test user. [Send a test from Herald](/docs/push-notifications/testing#send-a-test-from-the-mobile-sdk-card) can send a card that expires in 24 hours. 2. Open the screen with the feed. The card shows in the type you chose, in the position its pinned setting gives. 3. After the expiry time passes, refresh the feed. The card is gone. ## Troubleshooting - **The section is missing.** The variant is on a channel that has no delivery options, or it is still being created. Save it, then edit it. - **Save delivery options is disabled.** A field has an error, shown under it, or nothing has changed. - **An image-only card shows nothing.** The variant has no image. ## Next - [Pinning, expiry and categories](/docs/content-cards/pinning-expiry-categories) - [Content cards overview](/docs/content-cards/overview) Source: https://heraldsdk.com/docs/content-cards/authoring.md --- # Default feed > Show content cards with the built-in SwiftUI and Compose feed, which orders, dismisses and logs cards for you. Add one view and your app shows the signed-in user's content cards, with impressions, clicks and dismissals logged for you. ## Before you start - The SDK is configured and the user is identified. See [Quickstart: iOS](/docs/overview/quickstart-ios) or [Quickstart: Android](/docs/overview/quickstart-android). - iOS: your target links the `HeraldUI` library as well as `HeraldSDK`. - Android: your app depends on `herald-ui` as well as `herald-core`. ## 1. Add the feed :::tabs ::tab ios ```swift import SwiftUI import HeraldUI struct InboxView: View { var body: some View { NavigationStack { ContentCardFeed() .navigationTitle("For you") } } } ``` ::tab android ```kotlin import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.foundation.layout.padding import com.herald.ui.ContentCardFeed @Composable fun InboxScreen() { Scaffold { padding -> ContentCardFeed(modifier = Modifier.padding(padding)) } } ``` ::: From UIKit, wrap the feed in a hosting controller: `UIHostingController(rootView: ContentCardFeed())`. From an Android `View` layout, host it in a `ComposeView`. | iOS | Android | |---|---| | ![The default content card feed on iOS](/docs/img/ios-feed.png) | ![The default content card feed on Android](/docs/img/android-feed.png) | ## 2. Let users refresh The feed updates on its own when a sync brings new cards. Syncs run at session start and when a user is identified. To fetch on demand, for example when the user opens the inbox, call `refreshContentCards()`: :::tabs ::tab ios ```swift ContentCardFeed() .onAppear { Herald.shared.refreshContentCards() } ``` ::tab android ```kotlin LaunchedEffect(Unit) { Herald.refreshContentCards() } ContentCardFeed() ``` ::: ## What the feed does | Behavior | Detail | |---|---| | Order | Pinned cards first, then newest first. Cards that sort equal keep Herald's order. | | Impressions | Logged once per card per session, the first time at least half of the card is on screen. Rebuilding the feed or relaunching the app within the session does not log it again. | | Clicks | A tap logs the click, then opens the card's `url`. On iOS the URL goes to `Herald.shared.deepLinkHandler` first, then to the system. On Android it opens with an `ACTION_VIEW` intent. Cards without a `url` are not tappable. | | Dismissal | Dismissible cards can be swiped away. Screen reader users get a **Dismiss** action. The card disappears at once, the dismissal is logged, and it does not come back on the next sync. | | Empty state | "No updates right now", in the theme's secondary text color. | | Expired cards | Left out. A card that expires while the feed is open goes away at its expiry time, without a sync. | | Sign-out | After `reset()` or a user switch, the feed empties until the new user's cards arrive. | Card views use the theme's colors, fonts, corner radius and spacing, follow the system light or dark setting, scale with Dynamic Type and Android font size, and keep every tappable card at least 44 pt (iOS) or 48 dp (Android) tall. ## Verify it works 1. Run the app, sign in, and have an agent send a content card to that user through the same connection. 2. Pull the card in with a new session or a `refreshContentCards()` call. It appears at the top of the feed. 3. Tap it. Your deep link opens. The click reaches Herald with the next batch and is credited to the agent's decision. 4. Swipe it away and relaunch the app. It stays gone. ## Troubleshooting - **The feed is always empty.** The user is not identified, or identity verification rejects the sync. Check that you call `setUserToken` after `identify`. With verification set to **Optional**, a sync without a token returns no cards. - **A card does nothing when tapped.** It has no `url`. Give the message variant a deep link, or handle taps yourself with `onCardClick` (see [Customizing the feed](/docs/content-cards/customizing-the-feed)). - **A deep link opens the browser instead of the app (iOS).** Set `Herald.shared.deepLinkHandler` to route your scheme inside the app, or register the scheme in your Info.plist. - **A card the agent sent never shows.** Herald suppresses card sends to users who have no SDK device on that connection yet. Send again after the user has run the app once. ## Next - [Customizing the feed](/docs/content-cards/customizing-the-feed) - [Pinning, expiry and categories](/docs/content-cards/pinning-expiry-categories) Source: https://heraldsdk.com/docs/content-cards/default-feed.md --- # Customizing the feed > Change the default feed's colors, fonts and spacing, filter and sort cards, replace the view for a card type and handle taps yourself. Every part of the default feed can be changed without giving up its automatic logging: the theme, which cards appear and in what order, how each card type looks, and what a tap does. ## Before you start - The [default feed](/docs/content-cards/default-feed) is on screen. ## 1. Apply a theme A `HeraldTheme` holds light and dark color sets, fonts, a corner radius and a base spacing unit. Pass the same theme to the in-app message presenter so cards and messages match. :::tabs ::tab ios ```swift import SwiftUI import HeraldUI let lumenTheme: HeraldTheme = { var light = HeraldColors.light light.accent = Color(red: 0.07, green: 0.55, blue: 0.42) var dark = HeraldColors.dark dark.accent = Color(red: 0.36, green: 0.84, blue: 0.67) return HeraldTheme( lightColors: light, darkColors: dark, typography: HeraldTypography(title: .custom("Avenir Next", size: 17, relativeTo: .headline)), cornerRadius: 16 ) }() struct InboxView: View { var body: some View { ContentCardFeed().heraldTheme(lumenTheme) } } ``` ::tab android ```kotlin import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.herald.ui.ContentCardFeed import com.herald.ui.HeraldColors import com.herald.ui.HeraldTheme import com.herald.ui.LocalHeraldTheme val LumenTheme = HeraldTheme( lightColors = HeraldColors.Light.copy(accent = Color(0xFF128C6B)), darkColors = HeraldColors.Dark.copy(accent = Color(0xFF5CD6AB)), cornerRadius = 16.dp, ) @Composable fun InboxScreen() { CompositionLocalProvider(LocalHeraldTheme provides LumenTheme) { ContentCardFeed() } } ``` ::: What each color does in the feed: | Color | Used for | |---|---| | `background` | Behind the feed | | `surface` | Card background | | `onSurface` | Card title | | `onSurfaceVariant` | Card body and the empty-state text | | `accent` | Call-to-action text | | `outline` | Card border and image placeholder | `onAccent` and `scrim` are used by in-app messages. Fonts: `title`, `body` and `button` (the call to action). `spacing` is the card padding and the gap around cards. `darkMode` set to `true` or `false` forces dark or light colors; `nil` / `null` follows the system. Keep text scalable when you change fonts. On iOS, build custom fonts with `Font.custom(_:size:relativeTo:)` so Dynamic Type still applies. On Android, give sizes in `sp`. ## 2. Filter and sort `filter` keeps the cards it returns true for. `order` replaces the default pinned-first, newest-first sort. :::tabs ::tab ios ```swift // Only workout tips, oldest first. ContentCardFeed( filter: { $0.categories.contains("tips") }, order: { $0.createdAt < $1.createdAt } ) ``` ::tab android ```kotlin // Only workout tips, oldest first. ContentCardFeed( filter = { "tips" in it.categories }, order = compareBy { it.createdAt }, ) ``` ::: The default sort is available as `ContentCardFeedDefaults.order` (iOS) and `ContentCardFeedDefaults.Order` (Android) if you want to filter but keep it. ## 3. Handle taps yourself By default a tap opens the card's `url`. Pass `onCardClick` to route it yourself. The SDK logs the click before your handler runs. :::tabs ::tab ios ```swift ContentCardFeed(onCardClick: { card in router.open(card) }) ``` ::tab android ```kotlin ContentCardFeed(onCardClick = { card -> navController.navigate("card/${card.id}") }) ``` ::: ## 4. Replace the view for a card type Pass `cardContent` to draw cards yourself. Call `onClick` when your view is tapped, so the click is logged and handled. Fall back to the default view for the types you do not replace. The feed still measures impressions and handles swipe to dismiss around your view. :::tabs ::tab ios ```swift ContentCardFeed { card, onClick in if card.type == .classic { LumenTipCard(card: card, onClick: onClick) } else { ContentCardView(card: card, onClick: onClick) } } struct LumenTipCard: View { let card: ContentCard let onClick: () -> Void var body: some View { Button(action: onClick) { Label(card.title ?? "", systemImage: "figure.run") .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading) } } } ``` ::tab android ```kotlin ContentCardFeed( cardContent = { card, onClick -> if (card.type == ContentCardType.CLASSIC) { LumenTipCard(card, onClick) } else { ContentCardFeedDefaults.Card(card, onClick) } }, ) @Composable fun LumenTipCard(card: ContentCard, onClick: () -> Unit) { TextButton(onClick = onClick, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text(card.title.orEmpty()) } } ``` ::: The default per-type views are public, so you can reuse them inside your own layout: `ClassicContentCardView`, `CaptionedImageContentCardView` and `ImageOnlyContentCardView` on iOS, `ClassicContentCard`, `CaptionedImageContentCard` and `ImageOnlyContentCard` on Android. ## 5. Change the empty state and labels :::tabs ::tab ios ```swift ContentCardFeed(emptyMessage: "You're all caught up") ``` ::tab android ```kotlin ContentCardFeed(emptyContent = { Text("You're all caught up") }) ``` ::: - iOS looks up `emptyMessage`, the **Dismiss** action label and the **Close** button label in your app's strings files, so add those keys to translate them. - Android reads the `herald_feed_empty`, `herald_dismiss` and `herald_close` string resources. Override them in your app's `res/values*/strings.xml`. - On Android, `contentPadding` sets the padding around the list, and `modifier` applies to the list itself. ## Verify it works Switch the device between light and dark mode and raise the system text size: the feed should follow both. Tap a card with your `onCardClick` handler and confirm it runs once. ## Troubleshooting - **The theme has no effect (iOS).** `.heraldTheme(_:)` must be applied to the feed or one of its ancestors, not to a sibling view. - **The theme has no effect (Android).** `ContentCardFeed` must be inside the `CompositionLocalProvider` that provides `LocalHeraldTheme`. - **Custom cards are never marked as viewed.** Impressions are measured on the view you return, so it needs a real size. A zero-height view never counts as half visible. - **A custom card's tap is not logged.** Call the `onClick` you were given, not your own navigation code directly. ## Next - [Building a custom UI](/docs/content-cards/custom-ui): drop the feed entirely. - [Theming and dark mode](/docs/in-app-messages/theming-and-dark-mode): apply the same theme to in-app messages. Source: https://heraldsdk.com/docs/content-cards/customizing-the-feed.md --- # Building a custom UI > Read content cards from the SDK's observable store, render them in your own views, and log impressions, clicks and dismissals correctly. Use your own views when cards belong in a carousel, a banner slot or a home screen section instead of a feed. You read the card list from the SDK and report what the user does with each card. ## Before you start - The SDK is configured and the user is identified. - `HeraldUI` and `herald-ui` are not needed for a custom UI. The core library is enough. ## 1. Observe the cards `contentCards` always holds the current user's unexpired, undismissed cards, newest first. It updates after every sync, after every interaction you log, and when a card expires. :::tabs ::tab ios ```swift import SwiftUI import HeraldSDK struct HomeCards: View { @ObservedObject private var store = Herald.shared.contentCards var body: some View { ScrollView(.horizontal) { LazyHStack { ForEach(store.cards.filter { !$0.categories.contains("inbox") }) { card in PromoTile(card: card) } } } } } ``` ::tab android ```kotlin import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import com.herald.sdk.Herald @Composable fun HomeCards() { val cards by Herald.contentCards.collectAsState() LazyRow { items(cards.filter { "inbox" !in it.categories }, key = { it.id }) { card -> PromoTile(card) } } } ``` ::: Outside SwiftUI, iterate `Herald.shared.contentCards.updates`, an `AsyncStream` that yields the current list at once and then every change. On Android, `Herald.contentCards` is a `StateFlow`, so `collect` it from a coroutine in a `View`-based screen. The list is in Herald's order. The default feed puts pinned cards first; if you want that, sort with `pinned` before `createdAt`. ## 2. Log what the user does The default feed logs these for you. A custom UI must log them itself, or the agent cannot learn from your cards. | Call | When | Rule | |---|---|---| | `logImpression(card)` | The card is actually visible to the user | Once per card each time it comes into view on a screen, not on every redraw. Do not log cards that are loaded but off screen. | | `logClick(card)` | The user taps the card or its call to action | Log before you open the link or navigate. | | `logDismissal(card)` | The user removes the card | Offer it only when `card.dismissible` is true. | What each call changes: - `logImpression` sets `viewed` on the card. The SDK sends at most one impression per card per session on both platforms, so an extra call does no harm. - `logClick` sets `clicked` on the card. - `logDismissal` removes the card from `contentCards` at once, remembers the dismissal on the device, and tells Herald, which stops returning the card. - A call for a card the SDK no longer knows (for example after a sign-out): Android ignores it. iOS still sends the interaction but changes no card state; Herald ignores an interaction for a card that does not belong to the current user. :::tabs ::tab ios ```swift struct PromoTile: View { let card: ContentCard var body: some View { VStack(alignment: .leading) { Text(card.title ?? "").font(.headline) if card.dismissible { Button("Not now") { Herald.shared.logDismissal(card) } } } .onAppear { Herald.shared.logImpression(card) } .onTapGesture { Herald.shared.logClick(card) if let url = card.url { Herald.shared.openDeepLink(url) } } } } ``` ::tab android ```kotlin @Composable fun PromoTile(card: ContentCard) { LaunchedEffect(card.id) { Herald.logImpression(card) } Column( Modifier.clickable { Herald.logClick(card) card.url?.let(Herald::openUrl) }, ) { Text(card.title.orEmpty()) if (card.dismissible) { TextButton(onClick = { Herald.logDismissal(card) }) { Text("Not now") } } } } ``` ::: `onAppear` and `LaunchedEffect` fire when a lazy row composes an item, which is close to "visible". If your layout composes items well before they scroll into view, measure visibility yourself, as the default feed does (it waits until half the card is on screen). On iOS, `Herald.shared.openDeepLink(_:)` hands the URL to your `deepLinkHandler` first, then to the system. On Android, `Herald.openUrl(_:)` opens it with an `ACTION_VIEW` intent. ## 3. Refresh Cards sync at session start and when a user is identified. Call `refreshContentCards()` for pull to refresh or when a screen opens. The request uses an ETag, so frequent calls are cheap when nothing changed. :::tabs ::tab ios ```swift List(store.cards) { card in PromoTile(card: card) } .refreshable { Herald.shared.refreshContentCards() } ``` ::tab android ```kotlin Button(onClick = { Herald.refreshContentCards() }) { Text("Refresh") } ``` ::: `refreshContentCards()` returns at once. The new list arrives through `contentCards` when the request finishes. ## Verify it works 1. Show a card and scroll it into view. Then tap it. 2. Background the app to send the queue. The card's outcome is credited to the agent's decision in Herald. 3. Dismiss a card and relaunch: it should not return. ## Troubleshooting - **Cards show but the agent learns nothing.** Impressions and clicks are not logged, or they are logged with a copy of the card from an old list. Always pass the card from the current `contentCards` value. - **Impressions are far higher than real views.** You log in a place that runs on every redraw. Log on appear, once per card per screen visit. - **A dismissed card is back after a sync.** You hid it in your own state without calling `logDismissal`. ## Next - [Pinning, expiry and categories](/docs/content-cards/pinning-expiry-categories) - [Content cards overview](/docs/content-cards/overview): the full data model. Source: https://heraldsdk.com/docs/content-cards/custom-ui.md --- # Pinning, expiry and categories > How pinned cards, expiry dates, categories and extras behave on the device, and how to use them in the default feed and in your own UI. Four card fields control where a card appears and for how long: `pinned`, `expiresAt`, `categories` and `extras`. The SDK applies expiry for you; the other three are yours to act on. You set these fields per message variant in Herald. See [Create cards in Herald](/docs/content-cards/authoring). A variant with no saved options sends cards that are not pinned, never expire, and have no categories or extras. ## Pinned | | Behavior | |---|---| | Default feed | Pinned cards come first, newest first among them, then every other card, newest first. | | Custom UI | `contentCards` is not reordered for you. Sort with `pinned` first if you want the same order. | | Dismissal | Pinning does not stop dismissal. Use `dismissible` for that. | :::tabs ::tab ios ```swift let ordered = store.cards.sorted { a, b in a.pinned != b.pinned ? a.pinned : a.createdAt > b.createdAt } ``` ::tab android ```kotlin val ordered = cards.sortedWith(compareByDescending { it.pinned }.thenByDescending { it.createdAt }) ``` ::: ## Expiry - A card with an `expiresAt` in the past is never in `contentCards`. The SDK checks expiry every time it updates the list. - A card that expires while it is on screen leaves `contentCards` at its expiry time: the SDK updates the list then, without a sync, so an open feed drops it. - Herald stops returning a card once it expires, so it is gone from the next sync on every device. - A null `expiresAt` means the card stays until the user dismisses it or Herald retires it. ## Categories `categories` is a list of strings. Use it to place cards: an inbox, a home screen banner, a section per topic. :::tabs ::tab ios ```swift // Home banner: one "promo" card. let banner = store.cards.first { $0.categories.contains("promo") } // Inbox feed without promos. ContentCardFeed(filter: { !$0.categories.contains("promo") }) ``` ::tab android ```kotlin // Home banner: one "promo" card. val banner = cards.firstOrNull { "promo" in it.categories } // Inbox feed without promos. ContentCardFeed(filter = { "promo" !in it.categories }) ``` ::: A card can have several categories, or none. A filter that requires a category hides cards without one. ## Extras `extras` carries key-value data for your own UI, such as a badge label or a background color. Values can be any JSON value; strings, numbers and booleans are the usual choice. - The default feed reads one key: `alt`, the screen reader description for an `image_only` card that has no title. - Read other keys in a custom card view. On iOS a value is a `HeraldValue`, so match the case: `if case .string(let badge)? = card.extras["badge"] { ... }`. On Android it is `Any?`: `card.extras["badge"] as? String`. ## Edge cases - **Clock changes.** The SDK compares `expiresAt` with the device clock, so a device set ahead hides cards early. - **Sign-out.** `reset()` clears every card regardless of pinning or expiry. ## Related - [Customizing the feed](/docs/content-cards/customizing-the-feed) - [Building a custom UI](/docs/content-cards/custom-ui) Source: https://heraldsdk.com/docs/content-cards/pinning-expiry-categories.md --- # In-app messages overview > What in-app messages are, the slideup, modal, full-screen and HTML types, how messages reach the device and how the SDK decides to show one. In-app messages appear on top of your app while the user is in it: a banner, a dialog, a full-screen takeover or your own HTML page. They reach users who have not allowed push, at the moment they are most relevant, such as right after a workout. ## Who it's for - **Lifecycle teams** who want to reach active users in context, without depending on push permission. - **Mobile engineers** who install the default presenter once and decide when messages may appear. ## How it works 1. A Herald agent decides to send a user an in-app message. 2. Herald stores the message for that user, with its trigger and display rules. 3. The SDK downloads the user's messages at the start of each session, when a user is first identified, and on `refreshContentCards()`. It keeps them on the device. 4. When a trigger happens on the device (a session starts, the app tracks an event, the user opens a push), the SDK picks the best matching message and shows it. No network request is needed at that moment, so messages work offline once they have synced. 5. Impressions, clicks and dismissals go back to Herald and are credited to the agent's decision. Messages are delivered to identified users only, as with content cards. ## Message types | Type | Wire value | What the user sees | |---|---|---| | Slideup | `slideup` | A banner at the bottom (or top) of the screen. The app stays usable around it. A tap runs the first button's action; swiping it toward its edge (down for a bottom slideup, up for a top one) dismisses it. It can dismiss itself after a set time. | | Modal | `modal` | A centered dialog over a dimmed background, with an optional image, header, body, buttons and a close button. | | Full screen | `full` | Covers the screen: image on top, then header, body, buttons and a close button. | | HTML | `html` | Your own HTML page, full screen, in a web view with a small JavaScript bridge. See [Custom views](/docs/in-app-messages/custom-views#html-messages). | | | iOS | Android | |---|---|---| | Slideup | ![A slideup message on iOS](/docs/img/ios-slideup.png) | ![A slideup message on Android](/docs/img/android-slideup.png) | | Modal | ![A modal message on iOS](/docs/img/ios-modal.png) | ![A modal message on Android](/docs/img/android-modal.png) | | Full screen | ![A full-screen message on iOS](/docs/img/ios-full.png) | ![A full-screen message on Android](/docs/img/android-full.png) | | HTML | ![An HTML message on iOS](/docs/img/ios-html.png) | ![An HTML message on Android](/docs/img/android-html.png) | ## Turn on display The core SDK decides when a message should show; a presenter draws it. Install the default presenter from `HeraldUI` or `herald-ui` once, right after `configure`. Without a presenter, messages are not shown: they wait on the device until one is set. :::tabs ::tab ios ```swift import HeraldSDK import HeraldUI Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!) Herald.useDefaultInAppUI() ``` ::tab android ```kotlin import com.herald.sdk.Herald import com.herald.ui.HeraldInAppPresenter Herald.configure(this, appKey = "YOUR_APP_KEY", endpoint = "https://YOUR_HERALD_HOST") HeraldInAppPresenter.install() ``` ::: On iOS the presenter draws each message in its own window above your app's windows. On Android it draws in an overlay on the resumed activity, which must be a `ComponentActivity` (every Compose and AppCompat activity is). ## The message data model `InAppMessage` has the same shape on both platforms. | Field | Meaning | |---|---| | `id` | Unique message ID. Interactions are logged under it. | | `type` | `slideup`, `modal`, `full` or `html` | | `priority` | Higher wins when several messages match one trigger | | `trigger` | `session_start`, `event` (a name plus property filters) or `push_open`. See [Triggers and delivery rules](/docs/in-app-messages/triggers-and-delivery). | | `reEligibility` | `once`, or `after_hours` with a number of hours | | `expiresAt` | After this time the message is never shown. Null means no expiry. | | `content.header`, `content.body` | Text | | `content.imageUrl` | Image for modal and full-screen messages. For a video, its poster. | | `content.videoUrl`, `content.videoPosterUrl` | A video for modal and full-screen messages (0.6.0), and its poster, the same as `imageUrl`. See [Video](/docs/in-app-messages/authoring#video). | | `content.credit` | `name`, `profileUrl` and `sourceUrl` of a stock photo or video's creator, for apps that show a credit (0.6.0) | | `content.buttons` | Each has an `id`, `text` and an action: open a deep link or web URL, or close | | `content.html` | The page for `html` messages | | `content.slideFrom` | `top` or `bottom` for slideups. Bottom when unset. | | `content.dismissAfterSeconds` | Auto-dismiss delay for slideups. Null keeps the message until the user acts. | | `style` | Optional background, text, button and button-text colors (hex such as `#101828`) and corner radius. Null fields use your theme. | | `decisionId` | The Herald decision the message came from | ## What gets logged | Interaction | When | |---|---| | Impression | When the message is on screen | | Click | A tap on the message body, or a link tapped in an HTML page | | Button | A tap on a button, or `herald.click(id)` from an HTML page, with the button's `id` | | Dismiss | The message closes without any click: close button, swipe, tap outside, back button, auto-dismiss | A message that was clicked does not also log a dismissal. ## What an agent sends By default, an agent send on the **in-app** channel creates a slideup from the bottom, and the **modal in-app** channel creates a modal. Both show at the user's next session start, once. The message variant's title, body and image become the header, body and image, and its call to action and deep link become one button. You change the type (including full screen and HTML), buttons, trigger, property filters, priority, re-eligibility, expiry and colors per variant in **Delivery options (mobile SDK)**. See [Create in-app messages in Herald](/docs/in-app-messages/authoring). ## Next - [Create in-app messages in Herald](/docs/in-app-messages/authoring): set the options per message variant. - [Triggers and delivery rules](/docs/in-app-messages/triggers-and-delivery) - [Controlling display](/docs/in-app-messages/controlling-display) Source: https://heraldsdk.com/docs/in-app-messages/overview.md --- # Create in-app messages in Herald > How to set format, content, trigger, rules and style for an in-app message variant in Herald, with every option, default and limit, and a worked example. You control what an in-app message looks like, when it shows and how often on the message variant, in a section called **Delivery options (mobile SDK)**. It is available on the **in-app** channel and the **modal in-app** channel. ## Before you start - A message variant on the in-app or modal in-app channel. - The SDK installed in your app. The SDK already supports every option on this page, so no app update is needed. ## Find the options 1. Open the variant with **Edit**. The section appears when you edit an existing variant, not while you create one. 2. Open **Delivery options (mobile SDK)**. It is collapsed by default, with a one-line summary of the choices that differ from the defaults. 3. Change the options, then choose **Save delivery options**. The variant's own **Save** does not store them. **Reset to defaults** restores every option below. Options apply to messages sent after you save. A variant with no saved options sends what it did before 0.2: a slideup (in-app channel) or a modal (modal in-app channel) that shows at session start, once. ## Format | Option | Default | Limit | |---|---|---| | Type | Slideup on the in-app channel, Modal on the modal in-app channel | Slideup, Modal, Full screen or HTML | | Slide in from | Bottom | Top or Bottom. Shown for slideups only. | | Auto-dismiss after (seconds) | Empty (stays open) | 2 to 60 | ## Content The variant's title, body and image become the message's header, body and image. These options add to them. | Option | Default | Limit | |---|---|---| | HTML | Not used | Shown only for the HTML type, which requires it. 100 KB at most, counted in bytes. A preview renders in a sandbox with scripts off. | | Use the variant's button | On | One button from the variant's call to action and deep link, when it has both. | | Buttons | | Up to 2 when **Use the variant's button** is off. | Each button has: | Field | Limit | |---|---| | Button text | 1 to 40 characters | | Action | **Close**, **Open deep link** or **Open URL** | | Link | Required for a deep link or URL. A URL must start with `http://` or `https://`. | ## Video A message can show a video in place of its image. Pick one with **Choose media** (see the [media library](/docs/concepts/media-library)); the message's image is then the video's poster. Video needs SDK 0.6.0. - **Where it plays.** Modal and full-screen messages show the poster with a play button ("Play video" for VoiceOver and TalkBack). A tap plays the video inline, with sound, in the platform's standard player. Slideup and HTML messages show no video. - **What Herald sends.** The message's `content` gets `videoUrl`, `videoPosterUrl` (the same as `imageUrl`) and, for a stock photo or video, `credit`. See [In-app messages overview](/docs/in-app-messages/overview). - **Events.** The SDK logs `video_play` when the video starts and `video_complete` when it reaches the end, once per play. See [Event payload](/docs/reference/event-payload#interaction). ## When to show | Option | Detail | |---|---| | Show when | **Session starts** (default), **An event happens** or **A push is opened** | | Event name | Required for an event trigger, for example `workout_completed`. Your app must call `track` with this name. | | Property filters | Up to 5, all of which must match. Each has a property, an operator and a value. | Operators: equals, does not equal, greater than, at least, less than, at most, contains, and exists. **exists** has no value. Filter values that look like numbers are saved as numbers, so `7` matches a numeric property with the value 7, not the string "7". The values `true` and `false` are saved as booleans. Any other text is saved as a string. The SDK compares types, so make the filter match the type your app sends. How the device evaluates triggers is covered on [Triggers and delivery rules](/docs/in-app-messages/triggers-and-delivery). ## Rules | Option | Default | Limit | |---|---|---| | Priority | 0 | 0 to 100. Higher shows first when several messages are eligible. | | Show again | Never, show once | **Never, show once** or **After some hours**. | | Hours before showing again | 24, when you choose **After some hours** | 1 to 8,760 | | Expires after (hours) | Never | 1 to 8,760. Counted from the send time. | ## Style **Use app theme** is on by default: the message takes its colors and corner radius from your app's theme. Turn it off to set any of these for this message. An empty field keeps the app theme for that value. | Option | Format | |---|---| | Background, Text, Button, Button text | `#RRGGBB`, for example `#1F6FEB` | | Corner radius (px) | 0 to 32 | Turning **Use app theme** back on clears all five values. ## Worked example Lumen wants to celebrate a seven-day streak when the user finishes a workout, once. | Option | Value | |---|---| | Channel | Modal in-app | | Type | Modal | | Show when | An event happens | | Event name | `workout_completed` | | Property filter | `streak_days` equals `7` | | Priority | 10 | | Show again | Never, show once | | Use app theme | On | The variant's header reads "7 days in a row" and its button, from the variant's call to action and deep link, opens the streak screen. Your app sends the event with a numeric property: :::tabs ::tab ios ```swift Herald.shared.track("workout_completed", properties: ["streak_days": 7]) ``` ::tab android ```kotlin Herald.track("workout_completed", mapOf("streak_days" to 7)) ``` ::: The modal shows right after the call, once per user. If the app sent `"7"` as a string, the filter would not match, because the filter's `7` is saved as a number. ## Verify it works 1. Send the variant to a test user, or use [Send a test from Herald](/docs/push-notifications/testing#send-a-test-from-the-mobile-sdk-card) with the **In-app modal** channel. A test modal uses session-start rules, so it checks delivery and your theme, not the trigger. 2. Open the app and trigger the event. Check the message shows once, and not again on the next trigger. 3. Use the debug preview hooks to see each type with your theme. See [Logging and debugging](/docs/operations/logging-and-debugging#preview-messages-without-a-server). ## Troubleshooting - **The message never shows.** The event name differs from the name your app tracks, a filter's type differs from the property's type, or the message already showed and **Show again** is set to once. - **Save delivery options is disabled.** A field has an error, shown under it, or nothing has changed. The HTML type needs HTML, and other types must not have any. - **A button does nothing.** An **Open deep link** button needs a deep link your app handles. See [Deep links](/docs/push-notifications/deep-links). ## Next - [Triggers and delivery rules](/docs/in-app-messages/triggers-and-delivery) - [Theming and dark mode](/docs/in-app-messages/theming-and-dark-mode) - [In-app messages overview](/docs/in-app-messages/overview) Source: https://heraldsdk.com/docs/in-app-messages/authoring.md --- # Triggers and delivery rules > The three in-app triggers, property filters and their operators, priority, the minimum interval, one message at a time, pending messages and re-eligibility. A trigger is the moment on the device that can show an in-app message. When a trigger fires, the SDK looks through the messages it has synced, keeps the ones whose trigger matches and whose rules allow them to show, and offers the one with the highest priority. ## Triggers | Trigger | Wire value | Fires when | |---|---|---| | Session start | `session_start` | A new session starts and the message sync for it has finished (or failed, in which case the messages already on the device are used). | | Custom event | `event` | Your app calls `track` with the message's event name, and every property filter matches. | | Push open | `push_open` | The user opens a Herald push notification and your app passes it to `handleNotificationResponse` (iOS) or `handleNotificationIntent` (Android). | Only `track` fires event triggers. `screen`, `trackPurchase` and attribute calls do not. Events tracked by other systems, such as your backend or a warehouse sync, never trigger an in-app message: the decision is made on the device. :::tabs ::tab ios ```swift // Can trigger a message whose trigger is workout_completed with minutes > 20. Herald.shared.track("workout_completed", properties: ["minutes": 32, "type": "strength"]) ``` ::tab android ```kotlin // Can trigger a message whose trigger is workout_completed with minutes > 20. Herald.track("workout_completed", mapOf("minutes" to 32, "type" to "strength")) ``` ::: ## Property filters An event trigger can carry filters on the event's properties. Every filter must match. | Operator | Matches when the property | |---|---| | `eq` | Equals the value. Type matters: `32` does not equal `"32"`. Numbers compare by value, so `32` equals `32.0`. | | `neq` | Does not equal the value | | `gt`, `gte`, `lt`, `lte` | Is a number greater than, at least, less than, or at most the value. A string never matches. | | `contains` | Is a string that contains the value (case-sensitive), or a list that has the value as an element | | `exists` | Is present. The filter's value is ignored. | **A missing property fails every filter, `exists` included.** A property sent as null counts as missing. So `neq "free"` does not match an event that has no `plan` property at all. If you need "anything but free, or unknown", send the property every time. ## Which message wins When several messages match one trigger: 1. Messages that have expired are left out. 2. Messages the user is not eligible for again yet are left out (see re-eligibility below). 3. The highest `priority` wins. On a tie, the first in Herald's order wins, which is the newest. ## Display rules | Rule | Default | Detail | |---|---|---| | One at a time | Always | A message never shows over another Herald message. | | Minimum interval | 30 seconds | Measured from the moment the last message appeared. Configurable. `showNext()` skips it. | | Foreground only | Always | Messages show while the app is in the foreground. A trigger that fires in the background waits for the app to come forward. | | Presenter needed | Always | Without a presenter (see [the overview](/docs/in-app-messages/overview#turn-on-display)), a message waits on the device. | | Expiry | Per message | After `expiresAt`, the message is never shown. | Change the minimum interval at configuration: :::tabs ::tab ios ```swift Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!) { options in options.inAppMinimumInterval = 60 // seconds } ``` ::tab android ```kotlin Herald.configure( this, appKey = "YOUR_APP_KEY", endpoint = "https://YOUR_HERALD_HOST", options = HeraldOptions(inAppMinimumIntervalSeconds = 60), ) ``` ::: ## Re-eligibility Each message says how often the same user may see it. | Mode | Wire value | Behavior | |---|---|---| | Once | `once` | Shown at most once to this user on this device | | After hours | `after_hours` with `hours` | Eligible again that many hours after it last appeared | - The history is kept per user on each device: the signed-in user's history, or the anonymous history before sign-in. - It survives app restarts, `reset()` and user switches. If the same user signs in again, their history comes back. - `wipeData()` clears it. - A message counts as shown only once the presenter has it on screen. A message that never appeared (no presenter, the app went to the background) stays eligible. - History is per device. A user with two phones can see a `once` message on each. ## Pending messages A message that matches a trigger joins a pending list on the device. It is never dropped because it could not show at that moment. The same rules apply on iOS and Android. | Situation | What happens | |---|---| | Nothing is on screen, the minimum interval has passed, the app is in the foreground and a presenter is set | The SDK asks your delegate, then shows the message | | Another message is on screen | The message waits and is offered when that message closes | | The minimum interval has not passed | The message waits and is offered when the interval runs out | | No presenter, or no screen to draw on | The message waits and is offered again when the app comes to the foreground, when an activity resumes (Android), on the next trigger, when a message closes, when a presenter is set (iOS), and on `showNext()` | | The delegate answers **later** | The message stays pending and is offered again at those same moments; the delegate is asked again each time | | The delegate answers **drop** | The message leaves the pending list. It stays eligible for its next trigger. | | The message expires or stops being eligible while it waits | It leaves the pending list | When several messages are pending, the highest priority shows first. On a tie, the one that has waited longest goes first. The pending list is saved on the device, so it survives an app restart. Pending messages are cleared by `reset()`, a user switch and `wipeData()`. ## Edge cases - **The first session after install.** The session-start trigger runs after the first sync, so a message an agent sent before the user opened the app can show in that same session. - **Offline.** Triggers use the messages from the last successful sync. A message sent since then shows after the next sync. - **An unknown trigger, operator or message type** from a newer Herald version is skipped; the other messages still load. ## Related - [Controlling display](/docs/in-app-messages/controlling-display) - [Events and attributes](/docs/concepts/events-and-attributes) - [Sessions](/docs/concepts/sessions) Source: https://heraldsdk.com/docs/in-app-messages/triggers-and-delivery.md --- # Controlling display > Use the in-app message delegate to show, hold or drop a message, show held messages with showNext, and keep messages away from onboarding and checkout. Set a delegate to decide, message by message, whether it shows now, waits, or is dropped. Use it to keep messages out of flows where an interruption costs you, such as onboarding, checkout or a video. ## Before you start - The default presenter, or your own, is installed. See [the overview](/docs/in-app-messages/overview#turn-on-display). ## 1. Set a delegate The delegate returns one of three choices: | Choice | iOS | Android | Effect | |---|---|---|---| | Show now | `.display` | `InAppDisplayDecision.DISPLAY` | The message appears. | | Later | `.later` | `InAppDisplayDecision.LATER` | The message stays pending. It is offered again automatically, or at once with `showNext()`. | | Drop | `.discard` | `InAppDisplayDecision.DISCARD` | This occurrence is dropped. Nothing is recorded, so the message stays eligible for its next trigger. | With no delegate, every message shows. :::tabs ::tab ios ```swift import HeraldSDK @MainActor final class MessageGate: InAppMessageDelegate { static let shared = MessageGate() var isBusy = false func shouldDisplay(_ message: InAppMessage) -> InAppMessageDisplayChoice { if isBusy { return .later } // Never interrupt with a full-screen takeover; a banner is fine. if message.type == .full { return .discard } return .display } } // At launch, after configure. The SDK holds the delegate weakly: keep a strong reference. Herald.shared.inAppMessageDelegate = MessageGate.shared ``` ::tab android ```kotlin import com.herald.sdk.Herald import com.herald.sdk.InAppDisplayDecision import com.herald.sdk.InAppMessage import com.herald.sdk.InAppMessageDelegate import com.herald.sdk.InAppMessageType object MessageGate : InAppMessageDelegate { @Volatile var isBusy = false override fun shouldDisplay(message: InAppMessage): InAppDisplayDecision = when { isBusy -> InAppDisplayDecision.LATER // Never interrupt with a full-screen takeover; a banner is fine. message.type == InAppMessageType.FULL -> InAppDisplayDecision.DISCARD else -> InAppDisplayDecision.DISPLAY } } // In Application.onCreate, after configure. Herald.inAppMessageDelegate = MessageGate ``` ::: **Threading.** The delegate runs on the main thread on both platforms (the main actor on iOS). Return quickly. If an Android delegate throws, the SDK shows the message and logs the error. **When it is asked.** The delegate is asked when a message is about to appear, not when its trigger fires, so it sees your app's state at that moment. It can be asked more than once for the same message: after a **later**, and when it answered show now but there was no screen to draw on. Keep it free of side effects such as analytics calls. ## 2. Hold messages during onboarding or checkout Set your flag when the sensitive flow starts. When it ends, clear the flag and call `showNext()` to show the message that waited. :::tabs ::tab ios ```swift func checkoutDidStart() { MessageGate.shared.isBusy = true } func checkoutDidFinish() { MessageGate.shared.isBusy = false Herald.shared.showNext() } ``` ::tab android ```kotlin fun onCheckoutStarted() { MessageGate.isBusy = true } fun onCheckoutFinished() { MessageGate.isBusy = false Herald.showNext() } ``` ::: `showNext()` offers the highest-priority waiting message now, ignoring the minimum interval; on a tie, the one that has waited longest. Your delegate is asked again. It does nothing while another message is on screen or when nothing is waiting. You do not have to call `showNext()`. A message held with **later** is also offered again on its own the next time the app comes to the foreground, a trigger fires or a message closes. `showNext()` makes it show as soon as your flow ends instead. ## 3. Route message clicks (iOS) Button and body clicks open their URL through `Herald.shared.openDeepLink(_:)`. Set `deepLinkHandler` to route your own links inside the app; return `true` when you handled the URL, `false` to let the system open it. ```swift Herald.shared.deepLinkHandler = { url in guard url.scheme == "lumen" else { return false } AppRouter.shared.open(url) return true } ``` On Android, clicks go to `Herald.deepLinkHandler` first, with the same semantics. When it is `null` or returns `false`, the SDK opens the link with an `ACTION_VIEW` intent, so register your scheme with an intent filter on the activity that should handle it. ## Verify it works 1. Set the busy flag and trigger a message (for example with a session start). Nothing appears. 2. Clear the flag and call `showNext()`. The message appears. 3. With debug logging on, a dropped message logs `discarded by delegate` on Android. On iOS nothing is logged for a drop. ## Troubleshooting - **The delegate is never called (iOS).** The SDK keeps a weak reference. If nothing else holds your delegate object, it is released right after you assign it. - **A held message shows later than expected.** It is offered again at the next foreground, trigger or close. Call `showNext()` when your flow ends to show it at once. - **A message shows during checkout anyway.** The message was already on screen when the flow started. Set the flag before the flow's first screen appears. ## Next - [Theming and dark mode](/docs/in-app-messages/theming-and-dark-mode) - [Triggers and delivery rules](/docs/in-app-messages/triggers-and-delivery) Source: https://heraldsdk.com/docs/in-app-messages/controlling-display.md --- # Theming and dark mode > Match in-app messages to your app's colors, fonts, corner radius and spacing, control dark mode, and understand how per-message styles override the theme. The default message views take their look from a `HeraldTheme`: light and dark colors, fonts, corner radius and spacing. It is the same theme type the content card feed uses, so one definition styles both. ## Before you start - You install the default presenter with `Herald.useDefaultInAppUI` (iOS) or `HeraldInAppPresenter.install` (Android). ## 1. Pass your theme to the presenter :::tabs ::tab ios ```swift import SwiftUI import HeraldUI var light = HeraldColors.light light.accent = Color(red: 0.07, green: 0.55, blue: 0.42) var dark = HeraldColors.dark dark.accent = Color(red: 0.36, green: 0.84, blue: 0.67) let theme = HeraldTheme(lightColors: light, darkColors: dark, cornerRadius: 16, spacing: 20) Herald.useDefaultInAppUI(theme: theme) ``` ::tab android ```kotlin import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.herald.ui.HeraldColors import com.herald.ui.HeraldInAppPresenter import com.herald.ui.HeraldTheme val theme = HeraldTheme( lightColors = HeraldColors.Light.copy(accent = Color(0xFF128C6B)), darkColors = HeraldColors.Dark.copy(accent = Color(0xFF5CD6AB)), cornerRadius = 16.dp, spacing = 20.dp, ) HeraldInAppPresenter.install(theme) ``` ::: Both calls return the presenter. Its `theme` property can be changed later, for example when the user picks a different app theme; the next message uses the new value. ## What the theme controls | Theme value | Used in messages for | |---|---| | `surface` | Message background (all four types) | | `onSurface` | Header, body, the close button, and the text of secondary buttons | | `accent` | Background of the first (primary) button | | `onAccent` | Text of the primary button | | `scrim` | The dimmed layer behind a modal | | `outline` | Image placeholder while an image loads | | `typography.title`, `.body`, `.button` | Header, body and button text | | `cornerRadius` | Message and button corners | | `spacing` | Padding inside messages and the slideup's distance from the screen edge | Buttons after the first have no fill: they use the text color on the message background. ## Per-message styles A message can carry its own `style`: `backgroundColor`, `textColor`, `buttonColor`, `buttonTextColor` and `cornerRadius`. Each field that is set replaces the matching theme value for that message only. Fields left null, and colors that are not valid `#RRGGBB` or `#AARRGGBB` hex, fall back to the theme, with one exception: when a message sets `backgroundColor` without `textColor`, the text is black or white, whichever has the higher contrast against that background. `buttonColor` without `buttonTextColor` works the same way for the button label. The theme's text colors are picked for the theme's own surfaces, so they could be unreadable on a color the message chose. | Style field | Replaces | |---|---| | `backgroundColor` | `surface` | | `textColor` | `onSurface` | | `buttonColor` | `accent` | | `buttonTextColor` | `onAccent` | | `cornerRadius` | `cornerRadius` | **Message colors do not change with dark mode.** A message with a white `backgroundColor` stays white in dark mode. To keep dark mode working, leave colors null and let the theme decide, or pick colors that read well in both modes. ## Dark mode | `darkMode` | Behavior | |---|---| | `nil` / `null` (default) | Follows the system light or dark setting | | `true` | Always uses `darkColors` | | `false` | Always uses `lightColors` | If your app has its own appearance setting, set `darkMode` from it and update `presenter.theme` when the user changes it. On iOS, a forced value also sets the message window's interface style, so system controls inside the message match. ## Fonts :::tabs ::tab ios ```swift let typography = HeraldTypography( title: .custom("Avenir Next", size: 20, relativeTo: .title3).weight(.semibold), body: .custom("Avenir Next", size: 16, relativeTo: .body) ) Herald.useDefaultInAppUI(theme: HeraldTheme(typography: typography)) ``` ::tab android ```kotlin val typography = HeraldTypography( title = TextStyle(fontFamily = AvenirNext, fontSize = 20.sp, fontWeight = FontWeight.SemiBold), body = TextStyle(fontFamily = AvenirNext, fontSize = 16.sp), ) HeraldInAppPresenter.install(HeraldTheme(typography = typography)) ``` ::: The defaults are system text styles on iOS and `sp` sizes on Android, so they follow the user's text size. Keep that when you replace them: `relativeTo:` on iOS, `sp` on Android. ## HTML messages The theme does not style an HTML page. The message background (the theme's `surface`, or the message's `backgroundColor`) shows behind and around the page. Style the page with its own CSS, including dark mode, and test it in both modes on both platforms. ## Verify it works Show a modal in light mode and in dark mode, and once with the system text size at its largest. Use `Herald.shared.debugShowInAppMessage(_:)` / `Herald.debugShowInAppMessage(_:)` with a message loaded through `debugLoadMessages` to repeat this without waiting for a trigger; both are for debug builds only. ## Troubleshooting - **Messages ignore the feed theme.** The feed reads the theme from the view tree; the presenter does not. Pass the theme to `useDefaultInAppUI` or `install` as well. - **One message looks off-brand.** It carries its own `style` colors. Check the message, not the theme. - **Text is clipped at large text sizes.** A custom font with a fixed size. Use `relativeTo:` or `sp`. ## Next - [Custom views](/docs/in-app-messages/custom-views) - [Accessibility](/docs/in-app-messages/accessibility) Source: https://heraldsdk.com/docs/in-app-messages/theming-and-dark-mode.md --- # Custom views > Replace the default view for any in-app message type, write HTML messages with the JavaScript bridge and its security rules, or replace the presenter entirely. You can replace the view for one message type and keep everything else the default presenter does: the overlay, transitions, focus handling and interaction logging. For full control, replace the presenter itself. ## Before you start - You use the default presenter. See [the overview](/docs/in-app-messages/overview#turn-on-display). ## 1. Replace the view for a type Pass a view provider when you install the presenter. It receives the message and an `InAppMessageActions` object. Return your view for the types you replace; on iOS, return `nil` to use the default view for that message. :::tabs ::tab ios ```swift import SwiftUI import HeraldSDK import HeraldUI Herald.useDefaultInAppUI(theme: lumenTheme) { message, actions in guard message.type == .modal else { return nil } return AnyView(LumenModal(message: message, actions: actions)) } struct LumenModal: View { let message: InAppMessage let actions: InAppMessageActions var body: some View { VStack(spacing: 16) { Text(message.content.header ?? "").font(.title2.bold()) Text(message.content.body ?? "") ForEach(message.content.buttons) { button in Button(button.text) { actions.buttonClicked(button) } .frame(minHeight: 44) } Button("Not now") { actions.dismiss() }.frame(minHeight: 44) } .padding(24) .background(Color(.systemBackground), in: RoundedRectangle(cornerRadius: 20)) .padding(24) } } ``` ::tab android ```kotlin val lumenModal: InAppMessageContent = { message, actions -> LumenModal(message, actions) } HeraldInAppPresenter.install( theme = LumenTheme, customViews = mapOf(InAppMessageType.MODAL to lumenModal), ) @Composable fun LumenModal(message: InAppMessage, actions: InAppMessageActions) { Box(Modifier.fillMaxSize().background(Color(0x99000000)), contentAlignment = Alignment.Center) { Column(Modifier.padding(24.dp).background(Color.White, RoundedCornerShape(20.dp)).padding(24.dp)) { Text(message.content.header.orEmpty(), style = MaterialTheme.typography.titleLarge) Text(message.content.body.orEmpty()) message.content.buttons.forEach { button -> Button(onClick = { actions.buttonClicked(button) }, modifier = Modifier.heightIn(min = 48.dp)) { Text(button.text) } } TextButton(onClick = actions::dismiss, modifier = Modifier.heightIn(min = 48.dp)) { Text("Not now") } } } } ``` ::: Your view replaces everything the default view draws for that type, including a modal's dimmed background and close button. The presenter still places it (slideups at their edge, other types centered), animates it in and out, blocks the app behind modal, full-screen and HTML messages, and handles the escape gesture (iOS) and the back button (Android). ### Report every action Call one `InAppMessageActions` method for each user action. Each one logs the interaction and, except `clicked`, takes the message down. | Method | Use it when | Logs | Closes | |---|---|---|---| | `buttonClicked(button)` | The user taps one of `message.content.buttons`. Opens the button's link. | Button click with the button's `id` | Yes | | `bodyClicked(url)` | The user taps the message itself. Opens `url` when you pass one. | Click | Yes | | `clicked(buttonId)` | The user taps a control that should not close the message | Button click with that `id` | No | | `dismiss()` | The user closes the message without acting | Dismissal, only if nothing was clicked | Yes | After the message is down, further calls are ignored, so a double tap cannot log twice. The default building blocks are public if you want to wrap rather than replace them: `SlideupMessageView`, `ModalMessageView`, `FullScreenMessageView`, `HTMLMessageView` (iOS) / `HtmlMessageView` (Android). ## HTML messages An `html` message is a complete HTML document that the default presenter shows full screen in a web view. JavaScript is turned on for that web view only, and the page gets a `herald` object: | Call | Effect | |---|---| | `herald.close()` | Closes the message. Logs a dismissal if nothing was clicked. | | `herald.click(id)` | Logs a button click with `id` and keeps the message open. An empty `id` is ignored. | A link the user taps is logged as a click, closes the message and opens outside it: on iOS through `Herald.shared.openDeepLink(_:)`, on Android with an `ACTION_VIEW` intent. The page itself never navigates away. ```html

Strength week

Five sessions, 20 minutes each.

Join the challenge

``` ### What the SDK enforces - **No file access.** The page is loaded with no base URL. Android turns off file and content access. File, `javascript:`, `data:`, `about:` and `blob:` URLs are never handed to your app. - **No stored state.** On iOS the page gets a non-persistent website data store, so cookies and local storage end with the message. On Android, DOM storage is off. - **No pop-ups or extra windows.** Scripts cannot open windows. On iOS, a tapped `target="_blank"` link is treated like any other tapped link. - **Only link taps leave the page.** A navigation counts as a click only when the user tapped a link. Redirects, meta refreshes, script navigations and frame loads are blocked without logging anything. - **Bridge from the top frame (iOS).** Calls from iframes are ignored, and so are `herald.click` ids longer than 200 characters. - **HTTPS content only (Android).** Mixed content is blocked. On iOS, App Transport Security applies as it does to the rest of your app. - **A way out.** On both platforms the message always has a native close button in the top corner. On iOS it closes on its own if the page fails to load or the web content process ends. On Android it closes if the web view's renderer process dies, and your app keeps running. ### Rules for the page author - **Call the bridge only from user actions.** `herald.click` and `herald.close` do not check for a tap. A page that calls them on load reports clicks that never happened. - **Do not navigate from script.** It is blocked on both platforms. Use plain links. - **Include a visible close control** that calls `herald.close()`. Both SDKs add their own close button in the top trailing corner, so leave room for it there. - **Include a viewport tag.** iOS adds `width=device-width` when the page has none; Android does not. - **Keep it self-contained.** Inline styles and small images. The message syncs ahead of time, but images and fonts the page loads from the network are fetched when it opens, and fail offline. ## 2. Replace the presenter To draw messages with your own window or navigation system, implement `InAppMessagePresenter` and assign it to `Herald.shared.inAppMessagePresenter` (iOS) or `Herald.inAppMessagePresenter` (Android). The SDK still decides which message shows and when. | Rule | iOS | Android | |---|---|---| | Method | `present(_:onClose:) -> Bool`, on the main actor | `present(activity, message, callbacks): Boolean`, on the main thread | | Return value | `true` only when the message is on screen. `false` keeps it pending. | Same | | Impression | Logged by the SDK when you return `true` | Call `callbacks.onImpression()` when it is visible | | Clicks | `Herald.shared.logClick(message, buttonId:)` | `callbacks.onClick(buttonId)` | | Dismissal | `Herald.shared.logDismissal(message)` if the user closed it without clicking | Handled by `callbacks.onDismiss()` | | Close | Call `onClose` exactly once when it leaves the screen | Call `callbacks.onDismiss()` exactly once | | Forced removal | Not used | Implement `dismissCurrent()`: the SDK calls it on sign-out or a user switch | ## Verify it works Load test messages with `debugLoadMessages` and show each type with `debugShowInAppMessage` (debug builds only). Tap each control and confirm that exactly one interaction is logged per tap and that the message closes when it should. ## Troubleshooting - **The message stays on screen forever (custom view).** Your view never calls `dismiss()`, `buttonClicked` or `bodyClicked`. - **No more messages appear after a custom one (custom presenter).** `onClose` or `callbacks.onDismiss()` was not called, so the SDK still thinks a message is on screen. - **An HTML link does nothing.** The navigation did not come from a link tap (for example a script set `location`), so it was blocked. - **`herald` is undefined in the page.** You are testing in a browser. The object exists only inside the SDK's web view. ## Next - [Accessibility](/docs/in-app-messages/accessibility) - [Theming and dark mode](/docs/in-app-messages/theming-and-dark-mode) Source: https://heraldsdk.com/docs/in-app-messages/custom-views.md --- # Accessibility > What the default in-app message and content card views do for text size, VoiceOver and TalkBack, focus, touch targets and reduced motion, and what you must do for custom and HTML content. The default views in `HeraldUI` and `herald-ui` are built to work with the platform's assistive technology out of the box. Custom views and HTML messages are yours, and so is the content of every message. This page lists what the SDK does and what remains your job. ## What the default views do | Area | iOS | Android | |---|---|---| | Text size | Fonts are system text styles, so Dynamic Type applies. Long text scrolls in modal and full-screen messages. At accessibility text sizes a slideup shows at most three lines, so it never covers most of the screen. | Sizes are in `sp`, so the system font size applies. Long text scrolls in modal and full-screen messages. | | Screen reader labels | The close button reads "Close". Message headers are marked as headings. Decorative images are hidden. | The close button reads "Close". Message headers are marked as headings. Decorative images are hidden. | | Dismiss without gestures | Slideups and dismissible cards offer a **Dismiss** action. The escape gesture (two-finger scrub) closes any message. | Slideups and dismissible cards offer a **Dismiss** custom action. The back button closes modal, full-screen and HTML messages. | | Focus | Modal, full-screen and HTML messages are modal for VoiceOver: focus stays inside the message until it closes, then returns to the app. Slideups do not take focus. | Modal, full-screen and HTML messages hide the app's views from TalkBack while they are up, and restore them when the message closes. Slideups do not take focus. | | Touch targets | Buttons, the close button, slideups and tappable cards are at least 44 pt tall. The close button is 44 x 44 pt. | Buttons, the close button, slideups and tappable cards are at least 48 dp tall. The close button is 48 x 48 dp (44 x 44 dp on HTML messages, as on iOS). | | Reduced motion | With Reduce Motion on, messages fade instead of sliding or scaling. | With **Remove animations** on (animator duration scale 0), messages appear and disappear without animation. | | Auto-dismiss | A slideup's `dismissAfterSeconds` is ignored while VoiceOver runs, so the message stays until the user acts. | The timeout is lengthened to the user's accessibility timeout setting, or turned off when the system asks for that. | | Image-only cards | Read as the card title, or `extras["alt"]` when there is no title. | Same | | Labels in your language | "Close", "Dismiss" and the feed's empty text are looked up in your app's strings files. | Override `herald_close`, `herald_dismiss` and `herald_feed_empty` in your string resources. | ## What you are responsible for ### Message content - **Alt text.** Image-only cards need a title or an `alt` extra. Modal and full-screen images are treated as decorative, so do not put information only in the image. - **Contrast.** Per-message `style` colors override your theme in both light and dark mode. Check that text and button colors have enough contrast against the background in both. See [Theming and dark mode](/docs/in-app-messages/theming-and-dark-mode#per-message-styles). - **Button text** that makes sense on its own: "See the plan", not "Click here". - **Auto-dismiss.** Slideups that dismiss themselves can disappear before some users finish reading. Leave `dismissAfterSeconds` empty for anything the user must act on. ### Custom views When you replace a default view (see [Custom views](/docs/in-app-messages/custom-views)), the presenter still handles focus, reduced motion for its own transition, and the escape gesture or back button. Your view must handle the rest: - Use text styles (`Font.custom(_:size:relativeTo:)` on iOS, `sp` on Android) so text scales. - Give icon-only controls a label: `.accessibilityLabel(_:)` on iOS, `contentDescription` on Android. - Keep touch targets at 44 pt or 48 dp. - Offer a visible way to close that calls `actions.dismiss()`. - Mark the header as a heading: `.accessibilityAddTraits(.isHeader)` on iOS, `Modifier.semantics { heading() }` on Android. - Respect reduced motion in any animation inside your view: `@Environment(\.accessibilityReduceMotion)` on iOS, the animator duration scale on Android. ### HTML messages The presenter makes the web view modal and supports the escape gesture and back button, but it cannot fix the page. Write the page to the same standard as your website: - Set `lang` on the `html` element and use real headings, buttons and links, not clickable `div`s. - Give images `alt` text, or `alt=""` when they are decorative. - Use relative font sizes. On iOS, `font: -apple-system-body` follows Dynamic Type. - Include a visible close button that calls `herald.close()`, with a text label. Both SDKs add a native close button in the top corner as well, and Android's back button also closes the message. - Respect `prefers-reduced-motion` in CSS animations. - Test with VoiceOver and TalkBack: the page is read by the web view's own accessibility support. ### Custom content card UIs Apply the same rules as for custom views: scalable text, labels on icons, 44 pt or 48 dp targets, and a non-gesture way to dismiss a card if you support swipe to dismiss. ## Test checklist 1. Turn on VoiceOver or TalkBack and open each message type with `debugShowInAppMessage`. Every control should be reachable and labelled, and focus should not leave a modal message. 2. Close each blocking message with the escape gesture (iOS) or back button (Android). 3. Set the largest text size. Nothing should be cut off; long messages should scroll. 4. Turn on Reduce Motion or Remove animations and check that messages no longer slide. 5. Check every message's colors in light and dark mode. ## Related - [Custom views](/docs/in-app-messages/custom-views) - [Customizing the feed](/docs/content-cards/customizing-the-feed) Source: https://heraldsdk.com/docs/in-app-messages/accessibility.md --- # Data collection controls > Every control that limits what the SDK collects and sends: the two device data tiers, minimal mode, what is never collected, setEnabled and wipeData. You decide what the SDK collects. It sends a small fixed set of device data, a second set you can turn off, and nothing else unless your app calls it. This page lists every control and exactly what it changes. ## The controls at a glance | Control | What it does | Where | |---|---|---| | Minimal mode | Stops the second tier of device data | `deviceDataCollection` at configure | | Your own calls | Events, attributes, email, phone, purchases and location are sent only when your code sends them | Your app | | `setEnabled(false)` | Sends one best-effort push unsubscribe for the device, then stops all collection, sending and message display, hides cached content cards, and remembers that across launches. `setEnabled(true)` re-subscribes push when the device still has its token and permission. | Any time | | `wipeData()` | Sends one best-effort push unsubscribe for the device, deletes everything the SDK stored on the device and leaves the SDK off until `setEnabled(true)`, which starts with a new device ID | Any time | | Identity verification | Decides whose data Herald accepts and returns | The connection's **Mobile SDK** card. See [Security and identity verification](/docs/data-and-privacy/security-and-identity-verification). | | SDK settings | SDK 0.6.0+. Change data collection, lifecycle and deep link events, the send interval and session timeouts, or turn off **Collect events** for every device, without an app update. Apps pick up changes within an hour or on next launch. See [Remote SDK settings](#remote-sdk-settings). | Console: Settings, **SDK settings** | | Geofences | SDK 0.7.0+. Off by default: nothing location-related runs until your app adds the geofence module, holds background location permission and calls `enableGeofences()`. `disableGeofences()` stops it. The **Geofences** SDK setting set to Off stops it on every device. See [Geofences](/docs/concepts/geofences). | Your app; console: Settings, **SDK settings** | | Store location from IP address | When off, Herald doesn't record a country, region or approximate location from the request. Locale and time zone your app sends are still used. On by default. | Console: Settings, **SDK settings** | ## Tier 1: always sent The SDK cannot work without these, so minimal mode keeps them. | Data | Wire field | |---|---| | Device ID: a random UUID the SDK creates. Not the IDFA, IDFV, Android ID or advertising ID. | `deviceId` | | App name, version, build, and bundle ID or package name | `context.app` | | OS name and version | `context.os` | | The device's region setting (a two-letter code from the locale, not a location) | `context.region` | | SDK name and version | `sdk` | | Session start and end, with duration | `session_start`, `session_end` events | | Message interactions: impressions, clicks, button taps, dismissals, push opens | `interaction` events | Herald also records the country of each batch: the two-letter code its hosting edge derives from the request's IP address when available, otherwise the region setting. It does not store the request's IP address with SDK data. Turn off **Store location from IP address** (Settings, **SDK settings** in the console, per app) and Herald records no country from the request; the region setting your app sends is still kept. A country already stored for a device is replaced at that device's next batch, so a device that never sends again keeps the one it had. With the setting on, Herald also keeps an approximate location for each device: the latitude and longitude of the city its hosting edge derives from the request's IP address, rounded to 0.1° (about 11 km). It powers the console's **Live map**, which shows people active in the last 5 minutes as lights, grouped by place, with no names. Turn the setting off and the location is cleared at the device's next batch. If your app passes a location to the SDK, the Live map uses that instead, rounded the same way. ## Tier 2: sent by default, off in minimal mode | Data | Wire field | |---|---| | Device manufacturer, model and type (phone, tablet and so on) | `context.device` | | Screen width, height and density | `context.screen` | | Locale | `context.locale` | | Language | `context.language` | | Time zone (IANA name, such as `America/Chicago`) | `context.timezone` | | Network type: `wifi`, `cellular`, `ethernet`, `other` or `none` | `context.network.type` | | Notification permission state | `context.push.authorization` | In minimal mode these keys are left out of the batch, not sent empty. Herald keeps only the latest context per device, so stored tier 2 values are replaced by the next batch after you switch. :::tabs ::tab ios ```swift Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!) { options in options.deviceDataCollection = .minimal } ``` ::tab android ```kotlin Herald.configure( this, appKey = "YOUR_APP_KEY", endpoint = "https://YOUR_HERALD_HOST", options = HeraldOptions(deviceDataCollection = DeviceDataCollection.MINIMAL), ) ``` ::: What minimal mode costs: Herald cannot fill a user's time zone from the device, so send-time optimization relies on time zones you sync from your warehouse. ## Sent only when your app calls the SDK | Data | Call | |---|---| | External ID and traits | `identify` | | Custom events, screens, purchases | `track`, `screen`, `trackPurchase` | | User attributes | `setAttribute`, `setAttributes` | | Email address, phone number | `setEmail`, `setPhone` | | Channel subscriptions | `setSubscription`, and `requestPushAuthorization` for push | | Push token | `setPushToken` (on Android, `herald-fcm` calls it for you) | | Latitude and longitude | `setLocation`: only the values you pass | | Geofence entered or left: the geofence's id and name, never coordinates | `enableGeofences()` (SDK 0.7.0+, geofence module only) | Send only what you need for messaging. Event properties and attributes are stored as you send them, so do not put passwords, payment card numbers, health records or other sensitive data in them. ## Never collected - Advertising identifiers: IDFA on iOS, the advertising ID on Android. - Vendor and hardware identifiers: IDFV, Android ID. - Location from the operating system, unless your app calls `enableGeofences()`. Even then the SDK never asks for location permission and never sends the device's location: the operating system watches the geofences on the device, and only a crossing (the geofence's id and name) is sent. - Contacts, photos, files or other personal content. - Mobile carrier. ## Turn the SDK off and on `setEnabled(false)` stops everything until you call `setEnabled(true)`. The setting is saved, so it holds across launches. :::tabs ::tab ios ```swift Herald.shared.setEnabled(false) ``` ::tab android ```kotlin Herald.setEnabled(false) ``` ::: While the SDK is off: - Calls such as `track`, `identify` and `setAttributes` are ignored, not queued. - Nothing is sent. Events queued before you turned it off stay on the device and are sent after `setEnabled(true)`. - No new sessions start, messages do not sync, and in-app messages do not show. - Content cards already on the device are hidden: `contentCards` is empty until `setEnabled(true)`, which shows them again. - Push: as it turns off, the SDK sends one push unsubscribe for this device (only when it has a push token), so Herald stops sending it pushes. It tries once, in the background, and does not retry, so a device that is offline at that moment can still get pushes. On Android, `herald-fcm` does not show Herald pushes while the SDK is off. On iOS the system shows alert pushes without asking the app. - After `setEnabled(true)`, if the device still has its push token and notification permission, the SDK sends the token again with a push subscription of subscribed, which lifts the unsubscribe. After `wipeData()`, `setEnabled(true)` fetches the push token again when notification permission is still granted and sends it with subscribed; otherwise pushes resume only once the app records the push subscription again with `requestPushAuthorization()` or `setSubscription`. ## Remote SDK settings SDK 0.6.0 and later fetch the app's settings from Herald at launch and on a foreground at most once an hour. Set them per app in the console under Settings, **SDK settings**. Each one is either a value or **Use app's value**, which keeps what your app was built with. | Setting | Values | |---|---| | Collect events | On or Off. Off stops all event collection and sending in the SDK (iOS crash reports included), clears its queue, and skips message syncs until you turn it back on. Push tokens and subscription changes wait on the device and go out when it is back on. The SDK keeps checking the setting, so it resumes on its own. | | Send interval (seconds) | 5 to 300 | | Session timeout in foreground (minutes), Session timeout in background (minutes) | 1 to 1,440 | | Data collection | Standard or Minimal | | Track app lifecycle events, Track pushes your app sends, Track deep links | On or Off | | Geofences | On or Off. SDK 0.7.0+. Off stops geofence monitoring on every device the next time the app starts, even in apps that call `enableGeofences()`. On or **Use app's value** leaves it to the app. | The SDK caches the last settings it fetched and applies them at the next launch before it fetches again. When the fetch fails, the cached or built-in settings stay. `setEnabled(false)` in your app always wins: nothing is fetched or sent while it is in effect. ## Wipe the device `wipeData()` first sends the same one-time push unsubscribe as `setEnabled(false)`, under the old device ID. It then deletes the SDK's files and memory on the device: queued events, the External ID and token, cards (`contentCards` is emptied at once), in-app messages, in-app history and the device ID. When the SDK is turned on again it uses a new device ID, so the device looks like a new install to Herald. On Android it keeps one marker that records that the notification prompt was shown, so the permission keeps reading `denied` rather than `not_determined`; the marker holds no user data. :::tabs ::tab ios ```swift Herald.shared.wipeData() // The SDK is now off. Turn it back on when collection may resume: Herald.shared.setEnabled(true) ``` ::tab android ```kotlin Herald.wipeData() // The SDK is now off. Turn it back on when collection may resume: Herald.setEnabled(true) ``` ::: After `wipeData()` the SDK stays off until you call `setEnabled(true)`. It then starts with a new device ID. With the geofence module, the SDK stops monitoring and deletes its cached geofence list and crossing times the next time the app calls `enableGeofences()` or a geofence is crossed. Call `disableGeofences()` with `wipeData()` to stop monitoring at once. `wipeData()` does not delete anything Herald already received. See [User data deletion](/docs/data-and-privacy/user-data-deletion). ## Related - [Device data collected](/docs/concepts/device-data) - [Consent and opt-out](/docs/data-and-privacy/consent-and-opt-out) - [App store disclosures](/docs/data-and-privacy/app-store-disclosures) Source: https://heraldsdk.com/docs/data-and-privacy/data-collection-controls.md --- # Consent and opt-out > Gate the SDK on user consent with setEnabled, record per-channel subscriptions, and know what happens to data queued before a user opts out. If your app asks users for consent before it collects analytics or sends marketing, connect that choice to the SDK in two places: whether the SDK runs at all, and which channels the user agreed to receive. ## Before you start - Your app has a consent screen or a consent management platform, and you can read the user's current choice at launch. ## 1. Gate the SDK on consent Configure the SDK at every launch, then set it on or off from the stored consent in the same place, before anything else runs. The setting is saved, but setting it every launch keeps the SDK in step with your consent store. :::tabs ::tab ios ```swift func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!) Herald.shared.setEnabled(ConsentStore.shared.allowsMessaging) return true } ``` ::tab android ```kotlin class LumenApplication : Application() { override fun onCreate() { super.onCreate() Herald.configure(this, appKey = "YOUR_APP_KEY", endpoint = "https://YOUR_HERALD_HOST") Herald.setEnabled(ConsentStore.allowsMessaging(this)) } } ``` ::: SDK calls run in the order you make them, so `setEnabled(false)` takes effect before the SDK starts its first session. **Do not delay `configure` until consent instead.** Calls you make before `configure` are kept in memory and applied once it runs, so a `track` made before consent would be sent after it. Configure early and use `setEnabled`. ## 2. Update it when the user changes their mind :::tabs ::tab ios ```swift func consentChanged(allowsMessaging: Bool) { Herald.shared.setEnabled(allowsMessaging) if allowsMessaging { Herald.shared.flush() } } ``` ::tab android ```kotlin fun onConsentChanged(allowsMessaging: Boolean) { Herald.setEnabled(allowsMessaging) if (allowsMessaging) Herald.flush() } ``` ::: ## What happens when the SDK is off | | While off | |---|---| | New calls (`track`, `identify`, `setAttributes` and the rest) | Ignored. They are not queued for later. | | Events queued before the user opted out | Stay on the device, unsent. They are sent after `setEnabled(true)`. | | Sessions, message sync, in-app messages | Stopped | | Content cards already on the device | Hidden: `contentCards` is empty, so the default feed shows nothing. They come back after `setEnabled(true)`. | | Push notifications | When the SDK turns off, it sends one push unsubscribe for this device, so Herald stops sending it pushes. On Android, `herald-fcm` also stops showing Herald pushes while the SDK is off. | | Device ID | Kept | The push unsubscribe is best effort: the SDK tries once, in the background, and does not queue or retry it. It is sent only when the device has a push token, and Herald applies it like any other push unsubscribe (see [Record channel subscriptions](#3-record-channel-subscriptions)): for an identified user whose identity it accepts. If the device is offline at that moment, Herald can keep sending pushes. On iOS the system shows alert pushes without asking the app, so the SDK cannot hide one that still arrives. After `setEnabled(true)`, if the device still has its push token and notification permission, the SDK sends the token again with a push subscription of subscribed in its next batch, and Herald lifts the unsubscribe it recorded. A suppression from a bounce or one added by an admin stays. After `wipeData()` the device has a new ID and no token. When `setEnabled(true)` runs while notification permission is still granted, the SDK fetches the token again (iOS registers with APNs and gets it back through your `setPushToken` forwarding; Android needs `HeraldMessagingService.syncToken` to have run after `configure`) and sends it with a push subscription of subscribed. Without permission, pushes resume only once the app records the push subscription again: call `requestPushAuthorization()`, or `setSubscription` for push with subscribed or opted in. If the user withdraws consent and the events already queued must not be sent, call `wipeData()` as well. It sends the same one-time push unsubscribe first, then deletes the queue, the cached cards and messages (they disappear from `contentCards` at once) and every other piece of SDK data on the device. See [Data collection controls](/docs/data-and-privacy/data-collection-controls#wipe-the-device). :::tabs ::tab ios ```swift func consentWithdrawn() { Herald.shared.wipeData() // deletes the queue; leaves the SDK off } ``` ::tab android ```kotlin fun onConsentWithdrawn() { Herald.wipeData() // deletes the queue; leaves the SDK off } ``` ::: ## 3. Record channel subscriptions Consent to messages is often per channel. Tell Herald with `setSubscription`. The states are `subscribed`, `unsubscribed` and `opted_in` (explicit opt-in, for channels and regions that require it). :::tabs ::tab ios ```swift Herald.shared.setEmail("maya@example.com") Herald.shared.setSubscription(.email, .optedIn) Herald.shared.setSubscription(.sms, .unsubscribed) ``` ::tab android ```kotlin Herald.setEmail("maya@example.com") Herald.setSubscription(SubscriptionChannel.EMAIL, SubscriptionState.OPTED_IN) Herald.setSubscription(SubscriptionChannel.SMS, SubscriptionState.UNSUBSCRIBED) ``` ::: How Herald applies them: - **Unsubscribed** adds a suppression for the user's addresses on that channel, so Herald stops sending to them. For email and SMS that is the user's email address or phone number. For push it is only this device's push token, because push permission belongs to the device. - **Subscribed** and **opted in** lift an earlier unsubscribe. They never lift a suppression caused by a bounce or a complaint. - A subscription applies to addresses Herald already has. Set the email or phone first, in the same session, as in the example. - Subscriptions are written only for an identified user whose identity Herald accepts. See [Users and identity](/docs/concepts/users-and-identity#user-tokens-and-verification-modes). - Content cards and in-app messages have no subscription. To stop them, turn the SDK off. - Turning the SDK off, or calling `wipeData()`, sends a push unsubscribe for the device by itself. See [What happens when the SDK is off](#what-happens-when-the-sdk-is-off). ### Push `requestPushAuthorization()` records the push subscription for you: opted in when the user allows notifications, unsubscribed when they decline. If the user later turns notifications off in system settings, call `setSubscription(.push, .unsubscribed)` (iOS) or `setSubscription(SubscriptionChannel.PUSH, SubscriptionState.UNSUBSCRIBED)` (Android) when you notice the change, for example at launch. The current permission is also sent in the device context, unless you use minimal mode. ## 4. Record the lawful basis SDK 0.6.0 and later can record the lawful basis your app collects data under, and the policy it was given under. It is sent with each batch while set, kept on the device and on the person, and shown to admins on the person's page as **Consent basis**. :::tabs ::tab ios ```swift Herald.shared.setConsent(basis: .consent, documentId: "privacy-policy", documentVersion: "2026-11") // When it no longer applies: Herald.shared.clearConsent() ``` ::tab android ```kotlin Herald.setConsent(ConsentBasis.CONSENT, documentId = "privacy-policy", documentVersion = "2026-11") // When it no longer applies: Herald.clearConsent() ``` ::: The bases are the GDPR lawful bases: `consent`, `contract`, `legal_obligation`, `vital_interests`, `public_task` and `legitimate_interests`. `documentId` and `documentVersion` are optional, up to 100 characters each. This is recorded for your compliance records. It doesn't change what is collected: use the [data collection settings](/docs/data-and-privacy/data-collection-controls) or `setEnabled(false)` for that. After `clearConsent()` the device stops sending it; the person keeps the last record sent. ## Verify it works 1. Turn consent off, use the app, then turn it back on. With debug logging, no events from the "off" period are sent. 2. Unsubscribe from email in the app and send the queue. In Herald, open **Settings > Sending** and the connection: the **Suppressions** card lists the address with the reason `unsubscribe` and the source `sdk`. ## Troubleshooting - **Events from before consent show up in Herald.** You called the SDK before `configure` and then configured after consent. Configure at launch and gate with `setEnabled`. - **An unsubscribe has no effect.** The user had no email address, phone number or push token on file yet, or the batch was not verified. Set the address first and check the user token. ## Related - [Data collection controls](/docs/data-and-privacy/data-collection-controls) - [User data deletion](/docs/data-and-privacy/user-data-deletion) - [Permission prompts](/docs/push-notifications/permission-prompts) Source: https://heraldsdk.com/docs/data-and-privacy/consent-and-opt-out.md --- # User data deletion > Delete a user's SDK data on the device with wipeData, what the SDK stores in Herald for a user, and how to erase it there with the deletion API. Deleting a user's data has two halves: the data the SDK keeps on the device, and the data Herald received from it. The SDK handles the first with one call. Your backend handles the second with one API call. ## On the device `wipeData()` deletes everything the SDK stored in your app: the event queue, the External ID and user token, content cards, in-app messages, in-app history, the cached push token and the device ID. It does not touch your app's own data or the operating system's notification settings. :::tabs ::tab ios ```swift func accountDeleted() { Herald.shared.wipeData() // The SDK is now off. If the app keeps running signed out and collection may resume: Herald.shared.setEnabled(true) } ``` ::tab android ```kotlin fun onAccountDeleted() { Herald.wipeData() // The SDK is now off. If the app keeps running signed out and collection may resume: Herald.setEnabled(true) } ``` ::: - After the wipe the device gets a new device ID, so later activity cannot be linked to the deleted user on this device. - Events still queued are deleted, not sent. - The SDK stays off until you call `setEnabled(true)`. - `wipeData()` only affects the device it runs on. A user with the app on two phones needs it on both, or the server-side deletion API below. Use `reset()` for an ordinary sign-out. It clears the user from the device but keeps the device ID and the device's own history. See [Users and identity](/docs/concepts/users-and-identity#sign-out). ## In Herald For an identified user, Herald stores: | Data | Comes from | |---|---| | User profile: traits and attributes | `identify`, `setAttributes`, and any warehouse sync you run | | Events: tracks, screens, purchases, sessions, interactions, with the device ID | Every batch | | Device record: latest device context, country, the location you set, and the user it belongs to | Every batch | | Contact points: email, phone, push tokens | `setEmail`, `setPhone`, push token registration | | Suppressions | Unsubscribes, bounces and complaints | | Content card and in-app message records, with viewed, clicked and dismissed times | Agent sends and interactions | | Decisions and outcomes | Herald's agents | Anonymous activity (before sign-in, or after `reset()`) is stored with the device ID and no External ID. ## Delete a user in Herald Call the deletion API from your backend, for privacy requests such as GDPR and CCPA erasure. `DELETE /api/v1/users/{userId}` | Header | Value | |---|---| | `Authorization` | `Bearer `, the ingest token of your SDK connection | `userId` is the ID your app passes to `identify`, URL-encoded, 1 to 255 characters. The call deletes data held for the connection whose token you send. A user known to several connections needs one call per connection. ```shell curl -X DELETE "https://YOUR_HERALD_HOST/api/v1/users/u_123" \ -H "Authorization: Bearer $HERALD_INGEST_TOKEN" ``` ```json { "data": { "userId": "u_123", "sdkDevices": 2, "sdkEvents": 418, "sdkMessages": 6, "contactPoints": 3, "outboundMessages": 1, "userArmStats": 4, "userAgentAssignments": 1, "pseudonymizedDecisions": 12, "failedSendsScrubbed": 0, "trackedUser": "deleted" } } ``` Never call this from the app: the ingest token is a server secret. ### What is deleted | Data | Result | |---|---| | Device records of the user's devices: devices bound to the user now, and devices the user was signed in on before, including after `reset()` | Deleted (`sdkDevices`) | | Content card and in-app message records | Deleted (`sdkMessages`) | | Events stored with the External ID, anonymous events from those devices (before sign-in and after `reset()`), and events that claimed the External ID without a verified user token | Deleted (`sdkEvents`) | | Contact points: email, phone, push tokens | Deleted (`contactPoints`) | | Queued and sent pushes and emails for the user | Deleted (`outboundMessages`) | | Per-user agent learning state and agent assignments | Deleted (`userArmStats`, `userAgentAssignments`) | | Campaign recipient records for the connection's campaigns, and segment membership | Deleted | | Failed-send records | The External ID is removed; a record left with no users is deleted (`failedSendsScrubbed`) | | User profile: traits and attributes | `trackedUser` is `deleted` when nothing else references the user. It is `cleared` when it must stay for another source, such as a warehouse sync: attributes, time zone and computed profile fields are emptied. It is `none` when there was no profile, or when this connection held no data about the user; the profile is then left as it is. | ### What is kept, and why - **Decisions, with the External ID replaced.** Herald's agents learn from past decisions and outcomes. Each decision's External ID becomes a one-way pseudonym, `deleted:` followed by a keyed hash of the connection and External ID, so the row no longer identifies the person. `pseudonymizedDecisions` counts them. - **Suppressions.** An unsubscribe, bounce or complaint is stored against the address, not the External ID, and stays so Herald does not contact that address again. If you delete a user who unsubscribed, the address stays suppressed. - **Data from other sources.** Rows that belong to other connections, to Braze-sent decisions and to warehouse syncs are not part of this connection's data. Delete them in those systems. ### Repeat calls and errors The call is idempotent. Repeating it returns zero counts and `trackedUser` `none`: the first call already handled the profile, and the repeat finds no data for the connection, so it leaves the profile alone. It returns `200` for a user Herald has never seen. | Status | Body `error` | Cause | |---|---|---| | 200 | | Done, including when there was nothing to delete | | 400 | `userId must be 1 to 255 characters` | Bad External ID | | 401 | `Unauthorized` | Missing or unknown ingest token | | 403 | `Forbidden` | The connection is inactive, or its type does not take contacts | | 403 | `User deletion needs an SDK connection's ingest token` | The token belongs to a connection that is not an SDK connection, such as SendGrid | | 500 | `Internal server error` | Server failure. Retry. | A user who opens the app again after deletion creates new data. Call `wipeData()` on the device first, so nothing new arrives while you process the request. ### Smaller steps To stop sending without a full deletion, remove addresses with `DELETE /api/v1/contacts`. It takes the same body as `POST /api/v1/contacts`: a list of `userId`, `kind` (`email`, `phone`, `apns`, `fcm`, `webpush`) and `value`. See [SDK REST endpoints](/docs/reference/server-api#post-and-delete-api-v1-contacts). ## Retention Herald keeps SDK data until you delete it with the API above. There is no automatic expiry today. Tell your account team if your retention policy needs one. ## Related - [Data collection controls](/docs/data-and-privacy/data-collection-controls) - [Consent and opt-out](/docs/data-and-privacy/consent-and-opt-out) - [Security and identity verification](/docs/data-and-privacy/security-and-identity-verification) Source: https://heraldsdk.com/docs/data-and-privacy/user-data-deletion.md --- # App Tracking Transparency and privacy manifests > Why the SDK does not need App Tracking Transparency, and the exact contents of the privacy manifest that ships with the iOS SDK. The SDK does not track users across apps or websites owned by other companies, does not read the IDFA, and declares no tracking domains. Adding it does not by itself require an App Tracking Transparency prompt. ## App Tracking Transparency - The SDK never reads the advertising identifier (IDFA) or the vendor identifier (IDFV), and does not link the AdSupport or AppTrackingTransparency frameworks. - The device ID is a random UUID the SDK creates and keeps in your app's storage. It is not shared with other apps. - Data goes to one place: the Herald endpoint you configure. The SDK sends nothing to data brokers or ad networks. Apple's definition of tracking covers linking data from your app with data from other companies' apps, websites or offline properties for advertising or measurement, and sharing data with data brokers. Whether your app as a whole tracks depends on everything else it does with data, including what you sync into Herald from your warehouse. That decision is yours; the SDK's part in it is described above. ## The privacy manifest `HeraldSDK` ships a `PrivacyInfo.xcprivacy` file as a resource of the library. Xcode includes it in your app's bundle and in the privacy report you generate from an archive (**Product > Archive**, then **Generate Privacy Report** in the Organizer). | Key | Value | |---|---| | `NSPrivacyTracking` | `false` | | `NSPrivacyTrackingDomains` | Empty | | `NSPrivacyAccessedAPITypes` | Empty: the SDK uses none of Apple's required-reason APIs | | `NSPrivacyCollectedDataTypes` | The nine types below | No type is declared as used for tracking. Eight types are **linked** to the user with the purposes **App Functionality** and **Analytics**. Crash data is **not linked**, with the purpose **App Functionality** only. | Declared type | Linked | Tracking | Purposes | Why | |---|---|---|---|---| | `NSPrivacyCollectedDataTypeDeviceID` | Yes | No | App Functionality, Analytics | The SDK's random device ID | | `NSPrivacyCollectedDataTypeUserID` | Yes | No | App Functionality, Analytics | The External ID you pass to `identify` | | `NSPrivacyCollectedDataTypeProductInteraction` | Yes | No | App Functionality, Analytics | Sessions, screens, events and message interactions | | `NSPrivacyCollectedDataTypeOtherUsageData` | Yes | No | App Functionality, Analytics | Custom attributes and event properties | | `NSPrivacyCollectedDataTypeEmailAddress` | Yes | No | App Functionality, Analytics | When you call `setEmail` | | `NSPrivacyCollectedDataTypePhoneNumber` | Yes | No | App Functionality, Analytics | When you call `setPhone` | | `NSPrivacyCollectedDataTypePurchaseHistory` | Yes | No | App Functionality, Analytics | When you call `trackPurchase` | | `NSPrivacyCollectedDataTypePreciseLocation` | Yes | No | App Functionality, Analytics | When you call `setLocation`, or geofence crossings from `HeraldGeofence` | | `NSPrivacyCollectedDataTypeCrashData` | No | No | App Functionality | When you turn on `crashReports`: MetricKit crash and hang reports | The manifest declares every type the SDK can send, including the five that depend on calls or settings your app may never use. If your app does not use `setEmail`, `setPhone`, `trackPurchase`, `setLocation` or `crashReports`, those types are not collected through the SDK. Your App Store privacy answers should reflect what your app actually sends; see [App store disclosures](/docs/data-and-privacy/app-store-disclosures). `HeraldUI` and `HeraldNotificationService` collect nothing themselves and use no required-reason APIs, so they ship without a manifest of their own. `HeraldGeofence` (0.7.0, not released yet) ships without one too: the geofence events it sends are covered by `HeraldSDK`'s location entry, which every app that uses it links, and it uses no required-reason APIs. It links CoreLocation; your app supplies the location purpose strings in Info.plist and asks for permission. ## Android Android has no privacy manifest. `herald-core` adds three permissions to your merged manifest: | Permission | Why | |---|---| | `INTERNET` | Sending batches and syncing messages | | `ACCESS_NETWORK_STATE` | Reporting the network type in the device context | | `POST_NOTIFICATIONS` | Showing push notifications on Android 13 and later. The prompt appears only when you call `requestPushAuthorization`. | The SDK does not use the advertising ID and does not depend on Google Play services ads libraries. `herald-fcm` depends on Firebase Cloud Messaging for push. `herald-geofence` (0.7.0, not released yet) depends on Play Services location and adds no permissions: your app declares and requests `ACCESS_FINE_LOCATION` and `ACCESS_BACKGROUND_LOCATION` itself. ## Related - [App store disclosures](/docs/data-and-privacy/app-store-disclosures) - [Device data collected](/docs/concepts/device-data) Source: https://heraldsdk.com/docs/data-and-privacy/att-and-privacy-manifests.md --- # App store disclosures > A mapping from what the SDK sends to the App Store privacy label and the Google Play data safety form, as input for the answers your team gives. Both app stores ask what data your app collects and why. This page maps what the SDK sends to each store's categories, so your privacy team can fill in the forms. The final answers are yours: they cover your whole app, and they depend on which SDK calls you make and what you put in events and attributes. ## Before you start - List which SDK calls your app makes. The SDK always sends a fixed set of data; everything else depends on your calls. - Decide whether you use minimal mode. See [Data collection controls](/docs/data-and-privacy/data-collection-controls). ## What the SDK sends, mapped to each store | SDK data | Sent when | App Store category | Google Play category | |---|---|---|---| | Device ID (random UUID) | Always | Identifiers: Device ID | Device or other IDs | | External ID | You call `identify` | Identifiers: User ID | Personal info: User IDs | | Sessions, screens, custom events, message impressions and clicks | Always (sessions and message interactions); your calls for the rest | Usage Data: Product Interaction | App activity: App interactions | | Custom attributes and event properties | You call `track`, `screen`, `setAttributes` | Usage Data: Other Usage Data, or a more specific type if the values are, for example, health or financial data | App activity: Other actions, or the more specific type | | Email address | You call `setEmail` | Contact Info: Email Address | Personal info: Email address | | Phone number | You call `setPhone` | Contact Info: Phone Number | Personal info: Phone number | | Purchases | You call `trackPurchase` | Purchases: Purchase History | Financial info: Purchase history | | Latitude and longitude | You call `setLocation` | Location: Precise Location, or Coarse Location if you round the values first | Location: Precise location, or Approximate location | | Geofence entered or left (the geofence's id and name, no coordinates) | You add the geofence module and call `enableGeofences()` (SDK 0.7.0+) | Location: Coarse Location for geofences with a large radius, Precise Location if your geofences are small enough to place a person precisely (Apple counts three decimal places of latitude and longitude, about 100 meters, as precise) | Location: Approximate location, or Precise location for small geofences | | Crash and hang reports (iOS) | You set `crashReports = true` | Diagnostics: Crash Data (not linked to the user) | App info and performance: Crash logs | | Push token | You register for push | Usually not a separate category; check Apple's and Google's current guidance | Device or other IDs | | App, OS and device details, locale, time zone, network type, notification permission | Always (tier 1); by default (tier 2) | Check Apple's current guidance for device and diagnostic details | Check Google's current guidance for device and diagnostic details | The SDK never sends advertising identifiers, contacts, photos, files or carrier data, and never reads location on its own. It reads location only after your app calls `enableGeofences()`, and even then sends only geofence crossings, never coordinates. ## Answers the SDK lets you give | Question | What is true of the SDK | |---|---| | Used for tracking (Apple) | No. The SDK declares `NSPrivacyTracking` false and no tracking domains. | | Linked to the user (Apple) | Yes for identified users: data is stored with the External ID. Anonymous data is linked to the device ID. Crash reports are declared not linked. | | Purposes | App functionality (delivering messages) and analytics (measuring which messages work). The SDK's privacy manifest declares these two, and App Functionality only for crash data. Add others if your app uses the data for more. | | Encrypted in transit (Google) | Yes when your endpoint URL uses HTTPS, which Herald's hosted API does. | | Users can request deletion (Google) | You provide the request path. The SDK gives you `wipeData()` on the device; see [User data deletion](/docs/data-and-privacy/user-data-deletion) for Herald's side. | | Collection optional (Google) | Your decision. If you gate the SDK on consent with `setEnabled`, collection is optional for the user. | | Shared with third parties | Herald processes the data to deliver your messages. Whether that counts as sharing under each store's definitions is for your privacy team to decide. | ## Edge cases - **Minimal mode** removes locale, language, time zone, device model, screen, network type and notification permission. It does not change the categories you declare for the always-sent data. - **Sensitive values in events.** If event properties or attributes carry health, financial or other sensitive data, declare those types too, or stop sending them. - **Geofences.** Your app asks for background location permission itself, so its own purpose strings and store answers already cover location. Declare location once for the whole app, with the purposes you use geofence events for. Google Play also requires a background location declaration and review for apps that request `ACCESS_BACKGROUND_LOCATION`. - **Two SDKs, one form.** If you run Herald next to another messaging SDK during a migration, your answers must cover both. ## Related - [App Tracking Transparency and privacy manifests](/docs/data-and-privacy/att-and-privacy-manifests) - [Device data collected](/docs/concepts/device-data) - [Consent and opt-out](/docs/data-and-privacy/consent-and-opt-out) Source: https://heraldsdk.com/docs/data-and-privacy/app-store-disclosures.md --- # Security and identity verification > How the SDK authenticates, why the app key is public, how to mint user tokens on your backend, the three verification modes, token rotation, and what Herald encrypts at rest. An app key identifies your app to Herald. It ships inside the app, so anyone can extract it. Identity verification is what stops someone with the key from sending data as one of your users or reading their messages: your backend signs each External ID, and Herald checks the signature. ## How the SDK talks to Herald - The SDK sends to the endpoint URL you pass to `configure`, and nowhere else. Herald's hosted API is served over HTTPS. If you run your own endpoint, use an `https://` URL; App Transport Security on iOS, and Android's default network security policy for apps targeting API 28 or later, block cleartext HTTP unless your app allows it. - The SDK does not pin certificates. It trusts the operating system's certificate store. - Each request carries two headers: `x-herald-app-key` (always) and `x-herald-user-token` (when a user is identified and you have set a token). - Two endpoints are used: `POST /api/v1/sdk/batch` to send events and `GET /api/v1/sdk/messages` to fetch content cards and in-app messages. On iOS with `crashReports` on, a third, `POST /api/v1/sdk/diagnostics`, receives crash and hang reports. See [SDK REST endpoints](/docs/reference/rest-endpoints). ## Keys and secrets | Credential | Where it lives | Secret? | What it allows | |---|---|---|---| | App key | In your app. Shown on the connection's **Mobile SDK** card. | No. Treat it as public. | Sending anonymous device data. With verification **Off**, also acting as any user. | | Ingest token | On your backend only. Shown once when you rotate it on the connection page. | Yes | Minting user tokens and calling server APIs such as `/api/v1/contacts` | | User token | Minted by your backend for one user, passed to the app at sign-in | Per user. It proves who the user is. | Sending data as that user and reading that user's messages | Herald stores only the SHA-256 hash of the ingest token, never the token itself. That hash is also the key user tokens are signed with, so anyone who can read Herald's database could mint a valid user token for any user of the connection. The hash protects the ingest token itself, not user tokens. User tokens are not stored; Herald recomputes and compares them on each request, in constant time. Herald does not rotate app keys today. Because the key is public by design, protection comes from identity verification, not from keeping the key hidden. ## Mint user tokens on your backend A user token is the hex HMAC-SHA256 of the External ID, keyed with the SHA-256 hex digest of the connection's ingest token. Mint it after the user signs in and return it to the app with your session. ```javascript // Node.js, on your backend. HERALD_INGEST_TOKEN is the connection's ingest token. import { createHash, createHmac } from "node:crypto"; const key = createHash("sha256").update(process.env.HERALD_INGEST_TOKEN).digest("hex"); const userToken = createHmac("sha256", key).update(userId).digest("hex"); ``` To check a token by hand: ```shell key=$(printf %s "$HERALD_INGEST_TOKEN" | openssl dgst -sha256 -r | cut -d' ' -f1) printf %s "u_123" | openssl dgst -sha256 -hmac "$key" -r | cut -d' ' -f1 ``` In the app, call `setUserToken` right after `identify`: :::tabs ::tab ios ```swift Herald.shared.identify(userId: session.userId) Herald.shared.setUserToken(session.heraldToken) ``` ::tab android ```kotlin Herald.identify(session.userId) Herald.setUserToken(session.heraldToken) ``` ::: Never put the ingest token in the app, in source control or in client-side code. ## Verification modes Set the mode on the connection's **Mobile SDK** card. A connection without a setting uses **Required**. | Mode | Batch with a valid token | Batch with no token | Batch with a wrong token | Messages request | |---|---|---|---|---| | Required (default) | Accepted for that user | Rejected with 401 | Rejected with 401 | Returned with a valid token; 401 otherwise | | Optional | Accepted for that user | Stored as anonymous: events are kept with the claimed External ID marked unverified, and nothing is written to the profile, contact points or message outcomes | Rejected with 401 | Valid token: returned. No token: empty lists. Wrong token: 401. | | Off | Accepted for the claimed user | Accepted for the claimed user | Not checked | Returned for any External ID | - A request that names no user (an anonymous device) never needs a token, in any mode. A token sent with it is ignored. - When a signed-in user's batch gets a 401, the SDK keeps it on the device, logs `Herald needs a user token: call setUserToken` and holds that user's events until the app calls `setUserToken`, which sends them. A 401 for a wrong app key logs `Herald rejected the app key: check the publishable key in configure` instead; the SDK keeps every event and stops sending until the next launch. - **Optional** is useful during rollout, while older app versions without tokens are still in use. :::warning Off is for development only With verification off, anyone with your app key can send data as any user and read their messages. Use it only for testing. App keys ship inside your app, so assume they are public. ::: ## Rotating the ingest token Rotate the ingest token on the connection page if it may have leaked. Herald shows the new token once. - Every user token minted with the old ingest token stops working at once. There is no overlap period. - Under **Required** or **Optional**, identified requests from apps that still hold old tokens get 401 until they receive new ones. The SDK holds those users' events on the device (up to the 1,000-event queue limit) and sends them after the next `setUserToken`. - Plan for it: have your backend return a fresh user token with every session refresh, and call `setUserToken` whenever the app receives one. Then a rotation costs at most the data sent until each app's next session refresh. - The same ingest token also authorizes server API calls and web push user tokens. Update every system that uses it. User tokens do not expire on their own. To revoke one user's access without rotating everything, there is no per-user switch today; rotation is the only revocation. ## What is encrypted at rest | Data | Protection | |---|---| | Provider credentials on a connection (for example the APNs key and FCM service account) | Encrypted by Herald with AES-256-GCM, using a per-write data key wrapped by a key-encryption key held outside the database | | Ingest token | Stored only as a SHA-256 hash. The hash is the user-token signing key, so a database read allows forging user tokens. | | User tokens | Not stored | | Events, profiles, device records, messages | Stored in Herald's database without additional application-level encryption | On the device, the SDK keeps its state, including the user token and the event queue, in your app's private storage. On iOS that is Application Support, excluded from backups. On Android it is the `herald` folder in the app's no-backup files directory (`noBackupFilesDir`), which Android Auto Backup never copies, so a restored backup does not carry the device ID and user token to another phone. You do not need backup rules for it. SDK versions up to 0.4.0 kept it in the app's files directory; the next SDK release moves it on first launch. On those versions, exclude the `herald` folder in your backup rules. ## HTML in-app messages HTML messages run in a web view with no file access, no persistent storage and no navigation away from the page. The rules are on [Custom views](/docs/in-app-messages/custom-views#what-the-sdk-enforces). ## Security reviews For a security questionnaire or a review of the SDK and API, contact your Herald account team. ## Related - [Users and identity](/docs/concepts/users-and-identity) - [Data collection controls](/docs/data-and-privacy/data-collection-controls) - [User data deletion](/docs/data-and-privacy/user-data-deletion) Source: https://heraldsdk.com/docs/data-and-privacy/security-and-identity-verification.md --- # Braze concept map > How Braze concepts map to Herald, where there is no equivalent yet, and what to use instead, for lifecycle and CRM teams planning a migration. This map is for lifecycle and CRM leaders and the engineers who plan a move of mobile messaging from Braze to Herald. It lists each Braze concept your team relies on, the Herald equivalent, and the gaps you need to plan around. ## The main difference Braze is built around campaigns and journeys that your team designs step by step. Herald is built around agents: you give an agent an audience, a goal and a set of messages, and it decides for each user which message to send, on which channel and when, then learns from the outcome. Some Braze concepts therefore map to a setting on an agent rather than to a screen of their own. ## Setup and identity | Braze | Herald | Notes | |---|---|---| | Workspace (app group) | Sending connection | One connection holds the push credentials, the app key and the verification setting. Your iOS and Android apps use the same connection. | | App identifier / SDK API key | App key | Shown on the connection's **Mobile SDK** card. Public by design. | | REST API key | Ingest token | A server secret on the connection. Used to mint user tokens and to call the contacts API. | | SDK endpoint (cluster) | Your Herald base URL | Passed to `configure` | | `external_id` | External ID | The ID you pass to `identify`. Use the same ID your warehouse uses. | | Braze ID | User ID | Herald's short ID for a person (`XXXX-XXXX`), searchable on **People**. See [Support ID](/docs/concepts/users-and-identity#support-id). | | Anonymous user profile | Anonymous device | Events are stored with the device ID. Herald builds no profile until the user is identified. | | User aliases | No equivalent | Identify with your stable External ID instead | | SDK Authentication (JWT) | Identity verification with user tokens | An HMAC your backend mints per user. Required by default. See [Users and identity](/docs/concepts/users-and-identity). | | `changeUser` | `identify` | | | Logging out | `reset()` | Returns the device to anonymous and unbinds its push token from the user | | React Native SDK (`@braze/react-native-sdk`) | `@herald/react-native` | A wrapper over the iOS and Android SDKs, installed from git for now. Push tokens and taps stay in native code, as with Braze. See [Quickstart: React Native](/docs/overview/quickstart-react-native). | ## Data | Braze | Herald | Notes | |---|---|---| | Custom attributes | User attributes | String, number, boolean, null and string arrays. No nested objects. | | Standard attributes (first name, email, phone) | Attributes you name, plus `setEmail` and `setPhone` | Email and phone become contact points for sending | | Increment, array add and remove operations | No equivalent | Send the full new value | | Custom events | `track` events | Stored per device, used for in-app triggers, and counted toward agent goals for verified users; see [Events and agent goals](/docs/concepts/events-and-attributes#events-and-agent-goals). | | Purchases | `trackPurchase` | One product per call | | Sessions | Sessions | Same idea; 30-minute inactivity timeout by default | | Location | `setLocation` | Herald stores the last location your app passes. The SDK never collects location on its own. | | Geofences | Geofences (SDK 0.7.0, not released yet) | Add up to 100 per app in Settings, Geofences. The opt-in `HeraldGeofence` / `herald-geofence` module sends `$geofence_enter` and `$geofence_exit` events, which segments, in-app message triggers and agents use like any event. Unlike Braze, which sends the device's location to fetch nearby geofences, the SDK downloads the app's whole list and never sends the device's location. See [Geofences](/docs/concepts/geofences). | | Subscription states (subscribed, opted in, unsubscribed) | The same three states, per channel | Push, email and SMS | | Subscription groups | No equivalent | Keep topic preferences in your warehouse and send them as user attributes through the server API, so segments can include or exclude them | | Currents | No equivalent | Herald stores SDK events, interactions and outcomes. There is no streaming export of them today. | | Catalogs | No equivalent | | ## Audiences and orchestration | Braze | Herald | Notes | |---|---|---| | Segments | Segments | Built in the console from user attributes and events, and used to include or exclude users from an agent | | Campaign | Agent | An agent sends one message per decision to a target audience | | A/B test variants | Message variants | The agent allocates sends across variants by results, per user group, instead of a fixed split | | Intelligent Selection | Built into every agent | | | Intelligent Timing | Agent scheduling | The agent picks a send time per user within your scheduling rules | | Frequency capping | Agent send caps and scheduling rules | Set per agent: daily send cap and lifetime unique users | | Canvas (multi-step journeys) | No equivalent | Use several agents, each with its own goal and audience, and move users between audiences with segments. Branching, delays and multi-step paths are not modeled. | | API-triggered campaigns and Canvas entry | No equivalent | Agents select users from their audience on a schedule | | Liquid personalization and Connected Content | No equivalent in Herald's own sending | Personalize by writing variants for user groups. Agents that send through a Braze connection still have their Liquid rendered by Braze. | | Content Blocks | No equivalent | | | Test sends | **Send a test** on the connection's Mobile SDK card | Sends a push, content card or in-app modal to one user. See [Testing push](/docs/push-notifications/testing#send-a-test-from-the-mobile-sdk-card). | | Internal test groups | No equivalent | Use a test External ID. | | Control groups and holdouts | A segment you exclude | See [Running in parallel](/docs/migration/parallel-run) | ## Channels | Braze | Herald | Notes | |---|---|---| | Push (APNs, FCM) | Push | Sent by Herald with your APNs key and FCM service account | | Rich push images | Rich push | `HeraldNotificationService` on iOS; built into `herald-fcm` on Android | | Push action buttons | Action buttons in a push variant's delivery options | Up to three, with a title and deep link each. See [Rich push](/docs/push-notifications/rich-push#action-buttons). | | Android notification channel | Android channel ID in a push variant's delivery options | See [Android notification channels](/docs/push-notifications/android-notification-channels). | | Silent push for content sync | Sync push | Sent automatically after a card or message is written. See [Silent push](/docs/push-notifications/silent-push). | | Push stories | Push stories | The **Story** toggle on a campaign push, or `story` in the Send API. Needs SDK 0.7.0; see [Push stories](/docs/push-notifications/push-stories). | | Live Activities | Live Activity campaigns | iPhone (iOS 18+) through APNs broadcast, Android as Live Updates through FCM. See [Live Activities setup](/docs/live-activities/setup) and [Live Activities on Android](/docs/live-activities/android). | | Content Cards | Content cards | Classic, captioned image and image-only, with pinning, categories, extras and expiry. See [Create cards in Herald](/docs/content-cards/authoring) and [Rebuilding cards and in-app messages](/docs/migration/rebuilding-cards-and-messages). | | In-app messages | In-app messages | Slideup, modal, full screen and HTML, with triggers, priority and re-eligibility. See [Create in-app messages in Herald](/docs/in-app-messages/authoring). | | Braze in-app message triggers (session start, custom event with properties, push open) | Trigger: Session starts, An event happens, A push is opened | Up to five property filters per message. | | Braze re-eligibility | Show again | Never (show once), or after 1 to 8,760 hours. | | Banners | No equivalent | | | Feature flags | No equivalent | | | Email, SMS | Herald's own sending (Amazon SES email, SMS from shared numbers), SendGrid, or your Braze connection | Not part of the mobile SDK | ## SDK behavior | Braze | Herald | Notes | |---|---|---| | Default content card UI | `ContentCardFeed` | SwiftUI and Jetpack Compose | | Default in-app message UI | `HeraldUI` and `herald-ui` presenters | | | In-app display delegate (now, later, discard) | `InAppMessageDelegate` (display, later, discard) | Asked when the message is about to appear | | `wipeData`, disabling the SDK | `wipeData()`, `setEnabled(false)` | | | Minimum integration mode | Minimal device data mode | | | Request flush | `flush()` | | | Braze Flutter SDK (`braze_plugin`) | `herald_flutter` plugin, installed from git | Wraps the native SDKs; Live Activities, push stories and geofences stay native. See [Install on Flutter](/docs/overview/install-flutter). | ## Next - [Braze API mapping](/docs/migration/braze-api-mapping) - [Running in parallel](/docs/migration/parallel-run) - [Cutover checklist](/docs/migration/cutover-checklist) Source: https://heraldsdk.com/docs/migration/braze-concept-map.md --- # Braze API mapping > Braze SDK calls and the Herald calls that replace them, in Swift and Kotlin, with the calls that have no equivalent. Use these tables to replace Braze SDK calls with Herald calls during a migration. Every Herald call listed exists in version 0.2.0; full signatures are on [iOS API](/docs/reference/ios-api) and [Android API](/docs/reference/android-api). Where a Braze call has no equivalent, the table says so. Herald has no instance to keep: call `Herald.shared` on iOS and the `Herald` object on Android. ## Swift | Area | Braze | Herald | |---|---|---| | Setup | `Braze(configuration: Braze.Configuration(apiKey:endpoint:))` | `Herald.configure(appKey:endpoint:options:)` | | Setup | `configuration.sessionTimeout` | `options.foregroundSessionTimeout` and `options.backgroundSessionTimeout` | | Setup | `configuration.triggerMinimumTimeInterval` | `options.inAppMinimumInterval` | | Setup | `configuration.logger.level` | `options.logLevel` | | Identity | `braze.changeUser(userId:)` | `identify(userId:traits:)` | | Identity | `braze.set(sdkAuthenticationSignature:)` | `setUserToken(_:)` | | Identity | `braze.user.add(alias:label:)` | No equivalent | | Attributes | `braze.user.setCustomAttribute(key:value:)` | `setAttribute(_:_:)` or `setAttributes(_:)` | | Attributes | `braze.user.set(firstName:)` and other standard fields | `setAttribute("first_name", ...)` with a key you choose | | Attributes | `braze.user.set(email:)` | `setEmail(_:)` | | Attributes | `braze.user.set(phoneNumber:)` | `setPhone(_:)` (E.164) | | Attributes | `braze.user.unsetCustomAttribute(key:)` | `setAttribute(key, nil)` stores an explicit null | | Attributes | `braze.user.incrementCustomUserAttribute(key:by:)` | No equivalent; send the new value | | Attributes | `braze.user.addToCustomAttributeArray(key:value:)` | No equivalent; send the full array | | Attributes | `braze.user.setLastKnownLocation(latitude:longitude:)` | `setLocation(latitude:longitude:)` | | Subscriptions | `braze.user.set(emailSubscriptionState:)` | `setSubscription(.email, _:)` | | Subscriptions | `braze.user.set(pushNotificationSubscriptionState:)` | `setSubscription(.push, _:)` | | Events | `braze.logCustomEvent(name:properties:)` | `track(_:properties:)` | | Events | `braze.logPurchase(productID:currency:price:quantity:properties:)` | `trackPurchase(productId:price:currency:quantity:properties:)` | | Push | `braze.notifications.register(deviceToken:)` | `setPushToken(_:)` | | Push | `braze.notifications.handleUserNotification(response:withCompletionHandler:)` | `handleNotificationResponse(_:)`, then call the completion handler yourself | | Push | `Braze.Notifications.categories` | `registerPushCategories(_:)` with your own `HeraldPushCategory` values | | Push | `BrazeNotificationService.NotificationService` subclass in a notification service extension | `HeraldNotificationService` | | Content cards | `braze.contentCards.requestRefresh()` | `refreshContentCards()` | | Content cards | `braze.contentCards.cards` | `contentCards.cards` | | Content cards | `card.context?.logImpression()` | `logImpression(card)` | | Content cards | `card.context?.logClick()` | `logClick(card)` | | Content cards | `card.context?.logDismissed()` | `logDismissal(card)` | | Content cards | `BrazeContentCardUI.ViewController(braze:)` | `ContentCardFeed()` (SwiftUI) | | In-app | `braze.inAppMessagePresenter = BrazeInAppMessageUI()` | `Herald.useDefaultInAppUI()` | | In-app | `BrazeInAppMessageUIDelegate.inAppMessage(_:displayChoiceForMessage:)` | `InAppMessageDelegate.shouldDisplay(_:)` | | In-app | `.now`, `.reenqueue`, `.discard` | `.display`, `.later`, `.discard` | | Data control | `braze.enabled = false` | `setEnabled(false)` | | Data control | `braze.wipeData()` | `wipeData()` | | Data control | `braze.requestImmediateDataFlush()` | `flush()` | | Sign-out | `changeUser` to another ID | `reset()` returns the device to anonymous | ## Kotlin | Area | Braze | Herald | |---|---|---| | Setup | `Braze.configure(context, BrazeConfig)` or `braze.xml` | `Herald.configure(context, appKey, endpoint, options)` | | Setup | `BrazeActivityLifecycleCallbackListener` | Not needed; `configure` registers its own lifecycle callbacks | | Identity | `Braze.getInstance(context).changeUser(userId)` | `Herald.identify(userId, traits)` | | Identity | `changeUser(userId, sdkAuthSignature)` or `setSdkAuthenticationSignature(signature)` | `Herald.identify(userId)` then `Herald.setUserToken(token)` | | Attributes | `currentUser?.setCustomUserAttribute(key, value)` | `Herald.setAttribute(key, value)` | | Attributes | `currentUser?.setEmail(email)` | `Herald.setEmail(email)` | | Attributes | `currentUser?.setPhoneNumber(phone)` | `Herald.setPhone(phone)` (E.164) | | Attributes | `currentUser?.incrementCustomUserAttribute(key, by)` | No equivalent; send the new value | | Attributes | `currentUser?.addToCustomAttributeArray(key, value)` | No equivalent; send the full list | | Attributes | `currentUser?.setLastKnownLocation(latitude, longitude, altitude, accuracy)` | `Herald.setLocation(latitude, longitude)` | | Subscriptions | `currentUser?.setEmailNotificationSubscriptionType(type)` | `Herald.setSubscription(SubscriptionChannel.EMAIL, state)` | | Subscriptions | `currentUser?.setPushNotificationSubscriptionType(type)` | `Herald.setSubscription(SubscriptionChannel.PUSH, state)` | | Events | `logCustomEvent(name, properties)` | `Herald.track(name, properties)` | | Events | `logPurchase(productId, currencyCode, price, quantity)` | `Herald.trackPurchase(productId, price, currency, quantity)` | | Push | `BrazeFirebaseMessagingService` | `HeraldMessagingService` (registered by `herald-fcm`) | | Push | `BrazeFirebaseMessagingService.handleBrazeRemoteMessage(context, message)` | `HeraldNotifications.handleRemoteMessage(context, message)` | | Push | `registeredPushToken = token` | `Herald.setPushToken(token)` (`herald-fcm` does it for you) | | Push | Notification open handling | `Herald.handleNotificationIntent(intent)` in `onCreate` and `onNewIntent` | | Content cards | `requestContentCardsRefresh()` | `Herald.refreshContentCards()` | | Content cards | `subscribeToContentCardsUpdates(subscriber)` | Collect `Herald.contentCards` (a `StateFlow`) | | Content cards | `card.logImpression()`, `card.logClick()` | `Herald.logImpression(card)`, `Herald.logClick(card)` | | Content cards | `card.isDismissed = true` | `Herald.logDismissal(card)` | | Content cards | `ContentCardsFragment` or the Compose `ContentCardsList` | `ContentCardFeed()` (Compose) | | In-app | `BrazeInAppMessageManager` default display | `HeraldInAppPresenter.install()` | | In-app | `IInAppMessageManagerListener.beforeInAppMessageDisplayed` | `InAppMessageDelegate.shouldDisplay` | | In-app | `DISPLAY_NOW`, `DISPLAY_LATER`, `DISCARD` | `DISPLAY`, `LATER`, `DISCARD` | | Data control | `Braze.disableSdk(context)`, `Braze.enableSdk(context)` | `Herald.setEnabled(false)`, `Herald.setEnabled(true)` | | Data control | `Braze.wipeData(context)` | `Herald.wipeData()` | | Data control | `requestImmediateDataFlush()` | `Herald.flush()` | | Sign-out | `changeUser` to another ID | `Herald.reset()` | ## Behavior differences to check - **Token order.** Call `identify` first, then `setUserToken`. Identifying a different user clears the previous token. - **Verification is on by default.** A new connection requires a user token for every request that names a user. Plan the backend route before you ship. - **Push permission.** `requestPushAuthorization` on both platforms shows the prompt and records the subscription, so you do not set the subscription yourself after the prompt. - **In-app timing.** A message that cannot show at once is kept and shown later, and the delegate is asked each time it is about to appear. See [Triggers and delivery rules](/docs/in-app-messages/triggers-and-delivery). - **Properties.** iOS properties are `HeraldValue` literals. Android properties are a `Map`. ## Next - [Importing push tokens and users](/docs/migration/importing-tokens-and-users) - [Running in parallel](/docs/migration/parallel-run) Source: https://heraldsdk.com/docs/migration/braze-api-mapping.md --- # Importing push tokens and users > How users, attributes, email addresses, phone numbers and push tokens get into Herald today, through the server API, the contacts API and the SDK, and what to do with the tokens Braze holds. Before Herald can send to your existing users, it needs three things for each of them: a user record, the attributes agents target on, and the contact points it sends to (push tokens, email addresses, phone numbers). This page explains where each comes from today and the order to load them in. ## Where each kind of data comes from | Data | Source | When it arrives | |---|---|---| | User records and attributes | Server API `/api/v1/users`, called by your warehouse tool or job | On the schedule you set | | Segments | Built in the console from attributes and events | When you create them | | Conversion events for agent goals | Server API `/api/v1/events`, or SDK `track` and `trackPurchase` | On your schedule, or when the app sends its batch | | Push tokens, for users who already have the app | The contacts API, from a one-time export | When you run the import | | Push tokens, from then on | The SDK, on first launch after the update | When the user opens the updated app | | Email addresses and phone numbers | The contacts API, or `setEmail` and `setPhone` in the app | When you run the import, or when the app sends them | | Device data, sessions, in-app events | The SDK | From the first launch with the SDK | The External ID must be the same everywhere: the `userId` in your server API calls, the `userId` in contacts API calls, and the ID your app passes to `identify`. If your Braze `external_id` is that ID, you can reuse it as is. ## 1. Send users and attributes through the server API Point your warehouse tool, or a job you write, at `POST /api/v1/users` with the connection's ingest token. Each call creates or updates users, merges their attributes, registers them as members of the app and saves their email address. Event calls to `POST /api/v1/events` feed the conversion events that agent goals measure, unless the app sends that event through the SDK instead. Build segments in the console from the attributes and events you sent. Run these first, so every user exists in Herald before tokens and messages arrive. [Sync from your warehouse](/docs/migration/warehouse-sync) explains what to send from the warehouse and what moves to the SDK. ## 2. Import existing push tokens Users who already have your app hold push tokens that Braze registered. Those tokens belong to your app, not to Braze, so Herald can send to them with the same credentials: - **APNs.** A token works with any APNs auth key from the same Apple developer team, for the same bundle ID. Add your `.p8` key and bundle ID to the Herald connection. - **FCM.** A token works only with the Firebase project that issued it. Add a service account from that project to the connection. Export each user's tokens from Braze (its user export includes push tokens) or from your own backend, then send them to the contacts API with the connection's ingest token. Run the import from your servers, never from the app. ```sh curl -X POST "https://YOUR_HERALD_HOST/api/v1/contacts" \ -H "Authorization: Bearer $HERALD_INGEST_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "contacts": [ { "userId": "u_123", "kind": "apns", "value": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", "meta": { "bundleId": "com.lumen.app", "sandbox": false } }, { "userId": "u_456", "kind": "fcm", "value": "FCM_REGISTRATION_TOKEN" } ] }' ``` - Send up to 1,000 contacts per request. The response reports how many were stored: `{ "data": { "upserted": 2 } }`. - APNs tokens must be 64 or more hex characters. Set `meta.sandbox` to `true` only for tokens from development builds. - Re-running the import is safe: contacts are matched on kind and value. - A token that is no longer valid is marked invalid after the first send that APNs or FCM rejects, and is not used again. When an imported user opens the updated app, the SDK registers the device's current token for the same user. If it is the same token, the record is updated in place and linked to the device. If the token changed, the device's new token is stored as well. Field rules and errors are on [SDK REST endpoints](/docs/reference/server-api#post-and-delete-api-v1-contacts). ## 3. Import email addresses and phone numbers Send them through the same contacts API, with `"kind": "email"` or `"kind": "phone"`. Phone numbers must be E.164. Alternatively, call `setEmail` and `setPhone` in the app after `identify`; the SDK checks the format on the device. These matter for the mobile SDK in one case: an email or SMS unsubscribe recorded by the SDK applies only to addresses Herald already has for the user. ## 4. Carry over opt-outs There is no bulk import for unsubscribes today. To carry them over: - **Push.** The SDK records the device's notification permission with every batch and the push subscription when you call `requestPushAuthorization`. Users who turned notifications off in the system do not receive them. - **Email and SMS.** For users who opted out in Braze, exclude them from agents with a segment synced from your warehouse. If the app knows the preference, it can call `setSubscription(.email, .unsubscribed)` (iOS) or `setSubscription(SubscriptionChannel.EMAIL, SubscriptionState.UNSUBSCRIBED)` (Android) after the address is set. ## What needs the SDK Content cards and in-app messages are delivered only to users who have opened the app with the SDK. Herald suppresses a card or in-app send to a user with no SDK device on the connection, so it does not pile up for someone who will never see it. Imported tokens make push reachable before the app update; cards and in-app messages follow as users update. ## Verify it worked 1. Run the import for a few test users and check the `upserted` count. 2. Send a push from an agent to one of them through the Herald connection, before they install the update. 3. Install the update on that device, sign in, and confirm push still arrives once, not twice. ## Next - [Running in parallel](/docs/migration/parallel-run) - [Sync from your warehouse](/docs/migration/warehouse-sync) Source: https://heraldsdk.com/docs/migration/importing-tokens-and-users.md --- # Rebuilding cards and in-app messages > How each Braze content card and in-app message option maps to a Herald delivery option, and how to plan the rebuild. Content cards and in-app messages do not move from Braze automatically. You rebuild them as messages in Herald, and agents decide who gets them. This page maps each Braze option to the Herald option that replaces it, and sets out how to plan the work. ## What you author in Herald Agents create cards and in-app messages from the message variants you write in Herald's content libraries. Each variant has a **Delivery options (mobile SDK)** section that sets the options below. See [Create cards in Herald](/docs/content-cards/authoring) and [Create in-app messages in Herald](/docs/in-app-messages/authoring). A message that has no saved options is a classic or captioned image card, or a slideup or modal that shows at the next session start, once, in your app's theme. A scheduled send time is ignored for cards and in-app messages; they are available at the user's next fetch. ## Map each Braze option | Braze | Herald option | Where | |---|---|---| | Classic, captioned image and image-only card types | Card type: Automatic, Classic, Captioned image, Image only | Card | | Pinned card | Pinned | Card | | Card that cannot be dismissed | Dismissible off | Card | | Card categories | Categories, up to 10 | Card | | Card key-value pairs | Extras, up to 20 pairs | Card | | Card or message expiration | Expires after (hours), 1 to 8,760 | Card and message | | Slideup, modal, full and HTML message types | Type: Slideup, Modal, Full screen, HTML | Message | | Slide from top or bottom, auto-dismiss | Slide in from, Auto-dismiss after (seconds) | Message | | One or two buttons, with close, deep link or web URL actions | Buttons, up to 2, with Close, Open deep link or Open URL | Message | | Session start, custom event and push open triggers | Show when: Session starts, An event happens, A push is opened | Message | | Event property conditions | Property filters, up to five, with eight operators | Message | | Priority | Priority, 0 to 100 | Message | | Re-eligibility | Show again: never, or after 1 to 8,760 hours | Message | | Custom colors and corner radius | Background, Text, Button, Button text, Corner radius (0 to 32) | Message | Braze options that have no row here, such as Liquid in message text and Connected Content, are not built. A geofence trigger becomes **An event happens** with `$geofence_enter` or `$geofence_exit` (SDK 0.7.0, not released yet); see [Geofences](/docs/concepts/geofences). See the [Braze concept map](/docs/migration/braze-concept-map). ## Plan the rebuild 1. **Inventory.** Export the list of active Braze content cards and in-app messages, with their type, trigger, audience and goal. 2. **Sort each one.** - It maps to the table above: rebuild it. - It depends on Liquid, Connected Content or Canvas steps: redesign it. See [Braze concept map](/docs/migration/braze-concept-map). 3. **Write variants, not one message.** An agent learns which variant works for which users. Two to four variants per message give it something to choose between. 4. **Map triggers.** A Braze trigger on a custom event becomes **An event happens** with the event name your app tracks. Property conditions become property filters; numeric-looking values are saved as numbers, so match the type your app sends. See [Create in-app messages in Herald](/docs/in-app-messages/authoring#when-to-show). 5. **Map goals.** The conversion each message aims for becomes the agent's goal, measured from the events your warehouse sends through the server API or the SDK sends. 6. **Check the look.** The default views follow your `HeraldTheme`. Set colors, fonts and corner radius once in the app and leave **Use app theme** on, unless a message needs its own. See [Theming and dark mode](/docs/in-app-messages/theming-and-dark-mode). 7. **Custom card layouts.** If your Braze feed used custom card views keyed on key-value pairs, add them as extras. The SDK passes `extras` through unchanged. See [Building a custom UI](/docs/content-cards/custom-ui). ## Preview before you send Use the debug preview hooks to see each message type in your app with your theme, before an agent sends anything. See [Logging and debugging](/docs/operations/logging-and-debugging#preview-messages-without-a-server). ## Next - [Running in parallel](/docs/migration/parallel-run) - [Content cards](/docs/content-cards/overview) - [In-app messages](/docs/in-app-messages/overview) Source: https://heraldsdk.com/docs/migration/rebuilding-cards-and-messages.md --- # Running in parallel > Run Braze and Herald side by side during a migration, with separate audiences or a holdout, without double sends, with aligned identities and a fair measurement. A parallel run lets your team move users to Herald in stages while Braze keeps serving everyone else. It lowers the risk of the migration and gives you a measured comparison before cutover. This page covers how to split the audience, how to avoid sending twice, how to keep identities aligned and how to measure. ## What runs where During the run, your app ships with both SDKs. Each one does its own job: | | Braze SDK | Herald SDK | |---|---|---| | Identity | `changeUser` with your External ID | `identify` with the same External ID, plus `setUserToken` | | Events | As today | The same calls, sent to Herald | | Push tokens | Registered with Braze | Registered with Herald | | Push display and taps | Braze pushes | Herald pushes | | Content cards and in-app messages | Braze messages | Herald messages | Both SDKs can register the same APNs or FCM token: a token belongs to your app, and each platform sends to it independently. That is also why you must decide, per user, which platform sends. ## 1. Split the audience Pick one of two designs. **Separate audiences.** Assign each user to Braze or to Herald for each message type. Build the split as a warehouse segment, for example a stable hash of the External ID, and load it into both platforms: into Braze as an attribute, and into Herald as a user attribute through `/api/v1/users`, then build the Herald segment from it in the console. Target Braze campaigns at one side and Herald agents at the other. **Holdout.** Herald serves most users, and a fixed holdout, typically a stable 10 to 15 percent, stays on your current Braze program or receives nothing. Sync the holdout as a segment and exclude it from every Herald agent. The gap between the two groups is the incremental effect. Whichever you choose, keep the assignment stable for the whole run. A user who moves between groups weakens the comparison. ## 2. Avoid double sends | Risk | Prevention | |---|---| | Both platforms push the same user | Each user is in exactly one audience per channel. Exclude the Herald segment from Braze campaigns and Canvases, and the Braze segment from Herald agents. | | Both platforms show an in-app message in one session | The same split applies to in-app messages. If a user can still get both, set an `InAppMessageDelegate` in the Herald SDK that holds messages while a Braze message is on screen. | | A content card appears in two feeds | Show only one feed per user, chosen by the same assignment. | | Push taps are counted by the wrong SDK | Pass every notification response to both SDKs. Each recognizes only its own pushes: `handleNotificationResponse` and `handleNotificationIntent` return `false` for pushes that are not from Herald. | | Two FCM services in one Android app | Android delivers to one `FirebaseMessagingService`. Subclass `HeraldMessagingService`, override `onNonHeraldMessage` and pass those messages to Braze's handler there. | ## 3. Keep identities aligned - Call `identify` and `changeUser` with the same External ID at the same point in your sign-in flow, and `reset()` at sign-out. - Use the ID your warehouse uses, so segments, attributes and conversion events line up in both platforms. - Set the user token right after `identify`. With verification **Required**, identified traffic without a token is rejected. - Check a sample: look up a few test users in **Audience > Search users** in Herald and in Braze, and compare attributes. ## 4. Measure - **Pick the metric before you start.** Use the conversion your agents' goals measure, not opens or clicks alone. Both platforms should be judged on the same event, from the same warehouse source. - **Compare like for like.** Compare the two groups over the same dates, on the same channels. - **Give agents time.** An agent spreads sends across variants at first, then shifts toward what works. Judge after it has had several weeks of sends. - **Watch delivery health.** Track push send failures, opt-out rates and in-app impressions per group, so a setup problem does not pass as a result. ## 5. Expand in stages Move a small share first, confirm delivery and measurement, then widen the Herald audience step by step. Keep the holdout, if you use one, until cutover. ## Next - [Cutover checklist](/docs/migration/cutover-checklist) - [Sync from your warehouse](/docs/migration/warehouse-sync) Source: https://heraldsdk.com/docs/migration/parallel-run.md --- # Cutover checklist > The technical, data, privacy, communication and rollback steps to finish a migration and turn off Braze delivery for mobile messaging. Use this list when the parallel run has met your success criteria and you are ready to make Herald the only platform delivering mobile messages. Assign an owner to each item and keep the list in your change ticket. ## Technical - [ ] The app version with the Herald SDK is live on both stores, and the share of active users on it meets your threshold. - [ ] `configure` runs at launch in that version, with the production app key and endpoint. - [ ] Identity verification is **Required** on the production connection, and your backend returns user tokens for every signed-in user. - [ ] No `Herald rejected a batch` errors appear in a test session on the release build. - [ ] The APNs key and bundle ID, and the FCM service account, are set on the production connection, and a test push reaches iOS and Android. - [ ] Notification taps log opens and open deep links on both platforms. - [ ] The default in-app presenter, or yours, is installed, and the content card feed is in the app. - [ ] Debug logging and any `debugLoadMessages` or `debugShowInAppMessage` calls are excluded from release builds. - [ ] The push dispatcher runs every minute on your Herald deployment. ## Data - [ ] Warehouse user and event syncs to Herald's server API run on schedule and without errors, and the segments agents use exist in the console. - [ ] Push tokens for users not yet on the new app version are imported through the contacts API. - [ ] A sample of users matches between Braze and Herald: same External ID, same key attributes. - [ ] Every agent's goal is measured from the conversion event agreed for the run. - [ ] Every Braze content card and in-app message still in use has a Herald replacement, or a decision to retire it. ## Privacy - [ ] Your privacy policy and App Store and Google Play disclosures cover what the SDK collects, as your privacy review requires. See [App store disclosures](/docs/data-and-privacy/app-store-disclosures). - [ ] Consent gating with `setEnabled` follows your consent platform's state, if you use one. - [ ] Your data deletion process covers Herald: `wipeData()` on the device and the server-side request. See [User data deletion](/docs/data-and-privacy/user-data-deletion). - [ ] Opt-outs from Braze are carried over: email and SMS opt-outs excluded by segment or recorded with `setSubscription`. - [ ] The device data mode (standard or minimal) is the one your privacy review approved. ## Communication - [ ] Lifecycle, CRM and product teams know the cutover date and the freeze on new Braze mobile campaigns. - [ ] Support teams have the new troubleshooting path and know how to look up a user in Herald. - [ ] Analytics owners know where outcome data now lives and which dashboards change. - [ ] The person who can trigger a rollback is named and available on the cutover day. ## Cutover - [ ] Remove the parallel-run exclusions so Herald agents target the full audience, except any holdout you keep. - [ ] Stop the Braze campaigns, Canvases, content cards and in-app messages that Herald now covers. - [ ] Watch push failures, opt-out rates and in-app impressions for the first days. ## Rollback - [ ] The rollback trigger is written down, for example a delivery failure rate or a conversion drop over an agreed threshold. - [ ] To roll back, pause the Herald agents and restart the Braze campaigns. Keep the Braze SDK in the app until you are past the rollback window, so this needs no app release. - [ ] To stop the Herald SDK collecting without an app release, gate `setEnabled` on a remote setting you control. - [ ] Hightouch syncs to Braze stay on until the rollback window closes. ## After the rollback window - [ ] Remove the Braze SDK from the app in a later release. - [ ] Turn off the Hightouch syncs to Braze. - [ ] Revoke the Braze API keys the integration used. ## Related - [Running in parallel](/docs/migration/parallel-run) - [Importing push tokens and users](/docs/migration/importing-tokens-and-users) Source: https://heraldsdk.com/docs/migration/cutover-checklist.md --- # Sync from your warehouse > How Hightouch, Census or your own job sends warehouse data to Herald through the server API, what the SDK adds from the device, and how to avoid collecting the same data twice. Herald has no direct warehouse integration. A warehouse tool such as Hightouch or Census, or a job you write, calls the server API: [`POST /api/v1/users`](/docs/reference/server-api#post-api-v1-users) for users and attributes, and [`POST /api/v1/events`](/docs/reference/server-api#post-api-v1-events) for events. Both use the connection's ingest token. To bring results back, the same job reads [`GET /api/v1/decisions`](/docs/reference/server-api#get-api-v1-decisions) and [`GET /api/v1/holdout`](/docs/reference/server-api#get-api-v1-holdout). The SDK adds what only the device knows and handles delivery to the app. This page sets out which source owns which data, so your teams do not collect anything twice. ## Who owns what | Data | Owner | Notes | |---|---|---| | User records and profile attributes from your systems | Warehouse, through `/api/v1/users` | Plan, lifecycle stage, account data and anything else your warehouse holds | | Conversion events that agent goals measure | Either: warehouse through `/api/v1/events`, or SDK `track` and `trackPurchase` | Pick one source per event name | | Segments | Built in the console | From user attributes and from events, such as "did this event in the last 30 days". They are not synced from the warehouse. | | User time zone | Warehouse, when it has one | The SDK fills it from the device only when the profile has none | | Device data (app version, OS, model, locale, network, push permission) | SDK | Sent with every batch | | Push tokens and push subscription | SDK | Registered on launch and after sign-in | | Sessions | SDK | | | In-app events that trigger messages | SDK `track` | Evaluated on the device, so they must come from the app | | Message interactions (impressions, clicks, dismissals, push opens) | SDK | Credited to the decision that sent the message | | Email and phone contacts | Either: `/api/v1/users` (email) or the contacts API from your backend, or `setEmail` and `setPhone` in the app | Pick one per field | The server API does not take push tokens, device records or message interactions. Those come from the SDK. ## What changes from the Braze setup With Braze, Hightouch synced users, attributes, events and subscription states to Braze, and the Braze SDK handled the device. With Herald: - **User syncs** call `/api/v1/users` instead of Braze. Each user becomes a member of the app that owns the ingest token, so that app's agents can reach them. - **Event syncs** call `/api/v1/events` and feed agent goals. Keep sending the conversions you measure from the warehouse, or move a conversion to the SDK if the app is where it happens. - **Segment syncs** are no longer needed. Build segments in the console from attributes and events. - **Subscription status syncs** have no Herald destination. See [Importing push tokens and users](/docs/migration/importing-tokens-and-users#4-carry-over-opt-outs). - **Campaign and Canvas trigger syncs** have no equivalent: agents choose users from their segments. See [Braze concept map](/docs/migration/braze-concept-map). ## Do not collect twice **Attributes.** Server calls and SDK attribute calls write into the same profile. For each key, the most recent write wins. If both sources send the same key, the profile flips between their values. Give each key one owner: warehouse facts from the server API, in-app preferences from the SDK. If an attribute exists in the warehouse, do not also set it from the app. **Events.** Agent goals count conversions from both server events and SDK `track` and `trackPurchase` calls. If both send the same conversion, it can be counted twice, against two different messages. Give each goal event one source: warehouse outcomes from the server API, in-app actions from the SDK. Server events are idempotent by `id`, so a replayed batch never counts twice. See [Events and agent goals](/docs/concepts/events-and-attributes#events-and-agent-goals). **External IDs.** Use one ID in both places: the `userId` in your server calls and the `userId` in `identify`. A mismatch creates two users who never meet. **Time zone.** If your warehouse has a reliable time zone, send it as an attribute. The device's time zone fills the gap only for users without one. ## Example For Lumen, the workout app: | Fact | Source | |---|---| | `plan` (free, plus), signup date, lifetime workouts | Warehouse, through `/api/v1/users` | | `favorite_workout`, chosen in the app's settings | SDK `setAttribute` | | `plan_started` conversion for an upgrade agent | Warehouse, through `/api/v1/events` | | `workout_completed`, which triggers a congratulation modal | SDK `track` | | Push token, notification permission, app version | SDK | ## Next - [Server API](/docs/reference/server-api) - [Importing push tokens and users](/docs/migration/importing-tokens-and-users) - [Events and attributes](/docs/concepts/events-and-attributes) Source: https://heraldsdk.com/docs/migration/warehouse-sync.md --- # Integrations overview > What each group of Herald integrations does for the learning loop, every integration with its status, and where to connect it. :::note Built and tested against each vendor's documented API; tell us if anything differs in your account.::: Integrations connect the tools you already use, so Herald gets users and events without SDK work, learns from revenue, sends through your messaging platform and puts results where your analysts look. Each integration belongs to one app. An admin sets it up. ## What each group does | Group | What it does for the loop | |---|---| | Ask your AI | An AI assistant reads results, agents and people in Herald's own numbers | | Bring data in | Users, events, cohorts and install attribution reach Herald from another tool | | Learn from revenue | Purchases and renewals become events an agent can use as its goal | | Your CRM | CRM and Mailchimp audience data become attributes and segments, and results can be written back | | Send through your tools | Herald picks the message; your own platform delivers it | | Send results out | Decisions and outcomes land in a warehouse, a sheet, Slack, a webhook or a file | ## Every integration | Integration | Group | Status | Guide | |---|---|---|---| | MCP server (Claude, ChatGPT, Cursor, Gemini) | Ask your AI | Beta | [AI assistants](/docs/integrations/ai-assistants) | | Segment, RudderStack, signed webhook | Bring data in | Beta | [Segment, RudderStack and webhooks](/docs/integrations/event-sources) | | Hightouch, Census (server API) | Bring data in | Live | [Sync from your warehouse](/docs/migration/warehouse-sync) | | BigQuery (including Firebase Analytics and GA4), Snowflake | Bring data in | Beta | [BigQuery, Firebase and Snowflake](/docs/integrations/warehouses) | | Amplitude, Mixpanel | Bring data in | Beta | [Amplitude and Mixpanel](/docs/integrations/product-analytics) | | AppsFlyer, Adjust, Branch | Bring data in | Beta | [AppsFlyer, Adjust and Branch](/docs/integrations/attribution) | | RevenueCat, Stripe, App Store, Google Play | Learn from revenue | Beta | [RevenueCat, Stripe, App Store and Google Play](/docs/integrations/revenue) | | HubSpot, Salesforce | Your CRM | Beta | [HubSpot, Salesforce and Mailchimp](/docs/integrations/crm) | | Mailchimp (audience) | Bring data in | Beta | [HubSpot, Salesforce and Mailchimp](/docs/integrations/crm) | | Braze, SendGrid | Send through your tools | Live | [Sending through your tools](/docs/integrations/senders) | | OneSignal, Iterable, Customer.io, Klaviyo, Mailchimp Transactional, your own Twilio account | Send through your tools | Beta | [Sending through your tools](/docs/integrations/senders) | | Warehouse write-back (BigQuery, Snowflake) | Send results out | Beta | [BigQuery, Firebase and Snowflake](/docs/integrations/warehouses) | | Looker Studio, Tableau, Power BI | Send results out | Beta | [BigQuery, Firebase and Snowflake](/docs/integrations/warehouses) | | Google Sheets, Slack alerts, outbound webhooks, CSV export, ad audiences (daily sync to Meta, Google Ads and LinkedIn, or CSV) | Send results out | Beta | [Reporting and exports](/docs/integrations/reporting) | | Contentful, Sanity, JSON feeds, Braze catalogs | Content from | Beta | [Contentful, Sanity, JSON feeds and Braze catalogs](/docs/integrations/content-sources) | Amazon Ads audiences are on the roadmap. ## Where to connect Open **Settings → Integrations** and pick the app. Senders are connections, so you set them up in **Settings → Sending & SDK**. For a webhook integration, the console shows a URL and a secret once, when you create it. The tool posts to that URL. Herald checks the signature, translates the body and ingests it like a call to the server API. The console shows each integration's status, last event and event count. **Pause** stops it accepting requests. **Rotate secret** issues a new secret and the old one stops working at once. **Send test** runs a signed sample through the checks without writing anything. ## How secrets are handled Secrets are write-only: the console shows a secret once when you create or rotate it, and never returns it again. They are stored encrypted. A request with a missing or wrong signature, to an unknown or paused integration, answers `401`. ## Limits - 1,000 users and 1,000 events per request, like the server API. - 4.5 MB per request. - Replays are safe: every event has a deterministic id, so a retried delivery counts as a duplicate. Source: https://heraldsdk.com/docs/integrations/overview.md --- # AI assistants (MCP) > Connect Claude, ChatGPT, Cursor or Gemini CLI to the Herald MCP server to read results and, if you allow it, pause agents and draft variants. :::note Built and tested against each vendor's documented API; tell us if anything differs in your account.::: The Herald MCP server lets an AI assistant read an app's results and, if you allow it, pause agents and draft message variants. It is a remote [Model Context Protocol](https://modelcontextprotocol.io) server. Endpoint: `https://app.runherald.com/api/mcp` ## What you'll need - An admin of the account. - For Claude Code, Cursor and Gemini CLI: an API key from **Settings → Sending**, the app, then **API keys**. Give it `mcp.read`, and `mcp.write` if the assistant may make changes. | Scope | Allows | |---|---| | `mcp.read` | Every read tool. Required for any MCP call. | | `mcp.write` | Also `pause_agent`, `resume_agent` and `draft_variant`. | A key belongs to one app. Every tool reads or changes only that app's agents. Each request counts toward a limit of 3,600 per hour per app by default. ## What it does An assistant calls the [tools](#tools) below for one app, with an API key or an OAuth sign-in. It reads that app's overview, agents, messages, segments, people and decisions. With write access it can also pause or resume an agent and add a paused draft variant. ## Supported data | Data | Direction | Mode | Notes | |---|---|---|---| | Overview, agents, messages, segments, people and decisions | Out to the assistant | On demand | `mcp.read`; email and phone are left out of people | | Agent pause and resume | In from the assistant | On demand | `mcp.write` | | Draft variants | In from the assistant | On demand | `mcp.write`; created paused | ## Connect Claude.ai and ChatGPT sign in with OAuth. Claude Code, Cursor and Gemini CLI use an API key. ### Claude.ai or ChatGPT These two sign in with OAuth instead of a key. 1. Add a connector with the URL above. In Claude.ai: Settings → Connectors → Add custom connector. In ChatGPT: Settings → Connectors → Advanced → Developer mode, then create a connector. 2. Choose Connect. Sign in if asked. 3. Pick the app the assistant may use. "Read results" is always on. "Pause agents and draft messages" stays off unless you tick it. Approve. Only account admins can approve. Access tokens last 1 hour and refresh tokens 90 days. ### Claude Code, Cursor or Gemini CLI Replace `hk_…` with your key. **Claude Code** ```bash claude mcp add --transport http herald https://app.runherald.com/api/mcp --header "Authorization: Bearer hk_…" ``` **Cursor** (`~/.cursor/mcp.json` or `.cursor/mcp.json`) ```json { "mcpServers": { "herald": { "url": "https://app.runherald.com/api/mcp", "headers": { "Authorization": "Bearer hk_…" } } } } ``` **Gemini CLI** (`~/.gemini/settings.json`) ```json { "mcpServers": { "herald": { "httpUrl": "https://app.runherald.com/api/mcp", "headers": { "Authorization": "Bearer hk_…" } } } } ``` ## Tools | Tool | Scope | Arguments | Returns | |---|---|---|---| | `get_overview` | read | `days?`: 7, 30 or 90 (default 30) | The Overview numbers for the app: people, sends and conversions, and lift versus holdout | | `list_agents` | read | none | The app's agents with status and counts, and lift versus holdout for active agents | | `get_agent` | read | `agent_id` | The agent, its goals, its variants with tries and warmup, lift, and its 10 newest model metrics | | `list_messages` | read | `agent_id` | The agent's messages with every variant's copy and status | | `explain_decision` | read | `user_id`, `limit?`: 1 to 20 (default 5) | The person's newest decisions: agent, variant, channel, odds and conversion | | `list_segments` | read | none | Segments with sizes and the agents using them | | `get_person` | read | `user_id` | The person's profile, attributes (email and phone left out), channel stats and recent messages | | `pause_agent` | write | `agent_id` | Turns on the agent's sending pause | | `resume_agent` | write | `agent_id` | Turns the sending pause off | | `draft_variant` | write | `agent_id`, `body`, `title?`, `channel?` | Adds a paused variant named "AI draft" to the agent's first message (or its first message on `channel`) | ## What write access allows With `mcp.write`, an assistant can pause or resume an agent and add a draft variant. A draft is created paused and never sends until someone sets it active in the console. A push draft needs a title. Without `mcp.write`, a write tool is not listed, and calling it returns an error. ## Disconnect For a key, delete it on the app's API keys card. For Claude.ai or ChatGPT, open **Settings → Sending**, the app, **API keys**, then **Connected AI apps**, and choose **Disconnect**. That revokes the connection's tokens at once. ## Limits - 3,600 MCP requests per hour per app by default (`mcp.requests`), with the rate-limit headers on every answer. See [API errors](/docs/reference/api-errors#rate-limits). - One app per key or sign-in. - OAuth access tokens last 1 hour and refresh tokens 90 days. ## Troubleshooting | Symptom | Cause | Fix | |---|---|---| | The write tools are missing | The key or sign-in has no `mcp.write` | Create a key with `mcp.write`, or reconnect and tick "Pause agents and draft messages" | | The assistant asks you to sign in again | Its refresh token is more than 90 days old, or someone chose **Disconnect** | Connect again | | An agent can't be found | The agent belongs to another app | Use a key or sign-in for that app | ## Common errors | Message | Cause | Fix | |---|---|---| | `Invalid API key` | `401`: the key is missing, unknown, revoked or expired | Paste a current key. OAuth clients are sent to sign in | | `This API key lacks the mcp.read scope` | `403`: the key has no `mcp.read` | Create a key with `mcp.read` | | `This key can't make changes; create one with the mcp.write scope.` | A write tool without `mcp.write` | Create a key with `mcp.write` | | `No agent with id in this app.` | The agent belongs to another app | Use that app's key | | `Rate limit exceeded for mcp.requests: 3600 per hour` | `429`: over the hourly limit | Wait for `Retry-After` | | `The refresh token expired` | OAuth: the refresh token is more than 90 days old | Connect again | ## Not in this version Resources and prompts, server-initiated streams and a win probability per variant. `get_agent` reports tries and warmup instead. Source: https://heraldsdk.com/docs/integrations/ai-assistants.md --- # Segment, RudderStack and webhooks > Send users and events to Herald from Segment, RudderStack or any tool that can post a signed webhook, with the mapping and signature for each. :::note Built and tested against each vendor's documented API; tell us if anything differs in your account.::: These integrations push users and events to a webhook URL. Herald translates each body and ingests it exactly like the server API (`POST /api/v1/users` and `POST /api/v1/events`). ## What you'll need - An admin of the account. Integrations are set up in **Settings → Integrations**. - **Segment:** a Webhooks or Webhooks (Actions) destination you can edit. - **RudderStack:** a Webhook destination you can edit. - **Signed webhook:** a tool or script that can compute an HMAC-SHA256 signature. - Your own user id on every user and event, the same id your app passes to `identify`. ## Connect 1. In **Settings → Integrations**, pick the app, choose the provider and name it. 2. Copy the webhook URL and the secret. The secret is shown once. 3. Paste both into the sending tool, as below. 4. Choose **Send test** to run a signed sample through the checks. It writes nothing. The URL looks like `https://app.runherald.com/api/v1/integrations//`. ## Answers | Answer | When | |---|---| | `200` with `accepted`, `duplicates`, `skipped` | The body was translated and ingested. `accepted` is users upserted plus new events. | | `401` | Unknown integration, a different provider in the path, a paused integration, or a bad or missing signature | | `400` | A body that cannot be translated. Shown as the integration's last error. | | `413` | More than 1,000 users or 1,000 events, or a body over 4.5 MB | | `403` | The app is disabled | ## Segment In Segment, add a **Webhooks** destination (or **Webhooks (Actions)**). Paste the URL. Set the shared secret to the secret from the console. For Actions, add the header `Authorization: Bearer ` instead. Accepted signatures: `X-Signature: `, or `Authorization: Bearer `. Segment's Spec messages, sent one per request or batched as `{ "batch": [ ... ] }`, map like this: | Segment | In Herald | |---|---| | `identify` | A user upsert: `userId`; `traits` become attributes (strings, numbers, booleans and string arrays; nested objects are dropped); `traits.email` becomes the email contact; `traits.createdAt` becomes the signup date | | `track` | An event named `event`, with `properties` | | `page` | The event `page_viewed`, with `properties` plus `name` | | `screen` | The event `screen_viewed`, with `properties` plus `name` | | `alias`, `group` | Skipped, counted in `skipped` | | A message without `userId` | Skipped: people are keyed on your own user id, not `anonymousId` | | Event id | `segment:`. A message without `messageId` is skipped. | | Event time | `timestamp`, else `receivedAt`, else the time the webhook arrived | A message with a value the server API would refuse (an event name over 255 characters, a `userId` over 200) is skipped instead of failing the batch. An invalid email is dropped and the user is still upserted. ### Common errors | Message | Cause | Fix | |---|---|---| | `Unauthorized` | `401`: the secret or signature doesn't match, the integration is paused, or the URL names another provider | Copy the URL and secret from the console again, and resume the integration | | `batch must be an array` | `400`: `batch` is not a list | Send one message, or `{ "batch": [ ... ] }` | | `At most 1000 messages per request` | `400`: the batch holds more | Lower the destination's batch size | | `At most 1,000 users and 1,000 events per request` | `413`: the request holds more | Send smaller batches | ### Send decisions to Segment (optional) Turn on **Send decisions to Segment** when you connect. In Segment, add an **HTTP API** source and paste its write key, and pick the region (US or EU). The key is sealed with the integration's secret and never shown again. The hourly sync sends each decision changed since the last send as Segment `track` calls to `/v1/batch`. The first run covers the last 24 hours. Every destination connected to that source receives them: your warehouse, Amplitude, an ad platform. | Event | When | Properties | |---|---|---| | `herald_message_sent` | Every decision | `agent`, `agent_id`, `variant`, `variant_id`, `channel`, `decision_id`, `holdout` (always false) | | `herald_message_converted` | The decision converted | The same, plus `conversion_event` and `conversion_value` | `userId` is the person's External ID and `messageId` is `herald::sent` (or `:converted`), which Segment uses to drop duplicates. The cursor moves only after Segment accepts the batch. | Message | Cause | Fix | |---|---|---| | `Set the Segment write key` | Shown as the last error: the key is missing | Add the write key on the integration | | `segment export HTTP ` | Shown as the last error: Segment refused the batch | Check the write key and region; the next run retries | | `segment network error` | Shown as the last error: Segment couldn't be reached | None: the next run retries | ## RudderStack In RudderStack, add a **Webhook** destination. Paste the URL, set the method to POST, and add the header `Authorization: Bearer `. That is the only accepted signature. RudderStack sends the same Spec payload as Segment, so the Segment table applies. Event ids are `rudderstack:`. ### Common errors | Message | Cause | Fix | |---|---|---| | `Unauthorized` | `401`: the header isn't `Authorization: Bearer `, the integration is paused, or the URL names another provider | Set the header exactly, and resume the integration | | `batch must be an array` | `400`: `batch` is not a list | Send one message, or `{ "batch": [ ... ] }` | | `At most 1000 messages per request` | `400`: the batch holds more | Lower the destination's batch size | | `At most 1,000 users and 1,000 events per request` | `413`: the request holds more | Send smaller batches | ## Signed webhook For anything else: Zapier, Make, n8n, a cron job or your own code. The body is `{ "users"?: [...], "events"?: [...] }`, with the shapes of `POST /api/v1/users` and `POST /api/v1/events`. Either key may be absent, not both. Users are applied before events. Sign the exact bytes you send with HMAC-SHA256 and put the result in `X-Herald-Signature: sha256=`: ```bash BODY='{"events":[{"id":"evt-1","userId":"u1","name":"signup","timestamp":"2026-11-20T12:00:00Z"}]}' SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | sed 's/^.* //') curl -X POST "$WEBHOOK_URL" -H 'Content-Type: application/json' -H "X-Herald-Signature: sha256=$SIG" -d "$BODY" ``` Validation is the server API's: an invalid item fails the whole request with a `400` that names it. ### Common errors | Message | Cause | Fix | |---|---|---| | `Unauthorized` | `401`: `X-Herald-Signature` doesn't match the exact bytes sent, or the integration is paused | Sign the raw body you send, after any serialization | | `Send users, events or both` | `400`: the body has neither `users` nor `events` | Add one of them | | `Invalid users payload: ...` or `Invalid events payload: ...` | `400`: an item breaks the server API's rules; the message names it | Fix that item and resend the request | | `Invalid JSON` or `Expected a JSON object` | `400`: the body isn't a JSON object | Send JSON | | `At most 1,000 users and 1,000 events per request` | `413`: the request holds more | Send smaller batches | ## Troubleshooting - **Every request answers 401.** The secret does not match, the integration is paused, or the URL names a different provider. - **Everything is skipped.** Messages without a `userId` are skipped. Send your own user id. - **A retry created duplicates.** It should not: event ids are deterministic, so a retried delivery counts as a duplicate. Check the `duplicates` count in the answer. Source: https://heraldsdk.com/docs/integrations/event-sources.md --- # RevenueCat, Stripe, App Store and Google Play > Send purchases, renewals and refunds from RevenueCat, Stripe, the App Store or Google Play to Herald as events, and use a revenue event as an agent goal. :::note Built and tested against each vendor's documented API; tell us if anything differs in your account.::: Revenue events reach Herald from RevenueCat, Stripe, the App Store or Google Play as ordinary events, so an agent can learn from them. Every revenue event carries `revenue` (in major units: 9.99, not 999) and `currency`, so a goal tier can weight by value. ## What you'll need - An admin of the account. Integrations are set up in **Settings → Integrations**. - **RevenueCat:** access to the project's webhooks. - **Stripe:** access to Developers → Webhooks, to add an endpoint and copy its signing secret. - **App Store:** access to the app's App Store Server Notifications in App Store Connect. - **Google Play:** a Google Cloud project for Pub/Sub, and a service account with **View financial data** on the app in Play Console. - Purchases tagged with your own user id, as described under each store. ## Use a revenue event as a goal Pick `subscription_started` (or `purchase` for a one-off sale) as an agent's goal. The agent then learns which messages lead to paying. The goal picker lists the event names seen for the app, so a name appears once the first webhook arrives. ## RevenueCat 1. In **Settings → Integrations**, connect RevenueCat and copy the URL and secret. 2. In RevenueCat, open **Integrations → Webhooks** and add a webhook. Paste the URL. 3. Set the **Authorization header value** to the secret. It must equal the secret, with or without a `Bearer ` prefix. 4. Set RevenueCat's **App User ID** to the same user id your app sends Herald. Option: **Include sandbox purchases** (off by default). | RevenueCat `type` | Event | `subscription_status` attribute | |---|---|---| | `INITIAL_PURCHASE` with `period_type` `TRIAL` | `trial_started` | `active` | | `INITIAL_PURCHASE` | `subscription_started` | `active` | | `RENEWAL` with `is_trial_conversion: true` | `trial_converted` | `active` | | `RENEWAL` | `subscription_renewed` | `active` | | `NON_RENEWING_PURCHASE` | `purchase` | unchanged | | `CANCELLATION` | `subscription_cancelled` | `cancelled` | | `UNCANCELLATION` | `subscription_uncancelled` | `active` | | `EXPIRATION` | `subscription_expired` | `expired` | | `BILLING_ISSUE` | `billing_issue` | `billing_issue` | | `PRODUCT_CHANGE` | `subscription_changed` | `active` | | `TEST` | Nothing ingested; answers `200`, counted in `skipped` | | | Any other type | Skipped | | - Properties: `revenue` is RevenueCat's `price`, `currency` is `USD` (its `price` is always USD), plus `product_id`, `store`, `environment` and `period_type`. `price` can be 0 (trials) or negative (refunds). - Anonymous ids (`$RCAnonymousID:…`) are skipped. Sandbox events are skipped unless the option is on. - The event id is `revenuecat:`, so RevenueCat's retries count as duplicates. - `subscription_status` is set on the user with the event, so segments can target it. ### Common errors | Message | Cause | Fix | |---|---|---| | `Unauthorized` | `401`: the **Authorization header value** isn't the secret, or the integration is paused | Paste the secret again, with or without `Bearer ` | | `Expected a JSON object` | `400`: the body isn't a JSON object | Use RevenueCat's webhook, not a custom body | ## Stripe 1. In **Settings → Integrations**, connect Stripe to get the URL. 2. In Stripe, open **Developers → Webhooks** and add an endpoint with that URL. Choose `checkout.session.completed`, `invoice.paid`, `invoice.payment_failed`, `customer.subscription.deleted` and `charge.refunded`. 3. Paste the endpoint's signing secret (`whsec_…`) into the console. Stripe makes this secret. Until it is set, deliveries answer `401`. 4. Put your user id in `metadata.herald_user_id` on checkout sessions or subscriptions, or in `client_reference_id` on checkout. Options: **Include test mode events** (off by default). After rolling the secret in Stripe, paste the new one with **Rotate secret**. | Stripe event | Event | `revenue` from | |---|---|---| | `checkout.session.completed` | `purchase` | `amount_total` | | `invoice.paid` with `billing_reason: subscription_create` | `subscription_started` | `amount_paid` | | `invoice.paid`, other reasons | `subscription_renewed` | `amount_paid` | | `invoice.payment_failed` | `billing_issue` | `amount_due` | | `customer.subscription.deleted` | `subscription_cancelled` | none | | `charge.refunded` | `refund` | `amount_refunded` | | Any other type | Skipped: answers `200`, counted in `skipped` | | - `revenue` is the minor-unit amount divided by the currency's exponent: 100 for most currencies, no division for zero-decimal currencies such as JPY and KRW, 1000 for BHD, JOD, KWD, OMR and TND. `currency` is lower case, as Stripe sends it. There is no currency conversion. - The signature is `Stripe-Signature`, checked against the signing secret, and its timestamp must be within 5 minutes of now. - An event with no user id is skipped and counted. Herald never calls Stripe's API. - The event id is `stripe:`. ### Common errors | Message | Cause | Fix | |---|---|---| | `Unauthorized` | `401`: no signing secret is set, it doesn't match, or the `Stripe-Signature` timestamp is more than 5 minutes old | Paste the endpoint's `whsec_…` secret; after rolling it in Stripe, use **Rotate secret** | ## App Store and Google Play For apps that don't use RevenueCat: Apple and Google tell Herald about purchases directly. The events and the `subscription_status` attribute are the same as RevenueCat's, so goals work unchanged: pick `subscription_started` (or `trial_started`, `purchase`) as the agent's goal. **Identity (required).** A store notification doesn't say who the person is unless the app put it on the purchase. Herald never creates people from store notifications: an unmatched purchase answers `200` and is counted in `skipped`. - **Apple:** set `appAccountToken` when the app starts a purchase. If the user id your app sends Herald is a UUID, use it. Otherwise create a UUID, store it with the user, and send it to Herald as the `app_account_token` attribute. Herald matches the person whose user id equals the token (case-insensitive), then the person whose `app_account_token` attribute equals it. - **Google:** set `obfuscatedAccountId` (`BillingFlowParams.setObfuscatedAccountId`) to the user id your app sends Herald. Herald matches it exactly. ### App Store 1. In **Settings → Integrations**, connect App Store with the app's **Bundle ID**. Option: **Include sandbox purchases** (off by default). 2. In App Store Connect, open your app → **App Information → App Store Server Notifications**. Paste the URL as the **Production Server URL** (and as the Sandbox URL if sandbox is on). Choose **Version 2**. There is no secret: Apple's signature is the authentication. A notification with a missing or invalid signature answers `401` and nothing is ingested. **Test** can't sign anything for Apple: request a test notification with the App Store Server API and watch the event count (a `TEST` notification counts in `skipped`). A notification for another bundle id answers `200` (skipped) and shows as the last error. `environment: Sandbox` is skipped unless sandbox is on. | Apple `notificationType` / `subtype` | Event | `subscription_status` attribute | |---|---|---| | `SUBSCRIBED` / `INITIAL_BUY`, transaction `offerDiscountType: FREE_TRIAL` | `trial_started` | `active` | | `SUBSCRIBED` / `INITIAL_BUY` or `RESUBSCRIBE` | `subscription_started` | `active` | | `DID_RENEW` | `subscription_renewed` | `active` | | `DID_CHANGE_RENEWAL_STATUS` / `AUTO_RENEW_DISABLED` | `subscription_cancelled` | `cancelled` | | `EXPIRED` | `subscription_expired` | `expired` | | `DID_FAIL_TO_RENEW` | `billing_issue` | `billing_issue` | | `REFUND` | `refund` | unchanged | | `ONE_TIME_CHARGE` (consumables, non-consumables, non-renewing) | `purchase` | unchanged | | `TEST`, any other type | Skipped: answers `200`, counted in `skipped` | | - `revenue` is the transaction's `price` / 1000 (Apple's price is in milliunits), plus `currency`, `product_id`, `store: "app_store"` and `environment`. - The event id is `app_store:` (Apple's retries reuse it) and the event time is `signedDate`. #### Common errors | Message | Cause | Fix | |---|---|---| | `Unauthorized` | `401`: the notification's Apple signature is missing or invalid | Use the URL as a Version 2 notification URL | | `Notification for bundle id , not this integration's` | Shown as the last error; the notification is skipped | Set the integration's **Bundle ID** to the app's | ### Google Play 1. In Google Cloud, create a Pub/Sub topic and give `google-play-developer-notifications@system.gserviceaccount.com` the **Publisher** role. 2. Add a **push** subscription with the URL from the console, turn on **authentication** and pick a service account. Enter that account's email in the console (`pushServiceAccount`). 3. In Play Console → **Monetize → Monetization setup**, enter the topic. 4. Create a service account with access to your app in Play Console (**Users and permissions → View financial data**) and paste its JSON key as the secret. Config: `packageName` (required) and the option **Include test purchases** (off by default). **Test** signs in with the key and reads the app's subscriptions to prove access. The push request must carry a Google-signed token for your push service account and the exact webhook URL as its audience; otherwise it answers `401`. A notification only says something changed, so Herald reads the purchase from the Play Developer API before anything counts. Play answering 404 or 410 answers `200` (skipped); any other Play failure answers `503` so Pub/Sub retries, and shows as the last error. A notification for another package answers `200` (skipped) and shows as the last error. | Google Play notification | Event | `subscription_status` attribute | |---|---|---| | subscription `PURCHASED`, line item with a free trial | `trial_started` | `active` | | subscription `PURCHASED` | `subscription_started` | `active` | | subscription `RENEWED`, `RECOVERED` | `subscription_renewed` | `active` | | subscription `CANCELED` | `subscription_cancelled` | `cancelled` | | subscription `EXPIRED`, `REVOKED` | `subscription_expired` | `expired` | | subscription `IN_GRACE_PERIOD`, `ON_HOLD` | `billing_issue` | `billing_issue` | | one-time `ONE_TIME_PRODUCT_PURCHASED` | `purchase` | unchanged | | `voidedPurchaseNotification` | `refund` | unchanged | | `testNotification`, any other type | Skipped: answers `200`, counted in `skipped` | | - Test purchases are skipped unless the option is on. - `revenue` and `currency` come from the line item's recurring price when present; there is none for a free trial or a one-time product (the API gives no price). Also `product_id` and `store: "google_play"`. - The event id is `google_play:` (Pub/Sub redeliveries reuse it) and the event time is `eventTimeMillis`. #### Common errors | Message | Cause | Fix | |---|---|---| | `Unauthorized` | `401`: the push request has no Google-signed token for `pushServiceAccount`, or its audience isn't the exact URL | Turn on authentication on the push subscription and enter that account's email | | `Expected a Pub/Sub push message` | `400`: the body isn't a Pub/Sub push | Use a push subscription on the Play topic | | `Notification for package , not ` | Shown as the last error; the notification is skipped | Set `packageName` to the app's | | `Google's keys are unavailable; try again` or `Google Play is unavailable; try again` | `503`: Google couldn't confirm the notification now | None: Pub/Sub retries | | `Google Play answered HTTP ` | Shown as the last error: Google Play refused the purchase lookup | Check the service account's access in Play Console | | `Google Play doesn't know the app ` | **Test**: the service account can't see the app | Grant it access to the app, or fix `packageName` | ## Troubleshooting - **No goal to pick.** Event names appear in the picker after the first webhook arrives. Use **Send test** in the vendor, or make a sandbox purchase with the sandbox option on. - **Events are skipped.** Check that the vendor's user id matches the id your app sends Herald. For the App Store and Google Play, check that the purchase carries `appAccountToken` or `obfuscatedAccountId` as described above. Source: https://heraldsdk.com/docs/integrations/revenue.md --- # HubSpot, Salesforce and Mailchimp > Bring CRM and Mailchimp audience data into Herald as attributes and segments, optionally write results back to your CRM, and stop email to people who unsubscribed in Mailchimp. :::note Built from each vendor's documented API and tested against local mocks; tell us if anything differs in your account.::: These integrations pull from your CRM or audience every hour (or on **Sync now**) and only update people your app already sent Herald. Set them up in **Settings → Integrations**. An admin does it. Secrets are write-only and stored encrypted. ## What you'll need - An admin of the account. Integrations are set up in **Settings → Integrations**. - **HubSpot:** a private app with `crm.objects.contacts.read` and `crm.lists.read` (plus the write scopes for write-back). - **Salesforce:** a connected app with the client credentials flow and a run-as user that can read Contacts or Leads (and edit them for write-back). - **Mailchimp:** an API key and the audience id. ## How matching works A CRM or Mailchimp record never creates a person. It updates someone the app already sent Herald, in the same app. - **HubSpot and Salesforce** match by an id property first (config `idProperty`: a person whose user id equals its value), then by email (case-insensitive, against the person's email). HubSpot's `idProperty` defaults to `herald_user_id`. Salesforce has no default, so without one it matches by email only. - **Mailchimp** matches by email, case-insensitive, against the person's email contact. Records that match no one are counted as unmatched and never imported. ## What syncs - **Attributes.** You choose up to 20 properties or fields (letters, digits and `_`, starting with a letter). Each lands on the matched person as `hubspot_`, `salesforce_` or `mailchimp_`, lower case. An empty value removes the attribute. Nothing is copied by default. - **Segments.** HubSpot lists, Salesforce campaigns and Mailchimp tags (up to 10 each) become segments named "HubSpot: ", "Salesforce: " and "Mailchimp: ". Membership is replaced every run with the matched members. - **First run.** HubSpot and Salesforce read the last 7 days, then continue from where the last run stopped. A run that runs out of time continues next hour. ## Write-back (HubSpot and Salesforce) Off by default. When on, Herald writes four fields to the matched record for people with new decisions (first run: the last 24 hours): the latest agent, message (variant name), sent time and conversion time. Only values present are written. People without a matching record are skipped. | | HubSpot property (group `herald`) | Salesforce field | |---|---|---| | Last agent | `herald_last_agent` (text) | `Herald_Last_Agent__c` (Text 255) | | Last message | `herald_last_message` (text) | `Herald_Last_Message__c` (Text 255) | | Last sent at | `herald_last_sent_at` (datetime) | `Herald_Last_Sent_At__c` (Date/Time) | | Converted at | `herald_converted_at` (datetime) | `Herald_Converted_At__c` (Date/Time) | ## HubSpot 1. In HubSpot, open **Settings → Integrations → Private apps** and create an app with the scopes `crm.objects.contacts.read` and `crm.lists.read`. For write-back also add `crm.objects.contacts.write` and `crm.schemas.contacts.write`. 2. Paste its access token in the console. 3. If your contacts have a property holding your app's user id, enter its internal name. Otherwise people are matched by email. 4. Pick the properties and the list ids. With write-back on, **Test** checks the token and creates the `herald` property group and the four properties when they are missing (safe to run again). ### Common errors | Message | Cause | Fix | |---|---|---| | `HubSpot: ` or `HubSpot answered HTTP ` | Shown as the last error: HubSpot refused a call, often a missing scope or an expired token | Check the token and its scopes | | `HubSpot rate limit reached; continuing next hour` | HubSpot's rate limit | None: the next hourly run continues | | `Out of time reading the list; it syncs next hour` | A large list didn't finish in one run | None: the next run continues | | `HubSpot request failed` | HubSpot couldn't be reached | None: the next run retries | ## Salesforce 1. In Salesforce Setup, create a connected app (or external client app) with OAuth, enable the client credentials flow and pick a run-as user with read access to Contacts or Leads (and edit access for write-back). 2. Paste your My Domain URL, consumer key and consumer secret as `{ "instanceUrl": "https://.my.salesforce.com", "clientId": "…", "clientSecret": "…" }`. The URL must be https on `*.salesforce.com`. 3. Choose the object: `Contact` (default) or `Lead`. Pick the fields and the campaign ids. 4. For write-back, create the four custom fields above on the object. With write-back on, **Test** describes the object and lists any that are missing. ### Common errors | Message | Cause | Fix | |---|---|---| | `Salesforce: ` or `Salesforce answered HTTP ` | Shown as the last error: Salesforce refused a call, often the integration user's permissions | Check the user's object and field access | | `Salesforce: campaign not found` or `Invalid campaign id ` | A campaign in `lists` doesn't exist or isn't an id | Fix the campaign id | | `object must be Contact or Lead` | Saving the integration: wrong object | Choose Contact or Lead | | `Salesforce request failed` | Salesforce couldn't be reached | None: the next run retries | ## Mailchimp 1. In Mailchimp, open Profile, Extras, **API keys** and create a key (it ends in a data center such as `-us21`). 2. Paste it in the console with the audience id (Audience, Settings, Audience name and defaults). 3. Pick the tags (up to 10) and the merge tags (up to 20, such as `FNAME`). **Unsubscribes.** With the option **Sync unsubscribes** (on by default), a member who is `unsubscribed` or `cleaned` in Mailchimp gets an email suppression in Herald, so Herald stops emailing that address too. Herald never lifts a suppression, so a re-subscribe in Mailchimp does not unsuppress. Mailchimp never adds a person. **Test** reads the audience. ### Common errors | Message | Cause | Fix | |---|---|---| | `Mailchimp: ` or `Mailchimp answered HTTP ` | Shown as the last error: Mailchimp refused a call | Check the API key and audience id | | `listId must be the audience id` | Saving the integration: not an audience id | Copy the id from the audience's settings | | `mergeFields must be merge tags such as FNAME` | Saving the integration: a merge field isn't a tag | Use the merge tags, not the labels | | `The API key is not set or unreadable` | The secret is missing | Paste the API key again | ## Troubleshooting - **Records are unmatched.** Check the id property, or that the person's email in Herald equals the CRM or Mailchimp email. - **Write-back skips a person.** No matching record in the CRM. - **Salesforce Test lists missing fields.** Create the four custom fields on the chosen object. Source: https://heraldsdk.com/docs/integrations/crm.md --- # BigQuery, Firebase and Snowflake > Sync users and events from BigQuery (including the Firebase Analytics and GA4 export) or Snowflake with your own queries, and write decisions back to a table your BI tools can read. :::note Built and tested against each vendor's documented API; tell us if anything differs in your account.::: Warehouses are pulled, not pushed: there is no webhook URL. You paste a key and SQL queries when you connect. An hourly job runs each active warehouse integration. **Sync now** runs one immediately. **Test** signs in, runs `SELECT 1` and up to five rows of each query, and writes nothing. ## What you'll need - An admin of the account. Integrations are set up in **Settings → Integrations**. - **BigQuery:** a service account with BigQuery Data Viewer and Job User on the project (plus Data Editor on the dataset for write-back), and its JSON key. - **Snowflake:** a user with key-pair auth and a role that can read your tables and use the warehouse. - A SQL query for users and one for events that follow the [column contract](#column-contract). ## Connect :::note Warehouse tables and queries run in your account. Give the service account or user only the access listed here.::: **BigQuery.** Create a service account with BigQuery Data Viewer and Job User on the project (plus Data Editor on the dataset for write-back). Create a JSON key and paste it. Settings: | Setting | Meaning | |---|---| | `projectId` | Default: the key's `project_id` | | `location` | Optional | | `datasetId` | Needed for the Firebase preset and write-back | | `usersQuery`, `eventsQuery` | Your queries, standard SQL | | `audiencesQuery` | Optional: see [Audiences](#audiences) | | `preset` | `firebase`, or none | | `writeBack` | On or off | **Snowflake.** Create a user with key-pair auth (`ALTER USER … SET RSA_PUBLIC_KEY = '…'`) and a role that can read your tables and use the warehouse. Paste the unencrypted PKCS#8 private key (`-----BEGIN PRIVATE KEY-----`). Settings: `account` (for example `xy12345.us-east-1`), `user`, `role` (optional), `warehouse`, `database`, `schema`, `usersQuery`, `eventsQuery`, `audiencesQuery` and `writeBack`. Column names are matched without regard to case. ## Column contract Columns are matched by name. Other columns are ignored for events and become attributes for users. | Query | Column | Meaning | |---|---|---| | users | `user_id` | Required (text or number). Rows without it are skipped and counted. | | users | `email` | Email contact. An invalid one is dropped and the user kept. | | users | `signup_at`, `last_active_at` | Timestamps | | users | `updated_at` | Only moves the cursor | | users | any other | An attribute: strings, numbers and booleans; nulls and other types are left out | | events | `user_id`, `name`, `timestamp` | Required. A row missing one is skipped and counted. | | events | `event_id` | Optional. Otherwise it is derived from the user, name and time, so re-reading a row is a duplicate. | | events | `properties` | A JSON object, or a string holding one | ## `{{since}}` and the cursor In a query, `{{since}}` becomes a quoted ISO timestamp literal, such as `'2026-11-20T09:17:00.000Z'`, which both warehouses compare to a timestamp column: ```sql SELECT user_id, email, updated_at FROM app.users WHERE updated_at >= {{since}} ``` Each query keeps its own cursor. The first run reads from 7 days ago. - Events: the query is wrapped as `SELECT * FROM () ORDER BY timestamp LIMIT 50000`, and the cursor becomes the newest timestamp ingested. Use `>=` when several events can share a timestamp: ids make the overlap duplicates. - Users: the query is wrapped with `LIMIT 10000`. The cursor becomes the newest `updated_at` when the rows have one, otherwise the run's start time. Filter users on `updated_at` so a capped run catches up next hour. - The cursor moves only when every query of the run succeeded. A failed run records the error, shown on the integration's card, and the next run retries from the same place. - Runs never overlap. A run is skipped while another is less than 55 minutes old, and **Sync now** answers `409`. ## Firebase Analytics and GA4 (BigQuery) Link Firebase or GA4 to BigQuery, set `datasetId` to the `analytics_` dataset and turn on the Firebase preset. The events query is then generated, so you do not write one. It reads `events_*` from the dataset, takes `event_name` as the event name and turns `event_params` into the event's properties. Only events with a `user_id` (your app's `setUserId`) are read. Events with only a `user_pseudo_id` are not. Intraday tables match `events_*` too, and their rows become duplicates when the daily table lands. ## Write-back With `writeBack` on, the first sync at or after 02:00 UTC each day writes the previous UTC day's decisions, with their outcomes so far, to a table it creates if missing. | Column | BigQuery | Snowflake | |---|---|---| | `decision_id`, `user_id`, `agent_id`, `agent_name`, `variant_id`, `variant_name`, `channel`, `conversion_event` | STRING | STRING | | `sent_at`, `converted_at` | TIMESTAMP | TIMESTAMP_NTZ | | `reward` | FLOAT64 | FLOAT | | `holdout` | BOOL, always false because holdout users get no decision | BOOLEAN | BigQuery writes `.herald_decisions`. Snowflake writes `HERALD_DECISIONS` in the configured database and schema, merging on `decision_id`. A failed write-back is shown as the last error and retried next hour. Conversions that land after the export day are not re-sent. ## Audiences Define segments in SQL. The optional audiences query returns two columns, `user_id` and `audience`, and each distinct `audience` becomes an externally managed segment named `BigQuery: ` (or `Snowflake: `) that agents target like any other segment. ```sql SELECT user_id, tier AS audience FROM customers WHERE tier IN ('VIP', 'Churn risk') ``` - It runs in full every hour, without `{{since}}`. Each audience's members are replaced by what the query returned, and an audience that stops appearing is emptied. - Members Herald doesn't know yet are created, as cohort members are. Rows missing either column are skipped and counted. - Up to 50 audiences and 50,000 rows. Over either limit, the run changes nothing and shows the error, so a segment is never half-replaced. - You can't edit these segments in the console. Change the query instead. - **Test** shows up to five audience rows. ## Use with Looker Studio, Tableau and Power BI Point the tool at the write-back table (`herald_decisions` in BigQuery, `HERALD_DECISIONS` in Snowflake), or at the Google Sheets tab from [Reporting and exports](/docs/integrations/reporting). Looker Studio and Power BI read Google Sheets directly. For a one-off, use the decisions CSV. ## Limits - 10,000 users and 50,000 events per run per integration. The rest comes next hour. - 50 audiences and 50,000 audience rows per run. - Queries time out after 120 seconds. ## Troubleshooting - **Rows are skipped.** A users row needs `user_id`. An events row needs `user_id`, `name` and `timestamp`. - **The same rows arrive every hour.** Filter on a timestamp column with `{{since}}`. - **The Firebase preset finds nothing.** Check `datasetId` and that your app calls `setUserId`. ## Common errors | Vendor | Message | Cause | Fix | |---|---|---|---| | BigQuery | `BigQuery: ` or `BigQuery answered HTTP ` | BigQuery refused the query, often a SQL error or missing permission | Run the query in BigQuery and fix it | | BigQuery | `Google sign-in failed` | The service account key can't sign in | Paste a current JSON key | | BigQuery | `BigQuery query timed out` | The query ran too long | Narrow it with `{{since}}` | | BigQuery | `BigQuery refused rows` | Write-back rows were refused | Check the decisions table's schema | | BigQuery | `projectId is not a valid project id` or `datasetId may contain only letters, numbers and underscores` | Saving the integration: a bad id | Copy the ids from Google Cloud | | Snowflake | `Snowflake: ` or `Snowflake answered HTTP ` | Snowflake refused the statement | Run the query in Snowflake and fix it | | Snowflake | `Snowflake statement timed out` | The query ran too long | Narrow it with `{{since}}` | | Snowflake | `account is not a valid account identifier` | Saving the integration: a bad account | Use the account identifier, such as `xy12345.us-east-1` | | Both | `Write-back failed: ` | Writing decisions back failed | Check the user's write access | | Both | `Audiences failed: The audiences query returned more than 50,000 rows; nothing was changed` | The query returned too many rows | Narrow the query; the segments keep their members until it fits | | Both | `Audiences failed: The audiences query returned more than 50 audiences` | Too many distinct `audience` values | Return fewer audiences | Source: https://heraldsdk.com/docs/integrations/warehouses.md --- # Amplitude and Mixpanel > Sync Amplitude and Mixpanel cohorts to Herald as segments your agents can target, stream Amplitude events in, and optionally send decisions back as events. :::note Built and tested against each vendor's documented API; tell us if anything differs in your account.::: A synced cohort becomes an externally managed segment named `: `. Agents target it like any other segment. Only the integration writes its members. - A renamed cohort renames the segment, and the agents that target it. - Members are matched by user id against the app's people. An id Herald does not know yet is created and joins the app, as the server API does for an unknown user. - Users removed from the cohort leave the segment. Segments built from other conditions are untouched. - You cannot edit a cohort segment in the console. Delete it and the next sync recreates it. ## What you'll need - An admin of the account. Integrations are set up in **Settings → Integrations**. - **Amplitude:** access to add a Webhook cohort destination. - **Mixpanel:** access to add a Custom Webhook integration. - To send decisions out: the export credentials listed under [Send decisions out](#send-decisions-out-optional). ## Amplitude 1. In **Settings → Integrations**, connect Amplitude and copy the URL and secret. 2. In Amplitude, add a **Webhook** cohort destination with the URL and the custom header `Authorization: Bearer `. 3. Sync the cohort to it. The payload has `cohort_id`, `cohort_name`, `in_cohort` (true when these users entered, false when they left) and `users[].user_id`. A user without `user_id` is skipped and counted. Amplitude expects a `200` within 1 to 2 seconds and retries otherwise. A retried batch applies the same change again. ### Stream Amplitude events (optional) To send raw events as well, add a **Webhook** event streaming destination in Amplitude with the same URL and header, and keep the default payload (Amplitude's event format). Cohort updates and events share the URL. | Amplitude | In Herald | |---|---| | `event_type` | The event name | | `event_properties` | The event's properties | | `user_properties` | Attributes on the user (strings, numbers, booleans and string arrays; nested objects are dropped) | | `$identify` | Updates the user only, no event | | `user_id` | The External ID. An event without one (device only) is skipped and counted | | Event id | `amplitude:` (else `insert_id`); an event with neither is skipped. A replay is a duplicate | | Event time | `event_time`, else the time it arrived | ### Common errors | Message | Cause | Fix | |---|---|---| | `Unauthorized` | `401`: the secret or signature doesn't match, the integration is paused, or the URL names another provider | Copy the URL and secret from the console again, and resume the integration | | `Expected a cohort update with an id, a name and users` | `400`: the body isn't a cohort update | Use the vendor's cohort webhook, unchanged | ## Mixpanel 1. In **Settings → Integrations**, connect Mixpanel and copy the URL and secret. 2. In Mixpanel, add a **Custom Webhook** integration with the URL. Turn on Basic authentication and set the password to the secret. The username is ignored. Mixpanel sends the actions `members` (the whole cohort: page 1 replaces the segment's members, later pages add), `add_members` and `remove_members`. The cohort comes from `parameters.mixpanel_cohort_id` and `mixpanel_cohort_name`, and users from `parameters.members[].mixpanel_distinct_id`. Mixpanel sends at most 1,000 members per call, every 30 minutes. Answers use Mixpanel's shape: `200 { action, status: "success" }`, or `400 { action, status: "failure", error }` for a body that cannot be read. A bad password is the usual `401`. ### Common errors | Message | Cause | Fix | |---|---|---| | `Unauthorized` | `401`: the Basic authentication password isn't the secret, or the integration is paused | Set the password to the secret | | `Expected a cohort update with an id, a name and users` | `400`: the body isn't a cohort update | Use the vendor's cohort webhook, unchanged | | `Unknown action` | `400`: an action other than `members`, `add_members` or `remove_members` | None needed; other actions are refused | ## Send decisions out (optional) Turn on **Send decisions to Amplitude / Mixpanel** when you connect (Segment has the same option: see [Send decisions to Segment](/docs/integrations/event-sources#send-decisions-to-segment-optional)), and give the export credentials. They are sealed with the integration's secret and never shown again. | Vendor | Credentials | |---|---| | Amplitude | API key and data center (US or EU) | | Mixpanel | Project id, service account username and secret, and data residency (US or EU) | The hourly sync sends each decision changed since the last send, 500 per request. The first run covers the last 24 hours. | Event | When | Properties | |---|---|---| | `herald_message_sent` | Every decision | `agent`, `agent_id`, `variant`, `variant_id`, `channel`, `decision_id`, `holdout` (always false) | | `herald_message_converted` | The decision converted | The same, plus `conversion_event` and `conversion_value` | The cursor moves only after the vendor accepts the batch. A failure is shown as the integration's last error and the next run retries from the same place. A decision that changes again is sent again with the same insert id, which both vendors deduplicate. ### Common errors | Message | Cause | Fix | |---|---|---| | `Set the Amplitude API key` or `Set the Mixpanel service account and project id` | Shown as the last error: export credentials are missing | Add them on the integration | | `amplitude export HTTP ` or `mixpanel export HTTP ` | Shown as the last error: the vendor refused the batch | Check the credentials and data center; the next run retries | | `amplitude network error` or `mixpanel network error` | Shown as the last error: the vendor couldn't be reached | None: the next run retries | ## Troubleshooting - **A cohort does not appear.** Check that the destination sends the `Authorization` header or password, and look at the integration's last error. - **A user is missing.** A cohort member without a user id is skipped and counted. Source: https://heraldsdk.com/docs/integrations/product-analytics.md --- # AppsFlyer, Adjust and Branch > Send install attribution from AppsFlyer, Adjust or Branch to Herald, so each person carries their install source and campaign. :::note Built and tested against each vendor's documented API; tell us if anything differs in your account.::: Each postback becomes, for its user, the event `app_installed` (installs) or the vendor's event name (in-app events), with the attribution values as event properties. An install also sets these user attributes where present, so you can target a segment by install source. | Attribute | AppsFlyer | Adjust | Branch | |---|---|---|---| | `install_source` | `media_source` | `network_name` | `last_attributed_touch_data.~channel` | | `install_campaign` | `campaign` | `campaign_name` | `last_attributed_touch_data.~campaign` | | `install_channel` | `af_channel` | none | `last_attributed_touch_data.~feature` | | User id | `customer_user_id` | callback parameter `user_id` | `user_data.developer_identity` | | Event time | `event_time` (UTC) | `created_at` (unix seconds) | `timestamp` (ms) | A postback without a user id is skipped and counted. Replays are duplicates, because event ids are deterministic. ### Revenue Purchases carry their value as the event properties `revenue` and `currency`, so an agent's goal can weight by value. | Vendor | `revenue` and `currency` from | |---|---| | AppsFlyer | `event_revenue_usd` (as USD), else `event_revenue` and `event_revenue_currency`, else `revenue_in_selected_currency` and `selected_currency`. Add the field to the Push API endpoint | | Branch | `event_data.revenue` and `event_data.currency` (USD when no currency was logged). `custom_data` becomes event properties too | | Adjust | `{revenue_float}` (whole units), else `{revenue}` (cents), with `{currency}`. Both are in the callback URL the console shows | There's no currency conversion except AppsFlyer's own USD field, so prefer it when your apps sell in several currencies. ## What you'll need - An admin of the account. Integrations are set up in **Settings → Integrations**. - **AppsFlyer:** access to the Push API, to add a custom header. - **Adjust:** access to server callbacks. - **Branch:** access to webhooks. - Your own user id on each install: `customer_user_id`, the `user_id` callback parameter, or `developer_identity`. ## Connect In **Settings → Integrations**, connect the provider and copy the URL and secret. **AppsFlyer** (Push API). POST JSON with the custom header `Authorization: Bearer `. An install is `event_name` `install`. For an in-app event, `event_value` (a JSON string) becomes its properties. **Adjust** (server callbacks). GET or POST to the callback URL the console shows. It carries the secret as `?s=` and these placeholders: `{activity_kind}`, `{adid}`, `{event}`, `{event_name}`, `{network_name}`, `{campaign_name}`, `{tracker_name}`, `{installed_at}`, `{created_at}`, `{revenue_float}`, `{revenue}`, `{currency}`. Add the global callback parameter `user_id` in the Adjust SDK. The activities `install` and `event` are used, and others are skipped. An unreplaced `{placeholder}` counts as missing. Only Adjust accepts GET. :::warning Adjust callbacks cannot send headers, so the secret sits in the URL, where it can show up in Adjust's dashboard and in proxy or platform request logs. Herald's API never logs the query string. Keep the URL private and rotate the secret if it leaks.::: **Branch** (webhooks). POST JSON with the header `Authorization: Bearer `. An install is `name` `INSTALL`. ## Troubleshooting - **Everything is skipped.** The postback carries no user id. Send your own user id as `customer_user_id` (AppsFlyer), the `user_id` callback parameter (Adjust) or `developer_identity` (Branch). - **Answers `401`.** The secret is wrong or the integration is paused. See [the overview](/docs/integrations/overview). ## Common errors | Vendor | Message | Cause | Fix | |---|---|---|---| | All | `Unauthorized` | `401`: the secret is wrong, the integration is paused, or the URL names another provider | Copy the URL and secret again | | AppsFlyer, Branch | `Unauthorized` | `401` for a GET: only Adjust may call with GET | Send POST | | All | `Expected a JSON object` | `400`: the body isn't a JSON object | Use the vendor's postback, unchanged | Source: https://heraldsdk.com/docs/integrations/attribution.md --- # Sending through your tools > Let Herald pick the message while Braze, SendGrid, OneSignal, Iterable, Customer.io, Klaviyo, Mailchimp Transactional or your own Twilio account delivers it, with the setup and template variables for each. :::note Built and tested against each vendor's documented API; tell us if anything differs in your account. Braze and SendGrid are live.::: A sender is a connection: Herald picks the variant, channel and time for each person, and your platform delivers it. Set one up in **Settings → Sending & SDK**. Braze and SendGrid are live. OneSignal, Iterable, Customer.io, Klaviyo, Mailchimp Transactional and your own Twilio account are Beta. For Braze and SendGrid, see [Braze concept map](/docs/migration/braze-concept-map) and [Sync from your warehouse](/docs/migration/warehouse-sync). ## What you'll need - An admin of the account. Senders are connections in **Settings → Sending & SDK**. - The vendor's API key or token, as listed in each section. Your app must use your own user id as the vendor's user id, so Herald can address the right person. | Vendor | Your user id goes in | |---|---| | OneSignal | The **External ID**: call `OneSignal.login(userId)` | | Iterable | `userId` | | Customer.io | `id` | | Klaviyo | `external_id` | ## OneSignal 1. Create a connection of type OneSignal with the app's **App ID** and its **REST API key** (OneSignal dashboard: Settings, Keys & IDs). 2. Push is always on. Tick "Email is set up in OneSignal" or "SMS is set up in OneSignal" only for channels the OneSignal app has configured. Agents can send only on the channels listed. Herald sends one request per batch of up to 2,000 users, with the chosen variant's copy inline and an idempotency key, so a retried batch is not sent twice. Local-time agents use OneSignal's timezone delivery. Users OneSignal reports as not subscribed on that channel are marked suppressed. A 4xx or 5xx fails the batch. ### Common errors | Message | Cause | Fix | |---|---|---| | `onesignal HTTP ` | OneSignal refused the request | Check the App ID and REST API key | | `channel not supported by onesignal` | The agent sent on a channel the connection doesn't list | Tick the channel on the connection, or remove it from the agent | | `unrenderable email` | An email variant has no subject or an unreplaced `{{token}}` | Fix the variant | ## Iterable, Customer.io and Klaviyo These three keep the message template on the vendor's side. Herald picks the variant and sends its copy as template data, and the vendor's template renders it. Template data on every send: | Variable | Value | |---|---| | `channel`, `title`, `body` | The variant's channel and copy | | `variant_id`, `decision_id` | Ids for the variant and the decision | | `deeplink`, `image_url`, `cta` | Only when the variant has them | | `subject`, `html` | Email only: `subject` is the title and `html` is the body | An email variant without a subject, or with an unreplaced `{{token}}`, is not sent. **Iterable.** Secret: a server-side API key. Config: `region` (`us` or `eu`) and the campaign id for each channel you send on (email, push, SMS, in-app). Create one API-triggered campaign per channel whose template uses `{{title}}`, `{{body}}` and so on, and paste its numeric id. Iterable merges the data into the template at the top level, and `{{profile.}}` reads the user profile. Sends go one per user, up to 100 users per batch. Future and local-time sends use `sendAt`. Iterable has no idempotency key. **Customer.io.** Secret: an App API key. Config: `region` (`us` or `eu`) and the transactional message id (the numeric id or the trigger name) for each channel. Create a transactional message per channel whose template uses `{{trigger.title}}`, `{{trigger.body}}` and so on, and paste its id. For email the recipient is `{{customer.email}}` and for SMS `{{customer.phone}}`, so the person's profile needs them. Sends go one per user, up to 100 users per batch, and Customer.io allows scheduling up to 90 days ahead. There is no idempotency key. **Klaviyo.** Secret: a private API key with the `events:write` scope (plus `accounts:read` for the health check). Config: the channels your flows send (email, SMS, push). Create a flow triggered by the metric `Herald Message` that sends `{{ event.title }}` and `{{ event.body }}`, and filter on `{{ event.channel }}` when one flow handles several channels. Herald sends one event per user in bulk jobs of up to 1,000 users, with the decision id as the unique id, so a retried batch is deduplicated. A flow triggers when the event arrives, so a future or local-time send goes out when Herald sends the event. The planned time is in `event.send_at` for a flow that waits for it. Klaviyo accepts the whole job with no per-event result, so every decision in an accepted job counts as sent. Bulk jobs are limited to 10 per second. **Results.** A 2xx is a send. Iterable and Customer.io answer per user: when every call in a batch fails, the batch is a failed send, and when only some fail, those users are marked suppressed. Any Klaviyo non-2xx fails the batch. Opens and clicks do not flow back yet. Conversions still come from your app's events. ### Common errors | Message | Cause | Fix | |---|---|---| | `no iterable campaign id for ` or `no customerio transactional message id for ` | The connection has no campaign or message for that channel | Add it to the connection's config | | `iterable recipient ` | Iterable refused that user | Check the user exists in Iterable with your user id | | `iterable HTTP `, `customerio HTTP ` or `klaviyo HTTP ` | The vendor refused the request | Check the API key, its scopes and the region | | `channel not supported by ` | The agent sent on a channel the connection doesn't list | Add the channel to the connection, or remove it from the agent | ## Mailchimp Transactional Email only, through your own Mailchimp Transactional (Mandrill) account. Create a connection of type Mailchimp Transactional with a Transactional API key as the secret and the config `fromEmail`, `fromName` and, optionally, `templateName`. Herald finds each person's email like SendGrid does (the latest email contact, else a valid `email` attribute) and skips suppressed addresses. Herald sends one request per batch of up to 1,000 users, one recipient each, with open and click tracking on and the agent id as the tag. Each recipient carries `herald_decision_id` in its metadata. - **Plain.** Without `templateName`, the variant's title is the subject and its body is the HTML. - **Template.** With `templateName`, the template gets the copy as global merge variables: `*|title|*`, `*|body|*`, `*|subject|*`, `*|html|*`, `*|deeplink|*`, `*|image_url|*`, `*|cta|*` and `*|variant_id|*`. An email variant without a subject, or with an unreplaced `{{token}}`, is not sent. Mandrill answers per recipient. `sent`, `queued` and `scheduled` count as sent; `rejected` and `invalid` fail with the reject reason. When every recipient in a batch fails, the batch is a failed send; otherwise the failed users are marked suppressed. Herald sends immediately: a future or local-time schedule is not passed on. Opens and clicks do not flow back yet. Conversions still come from your app's events. ### Common errors | Message | Cause | Fix | |---|---|---| | `mandrill rejected: ` or `mandrill invalid: ` | Mandrill refused that recipient | Check the reason in Mandrill, such as a hard bounce | | `mandrill gave no result` | Mandrill answered without a result for the recipient | None: retry later | | `unrenderable email` | An email variant has no subject or an unreplaced `{{token}}` | Fix the variant | ## Your own Twilio account Turn on the SMS card and texts send from Herald's shared numbers, with nothing to set up. The first text to each person ends with "Reply STOP to unsubscribe", and STOP replies are handled automatically. To send from your own Twilio account instead, set `twilioAccountSid` (`AC` followed by 32 hex characters) and `twilioAuthToken` in the SMS card's "Use your own Twilio account" section. Set both or neither. Both are write-only secrets. 1. Create a Twilio Messaging Service in your account and enter its SID (`MG…`) in the same section. 2. On the Messaging Service, set the status callback and the inbound webhook to the URL the SMS card shows. 3. Sender registration (10DLC) with Twilio is manual and outside Herald. An inbound STOP creates a suppression. ### Common errors | Message | Cause | Fix | |---|---|---| | `twilio HTTP ` | Twilio refused the message | Check the Account SID, auth token and Messaging Service | | `twilio payload is malformed` | Your own Twilio account is set but the SMS card has no Messaging Service SID | Enter the SID in "Use your own Twilio account" | ## Troubleshooting - **A user is marked suppressed.** The vendor reported them as not subscribed on that channel, or the call failed for that user. - **An email is not sent.** It has no subject, or an unreplaced `{{token}}` in its copy. - **Nothing reaches a person.** Check that your app passes your own user id to the vendor, as in the table above. Source: https://heraldsdk.com/docs/integrations/senders.md --- # Contentful, Sanity, JSON feeds and Braze catalogs > Keep message copy in your CMS. Herald syncs it into your library, so agents test and pick from the copy your team already writes. :::note Built and tested against each vendor's documented API, and checked against live Contentful and JSON feed data; tell us if anything differs in your account.::: ## What you'll need - **Contentful:** the space ID, the environment (default `master`), the content type that holds your messages, and a **Content Delivery API** token for that space (Settings → API keys). - **Sanity:** the project ID, the dataset (default `production`), and a GROQ query that returns your messages. A read token only if the dataset is private (Settings → API → Tokens, Viewer). - **JSON feed:** a public `https` URL that returns your messages as JSON, and a bearer token if the feed needs one. - **Braze catalog:** a Braze connection in **Settings → Sending & SDK**, and the catalog's name. ## What it does Data in. Each item becomes a message variant in your Herald library, under one library message per source and channel (for example "[contentful] push library"). Agents can then use those variants like copy written in Herald. Edits in your CMS update the variant on the next sync, and an item removed from the source is archived. Contentful locales come in as translations. ## Supported data | Data | Direction | Mode | Notes | |---|---|---|---| | Message copy (title, subject, body, CTA, deep link, image, HTML body, tags) | In | Daily, or **Sync now** | One variant per item | | Translations | In | With each sync | Contentful locales | ## Connect 1. In **Settings → Content sources**, turn on the source. 2. Fill in its fields and paste the token in the token field. The token is saved encrypted when you press **Save**, and never shown again. 3. Press **Test connection**. You see up to three mapped items from the source. 4. Press **Sync now**. The run appears in the sync history with how many items were created, updated, archived or skipped. ## How matching works Each item is matched to its variant by its id in the source (`sys.id` in Contentful, `_id` in Sanity, `id` in a JSON feed, the item id in a Braze catalog). An item without a body is skipped and listed in the run's errors. ## Configure Field mapping says where each part of the message lives in your items. The defaults: | Field | Contentful | Sanity | JSON feed | |---|---|---|---| | Id | `sys.id` | `_id` | `id` | | Title | `fields.title` | `title` | `title` | | Body | `fields.body` | `body` | `body` | | Tags | `metadata.tags[*].sys.id` | `tags` | `tags` | Paths use dots, `[0]` for an index and `[*]` for every item in a list. A JSON feed can page by a cursor in the response (`nextPath` and the query `param` that carries it) or by page number (`param` and `pageSize`). ## Limits - 100 items per page and 500 pages per sync, so up to 50,000 items per source. - Each request times out after 10 seconds, and redirects aren't followed. - A JSON feed's host must be public: private and local addresses are refused. - An item is archived only after a complete listing, so a failed sync never archives anything. ## Validate your setup **Test connection** shows up to three items as Herald will store them: the id, title, body and any translations. If the body is empty, fix the mapping before you sync. ## Troubleshooting Each sync is listed under the source with its status and first error. ### Common errors | Error | What to do | |---|---| | Add a Contentful Content Delivery API token | Paste the space's delivery token and press **Save**. | | Content URL must be public https | Use an `https` URL on a public host. | | invalid or missing body | Point the body mapping at the field that holds your message text. | | Choose the Braze connection to read the catalog from | Pick the Braze connection, then save. | | The saved token can't be read; save it again | Paste the token again and press **Save**. | Source: https://heraldsdk.com/docs/integrations/content-sources.md --- # Reporting and exports > Get decisions and outcomes out of Herald with the CSV export, Slack alerts, signed outbound webhooks, Google Sheets and hashed ad audiences, with a daily sync to Meta, Google Ads and LinkedIn. :::note Built and tested against each vendor's documented API; tell us if anything differs in your account.::: Slack, outbound webhooks and Google Sheets are integrations you set up in **Settings → Integrations**, under Send results out. They run on the hourly sync. The CSV downloads need no setup. The ad audience CSV needs none either; the daily ad audience sync is an integration too. ## What you'll need - An admin of the account. Integrations are set up in **Settings → Integrations**. - **Decisions CSV by API:** an API key with the `exports.read` scope. - **Slack:** an incoming webhook URL for the channel. - **Outbound webhooks:** a public HTTPS endpoint you control. - **Google Sheets:** a service account JSON key, and the sheet shared with that account as an editor. - **Ad audiences:** an ad account on Meta, Google Ads or LinkedIn, and credentials for it. ## Decisions CSV **API.** `GET /api/v1/exports/decisions.csv?from=YYYY-MM-DD&to=YYYY-MM-DD` with `Authorization: Bearer hk_…`, an API key with the `exports.read` scope. Both days are included (UTC), and the range is at most 31 days (`400` otherwise). A key without the scope answers `403`. Each request counts toward `exports.requests`, 60 per hour by default. **Console.** **Download CSV** on the Overview header (admins) downloads the page's period (7, 30 or 90 days). The file has one row per decision sent in the range, in send order, with outcomes as of the download: `decision_id, user_id, agent_id, agent_name, variant_id, variant_name, channel, sent_at, converted_at, conversion_event, reward, holdout`. It is UTF-8 with a header row, RFC 4180 quoting and CRLF line ends. ### Common errors | Message | Cause | Fix | |---|---|---| | `from must be a date (YYYY-MM-DD)`, `to must not be before from` or `The range can be at most 31 days` | `400`: a bad range | Fix `from` and `to` | | `This API key lacks the exports.read scope` | `403`: the key lacks the scope | Create a key with `exports.read` | | `Rate limit exceeded for exports.requests: 60 per hour` | `429`: over the hourly limit | Wait for `Retry-After` | ## Slack alerts Paste a Slack **incoming webhook URL**. It must start with `https://hooks.slack.com/`. Each alert is on by default. | Alert | Sent when | |---|---| | `liftNegative` | An on agent's lift against its holdout is negative and significant | | `winnerFound` | A sending agent's leading variant has at least 70% of its last 7 days' sends (20 or more) | | `sendFailures` | Messages of the app failed to send in the last hour | Each alert goes out at most once per agent (per app for send failures) every 24 hours. The message is one line of plain text with a link to the agent in the console. **Send test** posts "Connected" to the channel. ### Common errors | Message | Cause | Fix | |---|---|---| | `Slack answered HTTP ` | Shown as the last error: Slack refused the post, often a removed webhook | Create a new incoming webhook and update the integration | | `Slack timed out after 10 s` or `Slack request failed` | Slack couldn't be reached | None: the next run retries | ## Outbound webhooks Give an https URL and pick the events: `decision.created` (a decision was sent) and `outcome.recorded` (a decision converted). The console shows a signing secret once. Each hourly sync posts every new event since the last delivery as a JSON array, up to 500 per request. ```json [ { "type": "decision.created", "id": "decision.created:cmh1x2y3z0001", "created_at": "2026-11-20T09:00:00.000Z", "data": { "decision_id": "cmh1x2y3z0001", "user_id": "user_42", "agent_id": "cmh0agent", "agent_name": "Welcome", "variant_id": "cmh0var", "variant_name": "Short", "channel": "push", "sent_at": "2026-11-20T09:00:00.000Z", "converted_at": null, "conversion_event": null, "reward": null, "holdout": false } } ] ``` `outcome.recorded` carries the same `data` with `converted_at`, `conversion_event` and `reward` set, and its `created_at` is the conversion time. `id` is unique per event: use it to drop repeats. Headers: `X-Herald-Signature: sha256=` and `X-Herald-Timestamp` (Unix seconds when sent). A batch moves past only when your endpoint answers 2xx within 10 seconds. Otherwise it is sent again next hour and the failure shows as the last error. Redirects are not followed. A URL on a private, loopback, link-local or reserved address is refused. A new webhook starts from the time it was created. Delivery is hourly. **Send test** posts one signed `{ "type": "test" }` event. Verify the signature over the raw body before you parse it. **Node** ```js import { createHmac, timingSafeEqual } from "node:crypto"; function verified(rawBody, header, secret) { const expected = "sha256=" + createHmac("sha256", secret).update(rawBody).digest("hex"); return header?.length === expected.length && timingSafeEqual(Buffer.from(header), Buffer.from(expected)); } ``` **Python** ```python import hashlib, hmac def verified(raw_body: bytes, header: str, secret: str) -> bool: expected = "sha256=" + hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest() return hmac.compare_digest(header or "", expected) ``` In Zapier use **Webhooks by Zapier → Catch Hook**, in Make a **Custom webhook**, and in n8n a **Webhook** node. Paste its URL into the console. ### Common errors | Message | Cause | Fix | |---|---|---| | `The endpoint answered HTTP ` | Your endpoint answered with an error | Check your endpoint's logs | | `The endpoint timed out after 10 s` or `The endpoint request failed` | Your endpoint didn't answer in time | Answer within 10 seconds and do the work later | | `The endpoint URL must be https on a public address` | The URL isn't public HTTPS | Use a public `https://` URL | | `url must be an https URL` or `Choose at least one event` | Saving the integration: a bad URL or no events | Fix the field | ## Google Sheets 1. Create a Google Cloud service account, enable the Google Sheets API on its project and create a JSON key. Paste the key into the console. 2. Share the spreadsheet with the service account's `client_email` as an Editor. 3. Enter the `spreadsheetId` (from the URL, `/d//edit`) and the `sheetName` (the tab). The first sync at or after 03:00 UTC each day appends one row per active agent for the previous UTC day. The first append adds a header row. | Date | Agent | Sends | Conversions | Conversion rate | Lift vs holdout | Top variant | |---|---|---|---|---|---|---| | 2026-11-19 | Welcome | 1200 | 84 | 0.07 | 0.123 | Short | Rates are fractions, so format the column as a percentage. Lift is the agent's holdout lift to date when it is ready, otherwise blank. The top variant has the most conversions that day. **Test** reads the sheet's metadata and checks the tab exists. It writes nothing. To chart the sheet, see [BigQuery, Firebase and Snowflake](/docs/integrations/warehouses). ### Common errors | Message | Cause | Fix | |---|---|---| | `Google Sheets: ` or `Google Sheets answered HTTP ` | Google refused the write, often because the sheet isn't shared with the service account | Share the sheet with the service account as an editor | | `"" has no sheet named "<sheet>"` | **Test**: the tab doesn't exist | Fix `sheetName` | | `The service-account key is not JSON` | The secret isn't a JSON key | Paste the whole JSON key file | | `spreadsheetId is the id in the sheet's URL (/d/<id>/)` | Saving the integration: a bad id | Copy the id from the sheet's URL | ## Ad audiences Each segment row has an **Export for ads** menu (admins). It downloads `GET /api/segments/{id}/audience.csv?format=meta`, `google` or `linkedin`, with one line per segment member who has an active email or phone. Any suppression of the address (unsubscribe, bounce, complaint, STOP, manual) leaves it out. Values are normalized and then SHA-256 hashed (lowercase hex). | Platform | Columns | Email | Phone | |---|---|---|---| | Meta Custom Audiences | `email,phone` | Trimmed, lower case | Digits with country code, no `+` | | Google Customer Match | `Email,Phone` | Trimmed, lower case; for gmail.com and googlemail.com the dots and `+suffix` before `@` are removed | E.164 with `+` | | LinkedIn Matched Audiences | `email` | Trimmed, lower case | Not used | Upload the file in each platform's audience manager as a customer list with pre-hashed data. The CSV also works for a one-off upload; the daily sync below replaces it for Meta, Google Ads and LinkedIn. ### Daily sync (Beta) Set up one integration per platform account (**Meta**, **Google Ads** or **LinkedIn**) in **Settings → Integrations**, under Send results out. Config: the account plus 1 to 10 pairs of a segment and an audience (the segment must belong to the account). Each day, on the first sync at or after 04:00 UTC, each pair's audience is made equal to the segment's members, built exactly as the CSV builds them (same member query, normalization, hashing and suppressions). A pair with no audience gets a new one named after the segment on its first sync. Each pair shows its last sync time, how many were sent and its last error; a failing pair doesn't stop the others. Herald doesn't hold back a segment below a platform's minimum size: it sends it and records the answer. **Sync now** runs every pair at once, whatever the hour. Tokens are stored encrypted. **Test** signs in and reads the account, writing nothing. - **Meta.** Secret: a system user access token with `ads_management`, for a system user that has the ad account. Accept the Custom Audience terms for the ad account. Config: `adAccountId` (`act_<digits>`; bare digits get the prefix). Meta can't replace an audience with nobody, so an empty segment leaves the audience as it was. Matching can take up to 24 hours, and an audience needs roughly 100 matched people to deliver. - **Google Ads.** Uses Google's Data Manager API. Secret: JSON `{ clientId, clientSecret, refreshToken, loginCustomerId? }` for an OAuth client from a Google Cloud project with the Data Manager API enabled, and a refresh token for a Google account with access to the Google Ads account, granted the `https://www.googleapis.com/auth/datamanager` scope. `loginCustomerId` is the manager account when the user signs in through one. No developer token is needed. Accept the Customer Match terms in Google Ads. Config: `customerId` (dashes optional). Herald sends no consent signals, so Google treats them as unspecified and members in the EEA may not be used. Processing can take up to 48 hours, and a list needs at least 100 active matched members to serve. - **LinkedIn.** Secret: JSON `{ clientId, clientSecret, refreshToken }` for an app with the Advertising API and the Audiences program (`rw_dmp_segments`, granted by LinkedIn on request), authorized by a member with a role other than Viewer on the ad account. Config: `adAccountId`. Emails only. LinkedIn has no replace-all, so Herald sends only the difference from what it sent before. Matching takes 24 to 48 hours, and an audience needs at least 300 matched members to deliver. **Amazon Ads.** Not synced and no CSV format is available: Amazon's hashed customer lists go through Amazon Ads Data Manager, which needs manager account access and an approved Amazon Ads API application. It is on the roadmap. ### Common errors | Message | Cause | Fix | |---|---|---| | `Meta: <message>`, `Google Ads: <message>` or `LinkedIn: <message>` | Shown on the audience as its last error: the platform refused the upload | Check the account's access and terms for customer lists | | `Sign-in failed: <reason>` or `The credentials are not JSON` | The credentials can't sign in | Paste current credentials | | `Add 1 to 10 audiences` or `Each audience needs a segment` | Saving the integration: audiences missing | Add an audience with a segment | ## Troubleshooting - **A webhook keeps re-sending a batch.** Your endpoint must answer 2xx within 10 seconds. - **The CSV request answers 403.** The key lacks the `exports.read` scope. - **The CSV request answers 400.** The range is longer than 31 days. - **An audience stays empty or small.** Check the pair's last error, then the platform's minimum matched size above. Source: https://heraldsdk.com/docs/integrations/reporting.md --- # iOS API > Every public type, method and property in the four iOS libraries (core, UI, notification service and Live Activity), with signatures, parameters and threading notes. This page lists every public symbol in the iOS SDK, version 0.4.0, grouped by area. It is written from the package source. The package has four libraries: | Library | Import | Platforms | Use it in | |---|---|---|---| | `HeraldSDK` | `import HeraldSDK` | iOS 16, macOS 13 | Your app target | | `HeraldUI` | `import HeraldUI` | iOS 16 | Your app target, for the default feed and in-app views | | `HeraldNotificationService` | `import HeraldNotificationService` | iOS 16 | Your Notification Service Extension target only | | `HeraldLiveActivity` | `import HeraldLiveActivity` | iOS 16 (Live Activities need iOS 18) | Your widget extension target, for Live Activities | | `HeraldPushStory` | `import HeraldPushStory` | iOS 16 | Your Notification Content Extension target only, for [push stories](/docs/push-notifications/push-stories) (0.7.0+) | ## Threading - Every method on `Herald` can be called from any thread. It returns at once, never throws, and runs in the order you called it. Invalid input is logged and skipped. - Calls made before `configure` are kept, up to 1,000, and applied once it runs. Later ones are dropped with a warning. - Members marked **main actor** must be used from the main actor: `inAppMessageDelegate`, `inAppMessagePresenter`, `deepLinkHandler`, `openDeepLink(_:)`, `ContentCardStore` and everything in `HeraldUI`. ## Setup ### `Herald.configure` ```swift static func configure(_ configuration: HeraldConfiguration) static func configure(appKey: String, endpoint: URL, options: (inout HeraldConfiguration) -> Void = { _ in }) ``` Starts the SDK. Call it once, early in app launch. A second call is ignored with a warning. | Parameter | Type | Description | |---|---|---| | `configuration` | `HeraldConfiguration` | All settings | | `appKey` | `String` | The connection's app key, from the **Mobile SDK** card | | `endpoint` | `URL` | Your Herald base URL, for example `https://YOUR_HERALD_HOST` | | `options` | closure | Changes settings on a configuration that starts from the defaults | ```swift Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!) { options in options.deviceDataCollection = .minimal options.logLevel = .debug } ``` ### `Herald.shared`, `Herald.sdkVersion` ```swift static let shared: Herald static let sdkVersion: String // "0.6.0" ``` `shared` is the only instance. `sdkVersion` is sent with every batch. ### `HeraldConfiguration` ```swift struct HeraldConfiguration: Sendable { init(appKey: String, endpoint: URL) } ``` | Property | Type | Default | Description | |---|---|---|---| | `appKey` | `String` | | Sent as the `x-herald-app-key` header | | `endpoint` | `URL` | | Base URL of the Herald API | | `deviceDataCollection` | `DeviceDataCollection` | `.standard` | Which device data tiers are sent | | `flushInterval` | `TimeInterval` | `10` | Seconds between automatic flushes in the foreground | | `flushAt` | `Int` | `20` | Queued event count that starts a flush | | `foregroundSessionTimeout` | `TimeInterval` | `1800` | Seconds of inactivity in the foreground before the next activity starts a new session. A cold start within it of the last activity continues the session. 0.6.0 and later. | | `backgroundSessionTimeout` | `TimeInterval` | `1800` | Seconds in the background before the next activity starts a new session. 0.6.0 and later. | | `sessionTimeout` | `TimeInterval` | `1800` | Deprecated in 0.6.0. Setting it sets both timeouts; reading it returns `foregroundSessionTimeout`. | | `trackLifecycleEvents` | `Bool` | `true` | Sends `$app_installed`, `$app_updated`, `$app_opened`, `$app_foreground` and `$app_background` ([Lifecycle events](/docs/reference/event-payload#lifecycle-events)). 0.6.0 and later. | | `trackDeepLinks` | `Bool` | `true` | Sends `$deep_link_opened` when a deep link goes through `openDeepLink` or a push tap. 0.6.0 and later. | | `trackDeepLinkQuery` | `Bool` | `false` | Adds the link's query string to `$deep_link_opened`. Off by default because a query can hold personal data. 0.6.0 and later. | | `maxQueuedEventAge` | `TimeInterval` | `2592000` | Seconds (30 days). Queued events older than this are dropped before a batch is built and counted in `dropped`; Herald rejects SDK events more than 30 days old. 0.6.0 and later. | | `inAppMinimumInterval` | `TimeInterval` | `30` | Minimum seconds between two triggered in-app messages | | `logLevel` | `HeraldLogLevel` | `.warning` | Lowest level written to the unified log | | `crashReports` | `Bool` | `false` | iOS only. When `true`, sends Apple MetricKit crash and hang reports to Herald (`POST /api/v1/sdk/diagnostics`). A report holds no user id and no device id. iOS delivers a report on the next launch after a crash, usually the day after. Reports that fail to send wait on the device (newest 50) and go out on the next launch. Nothing is sent while the SDK is disabled, and `wipeData()` deletes waiting reports. | | `trackExternalPushes` | `Bool` | `true` | 0.6.0+. Records a tapped push that isn't from Herald, forwarded to `handleNotificationResponse`, as `$external_push`, so the push limit counts it. Silent pushes and local notifications are never recorded. | ### DeviceDataCollection ```swift enum DeviceDataCollection: String, Sendable { case standard, minimal } ``` | Case | Sends | |---|---| | `standard` | Tier 1 and tier 2: adds time zone, locale, language, device model, screen, push permission and network type | | `minimal` | Tier 1 only: device ID, app, OS, SDK version, region, sessions and message interactions | ### `HeraldLogLevel` ```swift enum HeraldLogLevel: Int, Sendable, Comparable { case none, error, warning, info, debug } ``` See [Logging and debugging](/docs/operations/logging-and-debugging). ## Identity ### identify ```swift func identify(userId: String, traits: [String: HeraldValue] = [:]) ``` Identifies the current user. A different ID from the current one ends the session, clears the previous user's token, cards and messages, and starts a new session. After identifying, the SDK sends the device's push token again for this user, and fetches the user's messages when the device was anonymous. | Parameter | Type | Description | |---|---|---| | `userId` | `String` | Your stable user ID, 1 to 200 characters. The console calls it the External ID. | | `traits` | `[String: HeraldValue]` | Attributes to merge into the profile. Keys 1 to 255 characters; values string, number, bool, null or an array of strings | ### setUserToken ```swift func setUserToken(_ token: String?) ``` Sets the identity verification token for the current user: the hex HMAC-SHA256 of the External ID, minted by your backend. `nil` or an empty string clears it. Call it immediately after `identify`. A new token starts a fetch of the user's cards and messages. See [Users and identity](/docs/concepts/users-and-identity#user-tokens-and-verification-modes). ### reset ```swift func reset() ``` Signs the user out on this device. Ends the session, clears the External ID, token, cards, in-app messages and pending messages, starts a new anonymous session and sends the push token again. The device ID stays. In-app history is kept per user. ### `heraldId` ```swift var heraldId: String? { get } ``` The User ID of the identified person, such as `"7K3M-9QXA"`, for a "Support ID" line on your settings or help screen. `nil` until the first accepted batch for the user the batch is verified as (any claimed user under Off; never under Optional without a token), and again after `reset()` or a switch to another user. Cached across launches. Read-only and safe from any thread. See [Support ID](/docs/concepts/users-and-identity#support-id). ## Events and attributes ### track ```swift func track(_ event: String, properties: [String: HeraldValue] = [:], schemaVersion: String? = nil) ``` Records a custom event and evaluates in-app messages with an event trigger. | Parameter | Type | Description | |---|---|---| | `event` | `String` | Event name, 1 to 255 characters | | `properties` | `[String: HeraldValue]` | Any JSON values; keys up to 255 characters; numbers must be finite | | `schemaVersion` | `String?` | 0.6.0 and later. The [event schema](/docs/concepts/event-schemas) version to check the event against, such as `"1-0-0"`. `nil` (the default) checks it against the latest version. A value that isn't a version like `1-0-0` is left off with a debug log; the event is still sent | ### trackExternalPush ```swift func trackExternalPush(messageId: String? = nil, category: ExternalPushCategory = .other, source: String? = nil) ``` 0.6.0+. Reports a push your app sent itself, as `$external_push`, so the push limit counts it. Never include the push's title or body. | Parameter | Type | Description | |---|---|---| | `messageId` | `String?` | Up to 200 characters. The same ID your backend reports, so the push counts once | | `category` | `ExternalPushCategory` | `.transactional`, `.marketing` or `.other` | | `source` | `String?` | Up to 100 characters, such as `"orders"` | A longer `messageId` or `source` is logged and the call is skipped. ### screen ```swift func screen(_ name: String, properties: [String: HeraldValue] = [:]) ``` Records a screen view. Same rules as `track`. Screen views do not trigger in-app messages. ### trackPurchase ```swift func trackPurchase(productId: String, price: Double, currency: String, quantity: Int = 1, properties: [String: HeraldValue] = [:]) ``` | Parameter | Type | Description | |---|---|---| | `productId` | `String` | 1 to 255 characters | | `price` | `Double` | Finite number | | `currency` | `String` | 3-letter ISO 4217 code; converted to upper case | | `quantity` | `Int` | 1 or more | | `properties` | `[String: HeraldValue]` | Same rules as `track` | ### setAttribute, setAttributes ```swift func setAttribute(_ key: String, _ value: HeraldValue) func setAttributes(_ attributes: [String: HeraldValue]) ``` Merges attributes into the user's profile. Keys 1 to 255 characters; values string, finite number, bool, null or an array of strings. Do not start your own keys with `$`. An invalid `$email` or `$phone` is dropped with a warning and the other keys are sent. ### setEmail, setPhone ```swift func setEmail(_ email: String?) func setPhone(_ phone: String?) ``` Set the reserved `$email` and `$phone` attributes, which Herald stores as the user's email and SMS contacts. The phone number must be E.164, for example `+15551234567`. `nil` sends a null value. An invalid value is dropped with a warning. ### setSubscription ```swift func setSubscription(_ channel: SubscriptionChannel, _ state: SubscriptionState) enum SubscriptionChannel: String, Sendable, Codable { case push, email, sms } enum SubscriptionState: String, Sendable, Codable { case subscribed, unsubscribed, optedIn } // optedIn = "opted_in" ``` Records the user's opt-in state for a channel. A push opt-in made before the APNs token exists waits for the token. An opt-out is sent at once. ### setLocation ```swift func setLocation(latitude: Double, longitude: Double) ``` Stores a location your app obtained itself, as the reserved `$latitude` and `$longitude` attributes on the device record. Latitude must be -90 to 90 and longitude -180 to 180; other values are logged and skipped. The SDK never reads location on its own. ## Consent 0.6.0+. ```swift func setConsent(basis: ConsentBasis, documentId: String? = nil, documentVersion: String? = nil) func clearConsent() ``` Records the lawful basis your app collects data under. `ConsentBasis` is `.consent`, `.contract`, `.legalObligation`, `.vitalInterests`, `.publicTask` or `.legitimateInterests` (the GDPR lawful bases). `documentId` and `documentVersion` name your policy or terms, at most 100 characters each; a longer one is logged and the call skipped. The record and the time of the call are persisted and sent in each batch's `context.consent` until `clearConsent()`. Herald keeps it on the device and on the person, where admins see it on the person's page. This is a record for your compliance, not enforcement: it doesn't change what the SDK collects. Use `deviceDataCollection` or `setEnabled(false)` for that. See [Consent and opt-out](/docs/data-and-privacy/consent-and-opt-out). ## Remote config 0.6.0+. The SDK fetches the app's SDK settings (Settings, SDK settings in the console) at launch and on a foreground at most once an hour, with no user or device id. It caches the last good response on disk and applies the cached one at launch, before the fetch. A remote value overrides `flushInterval`, `foregroundSessionTimeout`, `backgroundSessionTimeout`, `deviceDataCollection`, `trackLifecycleEvents`, `trackExternalPushes` or `trackDeepLinks`; a setting left at "Use app's value" keeps yours. A network or parse error keeps what is applied, and startup never waits for the fetch. Nothing is fetched while `setEnabled(false)` is in effect. With "Collect events" off, the SDK records and sends nothing (crash reports included), skips message syncs and clears its queue. Push tokens and subscription changes are still queued, not sent, and go out when collection resumes, with the current push token, so a device that registered or unsubscribed meanwhile isn't lost. It keeps fetching config, so turning it back on resumes collection. The cached settings belong to the app key they were fetched with: a different key starts from your configuration. ```swift var remoteConfigVersion: String? { get } ``` The version of the settings in use (cached or fetched), for debugging; nil before any was fetched. ## Data control | Method | Description | |---|---| | `func flush()` | Sends queued events now, unless a server-requested retry delay is still running | | `func flush(timeout: Duration) async -> Bool` | 0.5.0+. Sends queued events now and waits. Returns `true` once every event recorded before the call has been accepted by Herald; `false` on timeout, offline, inside a server-requested retry delay, while the SDK is off, or when Herald refused an event (a dropped batch, or an event listed in `rejected`). Events recorded after the call don't hold it up. | | `func setEnabled(_ enabled: Bool)` | Turns all collection, sending and message display off or on. Persisted across launches. Turning it off first sends one best-effort push unsubscribe for the device and hides cached content cards until it is turned back on. Turning it back on re-sends the push token and a push subscription of subscribed when the device still has its token and notification permission. | | `var isEnabled: Bool` | Read-only. `false` after `setEnabled(false)` or `wipeData()` until `setEnabled(true)`. Reflects those calls at once; before `configure` has loaded the state it reads the saved opt-out from disk. Cheap and safe from any thread. | | `func wipeData()` | Sends one best-effort push unsubscribe for the device, then deletes every file and record the SDK keeps on the device (cached cards included), generates a new device ID and leaves the SDK off until `setEnabled(true)` | ## Push ### requestPushAuthorization ```swift func requestPushAuthorization() async -> Bool ``` Asks for alert, sound and badge permission. When granted, registers with APNs. Records the push subscription: opted in (sent after the APNs token arrives) or unsubscribed. Returns whether permission was granted; `false` on platforms without push. ### setPushToken ```swift func setPushToken(_ token: Data) ``` Forward the token from `application(_:didRegisterForRemoteNotificationsWithDeviceToken:)`. The SDK sends it as lowercase hex, with the APNs environment (`sandbox` for simulator and development-signed builds, `production` otherwise) and your bundle ID. ### handleNotificationResponse ```swift @discardableResult nonisolated func handleNotificationResponse(_ response: UNNotificationResponse) -> Bool @discardableResult nonisolated func handleNotificationResponse(userInfo: [AnyHashable: Any], actionIdentifier: String) -> Bool ``` Forward from `userNotificationCenter(_:didReceive:withCompletionHandler:)`. Callable from any isolation. Returns `false` when the notification did not come from Herald. `$app_opened` reports `from_push: true` only when this call reaches the SDK before the app becomes active. Scene-based apps, including SwiftUI apps, usually get the response after activation, so they usually report `false` even for a launch from a push. | Action | What the SDK logs | Then | |---|---|---| | Default tap | A push `open` | Evaluates `push_open` triggers; opens the push's `deeplink` | | Action button | A push `open`, then a `button` with the button ID | Evaluates `push_open` triggers; opens the button's `deeplink`, else the push's | | Dismiss (category with a custom dismiss action) | A push `dismiss` | Nothing opens | Opens and button taps are logged at most once per decision. With `trackExternalPushes` on, a tap (not a dismiss) on a push that isn't from Herald is recorded as `$external_push` and the call returns `false`. Its `message_id` is the payload key `herald_external_id`, else the notification's request identifier; its category is `herald_category` (`transactional`, `marketing` or `other`), else `other`. ### handleRemoteNotification ```swift @MainActor func handleRemoteNotification(_ userInfo: [AnyHashable: Any]) async -> Bool ``` Handles a Herald sync push: a silent push (`content-available: 1`) with `herald_sync` set to `"1"`. Returns `true` after refreshing content cards and in-app messages (or after 25 seconds at most, so the completion handler is called within iOS's background time; before `configure` it starts the refresh and returns `true` at once), `false` for any other push. It never shows anything or logs an open, and skips a sync push that arrives within 30 seconds of the last one. Call it from `application(_:didReceiveRemoteNotification:fetchCompletionHandler:)` and pass `.newData` or `.noData` to the completion handler. Needs the Remote notifications background mode. See [Silent push](/docs/push-notifications/silent-push). ### registerPushCategories ```swift func registerPushCategories(_ categories: [HeraldPushCategory]) ``` Registers notification categories for action buttons. Categories with other IDs are kept; one with the same ID is replaced. Call at launch. ### `HeraldPushCategory` ```swift struct HeraldPushCategory: Sendable, Hashable { static let maxButtons: Int // 3 let id: String let buttons: [Button] // at most 3; extras are dropped init(id: String, buttons: [Button]) struct Button: Sendable, Hashable { let id: String let title: String let opensApp: Bool // default true; needed to open a deep link let destructive: Bool // default false; shows the button in red init(id: String, title: String, opensApp: Bool = true, destructive: Bool = false) } } ``` A push shows these buttons when its APNs payload names the category in `aps.category`. ## Content cards ### contentCards ```swift let contentCards: ContentCardStore ``` The current user's cards. See `ContentCardStore` below. ### refreshContentCards ```swift func refreshContentCards() ``` Fetches the latest cards and in-app messages now. The SDK also fetches at session start and when an anonymous device is identified. ### logImpression, logClick, logDismissal (cards) ```swift func logImpression(_ card: ContentCard) func logClick(_ card: ContentCard) func logDismissal(_ card: ContentCard) ``` For custom card UIs. Each logs an interaction with the card's decision ID and updates `viewed`, `clicked` or hides the card. `logDismissal` hides the card on this device and remembers it. The `HeraldUI` feed calls these for you. ### ContentCardStore ```swift @MainActor final class ContentCardStore: ObservableObject { @Published private(set) var cards: [ContentCard] var updates: AsyncStream<[ContentCard]> } ``` **Main actor.** `cards` holds the unexpired, undismissed cards in server order. Observe it from SwiftUI with `@ObservedObject`. `updates` yields the current list at once, then every change. ### ContentCard ```swift struct ContentCard: Sendable, Hashable, Identifiable, Decodable ``` | Property | Type | Description | |---|---|---| | `id` | `String` | Card ID | | `type` | `CardType` | `.classic`, `.captionedImage`, `.imageOnly` | | `title`, `body`, `cta` | `String?` | Text | | `imageUrl` | `URL?` | Image | | `url` | `URL?` | Deep link or web URL opened on click | | `extras` | `[String: HeraldValue]` | Custom key-value data | | `pinned` | `Bool` | Pinned cards sort first in the default feed | | `dismissible` | `Bool` | Whether the user may dismiss it | | `categories` | `[String]` | Labels for filtering | | `createdAt` | `Date` | Creation time | | `expiresAt` | `Date?` | Hidden after this time | | `viewed`, `clicked`, `dismissed` | `Bool` | State (`var`) | | `decisionId` | `String?` | Herald decision, sent back with interactions | | `videoUrl` | `URL?` | A video to play in place of the image; `imageUrl` holds its poster (0.6.0) | | `videoPosterUrl` | `URL?` | The poster, the same as `imageUrl` | | `videoAutoplay` | `Bool` | Play muted and looped while the card is at least half visible in `ContentCardFeed`; `false` by default | | `credit` | `MediaCredit?` | The stock photo or video's creator: `name`, `profileUrl: URL?`, `sourceUrl: URL?`. A credit without a name is dropped. | `ContentCard.CardType` is a `String` enum: `classic`, `captionedImage` (`"captioned_image"`), `imageOnly` (`"image_only"`). The memberwise `init` takes every property, with defaults for all but `id` and `type`. ## In-app messages ### inAppMessageDelegate ```swift @MainActor var inAppMessageDelegate: InAppMessageDelegate? ``` **Main actor.** Held weakly. Asked when a message is about to appear. ### inAppMessagePresenter ```swift @MainActor var inAppMessagePresenter: InAppMessagePresenter? ``` **Main actor.** Draws messages. Messages are not shown while it is `nil`; setting it offers any pending message. ### deepLinkHandler, openDeepLink ```swift @MainActor var deepLinkHandler: ((URL) -> Bool)? @MainActor func openDeepLink(_ url: URL) ``` **Main actor.** `openDeepLink` passes the URL to `deepLinkHandler`; when the handler is `nil` or returns `false`, the system opens it. The SDK and `HeraldUI` use it for push, card and message clicks. From 0.6.0 each call also sends `$deep_link_opened` (`source` `push` for a push tap's link, `link` otherwise) unless `trackDeepLinks` is off. ### showNext ```swift func showNext() ``` Offers the highest-priority pending message now (ties: the one pending longest), ignoring the minimum interval. The delegate is asked again. Does nothing while a message is on screen. ### logVideoPlay, logVideoComplete ```swift func logVideoPlay(_ card: ContentCard) func logVideoComplete(_ card: ContentCard) func logVideoPlay(_ message: InAppMessage) func logVideoComplete(_ message: InAppMessage) ``` For custom displays; `HeraldUI` already calls them, once per view, when the video first starts and first reaches the end. Each logs an `interaction` with `action` `video_play` or `video_complete` and the item's decision ID. They change no viewed, clicked or dismissed state. See [Video in content cards](/docs/content-cards/authoring#video). ### logImpression, logClick, logDismissal (messages) ```swift func logImpression(_ message: InAppMessage) func logClick(_ message: InAppMessage, buttonId: String? = nil) func logDismissal(_ message: InAppMessage) ``` For custom presenters. The SDK already logs the impression when a presenter returns `true`, so do not call `logImpression` from a presenter. `logClick` with `buttonId` `nil` logs a body click; with an ID, a button click. ### debugLoadMessages, debugShowInAppMessage ```swift func debugLoadMessages(_ json: Data) func debugShowInAppMessage(_ messageId: String) ``` Debug and preview only. See [Logging and debugging](/docs/operations/logging-and-debugging#preview-messages-without-a-server). ### InAppMessage ```swift struct InAppMessage: Sendable, Hashable, Identifiable, Decodable ``` | Property | Type | Description | |---|---|---| | `id` | `String` | Message ID | | `type` | `MessageType` | `.slideup`, `.modal`, `.full`, `.html` | | `priority` | `Int` | Higher wins when several messages match | | `trigger` | `InAppTrigger` | When it is eligible | | `reEligibility` | `InAppReEligibility` | How often it may show | | `expiresAt` | `Date?` | Not shown after this time | | `content` | `Content` | Text, image, buttons, HTML | | `style` | `Style` | Per-message colors; `nil` fields use the theme | | `decisionId` | `String?` | Herald decision | Nested types: | Type | Members | |---|---| | `InAppMessage.MessageType` | `slideup`, `modal`, `full`, `html` | | `InAppMessage.SlideFrom` | `top`, `bottom` | | `InAppMessage.ButtonAction` | `.close`, `.deeplink(URL)`, `.url(URL)`; `var url: URL?` | | `InAppMessage.Button` | `id: String`, `text: String`, `action: ButtonAction` | | `InAppMessage.Content` | `header`, `body`, `html: String?`; `imageUrl: URL?`; `videoUrl: URL?`, `videoPosterUrl: URL?` (0.6.0); `credit: MediaCredit?`; `buttons: [Button]`; `slideFrom: SlideFrom?`; `dismissAfterSeconds: Double?` | | `InAppMessage.Style` | `backgroundColor`, `textColor`, `buttonColor`, `buttonTextColor: String?` (hex such as `#101828`); `cornerRadius: Double?` | Every nested type has a public memberwise `init` with defaults, which is useful for previews and tests. ### InAppTrigger, PropertyFilter, InAppReEligibility ```swift enum InAppTrigger: Sendable, Hashable, Decodable { case sessionStart case event(name: String, propertyFilters: [PropertyFilter]) case pushOpen } struct PropertyFilter: Sendable, Hashable, Decodable { enum Operator: String { case eq, neq, gt, gte, lt, lte, contains, exists } let key: String let op: Operator let value: HeraldValue init(key: String, op: Operator, value: HeraldValue = .null) } enum InAppReEligibility: Sendable, Hashable, Decodable { case once case afterHours(Double) } ``` A filter on a property that is missing or null is false for every operator, `exists` included. ### InAppMessageDelegate ```swift @MainActor protocol InAppMessageDelegate: AnyObject { func shouldDisplay(_ message: InAppMessage) -> InAppMessageDisplayChoice } enum InAppMessageDisplayChoice: Sendable { case display, later, discard } ``` **Main actor.** Can be asked more than once for the same message, so keep it free of side effects. | Choice | Effect | |---|---| | `display` | Show now | | `later` | Keep it pending; offered again automatically or with `showNext()` | | `discard` | Drop this occurrence; the message stays eligible for its next trigger | ### InAppMessagePresenter ```swift @MainActor protocol InAppMessagePresenter: AnyObject { func present(_ message: InAppMessage, onClose: @escaping @MainActor @Sendable () -> Void) -> Bool } ``` **Main actor.** Return `true` only when the message is on screen; the SDK then logs the impression and records it as shown. Return `false` when it cannot show now, and do not call `onClose`; the message stays pending. After returning `true`, log clicks with `logClick(_:buttonId:)`, log a dismissal with `logDismissal(_:)` when the user closed it without clicking, and call `onClose` exactly once when it leaves the screen. See [Custom views](/docs/in-app-messages/custom-views). ## Values ### `HeraldValue` ```swift enum HeraldValue: Sendable, Hashable, Codable { case string(String), number(Double), bool(Bool), array([HeraldValue]), object([String: HeraldValue]), null var stringValue: String? { get } var numberValue: Double? { get } var boolValue: Bool? { get } var arrayValue: [HeraldValue]? { get } var objectValue: [String: HeraldValue]? { get } } ``` A JSON value for properties, traits, attributes and card extras. It conforms to the string, integer, float, boolean, array, dictionary and nil literal protocols, so `["minutes": 32, "plan": "free"]` works directly. Whole numbers are encoded without a fraction. ## `HeraldUI` Every `HeraldUI` type is **main actor** (SwiftUI views and the presenter) and iOS only. ### `Herald.useDefaultInAppUI` ```swift @MainActor @discardableResult static func useDefaultInAppUI(theme: HeraldTheme = HeraldTheme(), viewProvider: HeraldInAppPresenter.ViewProvider? = nil) -> HeraldInAppPresenter ``` Creates the default presenter and sets it as `Herald.shared.inAppMessagePresenter`. Call once after `configure`. ### `HeraldInAppPresenter` ```swift @MainActor final class HeraldInAppPresenter: InAppMessagePresenter { typealias ViewProvider = @MainActor (InAppMessage, InAppMessageActions) -> AnyView? var theme: HeraldTheme var viewProvider: ViewProvider? init(theme: HeraldTheme = HeraldTheme(), viewProvider: ViewProvider? = nil) func present(_ message: InAppMessage, onClose: @escaping @MainActor @Sendable () -> Void) -> Bool } ``` Draws each message in its own window on the foreground window scene. `viewProvider` returns your view for a message, or `nil` for the default. `present` returns `false` while another message is up or when no scene is in the foreground. ### InAppMessageActions ```swift @MainActor final class InAppMessageActions { let message: InAppMessage func buttonClicked(_ button: InAppMessage.Button) func bodyClicked(url: URL? = nil) func clicked(buttonId: String) func dismiss() } ``` What a message view reports. Each call after the message is down does nothing. | Method | Logs | Then | |---|---|---| | `buttonClicked(_:)` | A button click | Opens the button's URL through `openDeepLink`, then closes | | `bodyClicked(url:)` | A body click | Opens `url` when given, then closes | | `clicked(buttonId:)` | A button click (empty IDs ignored) | Keeps the message up | | `dismiss()` | A dismissal, only when nothing was clicked | Closes | ### Message views ```swift struct SlideupMessageView: View { init(message: InAppMessage, actions: InAppMessageActions) } struct ModalMessageView: View { init(message: InAppMessage, actions: InAppMessageActions) } struct FullScreenMessageView: View { init(message: InAppMessage, actions: InAppMessageActions) } struct HTMLMessageView: View { init(message: InAppMessage, actions: InAppMessageActions) } struct DefaultInAppMessageView: View { init(message: InAppMessage, actions: InAppMessageActions) } ``` The default view for each type. `DefaultInAppMessageView` picks one by `message.type`. ### ContentCardFeed ```swift struct ContentCardFeed<CardContent: View>: View { init( filter: @escaping (ContentCard) -> Bool = { _ in true }, order: @escaping (ContentCard, ContentCard) -> Bool = ContentCardFeedDefaults.order, emptyMessage: LocalizedStringKey = "No updates right now", onCardClick: ((ContentCard) -> Void)? = nil, @ViewBuilder cardContent: @escaping (_ card: ContentCard, _ onClick: @escaping () -> Void) -> CardContent ) } extension ContentCardFeed where CardContent == ContentCardView { init(filter:order:emptyMessage:onCardClick:) // same defaults, default card views } ``` | Parameter | Description | |---|---| | `filter` | Keeps the cards it returns `true` for | | `order` | Sort order (`areInIncreasingOrder`); pinned first, then newest, by default. Equal cards keep server order. | | `emptyMessage` | Shown when there are no cards; looked up in your app's strings | | `onCardClick` | Runs after the click is logged. When `nil`, the card's `url` goes to `deepLinkHandler`, then to the environment's `openURL` | | `cardContent` | Draws one card; call `onClick` when it is tapped | The feed logs an impression once per card per session when at least half the card is visible. Dismissible cards can be swiped away, or dismissed with the VoiceOver "Dismiss" action. ### ContentCardFeedDefaults ```swift enum ContentCardFeedDefaults { static func order(_ a: ContentCard, _ b: ContentCard) -> Bool // pinned first, then newest } ``` ### Card views ```swift struct ContentCardView: View { init(card: ContentCard, onClick: @escaping () -> Void) } struct ClassicContentCardView: View { init(card: ContentCard, onClick: @escaping () -> Void) } struct CaptionedImageContentCardView: View { init(card: ContentCard, onClick: @escaping () -> Void) } struct ImageOnlyContentCardView: View { init(card: ContentCard, onClick: @escaping () -> Void) } ``` `ContentCardView` picks the view for `card.type`. Cards are tappable only when they have a `url`. ### `HeraldImage` ```swift struct HeraldImage: View { init(url: URL?, aspectRatio: CGFloat, accessibilityLabel: String? = nil) } ``` A remote image at a fixed aspect ratio, decoded at the drawn size, with a flat placeholder while it loads or when it fails. Loads `https` and `http` URLs and files inside the app bundle, up to 20 MB. Hidden from VoiceOver unless `accessibilityLabel` is set. ### Theme ```swift struct HeraldTheme: Sendable { var lightColors: HeraldColors // .light var darkColors: HeraldColors // .dark var typography: HeraldTypography var cornerRadius: CGFloat // 12 var spacing: CGFloat // 16 var darkMode: Bool? // nil follows the system init(lightColors:darkColors:typography:cornerRadius:spacing:darkMode:) // all defaulted func colors(for colorScheme: ColorScheme) -> HeraldColors } struct HeraldColors: Sendable, Hashable { var background, surface, onSurface, onSurfaceVariant, accent, onAccent, outline, scrim: Color static let light: HeraldColors static let dark: HeraldColors } struct HeraldTypography: Sendable { var title: Font // .headline var body: Font // .subheadline var button: Font // .subheadline.weight(.semibold) var caption: Font // .footnote } struct MessageColors: Sendable, Hashable { var background, text, button, buttonText: Color var cornerRadius: CGFloat init(style: InAppMessage.Style, theme: HeraldTheme, colorScheme: ColorScheme) } extension EnvironmentValues { var heraldTheme: HeraldTheme } extension View { func heraldTheme(_ theme: HeraldTheme) -> some View } extension Color { init?(heraldHex hex: String?) } // "#RRGGBB" or "#AARRGGBB" ``` `MessageColors` applies a message's style fields on top of the theme. An invalid hex value falls back to the theme. See [Theming and dark mode](/docs/in-app-messages/theming-and-dark-mode). ## `HeraldNotificationService` This library depends on Foundation and UserNotifications only, so it links into an app extension. ### `HeraldNotificationService` ```swift open class HeraldNotificationService: UNNotificationServiceExtension, @unchecked Sendable { open var imageTimeout: TimeInterval { get } // 20 } ``` Subclass it as your extension's principal class. It adds `herald_actions` buttons, then attaches the push image. When time runs out it delivers the best content it has. ### `HeraldRichPush` ```swift enum HeraldRichPush { static let imageKeys: [String] // ["image_url", "image"] static let defaultTimeout: TimeInterval // 20 static let actionsKey: String // "herald_actions" static let maxActions: Int // 3 static func prepare(_ content: UNNotificationContent, timeout: TimeInterval = defaultTimeout, session: URLSession = .shared) async -> UNNotificationContent static func applyActions(to content: UNNotificationContent) async -> UNNotificationContent static let mediaBudget: TimeInterval // 25 static func attachMedia(to content: UNNotificationContent, timeout: TimeInterval = defaultTimeout, budget: TimeInterval = mediaBudget, session: URLSession = .shared) async -> UNNotificationContent static func attachImage(to content: UNNotificationContent, timeout: TimeInterval = defaultTimeout, session: URLSession = .shared) async -> UNNotificationContent static func imageURL(in userInfo: [AnyHashable: Any]) -> URL? } ``` | Function | Description | |---|---| | `prepare` | `applyActions`, then `attachMedia` (the video, else the image). Returns the content unchanged when there is nothing to add. | | `applyActions` | Registers a category for the payload's `herald_actions` and sets it on the content. Unchanged when there are no actions or `aps.category` is already set. Keeps at most 10 such categories. | | `attachMedia(to:timeout:budget:session:)` | Attaches the push's `video_url` as a movie (HTTPS, `video/mp4` or `video/quicktime`, at most 10 MB, within 60% of `budget`, 25 seconds by default), else the image as `attachImage` does. Returns the content unchanged when both fail. `prepare` uses it. | | `attachImage` | Downloads the first HTTPS image URL and attaches it. Unchanged when the download fails, times out, is over 10 MB, or is not JPEG, PNG, GIF or HEIC. | | `imageURL(in:)` | The first `imageKeys` value that is an HTTPS URL | ### `HeraldStory` 0.7.0+. Push stories in the service extension: `HeraldNotificationService` attaches every page's image and registers the `HERALD_STORY` category (one Open button, renamed with `storyOpenTitle`) when the payload has `herald_story`. ```swift public struct HeraldStoryPage: Equatable, Sendable { public let imageURL: URL, title: String, subtitle: String, deeplink: URL? } public enum HeraldStory { static let pagesKey: String // "herald_story" static let category: String // "HERALD_STORY" static let pageActionPrefix: String // "herald_story_page_" static func attachmentId(_ index: Int) -> String // "herald-story-<index>" static func pages(in userInfo: [AnyHashable: Any]) -> [HeraldStoryPage] static func attachImages(to content: UNNotificationContent, pages: [HeraldStoryPage], timeout: TimeInterval, session: URLSession = .shared) async -> UNNotificationContent } ``` `pages(in:)` is empty unless at least 2 pages have an HTTPS image, a title and a subtitle. ## `HeraldPushStory` 0.7.0+. For a Notification Content Extension; depends on `HeraldNotificationService`, not `HeraldSDK`. ```swift open class HeraldStoryViewController: UIViewController, UNNotificationContentExtension { open var previousTitle: String { get } // "Previous" open var nextTitle: String { get } // "Next" open var openTitle: String { get } // "Open" } ``` Make a subclass the extension's principal class and set `UNNotificationExtensionCategory` to `HERALD_STORY`. It shows one page at a time with Previous, Next and Open. Open forwards the action `herald_story_page_<index>` to the app, where `handleNotificationResponse(_:)` logs a push open and a `button` interaction with that id and opens the page's deep link. See [Push stories](/docs/push-notifications/push-stories). ## `HeraldLiveActivity` This library does not depend on `HeraldSDK`, so it links into a widget extension. `HeraldSDK` depends on it. See [Live Activities setup](/docs/live-activities/setup). ### `HeraldActivityAttributes` ```swift public struct HeraldActivityAttributes: Codable, Hashable, Sendable { // ActivityAttributes on iOS 16.1 and later public let campaignId: String public let deeplink: String? public init(campaignId: String, deeplink: String? = nil) public struct ContentState: Codable, Hashable, Sendable { public let title: String public let body: String public let progress: Double? // 0 to 1, for progress mode public let endsAt: Double? // Unix seconds public init(title: String, body: String, progress: Double? = nil, endsAt: Double? = nil) } } ``` The attributes of the Live Activity Herald starts with a push-to-start. The type name and field names are part of the wire format, so do not wrap or rename them. ### `HeraldLiveActivityWidget` ```swift @available(iOS 16.1, *) public struct HeraldLiveActivityWidget: Widget { public init() } ``` Add `HeraldLiveActivityWidget()` to your widget extension's `WidgetBundle`, and set `NSSupportsLiveActivities` to YES in the app's Info.plist. ## `HeraldGeofence` 0.7.0+, not released yet. Opt-in geofence monitoring, a separate library product so apps that don't use it never link CoreLocation. Depends on `HeraldSDK`. See [Geofences](/docs/concepts/geofences). ```swift import HeraldGeofence extension Herald { func enableGeofences() func disableGeofences() } ``` `enableGeofences()` downloads the app's geofence list (`GET /api/v1/sdk/geofences`, no location sent) and monitors the 20 nearest with Core Location, re-picked on significant location change when there are more. Call it after `configure`, at every launch, once the app holds "Always" location permission; without it the call logs a warning and does nothing. The SDK never asks for permission and reads no location before this call. Crossings send `$geofence_enter` / `$geofence_exit` with `geofence_id` and `geofence_name`, at most one per geofence and direction every 5 minutes, and nothing while the SDK is off. The **Geofences** SDK setting set to Off stops monitoring. `disableGeofences()` stops monitoring Herald's regions until `enableGeofences()` is called again; regions your app monitors itself are never touched. ## Related - [Android API](/docs/reference/android-api) - [Event payload spec](/docs/reference/event-payload) - [Limits](/docs/reference/limits) Source: https://heraldsdk.com/docs/reference/ios-api.md --- # Android API > Every public class, function and property in the three Android modules (core, UI and FCM), with signatures, parameters and threading notes. This page lists every public symbol in the Android SDK, version 0.4.0, grouped by area. It is written from the module source. | Module | Package | Use it for | |---|---|---| | `herald-core` | `com.herald.sdk`, `com.herald.sdk.push` | Everything except UI and FCM | | `herald-ui` | `com.herald.ui` | The default feed and in-app views (Jetpack Compose) | | `herald-fcm` | `com.herald.fcm` | FCM token sync and notification display | ## Threading - Every function on `Herald` can be called from any thread, returns at once and never throws. Work runs in call order on one background thread named `herald-sdk`. Errors are logged. - Calls made before `configure` are kept, up to 1,000, and applied in order once it runs. Later ones are dropped with one warning. - `requestPushAuthorization` must be called from the main thread. Presenters are called on the main thread. - Functions are annotated `@JvmStatic` and, where they have defaults, `@JvmOverloads`, so Java can call `Herald.track("x")`. ## Setup ### `Herald.configure` ```kotlin fun configure(context: Context, appKey: String, endpoint: String, options: HeraldOptions = HeraldOptions()) ``` Starts the SDK. Call once, from `Application.onCreate`. Later calls are ignored with a warning. Registers activity lifecycle callbacks for sessions, flushing and in-app display. | Parameter | Type | Description | |---|---|---| | `context` | `Context` | Any context; the application context is used | | `appKey` | `String` | The connection's app key, from the **Mobile SDK** card | | `endpoint` | `String` | Your Herald base URL, for example `https://YOUR_HERALD_HOST` | | `options` | `HeraldOptions` | Settings; defaults below | ```kotlin Herald.configure( this, appKey = "YOUR_APP_KEY", endpoint = "https://YOUR_HERALD_HOST", options = HeraldOptions(deviceDataCollection = DeviceDataCollection.MINIMAL, logLevel = LogLevel.DEBUG), ) ``` ### Constants | Constant | Value | Description | |---|---|---| | `Herald.SDK_VERSION` | `"0.6.0"` | Sent with every batch | | `Herald.PUSH_PERMISSION_REQUEST_CODE` | `0x4E58` | Deprecated. The SDK reads the permission answer when the activity resumes, so apps don't need this code. It will be removed. | ### `HeraldOptions` ```kotlin data class HeraldOptions( val deviceDataCollection: DeviceDataCollection = DeviceDataCollection.STANDARD, val flushIntervalSeconds: Long = 10, val flushAt: Int = 20, @Deprecated("Use foregroundSessionTimeoutMinutes and backgroundSessionTimeoutMinutes") val sessionTimeoutMinutes: Long = 30, val inAppMinimumIntervalSeconds: Long = 30, val logLevel: LogLevel = LogLevel.WARN, val trackExternalPushes: Boolean = true, val foregroundSessionTimeoutMinutes: Long? = null, val backgroundSessionTimeoutMinutes: Long? = null, val trackLifecycleEvents: Boolean = true, val trackDeepLinks: Boolean = true, val trackDeepLinkQuery: Boolean = false, val maxQueuedEventAgeDays: Long = 30, ) ``` | Property | Description | |---|---| | `deviceDataCollection` | `STANDARD` sends tier 1 and tier 2 device data; `MINIMAL` sends tier 1 only | | `flushIntervalSeconds` | Seconds between automatic flushes while an activity is started | | `flushAt` | Queued event count that starts a flush | | `sessionTimeoutMinutes` | Deprecated in 0.6.0. Used for each timeout below that is null (the default), so setting it alone, in the constructor or in `copy`, sets both | | `inAppMinimumIntervalSeconds` | Minimum seconds between two triggered in-app messages | | `logLevel` | Lowest level written to Logcat | | `trackExternalPushes` | 0.6.0+. `herald-fcm` records an FCM message that isn't from Herald and carries a notification as `$external_push` when it reaches the app, so the push limit counts it. Data-only messages are never recorded. | | `foregroundSessionTimeoutMinutes` | Minutes of inactivity in the foreground before the next activity starts a new session. A cold start within it of the last activity continues the session. 0.6.0 and later. | | `backgroundSessionTimeoutMinutes` | Minutes in the background before the next activity starts a new session. 0.6.0 and later. | | `trackLifecycleEvents` | Sends `$app_installed`, `$app_updated`, `$app_opened`, `$app_foreground` and `$app_background` ([Lifecycle events](/docs/reference/event-payload#lifecycle-events)). Default `true`. 0.6.0 and later. | | `trackDeepLinks` | Sends `$deep_link_opened` when a deep link goes through `openUrl` or a notification tap. Default `true`. 0.6.0 and later. | | `trackDeepLinkQuery` | Adds the link's query string to `$deep_link_opened`. Default `false`, because a query can hold personal data. 0.6.0 and later. | | `maxQueuedEventAgeDays` | Queued events older than this are dropped before a batch is built and counted in `dropped`; Herald rejects SDK events more than 30 days old. Default 30. 0.6.0 and later. | ### Enums ```kotlin enum class DeviceDataCollection { STANDARD, MINIMAL } enum class LogLevel { DEBUG, INFO, WARN, ERROR, NONE } enum class SubscriptionChannel { PUSH, EMAIL, SMS } enum class SubscriptionState { SUBSCRIBED, UNSUBSCRIBED, OPTED_IN } ``` ## Identity | Function | Description | |---|---| | `fun identify(userId: String, traits: Map<String, Any?> = emptyMap())` | Identifies the user. A different ID ends the session, clears the previous user's token, cards and messages, and starts a new session. Sends the push token again for the new user, and fetches messages when the device was anonymous. | | `fun setUserToken(token: String?)` | Identity verification token for the identified user (hex HMAC-SHA256 of the External ID, from your backend). Call immediately after `identify`. Events the user queued before the token arrived are sent with it, and a new token starts a fetch of the user's cards and messages. | | `fun reset()` | Signs the user out: ends the session, clears the External ID, token, cards, messages and pending messages, takes down a message on screen, starts a new anonymous session and sends the push token again. The device ID stays. | | `val heraldId: String?` | The User ID of the identified person, such as `"7K3M-9QXA"`, for a "Support ID" line on your settings or help screen. `null` until the first accepted batch for the user the batch is verified as (any claimed user under Off; never under Optional without a token), and again after `reset()` or a switch to another user. Cached across launches. Read-only and safe from any thread. See [Support ID](/docs/concepts/users-and-identity#support-id). | `userId` is 1 to 200 characters. Traits follow the attribute rules below. ## Events and attributes | Function | Description | |---|---| | `fun track(event: String, properties: Map<String, Any?> = emptyMap(), schemaVersion: String? = null)` | Custom event; evaluates event triggers. Name 1 to 255 characters. `schemaVersion` (0.6.0 and later) names the [event schema](/docs/concepts/event-schemas) version to check it against, such as `"1-0-0"`; `null` (the default) means the latest. A value that isn't a version like `1-0-0` is left off with a debug log; the event is still sent. | | `fun screen(name: String, properties: Map<String, Any?> = emptyMap())` | Screen view. Name 1 to 255 characters. | | `fun trackExternalPush(messageId: String? = null, category: ExternalPushCategory = ExternalPushCategory.OTHER, source: String? = null)` | 0.6.0+. A push your app sent itself, as `$external_push`, so the push limit counts it. `messageId` up to 200 characters (the same ID your backend reports, so it counts once), `source` up to 100; longer values are logged and skipped. `ExternalPushCategory` is `TRANSACTIONAL`, `MARKETING` or `OTHER`. Never include the push's title or body. | | `fun handleExternalPush(data: Map<String, String>, hasNotification: Boolean, fcmMessageId: String?)` | 0.6.0+. Records a non-Herald FCM message with a notification as `$external_push` (with `trackExternalPushes` on). `herald-fcm` calls it; call it from `onMessageReceived` only in your own FirebaseMessagingService. | | `fun trackPurchase(productId: String, price: Double, currency: String, quantity: Int = 1, properties: Map<String, Any?> = emptyMap())` | Purchase. Product ID 1 to 255 characters, finite price, 3-letter currency (upper-cased), quantity 1 or more. | | `fun setAttribute(key: String, value: Any?)` | One attribute | | `fun setAttributes(attributes: Map<String, Any?>)` | Several attributes, merged into the profile | | `fun setEmail(email: String?)` | Reserved `$email`; must be a valid address | | `fun setPhone(phone: String?)` | Reserved `$phone`; must be E.164, such as `+15551234567` | | `fun setSubscription(channel: SubscriptionChannel, state: SubscriptionState)` | Opt-in state for a channel. A push opt-in waits for the FCM token; an opt-out is sent at once. | | `fun setLocation(latitude: Double, longitude: Double)` | A location your app obtained, stored on the device record as `$latitude` and `$longitude`. Out-of-range values are logged and skipped. | Property values: strings, numbers, booleans, null, lists and maps; numbers must be finite; keys up to 255 characters. Attribute values: `String`, `Number`, `Boolean`, `null`, or a `List` or `Array` of `String`; keys 1 to 255 characters. An invalid `$email` or `$phone` is dropped with a warning and the other keys are sent. ## Consent 0.6.0+. ```kotlin fun setConsent(basis: ConsentBasis, documentId: String? = null, documentVersion: String? = null) fun clearConsent() ``` Records the lawful basis your app collects data under. `ConsentBasis` is `CONSENT`, `CONTRACT`, `LEGAL_OBLIGATION`, `VITAL_INTERESTS`, `PUBLIC_TASK` or `LEGITIMATE_INTERESTS` (the GDPR lawful bases). `documentId` and `documentVersion` name your policy or terms, at most 100 characters each; a longer one is logged and the call skipped. The record and the time of the call are persisted and sent in each batch's `context.consent` until `clearConsent()`. Herald keeps it on the device and on the person, where admins see it on the person's page. This is a record for your compliance, not enforcement: it doesn't change what the SDK collects. Use `deviceDataCollection` or `setEnabled(false)` for that. See [Consent and opt-out](/docs/data-and-privacy/consent-and-opt-out). ## Remote config 0.6.0+. The SDK fetches the app's SDK settings (Settings, SDK settings in the console) at launch and on a foreground at most once an hour, with no user or device id. It caches the last good response on disk and applies the cached one at launch, before the fetch. A remote value overrides `flushIntervalSeconds`, `foregroundSessionTimeoutMinutes`, `backgroundSessionTimeoutMinutes`, `deviceDataCollection`, `trackLifecycleEvents`, `trackExternalPushes` or `trackDeepLinks`; a setting left at "Use app's value" keeps yours. A network or parse error keeps what is applied, and startup never waits for the fetch. Nothing is fetched while `setEnabled(false)` is in effect. With "Collect events" off, the SDK records and sends nothing, skips message syncs and clears its queue. Push tokens and subscription changes are still queued, not sent, and go out when collection resumes, with the current push token, so a device that registered or unsubscribed meanwhile isn't lost. It keeps fetching config, so turning it back on resumes collection. The fetch runs off the SDK thread, so sessions and events never wait for it. The cached settings belong to the app key they were fetched with: a different key starts from your options. ```kotlin val remoteConfigVersion: String? ``` The version of the settings in use (cached or fetched), for debugging; null before any was fetched. ## Data control | Function | Description | |---|---| | `fun flush()` | Sends queued events now, unless a retry delay is running | | `fun setEnabled(enabled: Boolean)` | `false` sends one best-effort push unsubscribe for the device, then stops all collection, sending and display and hides cached content cards until set back to `true`. `true` re-sends the push token and a push subscription of subscribed when the device still has its token and notifications are enabled. Persisted. | | `fun isEnabled(context: Context): Boolean` | `false` after `setEnabled(false)` or `wipeData()` until `setEnabled(true)`. Reflects those calls at once; otherwise reads the saved opt-out from disk, so it works before `configure`. `herald-fcm` checks it and does not show Herald pushes while it is `false`; check it too if you show them yourself. Cheap and safe from any thread. | | `fun wipeData()` | Sends one best-effort push unsubscribe for the device, then deletes every file and record the SDK keeps, including queued events and cached cards, and leaves the SDK off. `setEnabled(true)` starts again with a new device ID. | ## Push ### requestPushAuthorization ```kotlin fun requestPushAuthorization(activity: Activity) ``` Call from the main thread. On Android 13 and later, when `POST_NOTIFICATIONS` is not granted, shows the permission prompt and records the answer when the activity resumes: `OPTED_IN` when allowed (sent once the FCM token exists), `UNSUBSCRIBED` when denied. Below Android 13, or when already granted, records whether notifications are enabled for the app, without a prompt. From the first prompt on, device data reports the permission as `authorized` or `denied` instead of `not_determined`. ### setPushToken ```kotlin fun setPushToken(token: String) ``` The FCM registration token, 1 to 4,096 characters. `herald-fcm` calls it for you. ### handleNotificationIntent ```kotlin fun handleNotificationIntent(intent: Intent?): Boolean ``` Call from the activity that receives notification taps, in `onCreate` and `onNewIntent`, after `configure`. Returns `true` when the intent came from a Herald notification. The intent must carry this install's tap token, a random secret that `herald-fcm` and `putInto` add; an intent without it, such as one another app sends to your exported launcher activity, is ignored and returns `false`. It logs a push `open` (and then a `button` with the action ID when an action button was tapped), evaluates `push_open` triggers, cancels the notification and opens the deep link. It removes the Herald extras from the intent, so a redelivered intent is not counted twice. ### handleRemoteMessage ```kotlin fun handleRemoteMessage(data: Map<String, String>): Boolean ``` Handles a Herald sync push: a data-only FCM message with `herald_sync` set to `"1"`. Returns `true` and refreshes content cards and in-app messages; returns `false` for any other message. It never shows a notification or logs an open, and skips a sync push that arrives within 30 seconds of the last one. Called off the main thread, as `onMessageReceived` is, it returns once the refresh has finished, or after 8 seconds at most; on the main thread it returns at once. `herald-fcm` calls it for you; call it from `onMessageReceived` only in your own `FirebaseMessagingService`. See [Silent push](/docs/push-notifications/silent-push). ### canPostLiveUpdates ```kotlin fun canPostLiveUpdates(): Boolean ``` 0.7.0+. Whether Android may show Live Updates (Live Activity campaigns on Android) as promoted notifications, with a status bar chip and a place at the top of the lock screen: `NotificationManager.canPostPromotedNotifications()`. `false` below Android 16 (API 36), before `configure`, or when the person turned it off for your app; `herald-fcm` still shows the Live Update as an ongoing notification then. See [Live Activities on Android](/docs/live-activities/android). ### `HeraldPushPayload` ```kotlin package com.herald.sdk.push data class HeraldPushPayload( val decisionId: String?, val messageId: String?, val deeplink: String?, val title: String?, val body: String?, val imageUrl: String?, ) { @JvmOverloads fun putInto(intent: Intent, context: Context? = null): Intent companion object { const val KEY_DECISION_ID = "nexus_decision_id" const val KEY_MESSAGE_ID = "herald_message_id" const val KEY_DEEPLINK = "deeplink" const val KEY_TITLE = "title" const val KEY_BODY = "body" const val KEY_IMAGE = "image" const val KEY_NOTIFICATION_ID = "herald_notification_id" const val KEY_ACTION_ID = "herald_action_id" const val KEY_TAP_TOKEN = "herald_tap_token" const val NOTIFICATION_TAG = "herald" fun fromData(data: Map<String, String>): HeraldPushPayload? fun fromIntent(intent: Intent?): HeraldPushPayload? } } ``` The Herald fields of an FCM data message and of a notification tap intent. `fromData` and `fromIntent` return `null` when the message has neither a decision ID nor a message ID. `putInto` copies the decision ID, message ID and deep link into an intent as extras, plus the tap token `handleNotificationIntent` requires. It reads the token through `context`, or through the context passed to `configure` when `context` is `null`. Use these when you build your own notifications, and always build the tap intent with `putInto`: copying the extras by hand leaves out the token, so the tap is not counted and its link is not opened. ### `PushTokenSource` ```kotlin package com.herald.sdk.push object PushTokenSource { @Volatile var request: (() -> Unit)? } ``` For `herald-fcm`, not for apps. `HeraldMessagingService.syncToken` sets it to a fetch of the current FCM token. The SDK calls it when `setEnabled(true)` runs with notifications allowed and no stored token (after `wipeData()`), because FCM does not issue an unchanged token again on its own. If you use your own `FirebaseMessagingService` without `syncToken`, set it to a function that fetches the token and calls `Herald.setPushToken`. ## Content cards | Member | Description | |---|---| | `val contentCards: StateFlow<List<ContentCard>>` | The current user's cards, unexpired and not dismissed, in server order | | `fun refreshContentCards()` | Fetches cards and in-app messages now. The SDK also fetches at session start and when an anonymous device is identified. | | `fun logImpression(card: ContentCard)` | Logs an impression and sets `viewed`. At most one impression per card per session is sent. | | `fun logClick(card: ContentCard)` | Logs a click and sets `clicked` | | `fun logDismissal(card: ContentCard)` | Logs a dismissal and hides the card on this device | | `fun logVideoPlay(card: ContentCard)` | Logs `video_play` for a custom display (0.6.0); `herald-ui` does it once per play | | `fun logVideoComplete(card: ContentCard)` | Logs `video_complete` for a custom display (0.6.0) | A call for a card the SDK no longer has is logged and ignored. ### ContentCard ```kotlin data class ContentCard( val id: String, val type: ContentCardType, val title: String?, val body: String?, val imageUrl: String?, val cta: String?, val url: String?, val extras: Map<String, Any?>, val pinned: Boolean, val dismissible: Boolean, val categories: List<String>, val createdAt: Long, val expiresAt: Long?, val viewed: Boolean, val clicked: Boolean, val dismissed: Boolean, val decisionId: String?, val videoUrl: String? = null, val videoPosterUrl: String? = null, // the poster is the same as imageUrl (0.6.0) val videoAutoplay: Boolean = false, // muted and looped in ContentCardFeed while half visible val credit: MediaCredit? = null, // MediaCredit(name: String, profileUrl: String?, sourceUrl: String?) ) enum class ContentCardType { CLASSIC, CAPTIONED_IMAGE, IMAGE_ONLY } ``` Timestamps are epoch milliseconds. `url` is the deep link or web URL opened on click. `decisionId` is sent back with interactions. ## In-app messages | Member | Description | |---|---| | `var inAppMessageDelegate: InAppMessageDelegate?` | Decides whether a message shows now, later or never | | `var inAppMessagePresenter: InAppMessagePresenter?` | Draws messages; `herald-ui` installs the default. Messages wait while it is `null`; setting a presenter offers any pending message. | | `fun showNext()` | Offers the highest-priority pending message now (ties: the one pending longest), ignoring the minimum interval. The delegate is asked again. Does nothing while a message is on screen. | | `var deepLinkHandler: ((String) -> Boolean)?` | Opens Herald deep links: push taps, card clicks and in-app button and body clicks. Return `true` when your app handled the link; when `null` or returning `false`, the SDK opens it with `ACTION_VIEW`. Called on the thread that opens the link, the main thread for taps and clicks. Same semantics as iOS `deepLinkHandler`. | | `fun openUrl(url: String)` | Passes the link to `deepLinkHandler`, then, when it is `null` or returns `false`, opens it with an `ACTION_VIEW` intent. Presenters use it for clicks. From 0.6.0 it also sends `$deep_link_opened` (`source` `link`; a notification tap's link sends `push`) unless `trackDeepLinks` is off. | | `fun debugLoadMessages(json: String)` | Debug and preview only. See [Logging and debugging](/docs/operations/logging-and-debugging#preview-messages-without-a-server). | | `fun debugShowInAppMessage(messageId: String)` | Debug and preview only | ### InAppMessage ```kotlin data class InAppMessage( val id: String, val type: InAppMessageType, val priority: Int, val trigger: InAppTrigger, val reEligibility: ReEligibility, val expiresAt: Long?, val content: InAppContent, val style: InAppStyle, val decisionId: String?, ) ``` | Type | Definition | |---|---| | `InAppMessageType` | `SLIDEUP`, `MODAL`, `FULL`, `HTML` | | `InAppTrigger` | `data class InAppTrigger(val type: TriggerType, val event: String?, val propertyFilters: List<PropertyFilter>)` | | `TriggerType` | `SESSION_START`, `EVENT`, `PUSH_OPEN` | | `PropertyFilter` | `data class PropertyFilter(val key: String, val op: FilterOperator, val value: Any?)` | | `FilterOperator` | `EQ`, `NEQ`, `GT`, `GTE`, `LT`, `LTE`, `CONTAINS`, `EXISTS` | | `ReEligibility` | `data class ReEligibility(val mode: ReEligibilityMode, val hours: Double?)` | | `ReEligibilityMode` | `ONCE`, `AFTER_HOURS` | | `InAppContent` | `data class InAppContent(val header: String?, val body: String?, val imageUrl: String?, val buttons: List<InAppButton>, val html: String?, val slideFrom: String?, val dismissAfterSeconds: Double?, val videoUrl: String? = null, val videoPosterUrl: String? = null, val credit: MediaCredit? = null)` | | `InAppButton` | `data class InAppButton(val id: String, val text: String, val action: ButtonAction)` | | `ButtonAction` | `data class ButtonAction(val type: ButtonActionType, val value: String?)` | | `ButtonActionType` | `DEEPLINK`, `URL`, `CLOSE` | | `InAppStyle` | `data class InAppStyle(val backgroundColor: String?, val textColor: String?, val buttonColor: String?, val buttonTextColor: String?, val cornerRadius: Double?)` | `slideFrom` is `"top"` or `"bottom"`; slideups come from the bottom unless it is `"top"`. Style colors are hex strings such as `#101828`; `null` means use the theme. A filter on a missing or null property is false for every operator, `EXISTS` included. ### InAppMessageDelegate ```kotlin fun interface InAppMessageDelegate { fun shouldDisplay(message: InAppMessage): InAppDisplayDecision } enum class InAppDisplayDecision { DISPLAY, LATER, DISCARD } ``` Asked on the main thread when a message is about to appear. Return quickly: the SDK waits for the answer. It can be asked more than once for the same message. If it throws, the message shows and the error is logged. | Decision | Effect | |---|---| | `DISPLAY` | Show now | | `LATER` | Keep it pending; offered again automatically or with `showNext()` | | `DISCARD` | Drop this occurrence; the message stays eligible for its next trigger | ### InAppMessagePresenter, InAppMessageCallbacks ```kotlin fun interface InAppMessagePresenter { fun present(activity: Activity, message: InAppMessage, callbacks: InAppMessageCallbacks): Boolean fun dismissCurrent() {} } interface InAppMessageCallbacks { fun onImpression() fun onClick(buttonId: String?) fun onVideoPlay() {} // 0.6.0, optional fun onVideoComplete() {} // 0.6.0, optional fun onDismiss() } ``` Called on the main thread with the resumed activity. Return `true` only when the message is on screen; Herald then marks it shown. Return `false` and it stays pending and is retried on the next activity resume. `dismissCurrent` takes the message down without user action (sign-out or user switch). Report through the callbacks: `onImpression` when the message becomes visible, `onClick(null)` for a body tap or `onClick(id)` for a button, and `onDismiss` exactly once when it leaves the screen for any reason. A dismissal is logged only when nothing was clicked. `onVideoPlay` and `onVideoComplete` log `video_play` and `video_complete` for a message with a video, once per play; both have empty defaults. ## `herald-ui` Every composable here reads `LocalHeraldTheme` unless a theme is passed in. ### ContentCardFeed ```kotlin @Composable fun ContentCardFeed( modifier: Modifier = Modifier, filter: (ContentCard) -> Boolean = { true }, order: Comparator<ContentCard> = ContentCardFeedDefaults.Order, onCardClick: (ContentCard) -> Unit = ContentCardFeedDefaults.OpenUrl, contentPadding: PaddingValues = PaddingValues(LocalHeraldTheme.current.spacing), emptyContent: @Composable () -> Unit = { /* "No updates right now" */ }, cardContent: @Composable (card: ContentCard, onClick: () -> Unit) -> Unit = { card, onClick -> ContentCardFeedDefaults.Card(card, onClick) }, ) ``` | Parameter | Description | |---|---| | `modifier` | Applied to the list | | `filter` | Keeps the cards it returns `true` for | | `order` | Sort order; pinned first, then newest, by default | | `onCardClick` | Runs after the click is logged; opens the card URL by default | | `contentPadding` | Padding around the list | | `emptyContent` | Shown when there are no cards | | `cardContent` | Draws one card; call `onClick` when it is tapped | Impressions are logged once per card per session when at least half the card is visible. Dismissible cards can be swiped away, or dismissed with the TalkBack "Dismiss" action. ### ContentCardFeedDefaults ```kotlin object ContentCardFeedDefaults { val Order: Comparator<ContentCard> // pinned first, then newest val OpenUrl: (ContentCard) -> Unit // Herald.openUrl(card.url) @Composable fun Card(card: ContentCard, onClick: () -> Unit) // default view for card.type } ``` ### Card composables ```kotlin @Composable fun ClassicContentCard(card: ContentCard, onClick: () -> Unit) @Composable fun CaptionedImageContentCard(card: ContentCard, onClick: () -> Unit) @Composable fun ImageOnlyContentCard(card: ContentCard, onClick: () -> Unit) ``` Cards are clickable only when they have a `url`. An image-only card's TalkBack label is its title, else `extras["alt"]`. ### `HeraldInAppPresenter` ```kotlin class HeraldInAppPresenter @JvmOverloads constructor( var theme: HeraldTheme = HeraldTheme(), var customViews: Map<InAppMessageType, InAppMessageContent> = emptyMap(), ) : InAppMessagePresenter { companion object { @JvmStatic @JvmOverloads fun install(theme: HeraldTheme = HeraldTheme(), customViews: Map<InAppMessageType, InAppMessageContent> = emptyMap()): HeraldInAppPresenter } } typealias InAppMessageContent = @Composable (message: InAppMessage, actions: InAppMessageActions) -> Unit ``` `install` creates the presenter and sets it as `Herald.inAppMessagePresenter`. The presenter draws in an overlay on the resumed activity, which must be a `ComponentActivity`. `customViews` replaces the default view per message type. If the activity is destroyed while a message is up, the message is shown again on the next activity. ### InAppMessageActions ```kotlin interface InAppMessageActions { fun buttonClicked(button: InAppButton) fun bodyClicked(url: String? = null) fun clicked(buttonId: String) fun dismiss() fun videoPlayed() {} // 0.6.0, optional fun videoCompleted() {} // 0.6.0, optional } ``` | Function | Logs | Then | |---|---|---| | `buttonClicked` | A button click | Opens the deep link or URL, then dismisses | | `bodyClicked` | A body click | Opens `url` when given, then dismisses | | `clicked` | A button click | Keeps the message up (the HTML bridge's `herald.click(id)`) | | `dismiss` | A dismissal, only when nothing was clicked | Takes the message down | | `videoPlayed` | `video_play` | Nothing; the default views call it once per play | | `videoCompleted` | `video_complete` | Nothing; the default views call it when the video ends | ### Message views ```kotlin @Composable fun SlideupMessageView(message: InAppMessage, actions: InAppMessageActions, theme: HeraldTheme) @Composable fun ModalMessageView(message: InAppMessage, actions: InAppMessageActions, theme: HeraldTheme) @Composable fun FullScreenMessageView(message: InAppMessage, actions: InAppMessageActions, theme: HeraldTheme) @Composable fun HtmlMessageView(message: InAppMessage, actions: InAppMessageActions, theme: HeraldTheme) ``` The default view for each type, public so a custom view can wrap one. A slideup dismisses when swiped toward its edge; an HTML message has a close button in the top end corner. ### Theme ```kotlin @Immutable data class HeraldTheme( val lightColors: HeraldColors = HeraldColors.Light, val darkColors: HeraldColors = HeraldColors.Dark, val typography: HeraldTypography = HeraldTypography(), val cornerRadius: Dp = 12.dp, val spacing: Dp = 16.dp, val darkMode: Boolean? = null, // null follows the system ) { @Composable fun colors(): HeraldColors } @Immutable data class HeraldColors( val background: Color, val surface: Color, val onSurface: Color, val onSurfaceVariant: Color, val accent: Color, val onAccent: Color, val outline: Color, val scrim: Color, ) { companion object { val Light: HeraldColors; val Dark: HeraldColors } } @Immutable data class HeraldTypography( val title: TextStyle, // 17 sp semibold val body: TextStyle, // 15 sp val button: TextStyle, // 15 sp semibold val caption: TextStyle, // 13 sp ) val LocalHeraldTheme: ProvidableCompositionLocal<HeraldTheme> ``` Provide a theme to the feed with `CompositionLocalProvider(LocalHeraldTheme provides theme)` and pass it to `HeraldInAppPresenter`. A message's style fields override the theme for that message; an invalid hex value falls back to the theme. ### String resources Override these in your app's resources to change or translate them: `herald_close` ("Close"), `herald_dismiss` ("Dismiss"), `herald_feed_empty` ("No updates right now"). ## `herald-fcm` ### `HeraldMessagingService` ```kotlin open class HeraldMessagingService : FirebaseMessagingService() { override fun onNewToken(token: String) // Herald.setPushToken(token) override fun onMessageReceived(message: RemoteMessage) // shows Herald pushes open fun onNonHeraldMessage(message: RemoteMessage) // other pushes; does nothing by default companion object { @JvmStatic fun syncToken(context: Context) } } ``` Registered by the module's manifest. Subclass it and override `onNonHeraldMessage` to handle your other pushes. Before calling it, 0.6.0+ records such a push as `$external_push` when it carries a notification block (with `trackExternalPushes` on): its `message_id` is the data key `herald_external_id`, else `RemoteMessage.messageId`, and its category is `herald_category`, else `other`. `syncToken` fetches the current FCM token and passes it to `setPushToken`; call it after `configure`. It also sets `PushTokenSource.request`, so the SDK can fetch the token again when it is turned back on after `wipeData()`. It logs a warning and does nothing when Firebase is not initialized. ### `HeraldNotifications` ```kotlin object HeraldNotifications { const val DEFAULT_CHANNEL_ID = "herald_default" const val KEY_ACTIONS = "herald_actions" const val KEY_CHANNEL_ID = "herald_channel_id" const val KEY_STORY = "herald_story" // 0.7.0+ const val STORY_PAGE_ACTION_PREFIX = "herald_story_page_" // 0.7.0+ const val TAG = "herald" const val LIVE_UPDATE_TAG = "herald_live_update" @DrawableRes var smallIcon: Int fun createDefaultChannel(context: Context, name: CharSequence = /* herald_default_channel_name */, importance: Int = NotificationManager.IMPORTANCE_DEFAULT) fun handleRemoteMessage(context: Context, message: RemoteMessage): Boolean } data class HeraldNotificationAction(val id: String, val title: String, val deeplink: String?) data class HeraldStoryPage(val imageUrl: String, val title: String, val subtitle: String, val deeplink: String?) // 0.7.0+ ``` | Member | Description | |---|---| | `smallIcon` | A monochrome drawable for the status bar. `0` (default) uses the `com.google.firebase.messaging.default_notification_icon` meta-data, then the module's bell icon. | | `createDefaultChannel` | Creates the `herald_default` channel if it does not exist. The name comes from the `herald_default_channel_name` string resource ("Notifications") unless given. | | `handleRemoteMessage` | Shows a Herald push and returns `true`; returns `false` for other pushes. Blocks while the image downloads, so call it off the main thread (FCM already does). | `handleRemoteMessage` reads title, body and image from the data keys, else from the FCM notification block. It uses the channel named by `herald_channel_id` or the notification's channel when that channel exists, else the default channel. It shows up to three `herald_actions` buttons. 0.7.0+: a push with `herald_story` (2 to 10 valid pages) shows as a [push story](/docs/push-notifications/push-stories) instead, with Previous and Next buttons handled by the module's `HeraldStoryReceiver`; a tap logs a `button` interaction `herald_story_page_<index>`. ## `herald-geofence` 0.7.0+, not released yet. Opt-in geofence monitoring with Play Services `GeofencingClient`, a separate module so apps that don't use it never depend on Play Services location. See [Geofences](/docs/concepts/geofences). ```kotlin import com.herald.geofence.disableGeofences import com.herald.geofence.enableGeofences fun Herald.enableGeofences() fun Herald.disableGeofences() // From Java: HeraldGeofence.enableGeofences(Herald.INSTANCE) ``` `enableGeofences()` downloads the app's geofence list (`GET /api/v1/sdk/geofences`, no location sent) and registers all of them (an app has at most 100, Android's limit). Call it after `configure`, at every launch, once the app holds `ACCESS_FINE_LOCATION` and, on Android 10 and later, `ACCESS_BACKGROUND_LOCATION`; without them the call logs a warning and does nothing. The module adds no permissions to your manifest, only its `GeofenceReceiver`, and never asks for permission. Crossings send `$geofence_enter` / `$geofence_exit` with `geofence_id` and `geofence_name`, at most one per geofence and direction every 5 minutes, and nothing while the SDK is off. The **Geofences** SDK setting set to Off stops monitoring. `disableGeofences()` removes Herald's geofences until `enableGeofences()` is called again. 0.7.0+: it also shows Live Updates (data messages with `herald_type` set to `live_update`) as an ongoing notification on the default channel, tagged `LIVE_UPDATE_TAG`, and returns `true` for them. See [Live Activities on Android](/docs/live-activities/android). ## Related - [iOS API](/docs/reference/ios-api) - [Event payload spec](/docs/reference/event-payload) - [Limits](/docs/reference/limits) Source: https://heraldsdk.com/docs/reference/android-api.md --- # SDK REST endpoints > The HTTP endpoints the SDK calls, with headers, schemas, limits, status codes and verification modes, and how your backend mints user tokens. The SDK talks to these Herald endpoints. You do not call them from the app yourself; this page is for backend engineers, security reviewers and anyone debugging traffic. Your backend mints user tokens (below) and calls the [Server API](/docs/reference/server-api). All paths are relative to your Herald base URL, the `endpoint` you pass to `configure`. Every response body is JSON: `{ "data": ... }` on success, `{ "error": "..." }` on failure. ## Authentication | Header | Sent on | Value | |---|---|---| | `x-herald-app-key` | Every SDK request | The connection's app key (its publishable key). Public: it identifies the connection and grants no secret access. | | `x-herald-user-token` | Requests that name a user, when the SDK has a token | Hex HMAC-SHA256 of the External ID, keyed with the SHA-256 hex digest of the connection's ingest token | The app key must belong to an active Herald sending connection. Any other key gets `401 Invalid app key`. ### Getting the keys Both keys live on the app's connection, under **Settings → Sending & SDK**: - **App key.** Open the app and select **Generate app key** on the **Mobile SDK** card. It goes in the app. - **Ingest token** (`nx_ingest_…`). Open the app and select **Rotate** next to **Ingest token**. Herald shows the token once, so copy it into your backend's secret store then. It signs user tokens and authorizes server calls as `Authorization: Bearer <ingest token>`. Rotating it again invalidates the old token at once: see [Rotating the ingest token](/docs/data-and-privacy/security-and-identity-verification#rotating-the-ingest-token). ### Verification modes Set on the connection's **Mobile SDK** card. A connection without a setting uses **Required**. | Mode | Request names a user, valid token | Names a user, no token | Names a user, wrong token | Names no user | |---|---|---|---|---| | `required` | Verified | `401 Invalid user token` | `401 Invalid user token` | Anonymous | | `optional` | Verified | Processed as anonymous | `401 Invalid user token` | Anonymous | | `off` | Trusted as sent | Trusted as sent | Trusted as sent (not checked) | Anonymous | A batch names a user through its `userId` field, or, when that is empty, the `userId` of its first `identify` event. A message fetch names a user through its `userId` query parameter. A token sent on a request that names no user is ignored. :::warning Off is for development only With verification off, anyone with your app key can send data as any user and read their messages. Use it only for testing. ::: ## POST /api/v1/sdk/batch Uploads queued events. Native clients only, so no CORS. ### Request | Header | Required | Value | |---|---|---| | `Content-Type` | Yes | `application/json` | | `x-herald-app-key` | Yes | App key | | `x-herald-user-token` | Depends on the mode | User token | | Field | Type | Rules | |---|---|---| | `sdk.name` | string | 1 to 64 characters (`herald-ios`, `herald-android`) | | `sdk.version` | string | 1 to 32 characters | | `deviceId` | string | 1 to 128 characters | | `userId` | string or null | 1 to 200 characters; null or absent for an anonymous batch | | `sentAt` | string | ISO 8601 date-time with offset | | `dropped` | integer | 0 or more; events the device dropped (a full queue, over 32 KB, or queued more than 30 days). Default 0. | | `context` | object | Device data; see [Event payload spec](/docs/reference/event-payload#context) | | `events` | array | Up to 100 events; see [Event payload spec](/docs/reference/event-payload) | ```json { "sdk": { "name": "herald-ios", "version": "0.4.0" }, "deviceId": "6c1f2a9e-0b7d-4a8e-9f61-1b2c3d4e5f60", "userId": "u_123", "sentAt": "2026-11-09T14:00:00Z", "dropped": 0, "context": { "app": { "name": "Lumen", "version": "4.2.0", "build": "812", "namespace": "com.lumen.app" }, "os": { "name": "iOS", "version": "18.1" }, "region": "US" }, "events": [ { "id": "a1b2", "type": "track", "timestamp": "2026-11-09T13:59:58Z", "sessionId": "1731160800000", "name": "workout_completed", "properties": { "minutes": 32 } } ] } ``` ### Limits - 512 KB per request body. Checked against `Content-Length` and the body itself. - 100 events per request. - 32 KB per event, as JSON. The SDKs drop a larger event on the device and count it in `dropped`. - Each event is checked on its own: an invalid one is rejected and the rest are stored. Only a problem with the batch itself (JSON, `sdk`, `deviceId`, `userId`, `sentAt`, `dropped`, `context`, the `events` array) fails it with a 400. The SDKs check every call on the device, so rejects are rare in normal use. - Event time: Herald corrects each event's `timestamp` for the device's clock, using `sentAt` and the time the batch arrived, and rejects events more than 30 days old. See [Clock correction](/docs/concepts/batching-and-offline#clock-correction). ### Response ```json { "data": { "accepted": 1, "duplicates": 0, "heraldId": "7K3M-9QXA" } } ``` `accepted` counts new events stored. `duplicates` counts event IDs this connection already had; they are skipped, so a retried batch is safe. `heraldId` is the batch user's User ID (see [Support ID](/docs/concepts/users-and-identity#support-id)), sent for the user the batch is verified as once their profile exists: with a valid user token under Required or Optional, and for any claimed user under Off. Anonymous batches and Optional batches without a token leave it out. It isn't secret. When events were rejected, `rejected` lists them, and `accepted` and `duplicates` count only the valid ones: ```json { "data": { "accepted": 1, "duplicates": 0, "rejected": [{ "id": "e2", "index": 1, "reason": "too_old", "detail": "timestamp is more than 30 days old" }] } } ``` Each entry has the event's `id` (null when it has no usable one), its `index` in `events`, a `reason` code and a short `detail`. The codes are listed under [Rejected events](/docs/reference/error-codes#rejected-events). ### Status codes | Status | Body `error` | Cause | What the SDK does | |---|---|---|---| | 200 | | Stored, except any events listed in `rejected` | Removes the batch from its queue; logs each rejected event at debug level and never retries it | | 400 | `Invalid JSON` | Body is not JSON | Drops the batch, logs an error | | 400 | Path and message, such as `deviceId: Too small: expected string to have >=1 characters` | The batch breaks the schema | Drops the batch, logs an error | | 401 | `Invalid app key` | Missing, unknown or inactive app key | Keeps every queued event, logs an error, and sends nothing more until the app launches again | | 401 | `Invalid user token` | See the verification table | Keeps that user's events until the app calls `setUserToken`, logs a warning; anonymous events keep flowing | | 413 | `Batch exceeds 512 KB` or `Batch exceeds 100 events` | Too large | Drops the batch, logs an error | | 500 | `Internal server error` | Server failure | Keeps the batch and retries with backoff | The SDKs also retry 408, 429 and any 5xx, and honor a `Retry-After` header (seconds or HTTP date) or a `retryAfterSeconds` body field, capped at one hour. Herald itself does not return 429 today; a proxy or firewall in front of it may. ### What the server does with a batch - **Device record.** Creates or updates the device, with its platform, context and region. Region comes from the country of the request's IP address when the hosting platform supplies it, else from `context.region`. - **Verified user.** Only the verified user gets writes: attributes, email and phone contacts, push tokens, subscriptions, message state and outcome credit. Events that claim any other user are stored with no user, and the claim is kept in the stored payload. - **Sign-out.** A batch with no user unbinds the device from its previous user and deletes that user's push tokens for this device. - **Time zone.** A verified user's time zone is filled from `context.timezone` only when the profile has none. - **Idempotency.** Events are stored once per `(connection, id)`. ## POST /api/v1/sdk/diagnostics Uploads crash and hang reports from the iOS SDK, when `crashReports` is on. Native clients only, so no CORS. The request carries no user or device id. | Header | Required | Value | |---|---|---| | `Content-Type` | Yes | `application/json` | | `x-herald-app-key` | Yes | App key | A request holds 1 to 20 reports and is at most 256 KB. ## GET /api/v1/sdk/config SDK 0.6.0+. Returns the app's remote SDK settings, set in the console under Settings, SDK settings. Native clients only. | Header | Required | Value | |---|---|---| | `x-herald-app-key` | Yes | App key | | `If-None-Match` | No | The `ETag` of the last response | ```json { "data": { "version": "3f9c2a7b1d4e6f80", "settings": { "enabled": true, "flushIntervalSeconds": 30, "dataCollection": "minimal" } } } ``` `version` is opaque and changes on every save; it is `"0"` with empty `settings` until the first save. Every setting is optional, and an absent one means the value built into the app: | Setting | Values | |---|---| | `enabled` | `true` or `false`. `false` stops all collection and sending in the SDK and clears its queue (push tokens and subscriptions wait and go out when it is back on) | | `flushIntervalSeconds` | 5 to 300 | | `foregroundSessionTimeoutSeconds`, `backgroundSessionTimeoutSeconds` | 60 to 86400, a multiple of 60 (whole minutes) | | `dataCollection` | `standard` or `minimal` | | `trackLifecycleEvents`, `trackExternalPushes`, `trackDeepLinks` | `true` or `false` | | `geofences` | `true` or `false`. SDK 0.7.0+. `false` stops geofence monitoring on every device; see [Geofences](/docs/concepts/geofences) | The response carries `ETag` (the quoted version) and `Cache-Control: private, no-cache`. A matching `If-None-Match` returns 304 with no body. A bad app key returns 401 `Invalid app key`. The SDKs fetch it at launch and on a foreground at most once an hour; see [iOS API](/docs/reference/ios-api#remote-config) and [Android API](/docs/reference/android-api#remote-config). ## GET /api/v1/sdk/geofences SDK 0.7.0+. Not released yet. Returns the app's whole geofence list, set in the console under Settings, Geofences, for the `HeraldGeofence` (iOS) and `herald-geofence` (Android) modules. The request carries no location: the device picks the regions to monitor itself. Native clients only. | Header | Required | Value | |---|---|---| | `x-herald-app-key` | Yes | App key | | `If-None-Match` | No | The `ETag` of the last response | ```json { "data": { "enabled": true, "geofences": [ { "id": "4f1c2b9e-7a3d-4e8b-9c51-2d6f0a8b3e17", "name": "Store 12", "latitude": 40.7484, "longitude": -73.9857, "radiusMeters": 200 } ] } } ``` `enabled` is the app's **Geofences** SDK setting (`geofences` in [GET /api/v1/sdk/config](#get-api-v1-sdk-config)); it is `true` unless an admin set it to Off, and then `geofences` is empty and the SDK stops monitoring. Geofences are listed oldest first, at most 100. The response carries a strong `ETag` over the body and `Cache-Control: private, no-cache`; a matching `If-None-Match` returns 304 with no body. A bad app key returns 401 `Invalid app key`. See [Geofences](/docs/concepts/geofences). ## GET /api/v1/sdk/messages Returns the content cards and in-app messages for the SDK's user. ### Request | Query parameter | Required | Rules | |---|---|---| | `deviceId` | Yes | 1 to 128 characters | | `userId` | No | 1 to 200 characters; omit for an anonymous device | | Header | Required | Value | |---|---|---| | `x-herald-app-key` | Yes | App key | | `x-herald-user-token` | Depends on the mode | User token | | `If-None-Match` | No | The `ETag` of the last response | ### Response ```json { "data": { "syncedAt": "2026-11-09T14:00:00.000Z", "contentCards": [ { "id": "msg_1", "type": "captioned_image", "title": "Your 7 AM session, upgraded", "body": "Try Plus free for 7 days.", "imageUrl": "https://cdn.example.com/plus.jpg", "cta": "Try Plus", "url": "lumen://plus", "extras": {}, "pinned": false, "dismissible": true, "categories": [], "createdAt": "2026-11-09T13:00:00.000Z", "expiresAt": null, "viewed": false, "clicked": false, "dismissed": false, "decisionId": "dec_1" } ], "inAppMessages": [ { "id": "msg_2", "type": "modal", "priority": 0, "trigger": { "type": "session_start" }, "reEligibility": { "mode": "once" }, "expiresAt": null, "content": { "header": "Nice work, Maya", "body": "You logged 5 workouts this week.", "imageUrl": null, "buttons": [{ "id": "primary", "text": "See Plus", "action": { "type": "deeplink", "value": "lumen://plus" } }], "html": null, "slideFrom": null, "dismissAfterSeconds": null }, "style": { "backgroundColor": null, "textColor": null, "buttonColor": null, "buttonTextColor": null, "cornerRadius": null }, "decisionId": "dec_2" } ] } } ``` | Field | Values | |---|---| | Card `type` | `classic`, `captioned_image`, `image_only` | | Message `type` | `slideup`, `modal`, `full`, `html` | | `trigger.type` | `session_start`, `push_open`, `event` (with `event` and optional `propertyFilters`) | | `propertyFilters[].op` | `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `contains`, `exists` | | `reEligibility.mode` | `once`, `after_hours` (with `hours`, greater than 0) | | Button `action.type` | `deeplink`, `url`, `close` | | `slideFrom` | `top`, `bottom`, null | | Style fields | Hex color strings or null; null means use the app theme | Rules: - Only active, unexpired, undismissed messages are returned, newest first: up to 100 content cards and 50 in-app messages. - An anonymous or unverified caller gets empty lists. - The response carries a strong `ETag` and `Cache-Control: private, no-cache`. A matching `If-None-Match` returns 304 with no body. The ETag changes when any card or message changes, including its viewed or clicked state. - The SDKs skip an item they cannot read (for example a type from a newer version) and keep the rest. ### Status codes | Status | Body `error` | Cause | |---|---|---| | 200 | | The lists | | 304 | | Nothing changed since the ETag you sent | | 400 | Parameter and message, such as `deviceId: Required` | Bad query | | 401 | `Invalid app key` or `Invalid user token` | See the verification table | | 500 | `Internal server error` | Server failure | On any failure the SDK keeps showing its cached cards and messages. ## Backend: minting user tokens There is no endpoint for this: your backend computes the token. It needs the connection's ingest token, which **Rotate ingest token** on the connection page shows once. Keep the ingest token on your server only. ```javascript // Node.js. HERALD_INGEST_TOKEN is the connection's ingest token. import { createHash, createHmac } from "node:crypto"; const key = createHash("sha256").update(process.env.HERALD_INGEST_TOKEN).digest("hex"); const userToken = createHmac("sha256", key).update(userId).digest("hex"); ``` ```sh key=$(printf %s "$HERALD_INGEST_TOKEN" | openssl dgst -sha256 -r | cut -d' ' -f1) printf %s "u_123" | openssl dgst -sha256 -hmac "$key" -r | cut -d' ' -f1 ``` The token does not expire. Rotating the ingest token invalidates every user token at once, so re-mint after a rotation. ## Backend endpoints Your backend's own calls, authorized with the ingest token, are on [Server API](/docs/reference/server-api): users, events, decide, the decisions and holdout exports, contacts and user deletion. ## Related - [Event payload spec](/docs/reference/event-payload) - [Error codes](/docs/reference/error-codes) - [Server API](/docs/reference/server-api) - [Security and identity verification](/docs/data-and-privacy/security-and-identity-verification) - [Importing push tokens and users](/docs/migration/importing-tokens-and-users) Source: https://heraldsdk.com/docs/reference/rest-endpoints.md --- # Server API > The REST endpoints your backend calls: users, events, real-time decide, the decisions and holdout exports, the decisions CSV, contacts and user deletion. :::prereq - The app's ingest token (`nx_ingest_…`), kept on your server. See [Authentication](#authentication). - For the decisions CSV only: an API key with the `exports.read` scope. For adding people to a journey: one with `journeys.enter`. - Your users' External IDs: the same IDs your apps pass to `identify`. ::: Your backend or warehouse uses these endpoints to send users and events, ask which message to show, read results back, manage contact points and erase a user. They never run in the app. For the endpoints the SDK calls, see [SDK REST endpoints](/docs/reference/rest-endpoints). To send messages, see the [Send API](/docs/reference/send-api). ## Authentication | Credential | Header | Endpoints | |---|---|---| | Ingest token | `Authorization: Bearer <ingest token>` | Users, events, decide, decisions, holdout, contacts, user deletion | | API key (`hk_…`) with `exports.read` | `Authorization: Bearer hk_…` | Decisions CSV | | API key (`hk_…`) with `journeys.enter` | `Authorization: Bearer hk_…` | Adding people to a journey | **Ingest token.** Open the app under **Settings → Sending & SDK** and select **Rotate** next to **Ingest token**. Herald shows the token once, so copy it into your backend's secret store then. It also signs [user tokens](/docs/reference/rest-endpoints#backend-minting-user-tokens). Rotating it again invalidates the old token at once: see [Rotating the ingest token](/docs/data-and-privacy/security-and-identity-verification#rotating-the-ingest-token). **API key.** Create one under **Settings → Sending**, the app, then **API keys**. See [Send API authentication](/docs/reference/send-api#authentication) for scopes and key rules. A missing or unknown ingest token gets `401 Unauthorized`. A token whose connection is disabled gets `403 Forbidden`. ## Base URL Use your Herald base URL, the same `endpoint` your apps pass to `configure`. The examples use `https://YOUR_HERALD_HOST`. Every JSON response is `{ "data": ... }` on success and `{ "error": "..." }` on failure. ## Rate limits - The decisions CSV counts toward `exports.requests` (60 per hour per app) and `api.requests` (36,000 per hour per app), with the rate-limit headers described on [API errors](/docs/reference/api-errors#rate-limits). - Adding people to a journey counts each person toward `journeys.enter` (100,000 per hour per app) and each call toward `api.requests`. - The other endpoints have no hourly limit. :::note Beta: `POST /api/v1/events` and `POST /api/v1/users` share an hourly pool, `ingest.requests`, of 36,000 requests per app. Over it they answer `429` with `Retry-After`. This is not live in production yet.::: ## Idempotency These endpoints take no `Idempotency-Key` header. Retrying is safe because each write is keyed: | Endpoint | Retry behavior | |---|---| | `POST /api/v1/users` | Upserts on `userId` | | `POST /api/v1/events` | Stores each event once per `id` within the app; repeats count in `duplicates` | | `POST /api/v1/decide` | The same user and agent within 30 minutes get the same decision | | `POST` and `DELETE /api/v1/contacts` | Upserts or removes on `kind` and `value` | | `DELETE /api/v1/users/{userId}` | A repeat returns zero counts | ## POST /api/v1/users Creates or updates users. It merges attributes with the same reserved-key rules as the SDK (a `computed_` key, reserved for [computed attributes](/docs/concepts/computed-attributes), fails the request with 400), registers each user as a member of the connection's app so the app's agents can reach them, and saves the email address as a contact. ### Request | Field | Rules | |---|---| | `users` | 1 to 1,000 items; body up to 4 MB | | `userId` | 1 to 200 characters | | `attributes` | Optional object of attributes to merge into the profile; a `null` value removes that key | | `email` | Optional valid address | | `signupAt`, `lastActiveAt` | Optional ISO 8601 date-times with offset | :::tabs ::tab curl ```shell curl -X POST "https://YOUR_HERALD_HOST/api/v1/users" \ -H "Authorization: Bearer $HERALD_INGEST_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "users": [ { "userId": "u_123", "attributes": { "plan": "plus" }, "email": "maya@example.com", "signupAt": "2026-11-01T12:00:00Z", "lastActiveAt": "2026-11-15T08:00:00Z" } ] }' ``` ::tab node ```javascript const res = await fetch("https://YOUR_HERALD_HOST/api/v1/users", { method: "POST", headers: { Authorization: `Bearer ${process.env.HERALD_INGEST_TOKEN}`, "Content-Type": "application/json" }, body: JSON.stringify({ users: [{ userId: "u_123", attributes: { plan: "plus" }, email: "maya@example.com" }], }), }); const { data, error } = await res.json(); ``` ::: ### Response | Field | Value | |---|---| | `upserted` | Number of users created or updated | ```json { "data": { "upserted": 1 } } ``` | Status | Body `error` | Cause | |---|---|---| | 200 | | Done | | 400 | `Invalid JSON`, or `Invalid users payload: ...` with the field | Bad body | | 401 | `Unauthorized` | Missing or unknown ingest token | | 403 | `Forbidden` | The connection is disabled | | 413 | `Body exceeds 4 MB` | Too large | | 500 | `Internal server error` | Server failure | ## POST /api/v1/events Sends events. They are stored and count toward agent goals exactly like SDK `track` and `trackPurchase` calls. ### Request | Field | Rules | |---|---| | `events` | 1 to 1,000 items; body up to 4 MB | | `id` | 1 to 128 characters; unique per event | | `userId` | 1 to 200 characters | | `name` | 1 to 255 characters | | `timestamp` | ISO 8601 date-time with offset; no more than 5 minutes ahead of Herald's clock. Your server's clock is trusted: no correction and no age limit, so historical imports are kept | | `properties` | Optional object | | `schemaVersion` | Optional. The [event schema](/docs/concepts/event-schemas) version to check the event against, such as `1-0-0`; without it (or null), the latest version. Ignored when the event name has no schema | | Each event | Up to 32 KB as JSON | An event named `purchase` with a numeric `properties.price` is recorded as a purchase. `quantity`, `currency` and `productId` are optional. Report a push your app sent itself with an event named `$external_push`, right after your backend sends it, so the push limit counts it. `category` is `transactional`, `marketing` or `other` (default), `message_id` (up to 200 characters) makes the push count once even if the SDK reports it too, and `source` (up to 100) is optional. Don't send the title or body. See [Pushes your app sends](/docs/push-notifications/pushes-your-app-sends). :::tabs ::tab curl ```shell curl -X POST "https://YOUR_HERALD_HOST/api/v1/events" \ -H "Authorization: Bearer $HERALD_INGEST_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "events": [ { "id": "evt_1", "userId": "u_123", "name": "subscription_started", "timestamp": "2026-11-15T08:00:00Z", "properties": {} }, { "id": "evt_2", "userId": "u_123", "name": "$external_push", "timestamp": "2026-11-15T08:00:00Z", "properties": { "category": "transactional", "message_id": "order-42-shipped", "source": "orders" } } ] }' ``` ::tab node ```javascript const res = await fetch("https://YOUR_HERALD_HOST/api/v1/events", { method: "POST", headers: { Authorization: `Bearer ${process.env.HERALD_INGEST_TOKEN}`, "Content-Type": "application/json" }, body: JSON.stringify({ events: [ { id: "evt_1", userId: "u_123", name: "subscription_started", timestamp: new Date().toISOString(), properties: {} }, ], }), }); const { data, error } = await res.json(); ``` ::: ### Response | Field | Value | |---|---| | `accepted` | Number of new events stored | | `duplicates` | Event IDs the app already had; they are skipped | | `rejected` | Only when an event was left out: its `id`, `index`, `reason` and `detail`. See [Rejected events](/docs/reference/error-codes#rejected-events) | ```json { "data": { "accepted": 1, "duplicates": 0 } } ``` Each event is checked on its own: an invalid one is left out, the rest are stored, and the response lists it in `rejected`. Events whose name has an [event schema](/docs/concepts/event-schemas) are checked against it, as SDK events are. Fix and resend only those events. | Status | Body `error` | Cause | |---|---|---| | 200 | | Done, except any events listed in `rejected` | | 400 | `Invalid JSON`, or `Invalid events payload: ...` with the field | Bad body: not an object, no `events` array, or 0 or over 1,000 events | | 401 | `Unauthorized` | Missing or unknown ingest token | | 403 | `Forbidden` | The connection is disabled | | 413 | `Body exceeds 4 MB` | Too large | | 500 | `Internal server error` | Server failure | Send each goal event from one source: the server or the SDK, not both. ## POST /api/v1/decide Asks, at request time, which message an agent should show a user, for a web app or backend that renders the message itself instead of using the mobile SDK. Herald picks a variant with the agent's bandit and learned stats, records the decision, and returns the variant's content. A later goal event for that user, from `/api/v1/events` or the SDK, is credited to the decision like any other send. The user must already exist: send them through `POST /api/v1/users` first. The agent must belong to the same app as the ingest token. Call decide when you are about to show the message, not ahead of time. ### Request | Field | Rules | |---|---| | `agentId` | Required; the agent's ID from the console | | `userId` | 1 to 200 characters | | `channel` | Optional, such as `push` or `email`; only that channel's variants are considered | :::tabs ::tab curl ```shell curl -X POST "https://YOUR_HERALD_HOST/api/v1/decide" \ -H "Authorization: Bearer $HERALD_INGEST_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "agentId": "AGENT_ID", "userId": "u_123", "channel": "email" }' ``` ::tab node ```javascript const res = await fetch("https://YOUR_HERALD_HOST/api/v1/decide", { method: "POST", headers: { Authorization: `Bearer ${process.env.HERALD_INGEST_TOKEN}`, "Content-Type": "application/json" }, body: JSON.stringify({ agentId: "AGENT_ID", userId: "u_123", channel: "email" }), }); const { data } = await res.json(); if (!data.holdout && !data.noSend) render(data.content); ``` ::: ### Response | Field | Value | |---|---| | `decisionId`, `variantId` | IDs of the recorded decision and the chosen variant; null in holdout | | `agentId` | The agent | | `channel` | The variant's channel; null in holdout | | `holdout` | `true` when the user is in the agent's holdout group: show nothing | | `noSend` | `true` when the agent chose to send nothing to this person; render nothing | | `explore` | `true` when the pick was exploration rather than the best-known variant | | `warmupForced` | `true` when a new variant was shown to gather data | | `predictedReward` | The bandit's estimate for the variant; null in holdout | | `content` | The variant's `title`, `subject`, `body`, `cta`, `deeplink`, `iconImageUrl` and `htmlBody`; null in holdout | ```json { "data": { "decisionId": "cmh…", "agentId": "AGENT_ID", "variantId": "cmh…", "channel": "email", "holdout": false, "explore": false, "warmupForced": false, "predictedReward": 0.12, "content": { "subject": "Your plan is waiting", "title": "Pick up where you left off", "body": "…", "cta": "Continue", "deeplink": "https://example.com/plan", "htmlBody": "<p>…</p>" } } } ``` Fields the variant leaves unset or empty are left out of `content`; `body` is always present. When the agent has a deep link override, `deeplink` is that link. In holdout, no decision is recorded. Real-time decisions are recorded for learning and conversion credit. They count toward the agent's per-user frequency cap, and scheduled sends are less likely to repeat a variant the user just got. They don't count toward daily send caps, and they don't show as sends on delivery dashboards. Your app decides whether to show the message. A goal event is credited only if its `timestamp` is at or after the decision, by Herald's clock. Send event timestamps from a server with an accurate clock. | Status | Body `error` | Cause | |---|---|---| | 200 | | Done | | 400 | `Invalid JSON body`, or the field and its problem, such as `userId: must be at most 200 characters` | Bad body | | 400 | `No active variants` | The agent has no active variant (on that channel) | | 401 | `Unauthorized` | Missing or unknown ingest token | | 403 | `Forbidden` | The connection is disabled | | 404 | `Agent not found` | No such agent in this app | | 404 | `User not found` | The user has not been sent to Herald | | 409 | `Agent is not active` | The agent is not active, or its sending is paused | | 500 | `Internal server error` | Server failure | ## GET /api/v1/decisions Exports the app's decisions and their outcomes, for a warehouse job or a loader's HTTP source that runs on a schedule. Each row is one message decision for one user in the app that owns the ingest token. ### Request | Query parameter | Rules | |---|---| | `since` | Optional ISO 8601 date-time with offset. Returns decisions made, delivered, opened, converted or rescored at or after it. Omit it for every decision. | | `cursor` | Optional; the `nextCursor` of the previous page. Keep the same `since` while you page. | | `limit` | Optional, 1 to 1,000; default 500 | :::tabs ::tab curl ```shell curl "https://YOUR_HERALD_HOST/api/v1/decisions?since=2026-11-15T00:00:00Z&limit=500" \ -H "Authorization: Bearer $HERALD_INGEST_TOKEN" ``` ::tab node ```javascript let cursor = null; do { const url = new URL("https://YOUR_HERALD_HOST/api/v1/decisions"); url.searchParams.set("since", "2026-11-15T00:00:00Z"); if (cursor) url.searchParams.set("cursor", cursor); const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.HERALD_INGEST_TOKEN}` } }); const { data } = await res.json(); await upsertRows(data.rows); // upsert on decisionId cursor = data.nextCursor; } while (cursor); ``` ::: ### Response | Field | Value | |---|---| | `rows` | Decisions, each with `decisionId`, `userId` (your External ID), `agentId`, `agentName`, `variantId`, `variantName`, `channel`, `sentAt`, `deliveryStatus`, `deliveredAt`, `openedAt` (the push open), `conversionEvent`, `conversionAt`, `conversionValue` and `reward` | | `nextCursor` | The cursor for the next page, or null on the last page | ```json { "data": { "rows": [ { "decisionId": "cmh…", "userId": "u_123", "agentId": "cmh…", "agentName": "Upgrade nudges", "variantId": "cmh…", "variantName": "Short copy", "channel": "push", "sentAt": "2026-11-15T08:00:00.000Z", "deliveryStatus": "delivered", "deliveredAt": "2026-11-15T08:00:02.000Z", "openedAt": "2026-11-15T09:10:00.000Z", "conversionEvent": "plan_started", "conversionAt": "2026-11-15T09:12:00.000Z", "conversionValue": 59.99, "reward": 1 } ], "nextCursor": "MjAyNi0xMS0xNVQwOToxMjowMC4wMDBafGNtaC4uLg" } } ``` `deliveryStatus` is `delivered`, `bounced`, `complained`, `failed`, `suppressed`, `expired`, `paused` or null. Times are ISO 8601 in UTC; a missing value is null. A decision comes back again whenever an outcome arrives, so rows change after you first load them. To sync: 1. Upsert on `decisionId`. 2. On each run, set `since` to the start of your previous run minus an overlap of at least 2 days. Delivery failures and bounces carry no timestamp of their own, so they surface only through the overlap; a weekly full reload catches anything later. Errors are the same as for the holdout export below. ## GET /api/v1/holdout Exports which users an agent messaged and which it held out, so your warehouse can compute lift. The agent must belong to the token's app. ### Request It takes `agentId` (required) plus the same `since`, `cursor` and `limit` as the decisions export. :::tabs ::tab curl ```shell curl "https://YOUR_HERALD_HOST/api/v1/holdout?agentId=AGENT_ID" \ -H "Authorization: Bearer $HERALD_INGEST_TOKEN" ``` ::tab node ```javascript const url = new URL("https://YOUR_HERALD_HOST/api/v1/holdout"); url.searchParams.set("agentId", "AGENT_ID"); const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.HERALD_INGEST_TOKEN}` } }); const { data } = await res.json(); // { rows, nextCursor } ``` ::: ### Response | Field | Value | |---|---| | `rows` | Assignments, each with `userId`, `agentId`, `assignedAt`, `group` (`treated` or `holdout`) and `goalConvertedAt` | | `nextCursor` | The cursor for the next page, or null on the last page | ```json { "userId": "u_123", "agentId": "AGENT_ID", "assignedAt": "2026-11-15T08:00:00.000Z", "group": "holdout", "goalConvertedAt": null } ``` `goalConvertedAt` is the user's first conversion on the agent's main goal while assigned; a row comes back when it is set. Each row is the user's current assignment: when a user moves to another agent, they leave this export. Upsert on `(agentId, userId)`. | Status | Body `error` | Cause | |---|---|---| | 200 | | Done | | 400 | `since must be an ISO 8601 timestamp`, `Invalid cursor`, `limit must be an integer from 1 to 1000`, or `agentId is required` | Bad query | | 401 | `Unauthorized` | Missing or unknown ingest token | | 403 | `Forbidden` | The connection is disabled | | 404 | `Agent not found` | No such agent in this app (holdout only) | | 500 | `Internal server error` | Server failure | ## GET /api/v1/exports/decisions.csv Downloads the app's decisions and outcomes sent in a date range as CSV, for a spreadsheet or a one-off load. It uses an API key with the `exports.read` scope, not the ingest token. See [Decisions CSV](/docs/integrations/reporting#decisions-csv) for the columns. ### Request | Query parameter | Rules | |---|---| | `from`, `to` | Dates as `YYYY-MM-DD`, UTC. Both days are included; at most 31 days | :::tabs ::tab curl ```shell curl -o decisions.csv "https://app.runherald.com/api/v1/exports/decisions.csv?from=2026-11-01&to=2026-11-21" \ -H "Authorization: Bearer $HERALD_API_KEY" ``` ::tab node ```javascript const res = await fetch("https://app.runherald.com/api/v1/exports/decisions.csv?from=2026-11-01&to=2026-11-21", { headers: { Authorization: `Bearer ${process.env.HERALD_API_KEY}` }, }); const csv = await res.text(); ``` ::: ### Response `text/csv` with a header row, one row per decision. Errors are JSON: | Status | Body `error` | Cause | |---|---|---| | 200 | | The CSV | | 400 | `from must be a date (YYYY-MM-DD)`, `to must be a date (YYYY-MM-DD)`, `to must not be before from` or `The range can be at most 31 days` | Bad range | | 401 | `Invalid API key` | Missing, unknown, revoked or expired key | | 403 | `This API key lacks the exports.read scope` | Wrong scope | | 429 | `Rate limit exceeded for exports.requests: 60 per hour` | Over the hourly limit | ## POST /api/v1/journeys/{id}/enter Adds people to a live journey whose entry is set to **When your server adds them (API)**. The journey's id is in its console address and in the entry step's settings. Each person enters only if they may: not already in the journey, allowed by its re-entry setting, and in its entry audience if it has one. Sending the same people again is harmless, so there's no `Idempotency-Key`. ### Request | Field | Rules | |---|---| | `people` | 1 to 1,000 items, each `{ "externalId": "..." }` (up to 200 characters); repeats count once | ```bash curl -X POST "https://YOUR_HERALD_HOST/api/v1/journeys/JOURNEY_ID/enter" \ -H "Authorization: Bearer hk_..." -H "Content-Type: application/json" \ -d '{ "people": [{ "externalId": "user_42" }, { "externalId": "user_43" }] }' ``` ### Response ```json { "data": { "entered": ["user_42"], "skipped": ["user_43"] } } ``` People who enter move to the journey's first step within about a minute. | Status | Body `error` | Cause | |---|---|---| | 200 | | Who entered and who was skipped | | 400 | `Send 1 to 1,000 people` or `Every person needs an externalId (up to 200 characters)` | Bad body | | 401 | `Invalid API key` | Missing, unknown, revoked or expired key | | 403 | `This API key lacks the journeys.enter scope` | Wrong scope | | 403 | `Starting journeys from the API isn't on this account's plan.` | The account's plan doesn't include API entry | | 404 | `No live journey with that id for this app` | Unknown id, another app's journey, or not live (paused, stopped or never published) | | 409 | `This journey isn't set to let people in through the API` | Its entry is an event or an audience | | 429 | `Rate limit exceeded for journeys.enter: 100000 per hour` | Over the hourly limit | ## POST and DELETE /api/v1/contacts Registers or removes contact points (email addresses, phone numbers and push tokens) for your users. Use it to import addresses and tokens you already hold, and to remove them on request. ### Request | Field | Rules | |---|---| | `contacts` | 1 to 1,000 items; body up to 512 KB | | `userId` | 1 to 200 characters | | `kind` | `email`, `phone`, `apns`, `apns_live_activity`, `fcm`, `webpush` | | `value` | 1 to 4,096 characters. `email` must be a valid address; `phone` must be E.164; `apns` and `apns_live_activity` must be 64 or more hex characters; `webpush` must be an HTTPS endpoint with `meta.p256dh` and `meta.auth`. | | `meta` | Optional object. For `apns`, `bundleId` overrides the connection's bundle ID and `sandbox: true` sends to the APNs sandbox. | :::tabs ::tab curl ```shell curl -X POST "https://YOUR_HERALD_HOST/api/v1/contacts" \ -H "Authorization: Bearer $HERALD_INGEST_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "contacts": [ { "userId": "u_123", "kind": "email", "value": "maya@example.com" }, { "userId": "u_123", "kind": "phone", "value": "+15551234567" }, { "userId": "u_123", "kind": "apns", "value": "<64 or more hex characters>", "meta": { "bundleId": "com.lumen.app", "sandbox": false } } ] }' ``` ::tab node ```javascript const res = await fetch("https://YOUR_HERALD_HOST/api/v1/contacts", { method: "POST", // DELETE with the same body removes them headers: { Authorization: `Bearer ${process.env.HERALD_INGEST_TOKEN}`, "Content-Type": "application/json" }, body: JSON.stringify({ contacts: [{ userId: "u_123", kind: "fcm", value: fcmToken }] }), }); const { data, error } = await res.json(); ``` ::: ### Response | Field | Value | |---|---| | `upserted` | `POST`: contacts created or updated, keyed on `(connection, kind, value)` | | `removed` | `DELETE`: contacts removed, matched on `kind` and `value` | | Status | Body `error` | Cause | |---|---|---| | 200 | | Done | | 400 | `Invalid JSON`, or `Invalid contacts payload: ...` with the field | Bad body | | 401 | `Unauthorized` | Missing or unknown ingest token | | 403 | `Forbidden` | The connection is inactive, or its type does not take contacts | | 413 | `Request body too large` | Over 512 KB | | 500 | `Internal server error` | Server failure | ## DELETE /api/v1/users/{userId} Erases one user's data held for a connection, for privacy requests. Only an SDK connection's ingest token is accepted. The `userId` path segment is 1 to 255 characters. :::tabs ::tab curl ```shell curl -X DELETE "https://YOUR_HERALD_HOST/api/v1/users/u_123" \ -H "Authorization: Bearer $HERALD_INGEST_TOKEN" ``` ::tab node ```javascript const res = await fetch(`https://YOUR_HERALD_HOST/api/v1/users/${encodeURIComponent(userId)}`, { method: "DELETE", headers: { Authorization: `Bearer ${process.env.HERALD_INGEST_TOKEN}` }, }); const { data } = await res.json(); ``` ::: ### Response | Field | Value | |---|---| | `userId` | The External ID | | `sdkDevices`, `sdkEvents`, `sdkMessages`, `contactPoints`, `outboundMessages`, `userArmStats`, `userAgentAssignments`, `pseudonymizedDecisions`, `failedSendsScrubbed` | Numbers of rows | | `trackedUser` | `deleted`, `cleared` or `none`; `none`, and the shared profile is left alone, when the connection held no data about the user | | Status | Body `error` | Cause | |---|---|---| | 200 | | Done. Repeating the call returns zero counts and `trackedUser` `none`. | | 400 | `userId must be 1 to 255 characters` | Bad External ID | | 401 | `Unauthorized` | Missing or unknown ingest token | | 403 | `Forbidden` | The connection is inactive, or its type does not take contacts | | 403 | `User deletion needs an SDK connection's ingest token` | The token belongs to a connection that is not an SDK connection, such as SendGrid | | 500 | `Internal server error` | Server failure | Decisions are kept with a pseudonymous External ID, and suppressions are kept so the address is not contacted again. See [User data deletion](/docs/data-and-privacy/user-data-deletion#what-is-deleted) for what is deleted and kept. ## Errors Every error body is `{ "error": "<message>" }`. The tables above list each endpoint's messages. For status meanings, retries and rate-limit headers, see [API errors](/docs/reference/api-errors). ## Related - [SDK REST endpoints](/docs/reference/rest-endpoints) - [Send API](/docs/reference/send-api) - [Importing push tokens and users](/docs/migration/importing-tokens-and-users) - [Warehouse sync](/docs/migration/warehouse-sync) Source: https://heraldsdk.com/docs/reference/server-api.md --- # Send API > Send push, web push, email, SMS, in-app messages and content cards from your backend to named people or a segment, now or on a schedule, with scoped API keys, hourly limits and idempotency. :::prereq - An app whose connection sends through Herald. The Send API refuses other connections with a 400. - An API key for that app with the scopes you need. See [Authentication](#authentication). - For email: a verified sending domain on the connection. ::: The Send API sends every channel Herald delivers to people you name or to a segment, immediately or on a schedule, with the message content in the request. Each send shows in the console's campaign list. It uses the same scheduling, local time, quiet hours, suppression and unsubscribe checks as a campaign. ## Authentication Send `Authorization: Bearer hk_…` with every request. Create keys under **Settings → Sending**, the app, then **API keys**. Herald shows a key once. A key belongs to one app. Its scopes, optional IP allowlist and optional expiry are fixed when you create it; to change them, create a new key and revoke the old one. | Scope | Allows | |---|---| | `messages.send` | `POST /api/v1/messages/send` | | `messages.schedule` | A send with `schedule` (together with `messages.send`), and changing or cancelling a scheduled send | | `messages.read` | Reading one send and listing sends | | `exports.read` | The [decisions CSV](/docs/reference/server-api#get-api-v1-exports-decisions-csv) | | `journeys.enter` | [Adding people to a journey](/docs/reference/server-api#post-api-v1-journeys-id-enter) | | `mcp.read`, `mcp.write` | The [MCP server](/docs/integrations/ai-assistants) | A missing, unknown, revoked or expired key gets `401 Invalid API key`. A key without a scope gets `403 This API key lacks the <scope> scope`. The ingest token and the app key can never send, and an API key can't call the ingest or console endpoints. ## Base URL `https://app.runherald.com`. Requests and responses are JSON: `{ "data": ... }` on success and `{ "error": "..." }` on failure. ## Rate limits Each app has hourly pools, counted per UTC clock hour. A request charges every pool it touches at once: if any would go over, nothing is charged and the response is `429` naming the pool. | Pool | Counts | Default per hour | |---|---|---| | `api.requests` | Any request made with an API key | 36,000 | | `messages.push` | Recipients | 250,000 | | `messages.web_push` | Recipients | 250,000 | | `messages.email` | Recipients | 100,000 | | `messages.sms` | Recipients | 2,000 | | `messages.in_app` | Recipients | 250,000 | | `messages.content_card` | Recipients | 250,000 | | `messages.broadcast` | Broadcast requests | 25 | | `messages.schedule` | Change or cancel requests | 1,000 | | `messages.read` | Status or list requests | 3,600 | A send charges each channel's pool once per recipient. A broadcast charges `messages.broadcast` once, since its audience size isn't known until it goes out. A `dry_run` charges only `api.requests`. Every response carries the rate-limit headers; see [API errors](/docs/reference/api-errors#rate-limits). Send API pushes count toward the app's [push limit](/docs/push-notifications/pushes-your-app-sends#the-push-limit) but are never skipped by it. ## Idempotency Send `Idempotency-Key` (1 to 255 characters) on `POST /api/v1/messages/send` so a retry can't send twice. Keys are per app and kept for 24 hours. - The same key and the same body (key order doesn't matter) return the first response again, with nothing sent. - The same key with a different body gets `409 This Idempotency-Key was used with a different request`. - While the first request is still running, the key gets `409 A request with this Idempotency-Key is still in progress`. A claim unfinished after 2 minutes is treated as abandoned. - A failed request releases its key, so you can retry with it. - A `dry_run` never uses the key. ## POST /api/v1/messages/send Scope `messages.send`, plus `messages.schedule` when the body has `schedule`. ### Request | Field | Rules | |---|---| | `name` | Optional, 1 to 80 characters. Default `API send <time>` | | `recipients` | 1 to 50 people, each `{ "external_user_id": "...", "properties": { ... } }`. IDs are 1 to 255 characters and unique. `properties` holds strings, numbers or booleans for personalization | | `broadcast`, `segment` | Instead of `recipients`: `"broadcast": true` and a segment name. Never both | | `messages` | At least one channel: `push`, `web_push`, `email`, `sms`, `in_app`, `content_card`. See [Channel content](#channel-content) | | `schedule` | Optional; absent means now. `{ "time": "2026-12-01T09:00:00Z" }` is that instant. `{ "time": "2026-12-01T09:00:00", "in_local_time": true }` (no offset) is each person's local wall time, or the app's time zone when theirs is unknown. In the future and at most 30 days ahead | | `quiet_hours` | Optional `skip`, `wait` or `off`. Default `off` for recipients (transactional) and `skip` for broadcasts | | `category` | Optional category key, such as `transactional`, `lifecycle`, `engagement` or `promotions`. An unknown key is a 400. With a category the message follows that category's budget rules (transactional is exempt; in Enforce mode, others can be held or deferred like a campaign). Without one it is never held and counts toward the channel limit only. Pass one. See [Message priority](/docs/concepts/message-priority) | | `dry_run` | Optional `true`: validate and count without storing or sending | **Personalization.** Any string field can hold `{{key}}` or `{{key|fallback}}`, filled from each recipient's `properties`. Every placeholder without a fallback must exist for every recipient, or the request fails with 400. Values are HTML-escaped in email HTML. Broadcasts have no properties, so only placeholders with a fallback work there. People this app can't reach (an unknown `external_user_id`, or one with no reachable contact or device) are skipped, never created, and listed in `unknown_recipients`. If none of the recipients exist, the request fails with 400. :::tabs ::tab curl ```shell curl -X POST "https://app.runherald.com/api/v1/messages/send" \ -H "Authorization: Bearer $HERALD_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: order-A-991-shipped" \ -d '{ "name": "Order shipped", "recipients": [ { "external_user_id": "u_123", "properties": { "first_name": "Ana", "order": "A-991" } } ], "messages": { "push": { "title": "Hi {{first_name}}", "body": "Order {{order}} shipped", "deeplink": "myapp://orders" } } }' ``` ::tab node ```javascript const res = await fetch("https://app.runherald.com/api/v1/messages/send", { method: "POST", headers: { Authorization: `Bearer ${process.env.HERALD_API_KEY}`, "Content-Type": "application/json", "Idempotency-Key": "order-A-991-shipped", }, body: JSON.stringify({ name: "Order shipped", recipients: [{ external_user_id: "u_123", properties: { first_name: "Ana", order: "A-991" } }], messages: { push: { title: "Hi {{first_name}}", body: "Order {{order}} shipped", deeplink: "myapp://orders" } }, }), }); const { data, error } = await res.json(); ``` ::: ### Response `202` with the send: | Field | Value | |---|---| | `send_id` | The send's ID, for status, change and cancel | | `name` | The send's name | | `status` | `scheduled` | | `scheduled_for` | When it goes out: an instant, or a wall time with no offset when `in_local_time` | | `in_local_time` | Whether `scheduled_for` is each person's local time | | `created_at` | When the send was created | | `recipients` | People it will reach (for a broadcast, the segment's current count) | | `unknown_recipients` | External IDs that were skipped | | `channels` | The channels in the send | ```json { "data": { "send_id": "cmh…", "name": "Order shipped", "status": "scheduled", "scheduled_for": "2026-11-24T18:00:00.000Z", "in_local_time": false, "created_at": "2026-11-24T18:00:00.000Z", "recipients": 1, "unknown_recipients": [], "channels": ["push"] } } ``` A `dry_run` answers `200` with `{ "valid": true, "recipients", "unknown_recipients", "channels", "charges" }`, where `charges` maps each pool to what a real send would charge. ### Channel content | Channel | Fields | |---|---| | `push` | `title` (1 to 65), `body` (1 to 240), optional `imageUrl`, `deeplink`, `story` (see [Push stories](#push-stories)) | | `web_push` | `title` (1 to 65), `body` (1 to 240), optional `url`, `iconUrl` | | `email` | `fromName` (1 to 60, no `<`, `>` or quotes), `fromDomainId` (a verified sending domain), `subject` (1 to 120), optional `preheader` (up to 140), and exactly one of `html` or `templateId` | | `sms` | `body` (1 to 1,600) | | `in_app` | `layout` (`modal` or `slideup`), `title` (up to 60), `body` (up to 240), optional `imageUrl`, `buttons` (up to 2, each `label` up to 24 and optional `deeplink`), optional `trigger` (`{ "kind": "next_open" }` or `{ "kind": "event", "name": "..." }`) | | `content_card` | `title` (up to 60), `body` (up to 240), `pinned` (true or false), optional `imageUrl`, `link`, `expiresAt` (UTC, ending in `Z`) | Lengths count characters. Links must be `http(s)` URLs or app links such as `myapp://path`. ### Push stories A push can be a story: 2 to 10 pages the person flips through. Add `story` to `messages.push`: ```json { "push": { "story": { "pages": [ { "imageUrl": "https://cdn.example.com/plans.jpg", "title": "New plans", "subtitle": "Start one today", "deeplink": "myapp://plans" }, { "imageUrl": "https://cdn.example.com/streak.jpg", "title": "Streaks", "subtitle": "Keep yours going" } ] } } } ``` - Each page has `imageUrl` (an `https` URL, required), `title` (1 to 65), `subtitle` (1 to 240) and an optional `deeplink`. A page without a `deeplink` opens the app. - `title`, `body`, `imageUrl` and `deeplink` on the push are optional with a story and are replaced by the first page's (its subtitle becomes the body), so a device without story support shows the first page as a normal push. - The pages (as compact JSON) plus the first page's title, subtitle, image URL and link must fit in 3,400 bytes, because the first page is sent twice; Apple and Google cap a push at 4 KB. - A story takes no `media`. - Errors start with `messages.push: story: `, for example `messages.push: story: page 2 needs an https image URL`. See [Push stories](/docs/push-notifications/push-stories) for what the apps need. ## GET /api/v1/messages/{id} Scope `messages.read`. Returns one send this app created through the API. :::tabs ::tab curl ```shell curl "https://app.runherald.com/api/v1/messages/SEND_ID" \ -H "Authorization: Bearer $HERALD_API_KEY" ``` ::tab node ```javascript const res = await fetch(`https://app.runherald.com/api/v1/messages/${sendId}`, { headers: { Authorization: `Bearer ${process.env.HERALD_API_KEY}` }, }); const { data } = await res.json(); ``` ::: | Field | Value | |---|---| | `send_id`, `name`, `scheduled_for`, `in_local_time`, `created_at` | As in the send response | | `status` | `scheduled`, `expanding`, `sending`, `sent`, `partly_sent`, `cancelled` or `failed` | | `channels` | Per channel: `targeted`, `error` (why the channel failed, else null), and counts by status: `queued`, `sending`, `sent`, `failed`, `suppressed`, `cancelled`. In-app messages and content cards report `delivered` instead | Status lookups are meant for occasional checks; they count toward `messages.read`. ## GET /api/v1/messages Scope `messages.read`. Lists this app's API sends, newest first. | Query parameter | Rules | |---|---| | `status` | Optional; one of the statuses above | | `limit` | Optional, 1 to 100; default 50 | | `cursor` | Optional; the `next_cursor` of the previous page | :::tabs ::tab curl ```shell curl "https://app.runherald.com/api/v1/messages?status=scheduled&limit=20" \ -H "Authorization: Bearer $HERALD_API_KEY" ``` ::tab node ```javascript const res = await fetch("https://app.runherald.com/api/v1/messages?status=scheduled&limit=20", { headers: { Authorization: `Bearer ${process.env.HERALD_API_KEY}` }, }); const { data } = await res.json(); // { sends, next_cursor } ``` ::: The response is `{ "data": { "sends": [...], "next_cursor": "..." } }`. Each send has the fields of the send response plus `channels`. `next_cursor` is null on the last page. ## PATCH /api/v1/messages/{id} Scope `messages.schedule`. Changes a scheduled send. The body takes any of `schedule`, `messages` and `name`, with the same rules as the send. `messages` replaces the content of the channels it names; it can't add or remove channels. `schedule: null` is refused; leave it out to keep the current time. A send can change only while its status is `scheduled` and more than 5 minutes before it goes out. Otherwise the answer is `409 This send has already started`. :::tabs ::tab curl ```shell curl -X PATCH "https://app.runherald.com/api/v1/messages/SEND_ID" \ -H "Authorization: Bearer $HERALD_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "schedule": { "time": "2026-12-02T09:00:00", "in_local_time": true } }' ``` ::tab node ```javascript const res = await fetch(`https://app.runherald.com/api/v1/messages/${sendId}`, { method: "PATCH", headers: { Authorization: `Bearer ${process.env.HERALD_API_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ schedule: { time: "2026-12-02T09:00:00", in_local_time: true } }), }); ``` ::: The response is the send's summary with its `channels`. ## DELETE /api/v1/messages/{id} Scope `messages.schedule`. Cancels a scheduled send; messages not yet delivered are cancelled. A send that has started gets `409 This send has already started`. :::tabs ::tab curl ```shell curl -X DELETE "https://app.runherald.com/api/v1/messages/SEND_ID" \ -H "Authorization: Bearer $HERALD_API_KEY" ``` ::tab node ```javascript await fetch(`https://app.runherald.com/api/v1/messages/${sendId}`, { method: "DELETE", headers: { Authorization: `Bearer ${process.env.HERALD_API_KEY}` }, }); ``` ::: It returns `{ "data": { "send_id": "...", "status": "cancelled" } }`. ## Errors | Status | Body `error` | Cause | |---|---|---| | 400 | `Invalid JSON body` or `Body must be a JSON object` | The body is not a JSON object | | 400 | A rule and its field, such as `recipients must have 1 to 50 entries`, `messages.push: ...` or `schedule must be in the future` | The request breaks a rule above | | 400 | `Recipient "u_123" has no "first_name" property for messages.push` | A placeholder without a fallback has no value | | 400 | `category must be one of: <keys>` | `category` isn't a category key of this app | | 400 | `None of the recipients exist` | No recipient is known to this app | | 400 | `Pick a verified sending domain` | `email` has no `fromDomainId`, or it isn't a verified domain of this connection | | 400 | `The Send API needs a connection that sends through Herald` | The key's app sends through another tool | | 400 | `Idempotency-Key must be 1 to 255 characters` | Bad header | | 401 | `Invalid API key` | Missing, unknown, revoked or expired key | | 403 | `This API key lacks the <scope> scope` | Wrong scopes | | 403 | `This API key's app is disabled` | The app is turned off | | 403 | `This IP address isn't allowed for this API key` | The key has an IP allowlist | | 404 | `Send not found` | No such send created through this app's API keys | | 409 | `This send has already started` | Change or cancel too late | | 409 | `This Idempotency-Key was used with a different request`, or `A request with this Idempotency-Key is still in progress` | See [Idempotency](#idempotency) | | 429 | `Rate limit exceeded for <pool>: <limit> per hour` | Over a pool's hourly limit; wait for `Retry-After` | | 500 | `Internal server error` | Server failure | See [API errors](/docs/reference/api-errors) for status meanings, retries and headers. ## Held messages A send with a `category` can be held by the person's attention budget. The message is recorded as suppressed with the error `budget:budget_full`, `budget:category_cap`, `budget:reserved` or `budget:expired`; see [Message priority](/docs/concepts/message-priority#when-a-message-is-held). ## Not in this version Status webhooks, per-person frequency caps for API sends without a `category` (quiet hours apply; agent caps don't), per-key rate limits (limits are per app), optimal-time sends and Live Activities. ## Related - [Server API](/docs/reference/server-api) - [API errors](/docs/reference/api-errors) - [How delivery works](/docs/concepts/how-delivery-works) Source: https://heraldsdk.com/docs/reference/send-api.md --- # Event payload spec > Every event type the SDK sends, with its fields and the server's constraints, and the device context sent with each batch in its two tiers. Every SDK call that records something becomes an event in the device's queue. Events travel to Herald inside a batch, through `POST /api/v1/sdk/batch` ([SDK REST endpoints](/docs/reference/rest-endpoints#post-api-v1-sdk-batch)). This page lists every event type and the device context, with the rules the server enforces. Lengths count UTF-16 code units. The SDKs check these rules on the device and drop a call that breaks them. If an event still breaks a rule, Herald rejects only that event, keeps the rest of the batch and lists it in the response's `rejected` (see [Rejected events](/docs/reference/error-codes#rejected-events)). An event can be up to 32 KB as JSON. ## Fields on every event | Field | Type | Rules | |---|---|---| | `id` | string | 1 to 128 characters. A UUID the SDK creates. Herald stores each ID once per connection. | | `type` | string | One of the types below | | `timestamp` | string | ISO 8601 date-time with offset; when the call was made, by the device's clock. Herald stores it corrected for the device's clock (see [Clock correction](/docs/concepts/batching-and-offline#clock-correction)) and rejects events more than 30 days old | | `sessionId` | string | Optional, 1 to 64 characters. The session start time in epoch milliseconds. | ## Event types ### session_start | Field | Type | Rules | |---|---|---| | `properties.session_index` | integer | Optional (SDK 0.6.0 and later), 1 or more. Sessions started on this install, counting from 1. | | `properties.previous_session_id` | string or null | Optional (SDK 0.6.0 and later), 1 to 64 characters. The session before this one on the install; null for the first. After an update from an earlier SDK, the first new session has `session_index` 1 but can name the last session of the old SDK. | Queued when a session starts. A wrong type rejects the event (`invalid_field`); other keys in `properties` are dropped. SDKs before 0.6.0 send no `properties`. See [Sessions](/docs/concepts/sessions). ### session_end | Field | Type | Rules | |---|---|---| | `durationSeconds` | number | 0 or more; last activity minus start | Queued when the next session starts, at sign-out and at a user switch. Its timestamp is the session's last activity. ### identify | Field | Type | Rules | |---|---|---| | `userId` | string | 1 to 200 characters | | `traits` | object | Optional. Attribute map (see below). | From `identify`. Traits are merged into the profile of a verified user. ### track | Field | Type | Rules | |---|---|---| | `name` | string | 1 to 255 characters | | `properties` | object | Optional. Keys up to 255 characters; values any JSON. | | `schemaVersion` | string | Optional. SDK 0.6.0 and later. The [event schema](/docs/concepts/event-schemas) version to check the event against, such as `1-0-0`; without it (or null), the latest version. Ignored, whatever its value, when the event name has no schema; when it has one, a value that isn't one of its versions rejects the event (`unknown_schema_version`). The SDKs send only well-formed versions. | From `track`, and the SDK's lifecycle events below. #### Lifecycle events SDK 0.6.0 and later send these `track` events on their own. Each property is checked for its type when present; a wrong type rejects the event (`invalid_field`). They are sent in minimal data collection too, since they carry no personal data. They show as system events on the Events page, and you can pick them as goals and in segment rules like any event name. | Name | Fires | Properties | |---|---|---| | `$app_installed` | The first launch of this install. Doesn't start a session. | `version`, `build` (strings) | | `$app_updated` | The first launch with a different app version or build than the last launch. Doesn't start a session. | `version`, `build`, `previous_version`, `previous_build` (strings) | | `$app_opened` | The first foreground of the app's process: a cold start, or a process the system started in the background that the person then opens | `from_push` (boolean): the launch came from a notification tap the SDK saw first (see below) | | `$app_foreground` | Every move from the background to the foreground, and a launch's first foreground. Not after a system alert, Control Center, Face ID or a call banner (iOS), nor a rotation, dark mode change or resize (Android). | None | | `$app_background` | Every move to the background. Never starts or ends a session. | None | | `$deep_link_opened` | A deep link goes through the SDK: a push tap's link, or `openDeepLink` (iOS) / `openUrl` (Android), which the default message and card views use | `scheme`, `host`, `path`, `query` (strings), `source` (`push` or `link`) | `trackLifecycleEvents` (default on) turns off the first five, `trackDeepLinks` (default on) the last. `$deep_link_opened` never has the fragment or `;parameters`, and has the query only with `trackDeepLinkQuery` on. A URL without a host (`mailto:`, `tel:`, `sms:`, `data:`) sends `scheme` and `source` only, so an address or number never reaches the event log. In minimal data collection it has `scheme`, `host` and `source` only. The path of a web link is sent, so keep tokens out of link paths. On iOS, `from_push` is reliable only in apps that forward the notification response (`handleNotificationResponse`) before the app becomes active. Scene-based apps, including SwiftUI apps, usually get the response after activation, so they usually report `false` even for a launch from a push. On Android it is reliable when `handleNotificationIntent` runs in the activity's `onCreate`. `$app_opened`, `$app_foreground` and the app's other events count as app activity (last active, active days, send-time checks); `$app_installed`, `$app_updated`, `$app_background` and `$external_push` don't: iOS and Android can launch an app in the background, and a push your app reports isn't the person using it. Server events from your backend (other than `$external_push`) do update last active, active days and DAU/MAU, but never the send-time checks, which count only activity from the device. An app updated from an SDK before 0.6.0 doesn't send `$app_updated` on its first 0.6.0 launch; it stores the version then. `$external_push` is a reserved `track` name for a push your app sent itself. Its properties are `category` (`transactional`, `marketing` or `other`; default `other`; any other value rejects the event with `invalid_field`), an optional `message_id` (1 to 200 characters) and an optional `source` (1 to 100 characters). Other properties are dropped, so a title or body is never stored. Events with the same `message_id` for the same user are stored once, whether the SDK or your backend sends them. The SDKs send it with `trackExternalPush`. See [Pushes your app sends](/docs/push-notifications/pushes-your-app-sends). #### Geofence events SDK 0.7.0 and later (not released yet) send these `track` events from the `HeraldGeofence` (iOS) and `herald-geofence` (Android) modules, only after the app calls `enableGeofences()`. Each property is checked for its type when present; a wrong type rejects the event (`invalid_field`). They don't count as app activity: crossings happen in the background. | Name | Fires | Properties | |---|---|---| | `$geofence_enter` | The device entered one of the app's geofences. At most once per geofence every 5 minutes. | `geofence_id`, `geofence_name` (strings) | | `$geofence_exit` | The device left one. At most once per geofence every 5 minutes. | `geofence_id`, `geofence_name` (strings) | No coordinates are sent. See [Geofences](/docs/concepts/geofences). ### screen Same fields as `track`. From `screen`. ### purchase | Field | Type | Rules | |---|---|---| | `productId` | string | 1 to 255 characters | | `price` | number | Any number; the SDKs require it to be finite | | `currency` | string | Exactly 3 characters; the SDKs send it upper-cased | | `quantity` | integer | 1 or more | | `properties` | object | Optional. Same rules as `track`. | From `trackPurchase`. ### attributes | Field | Type | Rules | |---|---|---| | `attributes` | object | Attribute map (see below) | From `setAttribute`, `setAttributes`, `setEmail`, `setPhone` and `setLocation`. **Attribute map.** Keys 1 to 255 characters. Values: string, number, boolean, null, or an array of strings. Reserved keys: | Key | Stored as | |---|---| | `$email` | The user's email contact. An invalid address is skipped; the rest of the event is kept. | | `$phone` | The user's SMS contact, E.164. An invalid number is skipped. | | `$latitude`, `$longitude` | The device's location (numbers, -90 to 90 and -180 to 180). Not written to the user profile. | | `computed_…` | Reserved for [computed attributes](/docs/concepts/computed-attributes). An event with such a key is rejected with `invalid_field`. | Every other key is merged into the verified user's profile: a key you send replaces the stored value, and keys you do not send stay. ### subscription | Field | Type | Rules | |---|---|---| | `channel` | string | `push`, `email`, `sms` | | `state` | string | `subscribed`, `unsubscribed`, `opted_in` | From `setSubscription` and `requestPushAuthorization`. `unsubscribed` suppresses the channel: for push, this device's tokens; for email and SMS, the user's addresses. The other states lift an earlier unsubscribe, never a bounce or complaint. With no matching contact, the event changes nothing. ### push_token | Field | Type | Rules | |---|---|---| | `platform` | string | `apns`, `fcm`, or `apns_live_activity` (the iOS Live Activity push-to-start token) | | `token` | string | 1 to 4,096 characters. APNs tokens are lowercase hex. | | `environment` | string | Optional, APNs only: `production` or `sandbox` | | `bundleId` | string | Optional, 1 to 255 characters | From `setPushToken`, and sent again after `identify`, a user switch and `reset()`. Within a batch, a `push_token` always comes before a push `subscription`. A new token replaces this device's previous one. ### interaction | Field | Type | Rules | |---|---|---| | `messageId` | string | 1 to 200 characters | | `kind` | string | `content_card`, `in_app`, `push` | | `action` | string | `impression`, `click`, `dismiss`, `open`, `button`, `video_play`, `video_complete` | | `buttonId` | string | 1 to 200 characters; required when `action` is `button` | | `decisionId` | string or null | Optional, 1 to 200 characters | | Kind | Actions the SDK sends | From | |---|---|---| | `content_card` | `impression`, `click`, `dismiss`, `video_play`, `video_complete` | The default feed, or `logImpression`, `logClick`, `logDismissal`, `logVideoPlay`, `logVideoComplete` | | `in_app` | `impression`, `click`, `button`, `dismiss`, `video_play`, `video_complete` | The presenter, or `logVideoPlay`, `logVideoComplete` (iOS) and `InAppMessageActions` or `InAppMessageCallbacks` (Android) | | `push` | `open`, `button`, `dismiss` (iOS, with a custom dismiss action) | `handleNotificationResponse` (iOS), `handleNotificationIntent` (Android) | For a push, `messageId` is the push's `herald_message_id`, else its decision ID. A push button tap sends `open`, then `button`. `video_play` and `video_complete` (SDK 0.6.0) are sent once per play of a video in a card or an in-app message. They are stored as events and are not credited to a decision: they change none of the viewed, clicked or dismissed states. How Herald credits a decision: `impression` counts as delivered; `click` and `button` count as a click; `dismiss` as a dismissal; a push `open` as an open. Credit goes only to a decision that belongs to the verified user. ## Context Each batch carries a `context` object with the device's current data. Tier 2 keys are absent, not null, in minimal mode. ### Tier 1: always sent | Field | Type | Max length | Example | |---|---|---|---| | `app.name` | string | 255 | `Lumen` | | `app.version` | string | 64 | `4.2.0` | | `app.build` | string | 64 | `812` | | `app.namespace` | string | 255 | `com.lumen.app` (bundle ID or package name) | | `os.name` | string | 1 to 64 | `iOS`, `Android` | | `os.version` | string | 64 | `18.1` | | `region` | string or null | 8 | `US`, from the device locale | The batch also carries `deviceId`, `sdk.name` and `sdk.version` at the top level. ### Tier 2: standard mode only | Field | Type | Max length | Values | |---|---|---|---| | `device.manufacturer` | string | 128 | `Apple`, or the Android build manufacturer | | `device.model` | string | 128 | Model identifier, such as `iPhone16,1` | | `device.type` | string | 32 | iOS: `phone`, `tablet`, `tv`, `desktop`, `car`, `headset`. Android: `phone`, `tablet`. | | `screen.width`, `screen.height` | number | | Points on iOS, dp on Android | | `screen.density` | number | | Scale factor | | `locale` | string | 64 | BCP 47 tag, such as `en-US` | | `language` | string | 32 | `en` | | `timezone` | string | 64 | IANA zone, such as `America/Chicago` | | `network.type` | string | 32 | `wifi`, `cellular`, `ethernet`, `other`, `none` | | `push.authorization` | string | 32 | iOS: `authorized`, `denied`, `provisional`, `ephemeral`, `not_determined`. Android: `authorized`, `denied`, `not_determined` (Android 13 and later, before the permission is requested). | The SDKs cut over-long strings to these maxima. A field the device cannot read is left out. ### Consent: while set SDK 0.6.0+. Sent in both modes from the app's `setConsent` call until `clearConsent`. An invalid or null value is left out and the rest of the batch is kept; Herald stores it as a rejected event with reason `invalid_consent` (see [Rejected events](/docs/reference/error-codes#rejected-events)). | Field | Type | Max length | Values | |---|---|---|---| | `consent.basis` | string | | `consent`, `contract`, `legal_obligation`, `vital_interests`, `public_task`, `legitimate_interests` | | `consent.documentId` | string, optional | 100 | Your policy or terms, such as `privacy-policy` | | `consent.documentVersion` | string, optional | 100 | Such as `2026-11` | | `consent.recordedAt` | ISO 8601 time | | When the app called `setConsent` | Herald keeps it on the device record and, for a verified user, as the reserved attribute `$consent` (the latest one sent). Apps can't set `$consent` through attributes. Never sent: advertising identifiers, IDFV, Android ID, carrier, IP address, and location (unless your app calls `setLocation`). ## Example ```json { "sdk": { "name": "herald-android", "version": "0.4.0" }, "deviceId": "0f5e8c1a-7d1b-4b9e-8a52-3c6d2e1f4a90", "userId": "u_123", "sentAt": "2026-11-09T14:00:05Z", "dropped": 0, "context": { "app": { "name": "Lumen", "version": "4.2.0", "build": "812", "namespace": "com.lumen.app" }, "os": { "name": "Android", "version": "15" }, "region": "US", "device": { "manufacturer": "Google", "model": "Pixel 8", "type": "phone" }, "screen": { "width": 412, "height": 915, "density": 2.625 }, "locale": "en-US", "language": "en", "timezone": "America/Chicago", "network": { "type": "wifi" }, "push": { "authorization": "authorized" } }, "events": [ { "id": "e1", "type": "session_start", "timestamp": "2026-11-09T13:58:00Z", "sessionId": "1762696680000", "properties": { "session_index": 4, "previous_session_id": "1762610280000" } }, { "id": "e2", "type": "push_token", "timestamp": "2026-11-09T13:58:01Z", "sessionId": "1762696680000", "platform": "fcm", "token": "fcm-token", "bundleId": "com.lumen.app" }, { "id": "e3", "type": "subscription", "timestamp": "2026-11-09T13:58:01Z", "sessionId": "1762696680000", "channel": "push", "state": "opted_in" }, { "id": "e4", "type": "track", "timestamp": "2026-11-09T13:59:58Z", "sessionId": "1762696680000", "name": "workout_completed", "properties": { "minutes": 32 } }, { "id": "e5", "type": "interaction", "timestamp": "2026-11-09T14:00:02Z", "sessionId": "1762696680000", "messageId": "msg_1", "kind": "content_card", "action": "click", "decisionId": "dec_1" } ] } ``` ## Related - [SDK REST endpoints](/docs/reference/rest-endpoints) - [Events and attributes](/docs/concepts/events-and-attributes) - [Device data collected](/docs/concepts/device-data) - [Limits](/docs/reference/limits) Source: https://heraldsdk.com/docs/reference/event-payload.md --- # Error codes > The HTTP status codes the SDK endpoints return, what the SDK does with each, and the SDK log messages worth acting on. The SDK never throws into your app. A problem shows up in two places: an HTTP status from Herald, which the SDK handles on its own, and a line in the device log. This page lists both. ## HTTP status codes These apply to `POST /api/v1/sdk/batch` and `GET /api/v1/sdk/messages`. Every error body is `{ "error": "<message>" }`. | Status | Error message | Cause | SDK behavior | Fix | |---|---|---|---|---| | 200 | | Accepted. Events Herald couldn't accept are listed in `rejected` (see [Rejected events](#rejected-events)); the rest were kept | Batch removed from the queue; each rejected event logged at debug level, never retried | Fix the reason in your app | | 304 | | Messages unchanged (fetch only) | Keeps the cached messages | | | 400 | `Invalid JSON` | The body is not JSON | Batch dropped | Should not happen with the SDKs; report it | | 400 | A field path and message, such as `deviceId: Too small: expected string to have >=1 characters` | The batch itself breaks the schema (a bad event is rejected on its own instead). Servers before per-event validation answered this for a bad event too, such as `events[2].name: Required` | Batch dropped | Update the SDK; the device checks should have stopped the call | | 400 | `deviceId: ...` | Bad fetch query | Cached messages kept | Should not happen with the SDKs | | 401 | `Invalid app key` | The key is wrong, or its connection is not active | Keeps every queued event and sends nothing more until the app launches again | Copy the key again from the **Mobile SDK** card | | 401 | `Invalid user token` | Verification is **Required** and the token is missing or wrong, or it is **Optional** and the token is wrong | Keeps that user's events until the app calls `setUserToken`; anonymous events keep flowing | Mint the token from the same user ID; call `setUserToken` after `identify`; re-mint after rotating the ingest token | | 408 | | Request timeout (from a proxy) | Kept and retried | None needed | | 413 | `Batch exceeds 512 KB` or `Batch exceeds 100 events` | Too large | Batch dropped | Should not happen with the SDKs; report it | | 429 | | Rate limited (from a proxy or firewall) | Kept and retried after `Retry-After` | None needed; check firewall rules if it persists | | 500 | `Internal server error` | Server failure | Kept and retried with backoff | Contact your account team if it persists | | 5xx | | Server or gateway failure | Kept and retried with backoff | None needed if it clears | A batch that is dropped is gone: its events are not sent again. Kept events still count toward the queue limit, so the oldest are dropped if the cause is never fixed. See [Batching and offline](/docs/concepts/batching-and-offline). ## Rejected events `POST /api/v1/sdk/batch` and `POST /api/v1/events` check each event on their own. A bad event is left out and the rest are applied; the response is still 200 and lists it: ```json { "data": { "accepted": 2, "duplicates": 0, "rejected": [{ "id": "e2", "index": 1, "reason": "missing_field", "detail": "events[1].name: Invalid input: expected string, received undefined" }] } } ``` `rejected` is there only when something was rejected. `id` is the event's ID, or null when it has no usable one; `index` is its position in `events`. Retrying never helps, so the SDKs don't retry a rejected event. Each connection's page in the console (**Settings → Sending & SDK**, then the connection) lists its recent rejected events under **Rejected events**, from the SDK or from `POST /api/v1/events`, kept for 30 days. Any email, phone, token, password, secret, authorization or API key field, at any depth (traits, attributes, properties), and any value that looks like an email, is blanked in the stored copy. | Reason | Console label | Cause | |---|---|---| | `invalid_type` | Unknown event type | `type` is not one the API knows | | `missing_field` | Missing field | A required field is missing | | `invalid_field` | Invalid field | A field has the wrong type, length or value, or the event is not an object. Includes a [lifecycle event](/docs/reference/event-payload#lifecycle-events) property of the wrong type, such as a `from_push` that isn't a boolean, and an attribute key starting with `computed_`, which is reserved for [computed attributes](/docs/concepts/computed-attributes) | | `too_old` | Too old | SDK events only: the event time is more than 30 days before Herald received it (after [clock correction](/docs/concepts/batching-and-offline#clock-correction)). Server events have no age limit | | `in_future` | Time in the future | The event time is more than 5 minutes after Herald received it. Only `POST /api/v1/events` can hit it: SDK event times are never later than arrival | | `too_large` | Too large | The event is over 32 KB as JSON. The SDKs drop such an event on the device (counted in `dropped`), so it comes from older SDKs or server events | | `schema_violation` | Schema violation | The event's name has an [event schema](/docs/concepts/event-schemas) in **Reject invalid events** mode and the event breaks it. `detail` names the first failing property and rule, such as `properties.plan: must be one of free, pro (schema signup 1-0-0)` | | `unknown_schema_version` | Unknown schema version | The event's `schemaVersion` names a version its event schema doesn't have | | `schema_warning` | Schema warning (accepted) | Not a reject: the event broke a schema in **Accept and warn** mode and was kept. Stored for the console only (up to 200 a day, apart from the 1,000 rejects), never listed in the response's `rejected` | | `invalid_consent` | invalid_consent | Not an event: the batch's `context.consent` (SDK 0.6.0) is invalid or null, so it was left out and the batch kept. Stored with no event type and never listed in the response's `rejected`. The SDKs check `setConsent`, so it comes from other clients | New codes may be added; treat an unknown one like `invalid_field`. ## Contacts API `POST` and `DELETE /api/v1/contacts`, called from your backend: | Status | Error message | Cause | |---|---|---| | 400 | `Invalid JSON` | The body is not JSON | | 400 | `Invalid contacts payload: <reason> (<field>)` | A contact breaks a rule, such as `apns token must be 64+ hex characters` or `phone must be E.164` | | 401 | `Unauthorized` | Missing or unknown ingest token | | 403 | `Forbidden` | The connection is inactive, or its type does not take contacts | | 500 | `Internal server error` | Server failure | ## Users and events APIs `POST /api/v1/users` and `POST /api/v1/events`, called from your backend: | Status | Error message | Cause | |---|---|---| | 400 | `Invalid JSON` | The body is not JSON | | 400 | `Invalid users payload: ...` or `Invalid events payload: ...` | A field breaks a rule; the message names it. For events, only the request itself (not an object, no `events` array, 0 or over 1,000 events); a bad event is [rejected on its own](#rejected-events) | | 401 | `Unauthorized` | Missing or unknown ingest token | | 403 | `Forbidden` | The connection is disabled | | 413 | `Body exceeds 4 MB` | Too large | | 500 | `Internal server error` | Server failure | ## SDK log messages iOS writes to the unified log under subsystem `com.herald.sdk` (category `Herald`, and `ui` for `HeraldUI`). Android writes to Logcat with the tag `Herald`. The default level shows errors and warnings. See [Logging and debugging](/docs/operations/logging-and-debugging). ### Setup | Message | Platform | Level | Meaning | |---|---|---|---| | `Herald.configure was called more than once; ignoring the later call` | iOS | Warning | Only the first configuration applies | | `Herald.configure called more than once; ignored` | Android | Warning | Same | | `Herald call dropped: more than 1000 calls are waiting (is Herald.configure called?)` | iOS | Warning | 1,000 calls are waiting for `configure`; later ones are lost | | `More than 1000 calls before Herald.configure; dropping later ones until it runs` | Android | Warning | Same | | `Could not create storage directory: ...` | iOS | Error | The SDK cannot write its files; nothing persists | | `SDK state file unreadable; starting fresh` | Android | Error | The state file was corrupt; the device starts as new | ### Calls rejected on the device A call that breaks a rule is dropped and never queued. The message names the call and the problem. | Message pattern | Platform | Level | |---|---|---| | `<call> ignored: <problem>`, for example `track ignored: name must not be empty` | iOS | Error | | `<call> ignored: <problem>` | Android | Warning | | `<what> contain an unsupported value (...); call ignored` | Android | Warning | | `setAttributes: $email is not a valid email; dropped that key` | Both | Warning | | `setAttributes: $phone must be E.164, for example +15551234567; dropped that key` | Both | Warning | | `setLocation: latitude must be -90...90 and longitude -180...180` | iOS | Error | | `setLocation ignored: out of range` | Android | Warning | Problems include `must not be empty`, `is longer than N characters`, `currency must be a 3-letter ISO 4217 code`, `quantity must be positive` (iOS) or `quantity must be at least 1` (Android), `price must be finite` (iOS) or `price is not finite` (Android), and `contains a number that is not finite`. ### Delivery | Message | Platform | Level | Meaning | |---|---|---|---| | `Herald rejected a batch of N event(s) with HTTP S; dropping it` | iOS | Error | A 4xx other than 408 and 429; see the status table | | `Herald rejected a batch (S): <body>. Dropping N events.` | Android | Error | Same, with the server's message | | `Batch send failed: ...` / `Batch will be retried in N s` | iOS | Info | Network error or retryable status | | `Batch send failed (...); will retry` / `Batch send got S; will retry` | Android | Info | Same | | `Sent N events` | Android | Debug | A batch was accepted | | `Herald rejected event <id>: <reason> (<detail>)` | Both | Debug | Herald accepted the batch but left this event out; see [Rejected events](#rejected-events) | | `Dropping a <type> event larger than 32 KB` | Both | Debug | The event was over the 32 KB limit; dropped before queueing and counted in `dropped` | | `Event queue full: dropped N oldest event(s)` | iOS | Warning | The 1,000-event queue overflowed; the count is reported to Herald | | `Dropped N queued event(s) older than 30 days` | Both | Debug | SDK 0.6.0 and later: queued events past `maxQueuedEventAge` were dropped before a batch was built and counted in `dropped` | | `Dropping an event larger than 512 KB` | iOS | Error | One event cannot fit in a batch | | `Collection is turned off remotely` | Both | Info | SDK 0.6.0 and later: the app's SDK settings turned off "Collect events"; the queue was cleared and nothing is recorded or sent until it is turned back on | | `Config fetch failed (...); keeping the current config` / `Config fetch returned an unreadable body` | Android | Info / Warning | The remote config fetch failed; the cached or built-in settings stay | | `Could not cache the remote config: ...` / `Could not cache the remote config` | iOS / Android | Error | Disk write failed; the fetched settings still apply until the app quits | | `Skipping an event that cannot be encoded as JSON` | iOS | Error | For example a NaN in properties | | `Could not persist event: ...` / `Could not persist event queue` | iOS / Android | Error | Disk write failed | ### Messages | Message | Platform | Level | Meaning | |---|---|---|---| | `Message sync failed with HTTP S` / `Message sync got S: <body>` | iOS / Android | Warning | The fetch failed; cached messages stay | | `Message sync failed: ...` / `Message sync failed (...); using cached messages` | iOS / Android | Info | Network error | | `Message sync needs a user token; waiting for setUserToken` | Both | Debug | A signed-in fetch without a token got 401; `setUserToken` fetches again | | `Message sync waits for setUserToken` | Both | Debug | The connection requires a user token and none is set yet, so no fetch is sent | | `Message sync failed with HTTP 401: Herald refused the user token` / `Message sync got 401: Herald refused the user token` | iOS / Android | Warning | The token sent was wrong | | `Messages unchanged` | Both | Debug | 304 from the server | | `Message sync returned an unreadable body` | Android | Warning | The response could not be parsed | | `Skipping malformed <type>: ...` / `Skipping malformed message at index N` | iOS / Android | Warning | One card or message could not be read, for example an unknown type; the rest load | | `In-app message X not shown (no presenter or no active scene); stays pending` | iOS | Info | Set a presenter, or the app was not active | | `In-app message X discarded by delegate` | Android | Debug | Your delegate returned discard | | `InAppMessageDelegate threw; displaying` | Android | Error | Your delegate crashed; the message was shown | | `InAppMessagePresenter threw` / `In-app display failed` | Android | Error | Your presenter crashed; the message stays pending | | `Unknown content card X` | Android | Warning | A log call for a card the SDK no longer has | | `debugLoadMessages: unreadable body` | Both | Warning | The debug JSON is not a messages response | | `Card impression <id>` | iOS (`ui`) | Debug | The default feed logged an impression | ### Push and UI (Android modules) | Message | Module | Meaning | |---|---|---| | `Firebase is not initialized; push token not synced` | `herald-fcm` | `google-services.json` is missing or the Google services plugin is not applied | | `FCM token sync failed` | `herald-fcm` | Firebase could not return a token | | `Could not show Herald notification` | `herald-fcm` | Building the notification failed | | `Notification image failed (...)` / `Notification image too large to decode` | `herald-fcm` | The push shows without its image | | `Image load failed for <host> (...)` / `Image too large to decode from <host>` | `herald-ui` | A card or message image did not load | | `WebView unavailable; HTML message closed` / `HTML message renderer gone; message closed` | `herald-ui` | The HTML message could not run | | `openUrl failed` | `herald-core` | No activity handles the URL | ## Related - [Troubleshooting](/docs/operations/troubleshooting) - [SDK REST endpoints](/docs/reference/rest-endpoints) - [Data batching and offline behavior](/docs/concepts/batching-and-offline) Source: https://heraldsdk.com/docs/reference/error-codes.md --- # API errors > The error envelope every API endpoint shares, what each HTTP status means, when to retry, the rate-limit headers and idempotency conflicts. :::prereq - You call the [Server API](/docs/reference/server-api) or the [Send API](/docs/reference/send-api) from your backend. The SDK handles its own errors: see [Error codes](/docs/reference/error-codes). ::: ## The error envelope Every JSON endpoint answers a failure with one field: ```json { "error": "Invalid API key" } ``` The message is a short sentence you can log or show to an operator. A server failure reads `Internal server error`, and the details stay in Herald's logs. Success is always `{ "data": ... }`. A validation message names the field, such as `recipients[0].external_user_id must be 1 to 255 characters` or `Invalid events payload: ...`. Two endpoints answer differently: the decisions CSV returns `text/csv` on success (its errors are still JSON), and the MCP server answers with JSON-RPC errors inside a `200` once the key is accepted. ## HTTP status codes | Status | Meaning | Retry? | What to do | |---|---|---|---| | 200 | Done. For events, check `rejected` | | Fix and resend any rejected events | | 202 | Accepted: a send was scheduled | | Keep `send_id` | | 400 | The request breaks a rule; the message says which | No | Fix the request | | 401 | Missing, unknown, revoked or expired credential | No | Check the key or token | | 403 | The credential is valid but not allowed: a missing scope, a disabled app, an IP outside the key's allowlist, or the wrong kind of connection | No | Fix the key's scopes or the app's settings | | 404 | The resource doesn't exist in this app | No | Check the ID | | 409 | A conflict: the send already started, the agent isn't active, or an idempotency key clash | No, except "still in progress" | See [Idempotency conflicts](#idempotency-conflicts) | | 413 | The body is too large, such as `Body exceeds 4 MB` or `Request body too large` (over 4.5 MB on any endpoint) | No | Split the request | | 429 | Over an hourly rate limit | Yes, after `Retry-After` | Wait, or spread the load | | 500 | Server failure, `Internal server error` | Yes, with backoff | Contact your account team if it persists | | 502, 503, 504 | Gateway or upstream failure | Yes, with backoff | None needed if it clears | Retry with exponential backoff and jitter, and cap the wait. Never retry a 4xx other than 409 "still in progress" and 429. ## Rate limits Requests made with an API key are counted in hourly pools per app, per UTC clock hour. The [Send API](/docs/reference/send-api#rate-limits) lists them; the MCP server counts toward `mcp.requests` (3,600 per hour) and the decisions CSV toward `exports.requests` (60 per hour). Every response to a request with a valid API key carries the headers of the tightest pool it charged: | Header | Value | |---|---| | `X-RateLimit-Pool` | The pool, such as `messages.push` | | `X-RateLimit-Limit` | Its limit per hour | | `X-RateLimit-Remaining` | What is left this hour | | `X-RateLimit-Reset` | When the hour ends, in Unix epoch seconds | | `Retry-After` | On a 429 only: seconds until the hour ends | A 429 body names the pool: `Rate limit exceeded for messages.sms: 2000 per hour`. Nothing in the request was charged or done, so you can retry the same request after `Retry-After`. A 401, and the 403s for a disabled app or a blocked IP, come before any charge and carry no rate-limit headers. :::note Beta: the SDK, web push subscribe and server ingest endpoints (`POST /api/v1/events`, `POST /api/v1/users`) also get hourly pools per app, answering `429` with `Retry-After` and the same headers. The SDKs honor it. This is not live in production yet.::: ## Idempotency conflicts `POST /api/v1/messages/send` takes an `Idempotency-Key`. See [Send API idempotency](/docs/reference/send-api#idempotency). | Status | Body `error` | What to do | |---|---|---| | 409 | `This Idempotency-Key was used with a different request` | Use a new key for a new request; reuse a key only for an exact retry | | 409 | `A request with this Idempotency-Key is still in progress` | Wait a few seconds and retry with the same key. A claim unfinished after 2 minutes is taken over | A replay of a finished request returns the first response with its original status, not an error. The server API endpoints take no key; their writes are keyed instead (see [Server API idempotency](/docs/reference/server-api#idempotency)). ## Rejected events `POST /api/v1/events` checks each event on its own. A bad event doesn't fail the request: it is left out and listed in `rejected` with a `reason` code, and the rest are stored with a `200`. Retrying a rejected event never helps; fix it first. The codes are listed under [Rejected events](/docs/reference/error-codes#rejected-events). ## Common messages | Status | Body `error` | Where | Cause | |---|---|---|---| | 400 | `Invalid JSON` or `Invalid JSON body` | All | The body is not JSON | | 401 | `Unauthorized` | Server API | Missing or unknown ingest token | | 401 | `Invalid API key` | Send API, decisions CSV, MCP | Missing, unknown, revoked or expired API key | | 403 | `Forbidden` | Server API | The connection is disabled | | 403 | `This API key lacks the <scope> scope` | Send API, decisions CSV, MCP | Wrong scopes | | 403 | `This API key's app is disabled` | Send API, decisions CSV, MCP | The app is turned off | | 403 | `This IP address isn't allowed for this API key` | Send API, decisions CSV, MCP | The key has an IP allowlist | | 413 | `Request body too large` | All | Over the endpoint's body limit | | 429 | `Rate limit exceeded for <pool>: <limit> per hour` | API key endpoints | Over a pool's hourly limit | | 500 | `Internal server error` | All | Server failure | Each endpoint's own messages are in its table on [Server API](/docs/reference/server-api) and [Send API](/docs/reference/send-api). ## Related - [Error codes](/docs/reference/error-codes) (SDK) - [Limits](/docs/reference/limits) - [Troubleshooting](/docs/operations/troubleshooting) Source: https://heraldsdk.com/docs/reference/api-errors.md --- # Limits > Every limit in the SDK and its endpoints, with its value: batch size, string lengths, queue cap, flush and session timing, message caps, image sizes, media uploads and search limits and more. Every limit the SDK and its endpoints enforce, as of the current release. A row that needs a newer SDK names the version. Values are the same on iOS and Android unless a row says otherwise. Lengths count UTF-16 code units. ## Batches and the queue | Limit | Value | Notes | |---|---|---| | Events per batch | 100 | Server limit; the SDK builds batches of up to 100 | | Batch body size | 512 KB | Server limit; the SDK halves a batch until it fits | | Size of one event | 32 KB as JSON | The SDK drops a larger event before queueing it, logs it at debug level and counts it in `dropped`; the server rejects one as `too_large` and keeps the rest of the batch | | Event age | 30 days | Server limit for SDK events, on the [corrected time](/docs/concepts/batching-and-offline#clock-correction); an older event is rejected as `too_old` | | Rejected events kept | 30 days; up to 1,000 stored per connection per UTC day | Shown on the connection's page in the console; past 1,000 in a day they are still rejected but not stored. Schema warnings don't count toward the 1,000 | | Schema warnings kept | 30 days; up to 200 stored per connection per UTC day | Events kept in **Accept and warn** mode; past 200 in a day they are still accepted, but the warning isn't stored | | Reports per diagnostics request | 20 | Server limit; iOS crash reports only | | Diagnostics body size | 256 KB | Server limit; the SDK drops a single report larger than this | | Single event larger than a batch | Dropped | Dropped on the device with a warning; never sent | | Events in the on-device queue | 1,000 | The oldest are dropped first and counted in `dropped` | | Age of a queued event | 30 days (SDK 0.6.0 and later; `maxQueuedEventAge` on iOS, `maxQueuedEventAgeDays` on Android) | Older events are dropped before a batch is built and counted in `dropped`, matching the server's 30-day limit | | Calls kept before `configure` | 1,000 | Later calls are dropped with a warning | | Request timeout | 30 seconds on iOS; 10-second connect and 15-second read on Android | | | Remote config fetch | At launch, then on a foreground at most once an hour | SDK 0.6.0 and later | | [Event schemas](/docs/concepts/event-schemas) per app | 100 | Each event name counts once, whatever its number of versions | | Properties per event schema | 50 | | | Versions per event schema | 50 | Contact support to archive old ones | | [Computed attributes](/docs/concepts/computed-attributes) per app | 20 | | | [Model signals](/docs/concepts/app-signals) per account | 6 | Across all the account's apps | | Computed attribute window | 90 days (2,160 hours) | Counts and sums only; last and first time cover all history | ## Flushing and retries | Setting | Default | Option | |---|---|---| | Flush timer, in the foreground | 10 seconds | iOS `flushInterval`, Android `flushIntervalSeconds`; values below 1 second act as 1 | | Flush at queue size | 20 events | `flushAt` | | Flush on background | Always | | | First retry delay | 0.5 to 1 second | Doubles after each failure | | Longest retry delay | 5 minutes | | | Longest `Retry-After` honored | 1 hour | Header (seconds or HTTP date) or `retryAfterSeconds` in the body | ## Sessions and in-app timing | Setting | Default | Option | |---|---|---| | Session timeout | 30 minutes of inactivity in the foreground; 30 minutes in the background | iOS `foregroundSessionTimeout` and `backgroundSessionTimeout` (seconds), Android `foregroundSessionTimeoutMinutes` and `backgroundSessionTimeoutMinutes` | | Minimum interval between triggered in-app messages | 30 seconds | iOS `inAppMinimumInterval`, Android `inAppMinimumIntervalSeconds` | | Session activity saved to disk | At least once a minute, and on background | | | In-app messages on screen at once | 1 | | ## Field lengths and values | Field | Rule | |---|---| | External ID (`userId`) | 1 to 200 characters | | Event and screen name | 1 to 255 characters | | Event property key | Up to 255 characters | | Attribute and trait key | 1 to 255 characters | | Attribute value | String, number, boolean, null, or array of strings | | Product ID | 1 to 255 characters | | Currency | 3 letters | | Quantity | Whole number, 1 or more | | Price, numeric properties and attributes | Finite | | Email | Valid address (the server's email check) | | Phone | E.164: `+`, then 7 to 15 digits, first digit not 0 | | Latitude, longitude | -90 to 90, -180 to 180 | | Push token | 1 to 4,096 characters | | Message ID, decision ID, button ID in interactions | 1 to 200 characters | | Event ID | 1 to 128 characters | | Session ID | 1 to 64 characters | | Device ID | 1 to 128 characters | | Bundle ID on a push token | 1 to 255 characters | | Context strings | See [Event payload spec](/docs/reference/event-payload#context) | | Consent document ID and version | Up to 100 characters each | | Remote send interval | 5 to 300 seconds | | Remote session timeouts | 60 to 86,400 seconds in whole minutes (1 to 1,440 minutes in the console) | ## Messages | Limit | Value | |---|---| | Content cards per fetch | 100, newest first | | In-app messages per fetch | 50, newest first | | Push action buttons | 3 | | HTML bridge button ID (iOS) | 200 characters | | Push open records kept for deduplication | The last 50 decisions | | Push limit across all sources, per person per app | On by default at 3 pushes per 24 hours; adjustable from 1 to 20, or off, in Settings > General. Counts every mobile push, including ones your app sends itself; skips only agent and campaign pushes. Used in Observe mode; Enforce mode uses the messaging limits below. See [Pushes your app sends](/docs/push-notifications/pushes-your-app-sends) | | Messaging limits (max a day / max a week / min a week), per person per channel | Push 3/8/1, web push 3/8/1, email 1/4/1, SMS 1/2/1, over a trailing 24 hours and 7 days; an empty maximum means no limit. Category caps: Engagement 2 a day, Promotions 1 a day and 3 a week. Set in Settings > Messaging limits. See [Message priority and attention budget](/docs/concepts/message-priority) | | `$external_push` `message_id` / `source` | 200 / 100 characters | ## Images | Where | Limit | |---|---| | iOS rich push (`HeraldNotificationService`) | HTTPS only, 10 MB, JPEG, PNG, GIF or HEIC, 20-second timeout | | iOS `HeraldUI` images | 20 MB download, decoded at the drawn size up to 4,096 pixels on the long edge, 64 MB in-memory cache | | Android push image (`herald-fcm`, app in foreground) | 5 MB, 5-second connect and read timeouts, 8 seconds in total, scaled to fit 1,024 by 1,024 pixels | | Android `herald-ui` images | 10 MB download, 10-second connect and read timeouts, decoded to at most 4 megapixels and the display width | ## Media | Limit | Value | |---|---| | Uploaded image | JPEG, PNG, GIF or WebP, 10 MB | | Uploaded video | MP4, 50 MB, with a poster image | | Upload description | 500 characters | | iOS push video | HTTPS, `video/mp4` or `video/quicktime`, 10 MB, 60% of a 25-second budget; the poster is attached when the video fails | | Push image presets | 1,024 by 512 pixels (JPEG, quality 80; 70 for Android) | | In-app message and content card presets | 1,080 by 1,080 and 1,200 by 800 pixels | | Email image preset | 1,200 pixels wide | | Stock search query | 100 characters | | Stock search page | up to page 50, 1 to 30 results per page, 24 by default | | Stock searches per account | 120 per hour (cached repeats don't count) | | Stock searches across all accounts | 45 per hour for Unsplash and 180 per hour for Pexels (cached repeats don't count) | | Search cache | 10 minutes | | Library page | 40 items | | APNs payload | 4,096 bytes; the body is shortened first, then `video_url` is dropped, never the poster | Media in a message can only come from Unsplash, Pexels or your Herald uploads, over HTTPS. See [Media library](/docs/concepts/media-library). ## Geofences SDK 0.7.0+, not released yet. See [Geofences](/docs/concepts/geofences). | Limit | Value | |---|---| | Geofences per app | 100 | | Radius | 100 to 10,000 meters | | Name | 1 to 100 characters | | Regions monitored on iOS | The 20 nearest, minus regions your app monitors itself | | Geofences registered on Android | All of them (Android allows 100 per app). After a restart, or Location turned off and on, they resume the next time the app opens | | Events per geofence and direction | 1 every 5 minutes, on the device | ## Users and events APIs | Limit | Value | |---|---| | Users per request | 1 to 1,000 | | Events per request | 1 to 1,000 | | Request body | 4 MB | | Event ID | 1 to 128 characters | | Size of one event | 32 KB as JSON | | Event time | No more than 5 minutes ahead of Herald's clock; no age limit | ## Contacts API | Limit | Value | |---|---| | Contacts per request | 1 to 1,000 | | Contact value | 1 to 4,096 characters | | APNs token | 64 or more hex characters | ## Related - [Data batching and offline behavior](/docs/concepts/batching-and-offline) - [Event payload spec](/docs/reference/event-payload) - [Error codes](/docs/reference/error-codes) Source: https://heraldsdk.com/docs/reference/limits.md --- # Changelog > What each SDK release contains: 0.7.0 (not released yet) with geofences, 0.6.0 with reporting pushes your app sends, the Support ID, lifecycle events, better sessions, per-event rejects, guest events linked at sign-in, remote SDK settings, a consent record, event schema versions and video in rich push, in-app messages and cards, 0.5.0 with build kind and confirmed flush on iPhone, 0.4.0 with opt-in crash reports on iPhone, 0.3.0 with Live Activities on iPhone, 0.2.3 with push, card and permission fixes from hands-on testing, 0.2.2 with consent, identity and dark-mode fixes, 0.2.1 with an Android sync push fix, 0.2.0 with sync push and authoring in Herald, and the first release, 0.1.0, for iOS and Android. Releases follow the policy on [Versioning and support](/docs/operations/versioning-and-support). iOS and Android share version numbers. ## 0.7.0 Not released yet. - React Native: `@herald/react-native`, a TurboModule that wraps the iOS and Android SDKs (configure, identity, events, attributes, push permission and tokens, data control, content cards and an in-app message handler). It installs from git for now. See [Quickstart: React Native](/docs/overview/quickstart-react-native). - Geofences. New opt-in modules: `HeraldGeofence` (iOS library product) and `herald-geofence` (Android, depends on Play Services location). `Herald.shared.enableGeofences()` (iOS) and `Herald.enableGeofences()` (Android) download the app's geofence list and monitor the nearest 20 (iOS) or all of them (Android, at most 100); crossings send `track` events `$geofence_enter` and `$geofence_exit` with `geofence_id` and `geofence_name`, at most one per geofence and direction every 5 minutes. `disableGeofences()` stops it. The SDK never asks for location permission, reads no location before `enableGeofences()`, and never sends the device's location. See [Geofences](/docs/concepts/geofences). - Herald (server): geofences per app in the console under Settings, Geofences (up to 100, radius 100 m to 10 km), served by `GET /api/v1/sdk/geofences` with an ETag. A new SDK setting, **Geofences** (`geofences`), turns monitoring off for every device. `$geofence_enter` and `$geofence_exit` properties are checked for their types (`invalid_field`), and the events don't count as app activity. - Flutter: the `herald_flutter` plugin wraps the iOS and Android SDKs, installed from git (`sdks/flutter`). It covers configure, identity, events, attributes, email and phone, push registration and taps, the Support ID, flush, opt-out and wipe, content cards and in-app messages with a Dart display handler. See [Install on Flutter](/docs/overview/install-flutter). - Push stories: a push with 2 to 10 pages, each with an image, title, subtitle and deep link. iOS shows them with the new `HeraldPushStory` library in a Notification Content Extension (`HeraldStoryViewController`), and `HeraldNotificationService` downloads every page's image; Android's `herald-fcm` shows them with no extra code. Opening a page logs a push open and a `button` interaction `herald_story_page_<index>`. Older SDKs show the first page as a normal push. See [Push stories](/docs/push-notifications/push-stories). - Unity: the `com.herald.sdk` package, a C# API over the iOS and Android SDKs, installed from git. It covers configure, identity, events, purchases, attributes, push permission and taps, the Support ID, data control, content cards and in-app messages with a delegate to show, defer or discard them. See [Install on Unity](/docs/overview/install-unity). - Herald (server, all SDK versions): [long-term value](/docs/concepts/long-term-value). A Thompson Sampling agent can learn from the extra active days its messages cause over 90 days, against its holdout group, with annoyance counted against a message, and can skip a send when nothing is likely to help. Optional SDK events: `share` and `referral_signup`. Agents that learn from goals are unchanged. - Herald (server, all SDK versions): long-term value agents can learn [by message features](/docs/concepts/long-term-value#message-features), [test a new approach](/docs/concepts/long-term-value#testing-a-new-approach) in shadow or on 10% of people, and [learn from other apps](/docs/concepts/long-term-value#learning-from-other-apps) when the account opts in. No SDK changes. - Herald (server, all SDK versions): long-term value agents can choose [the time and channel](/docs/concepts/long-term-value#time-and-channel), journey steps can [choose a version per person](/docs/concepts/long-term-value#journeys), an app can set a weekly message aim and let the agent whose message adds the most value [get a person](/docs/concepts/long-term-value#attention-as-a-budget), agents can [write new messages each week](/docs/concepts/long-term-value#new-messages), and very large apps can test [sequence learning](/docs/concepts/long-term-value#sequence-learning-for-very-large-apps). Long-term value agents [don't repeat a message](/docs/concepts/long-term-value#no-repeated-messages) to someone within 7 days. No SDK changes. - Live Activities on Android. Live Activity campaigns also reach Android phones as Live Updates through FCM. `herald-fcm` shows each as an ongoing notification that Android 16 can promote to a status bar chip and the top of the lock screen, with a progress bar or a countdown, and removes it at the end. It adds the `POST_PROMOTED_NOTIFICATIONS` permission. `Herald.canPostLiveUpdates()` (Android) says whether Android will promote it. See [Live Activities on Android](/docs/live-activities/android). ## 0.6.0 Released 2026-11-26. iOS and Android: report pushes your app sends itself, so the push limit counts every push; read the person's User ID for a Support ID line; automatic lifecycle and deep link events; separate session timeouts with sessions that continue across restarts; a 30-day limit on queued events; partial-reject handling; remote SDK settings with a kill switch; a consent record; and event schema versions on `track`. No API removals; the single session timeout is deprecated. Update the version in your install lines. - `trackExternalPush(messageId:category:source:)` (iOS) and `Herald.trackExternalPush(messageId, category, source)` (Android) record `$external_push`. Category is transactional, marketing or other. See [Pushes your app sends](/docs/push-notifications/pushes-your-app-sends). - Auto-capture, on by default (`trackExternalPushes`): iOS records a tapped push that isn't from Herald; Android's `herald-fcm` records a non-Herald FCM message with a notification when it reaches the app. Silent and data-only pushes are never recorded. Payload keys `herald_external_id` and `herald_category` set the ID and category. - `Herald.shared.heraldId` (iOS) and `Herald.heraldId` (Android): the identified person's User ID (`XXXX-XXXX`), nil until the first accepted batch after `identify` and cleared by `reset()`. Show it as a "Support ID". See [Support ID](/docs/concepts/users-and-identity#support-id). - Both SDKs send lifecycle events on their own: `$app_installed`, `$app_updated`, `$app_opened` (with `from_push`), `$app_foreground` and `$app_background`, also in minimal data collection. `trackLifecycleEvents` (default on) turns them off. See [Lifecycle events](/docs/reference/event-payload#lifecycle-events). - Both SDKs send `$deep_link_opened` with `scheme`, `host`, `path` and `source` (`push` or `link`) when a deep link goes through the SDK; never the fragment, and the query only with `trackDeepLinkQuery`. A URL without a host (`mailto:`, `tel:`) sends its scheme only. Minimal data collection sends scheme and host only. `trackDeepLinks` (default on) turns it off. - Sessions: separate foreground and background timeouts (`foregroundSessionTimeout` / `backgroundSessionTimeout` on iOS, `foregroundSessionTimeoutMinutes` / `backgroundSessionTimeoutMinutes` on Android, both 30 minutes). The single `sessionTimeout` / `sessionTimeoutMinutes` is deprecated and sets both. A cold start within the foreground timeout continues the session. `session_start` carries `session_index` and `previous_session_id`. See [Sessions](/docs/concepts/sessions). - Both SDKs fetch the app's SDK settings, set in the console under Settings, SDK settings, at launch and on a foreground at most once an hour, cache them and apply the cached ones at launch. They can change the send interval, the session timeouts, data collection, lifecycle events, tracking of pushes your app sends and deep links without an app update; a setting left at "Use app's value" keeps the app's own. Turning off "Collect events" stops all collection and sending and clears the queue until it is turned back on; push tokens and subscription changes wait and go out when it is. `remoteConfigVersion` shows the version in use. See [iOS API](/docs/reference/ios-api#remote-config) and [Android API](/docs/reference/android-api#remote-config). - Both SDKs add `setConsent(basis, documentId, documentVersion)` and `clearConsent()`: the GDPR lawful basis and your policy's id and version, sent with each batch while set and shown to admins on the person's page. A record for your compliance; it doesn't change what is collected. See [Consent and opt-out](/docs/data-and-privacy/consent-and-opt-out). - Herald (server, all SDK versions): [app signals](/docs/concepts/app-signals). In **Settings → Computed attributes**, switch on **Use in personas and decisions** for up to 6 computed attributes per account, or start from a template for your kind of app (fitness, meditation, learning, shopping, media, finance, games, community). Each person's profile numbers become the ten core numbers plus your signals, scaled 0 to 1; personas, persona traits and LinUCB decisions use them. Changing the set makes LinUCB for the account relearn, and personas refresh at the next nightly discovery. - Herald (server, all SDK versions): [learning with small audiences](/docs/concepts/learning-with-small-audiences): new Thompson Sampling agents start from public benchmarks and your app's history, small personas borrow from the whole agent, a Learning fit card shows whether traffic suits the setup, and old results fade back to their starting point, not past it. The fading change applies to every agent; the rest changes for an existing agent only when you turn on **Learn faster with small audiences**. - Herald (server, all SDK versions): [computed attributes](/docs/concepts/computed-attributes), set in the console under Settings, Computed attributes: per-person counts, sums, and first and last times of an event, stored as `computed_<name>` and updated as events arrive, for segments and agent targeting. Attribute keys starting with `computed_` are now reserved: an SDK event that sets one is rejected with `invalid_field`, and `POST /api/v1/users` answers 400. - Herald (server, all SDK versions): a per-app setting, "Store location from IP address" (on by default). When off, Herald records no country from the request's IP address; the region the app sends from the device locale is still kept. See [Data collection controls](/docs/data-and-privacy/data-collection-controls). - Both SDKs add an optional `schemaVersion` to `track` (`track(name, properties, schemaVersion:)` on iOS, `track(event, properties, schemaVersion)` on Android), naming the [event schema](/docs/concepts/event-schemas) version to check the event against. A malformed version is left off with a debug log, and the event is still sent. Existing calls are unchanged. - Herald (server, all SDK versions): optional [event schemas](/docs/concepts/event-schemas), set in the console under Settings, Event schemas. A `track` event, or a `POST /api/v1/events` event, whose name has a schema is checked against it: in **Reject invalid events** mode a failing event is rejected (`schema_violation`); in **Accept and warn** mode it is kept and shown as a warning with the rejected events. Events without a schema are accepted as before. - Video in rich push, in-app messages and content cards. iOS: the Notification Service Extension attaches a push's `video_url` (HTTPS, MP4 or QuickTime, at most 10 MB) and falls back to the poster, then text; new `HeraldRichPush.attachMedia(to:timeout:budget:session:)`. Both SDKs: `InAppMessage.Content` / `InAppContent` and `ContentCard` get `videoUrl`, `videoPosterUrl` and `credit` (`MediaCredit`), cards also `videoAutoplay`. `HeraldUI` and `herald-ui` show the poster with a play button in modal and full-screen messages and captioned-image cards, play inline on tap, and autoplay muted in the card feed. Android push shows the poster. See [Media library](/docs/concepts/media-library). - Both SDKs send `interaction` events with `action` `video_play` and `video_complete`: `logVideoPlay` and `logVideoComplete` for cards and in-app messages on iOS; `Herald.logVideoPlay(card)` and `Herald.logVideoComplete(card)`, `InAppMessageCallbacks.onVideoPlay()` / `onVideoComplete()` and `InAppMessageActions.videoPlayed()` / `videoCompleted()` on Android. See [Event payload](/docs/reference/event-payload#interaction). - Herald (server, all SDK versions): a [media library](/docs/concepts/media-library) for images and videos, with uploads and search of Unsplash photos and Pexels photos and videos, and a **Choose media** picker on every image field. - Herald (server, all SDK versions): [message priority and an attention budget](/docs/concepts/message-priority), set in the console under Settings, Messaging limits. A `$external_push` with `category` transactional no longer counts toward the budget; any other counts toward the push channel only. No SDK change. - Both SDKs drop queued events more than 30 days old before building a batch and count them in `dropped` (`maxQueuedEventAge` on iOS, `maxQueuedEventAgeDays` on Android). - Both SDKs drop an event over 32 KB before queueing it, log it at debug level and count it in `dropped` (Herald would reject it). - Both SDKs handle a batch response that lists rejected events: the batch leaves the queue as before, each rejected event is logged at debug level with its reason, and none is retried. On iOS, `flush(timeout:)` returns `false` when an event it waited for was rejected. See [Rejected events](/docs/reference/error-codes#rejected-events). - Herald (server, all SDK versions): every person has a User ID, searchable on People by every role and returned as `heraldId` in the batch response. The console now calls the ID your app passes to `identify` the External ID. - Herald (server, all SDK versions): a per-app push limit across all sources, on by default at 3 pushes per person per 24 hours, skips agent and campaign pushes for anyone who reached it. Send API messages count but are never skipped. - Herald (server, all SDK versions): each event in a batch or a `POST /api/v1/events` request is checked on its own. A bad event is rejected and listed in the response's `rejected`; the rest are kept (before, one bad event failed the whole request with a 400, and the SDKs dropped all of it). Events over 32 KB, and SDK events more than 30 days old, are rejected; server events have no age limit. The console lists rejected events on each connection's page for 30 days. - Herald (server, all SDK versions): SDK event times are corrected for the device's clock, using the batch's `sentAt` and the time it arrived, so a phone with a wrong clock no longer puts activity, send times or goal credit in the wrong window. See [Clock correction](/docs/concepts/batching-and-offline#clock-correction). - Herald (server, all SDK versions): guest events are linked at sign-in. When a device is first bound to a verified user, its anonymous events from the last 30 days (at most 5,000) become that user's: first seen, activity, and goal credit for earlier messages. After a sign-out only the events since then are linked, so a shared device never gives one person's guest browsing to another. See [Guests and signed-in users](/docs/concepts/users-and-identity#guests-and-signed-in-users). - Herald (server, all SDK versions): lifecycle event properties and the `session_start` properties are checked for their types (`invalid_field`). `$app_opened` and `$app_foreground` count as app activity; `$app_installed`, `$app_updated`, `$app_background` and `$external_push` don't. The Events page lists the lifecycle events as system events. ## 0.5.0 Released 2026-11-18. iOS: build kind in device data and a flush that confirms delivery. Android: no changes; the version moves with iOS. No API removals. - iOS reports the build kind in device data, `context.app.distribution`: `development`, `testflight` or `appstore`, in every collection mode, left out until known. The console shows it next to each test phone. See [Device data](/docs/concepts/device-data). - iOS `flush(timeout:) async -> Bool` sends queued events and returns `true` once everything recorded before the call was accepted by Herald. Use it before `setEnabled(false)`. See [Batching and offline](/docs/concepts/batching-and-offline). - Herald (server, all SDK versions): Attributes set to `null` (from the SDK or `POST /api/v1/users`) now remove the key from the user's profile instead of storing a null. A segment condition that checks an attribute exists no longer matches a user who sent `null` for it (it used to). Apps can clear `email` at sign-out this way. The stored event log no longer keeps `email` or `$email` values from identify traits or attribute events; the profile and contacts still get them. ## 0.4.0 Released 2026-11-15. iOS: new opt-in crash and hang reports. Android: no changes; the version moves with iOS. No API removals; update the version in your install lines. - Crash and hang reports on iPhone, off by default: set `crashReports = true` on `HeraldConfiguration`. The SDK then sends Apple MetricKit crash and hang reports to Herald (`POST /api/v1/sdk/diagnostics`), with no user id and no device id. iOS delivers a report on the next launch after a crash. See [iOS API](/docs/reference/ios-api). - Reports that fail to send wait on the device (newest 50) and go out on the next launch. Nothing is sent while the SDK is disabled, and `wipeData()` deletes waiting reports. - The privacy manifest declares crash data: not linked to the user, not used for tracking, for app functionality. ## 0.3.0 Released 2026-11-15. iOS: new Live Activities support. Android: no changes; the version moves with iOS. No API removals; update the version in your install lines. - Live Activities (iPhone, iOS 18+). New library product `HeraldLiveActivity`, with no dependency on `HeraldSDK` so a widget extension can link it. It holds `HeraldActivityAttributes` and `HeraldLiveActivityWidget`, a lock screen and Dynamic Island view that shows a title, body and either a progress bar or a countdown, and opens the campaign's deep link on tap. Add `HeraldLiveActivityWidget()` to your `WidgetBundle` and set `NSSupportsLiveActivities` to YES. See [Live Activities setup](/docs/live-activities/setup). - On iOS 18+, `HeraldSDK` sends the Live Activity push-to-start token to Herald (`push_token` with platform `apns_live_activity`), so campaigns can start a Live Activity. Like the APNs token, it is not sent while the SDK is disabled, and is sent again on `setEnabled(true)` and when the user changes. ## 0.2.3 Released 2026-11-11. iOS and Android. No API removals; update the version in your install lines. - Android: new `com.herald.sdk.push.PushTokenSource`, which `herald-fcm` sets so the SDK can fetch the FCM token again. Apps with their own `FirebaseMessagingService` that do not call `syncToken` can set it. See [Android API](/docs/reference/android-api#pushtokensource). - Both: after `wipeData()` and then `setEnabled(true)`, push comes back when notification permission is still granted. iOS registers with APNs again (and at each launch with permission but no stored token); Android has `herald-fcm` fetch the FCM token again, which needs `HeraldMessagingService.syncToken` after `configure`. See [Consent and opt-out](/docs/data-and-privacy/consent-and-opt-out#what-happens-when-the-sdk-is-off). - Both: content card impressions are logged once per card per session, not each time a feed is built. An expired card leaves an open feed at its expiry time, without a sync. See [Content cards](/docs/content-cards/overview). - Both: once Herald has refused a signed-in user's message sync without a user token, the SDK waits for `setUserToken` before it syncs that user again, and that expected 401 is no longer logged as a warning. - Both: slideups dismiss only by swiping toward their edge (up for a top slideup, down for a bottom one); a sideways swipe no longer dismisses. The VoiceOver and TalkBack **Dismiss** action is unchanged. - Android: HTML in-app messages have a close button, as on iOS. `ContentCardFeed` re-filters when state its filter reads changes. - Android: push permission is reported as `not_determined` on Android 13 and later until the app asks through `Herald.requestPushAuthorization`, instead of `denied`. See [Device data](/docs/concepts/device-data). ## 0.2.2 Released 2026-11-10. iOS and Android. No API removals; update the version in your install lines. - Both: events recorded between `identify` and `setUserToken` are no longer lost. When a signed-in user's batch gets a 401, the SDK keeps it, logs `Herald needs a user token: call setUserToken` and sends it after `setUserToken`. Anonymous events keep flowing. A wrong app key no longer drops events either: the SDK logs `Herald rejected the app key: check the publishable key in configure` and keeps them for the next launch. See [Batching and offline](/docs/concepts/batching-and-offline). - Server: a subscribe sent by the SDK lifts only an unsubscribe the SDK recorded. An unsubscribe the user made from an email or SMS link stays. - Both: `setEnabled(false)` and `wipeData()` send one best-effort push unsubscribe for the device, so Herald stops sending it pushes, and hide cached content cards while the SDK is off. On Android, `herald-fcm` does not show Herald pushes while the SDK is off. `setEnabled(true)` re-subscribes push when the device still has its token and notification permission. New read-only `isEnabled` on both platforms (iOS `Herald.shared.isEnabled`, Android `Herald.isEnabled(context)`). See [Consent and opt-out](/docs/data-and-privacy/consent-and-opt-out#what-happens-when-the-sdk-is-off). - Both: an in-app message that sets a background or button color without its text color gets black or white text, whichever reads better, instead of the theme's text color. See [Theming and dark mode](/docs/in-app-messages/theming-and-dark-mode#per-message-styles). - Android: new `Herald.deepLinkHandler`, with the same semantics as on iOS. See [Deep links](/docs/push-notifications/deep-links). - iOS: an unreadable state file no longer turns a disabled SDK back on. - iOS: `handleRemoteNotification` returns within 25 seconds, and at once before `configure`. ## 0.2.1 Released 2026-11-10. Update the version in your install lines. - Android: `Herald.handleRemoteMessage` waits for the sync push refresh to finish (8 seconds at most) before it returns, so FCM no longer stops the process mid-refresh. Called on the main thread it still returns at once. - iOS: no functional change; version kept in step. ## 0.2.0 Released 2026-11-10. iOS and Android. No API removals; update the version in your install lines. ### SDKs - Sync push handling on both platforms. The SDK refreshes content cards and in-app messages when a silent push with `herald_sync` arrives. iOS: `Herald.shared.handleRemoteNotification(_:)`, which needs the Remote notifications background mode. Android: automatic with `herald-fcm`, or `Herald.handleRemoteMessage(data)` from your own messaging service. A sync push that arrives within 30 seconds of the last one is skipped. See [Silent push](/docs/push-notifications/silent-push). - iOS rich push: `HeraldNotificationService` keeps a category your app registered, and replaces a category whose id starts with `herald.` with the buttons in the push. ### Server - Delivery options per message variant: card type, pinning, dismissal, categories, extras and expiry for content cards; type, buttons, triggers, property filters, priority, re-eligibility, expiry and colors for in-app messages. See [Create cards in Herald](/docs/content-cards/authoring) and [Create in-app messages in Herald](/docs/in-app-messages/authoring). - Push action buttons and a per-message Android channel. See [Rich push](/docs/push-notifications/rich-push#action-buttons). - Sync push, sent after a card or in-app message is written. See [How delivery works](/docs/concepts/how-delivery-works#sync-push). - User deletion API, `DELETE /api/v1/users/{userId}`. See [User data deletion](/docs/data-and-privacy/user-data-deletion). - Send a test from Herald on the connection's Mobile SDK card. See [Testing push](/docs/push-notifications/testing#send-a-test-from-the-mobile-sdk-card). ## 0.1.0 The first public release. iOS 16 and later; Android 8.0 (API level 26) and later. ### Distribution - iOS: Swift Package Manager, from `https://github.com/ender1311/herald-ios`. - Android: JitPack, as `com.github.ender1311.herald-android:herald-core`, `herald-ui` and `herald-fcm`. - Source for both under the Apache License 2.0. ### Modules | iOS | Android | Contents | |---|---|---| | `HeraldSDK` | `herald-core` | Identity, events, sessions, push registration, content card data, in-app message rules | | `HeraldUI` | `herald-ui` | Default content card feed and in-app message views, with theming and dark mode | | `HeraldNotificationService` | `herald-fcm` | Push images and action buttons (iOS extension); FCM service, token sync, channel and notification display (Android) | ### Data collection - Users: anonymous and identified users, `identify` with traits, `reset`, user switching, and identity verification with user tokens in three modes (required, optional, off). - Events: `track`, `screen`, `trackPurchase`, user attributes, email and phone contacts, channel subscriptions, and an app-supplied location. - Sessions with a configurable inactivity timeout. - Two device data tiers, with a minimal mode. No advertising identifiers, carrier or automatic location. - An on-disk queue of up to 1,000 events, batched uploads, retries with backoff, and validation of every call on the device. - `setEnabled` and `wipeData` for consent and deletion. Calls made before `configure` are kept, up to 1,000. - A privacy manifest in `HeraldSDK`. ### Push - APNs and FCM token registration, re-sent after sign-in and sign-out. - A permission prompt helper on both platforms that records the push subscription. - Open tracking, deep link routing, and `push_open` in-app triggers. - Images: a Notification Service Extension class on iOS, big picture style on Android. - Up to three action buttons from a `herald_actions` payload key, reported as an open, then a button tap. ### Content cards - Classic, captioned image and image-only cards; pinning, expiry, categories and extras. - A default feed with impression, click and swipe-to-dismiss logging. - Data APIs for a custom UI. ### In-app messages - Slideup, modal, full-screen and HTML messages. - Triggers on session start, custom events with property filters, and push opens; priority, re-eligibility, expiry and a minimum interval. - Pending messages that wait until they can show, a delegate to show, hold or drop each one, and `showNext()`. - Default views and presenter, with themes, per-message colors, custom views and accessibility support. - Debug-only preview hooks: `debugLoadMessages` and `debugShowInAppMessage`. ### Known limitations - Herald authored only classic and captioned image cards, and slideup and modal messages that trigger at session start, once. Version 0.2.0 removes this limit. - Herald's push senders did not add action buttons, a per-message Android channel or silent pushes. Version 0.2.0 removes this limit. - App keys cannot be rotated. ## Related - [Versioning and support](/docs/operations/versioning-and-support) - [Platform support](/docs/overview/platform-support) Source: https://heraldsdk.com/docs/reference/changelog.md --- # What's new > Product changes to the Herald server, console, integrations and APIs, newest first, each with a link to its docs. Changes to Herald itself, newest first. SDK releases are on the [Changelog](/docs/reference/changelog). ## 2026-12-01 **New** Live map. Analytics, **Live map** shows where people are using your app right now: each person active in the last 5 minutes is a point of light on a map of the United States, placed near their city. New arrivals flash as they come in, and people who leave fade out. Switch to **World** for a slowly turning globe you can drag. People without a location are counted separately. Locations are approximate (about 11 km) and come from the request when **Store location from IP address** is on. [Data collection controls](/docs/data-and-privacy/data-collection-controls#tier-1-always-sent) ## 2026-11-29 **New** More for long-term value agents. An agent that learns by message features can choose the time of day as well as the message, and a journey message step can **Let Herald choose per person**, with an option to skip. Under Settings, Messaging limits, set **Messages per person per week, aim** and choose which agent gets a person when several want them; a **Sending less** card shows personas that messages make less active. Agents can write new messages each week and pause ones that can't win, and very large apps can test sequence learning, which must also beat the current approach in a 90-day simulation of the app. Long-term value agents also stop repeating themselves: nobody gets the same message from an agent twice within 7 days. [Long-term value](/docs/concepts/long-term-value#time-and-channel) **New** Message features and testing approaches for long-term value. Message variants carry features (tone, approach, offer, call to action, length, personalized, emoji) that AI can fill, so an agent can learn which kinds of message work for which kinds of person and start new messages from what similar ones did. A long-term value agent's new Learning tab tests another approach in shadow or on 10% of people and lets an admin switch only once the result's whole 95% range is above zero. Accounts can also opt in to learn from other apps under Settings, General. [Long-term value](/docs/concepts/long-term-value#message-features) **New** Long-term value. A Thompson Sampling agent can learn which messages make people use your app more over the next 90 days, compared with people who got nothing, with shares, referrals and purchases counted and unsubscribes and uninstalls counted against a message. It can also skip a send when no message is likely to help. Set how value is counted in Settings, General. [Long-term value](/docs/concepts/long-term-value) ## 2026-11-26 **New** Every person has a fixed random number from 0 to 9,999, so a segment can pick a random sample: "Random number is less than 100" is a 1% pilot. [Random samples](/docs/concepts/users-and-identity#random-samples) **New** Contentful, Sanity, JSON feeds and Braze catalogs as content sources for every account (Beta). Paste your own read token in **Settings → Content sources**; it's saved encrypted and never shown again. Message copy syncs into your library daily or with **Sync now**. [Content sources](/docs/integrations/content-sources) ## 2026-11-25 **New** Message priority and an attention budget. Every campaign and agent has a category (Transactional, Lifecycle, Engagement, Promotions, or your own), and each person has a per-channel budget that adapts to how they respond. When a budget is full, the higher category wins; campaign messages wait for a free slot and then drop, and agent messages are skipped. Set it in Settings, Messaging limits; existing apps start in Observe, which only records what would be held. [Message priority and attention budget](/docs/concepts/message-priority) **New** The Send API takes an optional `category`. Transactional sends are never held; other categories follow the budget. [Send API](/docs/reference/send-api) **Changed** In Enforce mode the budget replaces the push limit, and a `$external_push` with category transactional no longer counts. [Pushes your app sends](/docs/push-notifications/pushes-your-app-sends) **New** Warehouse audiences, in Beta: an audiences query in BigQuery or Snowflake returns `user_id` and `audience`, and each audience becomes a segment your agents can target, refreshed every hour. [Audiences](/docs/integrations/warehouses#audiences) **New** Send decisions to Segment, in Beta: every send and conversion arrives as a track call in a Segment HTTP API source, and from there in every destination you've connected. [Send decisions to Segment](/docs/integrations/event-sources#send-decisions-to-segment-optional) **New** Stream Amplitude events in, in Beta: an Amplitude webhook event stream on the Amplitude integration's URL brings events and user properties, next to cohorts. [Stream Amplitude events](/docs/integrations/product-analytics#stream-amplitude-events-optional) **Improved** AppsFlyer, Adjust and Branch purchases carry `revenue` and `currency`, so an agent's goal can weight by value; Branch custom data comes through as event properties. [Revenue](/docs/integrations/attribution#revenue) ## 2026-11-22 **New** Send-time checks: right before an agent message Herald delivers goes out, it checks that the person still matches the audience and hasn't completed the goal. Campaigns do the same with **Check again at send time**, on by default for new ones. You can also skip people who used the app since the message was queued. [Send-time checks](/docs/concepts/how-delivery-works#send-time-checks) **New** A push limit across all sources, on by default at 3 pushes per person in 24 hours. It counts Herald pushes and the pushes your app reports, and skips agent and campaign pushes for anyone who reached it. [The push limit](/docs/push-notifications/pushes-your-app-sends#the-push-limit) **New** Every identified person has a short User ID, such as `7K3M-9QXA`, that support can search for on People. The console now calls the ID your app passes to `identify` the External ID. [Support ID](/docs/concepts/users-and-identity#support-id) **Changed** Each event in an SDK batch or a `POST /api/v1/events` request is checked on its own. A bad event is rejected and listed in the response; the rest are kept, and the console shows rejected events for 30 days. [Rejected events](/docs/reference/error-codes#rejected-events) **Improved** SDK event times are corrected for the device's clock, so a phone with a wrong clock no longer puts activity or goal credit in the wrong window. [Clock correction](/docs/concepts/batching-and-offline#clock-correction) **Improved** When a device first signs in, its guest events from the last 30 days become that person's, including goal credit for earlier messages. [Guests and signed-in users](/docs/concepts/users-and-identity#guests-and-signed-in-users) **New** Lifecycle events (`$app_installed`, `$app_opened`, `$app_foreground` and more) and sessions with separate foreground and background timeouts. Herald accepts them now; SDK 0.6.0 sends them. [Lifecycle events](/docs/reference/event-payload#lifecycle-events) **New** Remote SDK settings: change the send interval, session timeouts, data collection and tracking from the console without an app update. Turning off **Collect events** is a kill switch that stops all collection. SDK 0.6.0 reads them. [Remote SDK settings](/docs/data-and-privacy/data-collection-controls#remote-sdk-settings) **New** A per-app **Store location from IP address** switch, on by default, and a consent record for the lawful basis your app collects data under. [Data collection controls](/docs/data-and-privacy/data-collection-controls) and [Record the lawful basis](/docs/data-and-privacy/consent-and-opt-out#4-record-the-lawful-basis) **New** Event schemas: describe an event's properties in the console and choose to reject invalid events or accept them with a warning. [Event schemas](/docs/concepts/event-schemas) ## 2026-11-21 **New** An MCP server, in Beta. Connect Claude, ChatGPT, Cursor or Gemini CLI to read an app's results and, if you allow it, pause agents and draft variants. Claude.ai and ChatGPT sign in with OAuth. [AI assistants](/docs/integrations/ai-assistants) **New** Integrations, in Beta: Segment, RudderStack and signed webhooks for events; RevenueCat and Stripe for revenue; BigQuery, Firebase and Snowflake, with write-back; Amplitude and Mixpanel cohorts; AppsFlyer, Adjust and Branch attribution. [Integrations overview](/docs/integrations/overview) **New** Send through your own tools, in Beta: OneSignal, Iterable, Customer.io, Klaviyo, Mailchimp Transactional and your own Twilio account. Results go out with the decisions CSV, Slack alerts, outbound webhooks and Google Sheets. [Sending through your tools](/docs/integrations/senders) and [Reporting and exports](/docs/integrations/reporting) **New** More integrations, in Beta: HubSpot, Salesforce and Mailchimp audiences, the App Store and Google Play for purchases, and a daily ad audience sync to Meta, Google Ads and LinkedIn. [HubSpot, Salesforce and Mailchimp](/docs/integrations/crm), [App Store and Google Play](/docs/integrations/revenue#app-store-and-google-play) and [Ad audiences](/docs/integrations/reporting#ad-audiences) ## 2026-11-20 **New** The Send API sends push, web push, email, SMS, in-app messages and content cards from your backend, to named people or a segment, now or on a schedule. It uses scoped API keys, hourly limits and idempotency keys. [Send API](/docs/reference/send-api) Source: https://heraldsdk.com/docs/reference/whats-new.md --- # Logging and debugging > Turn on SDK logging on iOS and Android, read the log, preview in-app messages and cards without a server, and confirm what reached Herald. Turn on debug logging while you integrate, read what the SDK reports, and use the preview hooks to check your message UI without waiting for a real send. ## Log levels | Level | iOS | Android | What it shows | |---|---|---|---| | None | `.none` | `LogLevel.NONE` | Nothing | | Error | `.error` | `LogLevel.ERROR` | Rejected batches, invalid calls (iOS), disk failures | | Warning (default) | `.warning` | `LogLevel.WARN` | Plus invalid calls (Android), dropped keys, queue overflow, failed message fetches | | Info | `.info` | `LogLevel.INFO` | Plus network failures and retry timing, messages that could not show yet | | Debug | `.debug` | `LogLevel.DEBUG` | Plus accepted batches (Android), events Herald rejected from an accepted batch, unchanged message fetches, discarded messages (Android), card impressions (iOS feed) | Set the level in the configuration. Use debug in development builds only. :::tabs ::tab ios ```swift Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!) { options in #if DEBUG options.logLevel = .debug #endif } ``` ::tab android ```kotlin Herald.configure( this, appKey = "YOUR_APP_KEY", endpoint = "https://YOUR_HERALD_HOST", options = HeraldOptions(logLevel = if (BuildConfig.DEBUG) LogLevel.DEBUG else LogLevel.WARN), ) ``` ::: ## Read the log :::tabs ::tab ios The SDK writes to the unified log under subsystem `com.herald.sdk`. Core messages use the category `Herald`; `HeraldUI` uses `ui`. In the Xcode console, filter by the subsystem. From a terminal, with a simulator running: ```sh xcrun simctl spawn booted log stream --level debug --predicate 'subsystem == "com.herald.sdk"' ``` On a device, use Console.app with the device selected and the same subsystem filter. Turn on **Include Debug Messages** in Console.app's **Action** menu to see debug lines. ::tab android The SDK writes to Logcat with the tag `Herald`. `herald-ui` and `herald-fcm` use the same tag. In Android Studio, filter by `tag:Herald`. From a terminal: ```sh adb logcat -s Herald ``` ::: Log lines name calls, statuses and card or message IDs. They do not contain event properties, attribute values or push tokens. On Android, a rejected batch line includes the first 300 characters of the server's error message. ## What to look for | You see | It means | Next step | |---|---|---| | `Herald rejected a batch ...` | Herald returned a 4xx and the batch was dropped | Check the status in [Error codes](/docs/reference/error-codes) | | `... ignored: ...` | A call broke a rule and was dropped on the device | Fix the call; see [Limits](/docs/reference/limits) | | `Batch will be retried in N s` (iOS) or `will retry` (Android) | No network or a retryable status | Nothing, unless it repeats for minutes | | `Event queue full` | More than 1,000 events waited | Find why uploads fail; check for a call in a tight loop | | `Message sync failed ...` | The fetch failed; cached messages are used | Check the status and the user token | | `not shown (no presenter or no active scene)` | An in-app message is waiting | Install a presenter after `configure` | | `Sent N events` (Android, debug) | A batch was accepted | Confirm in Herald | | `Herald rejected event <id>: <reason> (<detail>)` (debug) | Herald kept the batch but left this event out | Fix the call; see [Rejected events](/docs/reference/error-codes#rejected-events) | | Nothing at all | `configure` never ran, or the level is too low | Set the level to debug and check `configure` is called | ## Inspect the traffic To see the exact requests, run the app through an HTTPS debugging proxy you trust and filter for your Herald host. The SDK calls two paths: `POST /api/v1/sdk/batch` and `GET /api/v1/sdk/messages`. Their formats are on [SDK REST endpoints](/docs/reference/rest-endpoints). To force an upload while you watch, call `flush()`, or send the app to the background. ## Preview messages without a server Two hooks load and show messages from JSON on the device, so designers and engineers can check every message type and card without an agent send. :::warning Debug and preview only `debugLoadMessages` and `debugShowInAppMessage` are public in every build, but they are for debug builds and internal preview screens only. Do not call them in production code paths. Wrap the calls in `#if DEBUG` (iOS) or `if (BuildConfig.DEBUG)` (Android), or keep them in a debug-only source set. ::: | Hook | What it does | |---|---| | `debugLoadMessages(json)` | Replaces the cards and in-app messages in memory with a `GET /api/v1/sdk/messages` response body. Nothing is saved, and the next real fetch replaces them. An unreadable body logs `debugLoadMessages: unreadable body`. | | `debugShowInAppMessage(messageId)` | Shows a loaded or fetched in-app message now, skipping its trigger, re-eligibility and the minimum interval. Your delegate is still asked on iOS. Does nothing while another message is on screen. | :::tabs ::tab ios ```swift #if DEBUG func previewWelcomeModal() { guard let url = Bundle.main.url(forResource: "preview-messages", withExtension: "json"), let json = try? Data(contentsOf: url) else { return } Herald.shared.debugLoadMessages(json) Herald.shared.debugShowInAppMessage("msg_2") } #endif ``` ::tab android ```kotlin fun previewWelcomeModal(context: Context) { if (!BuildConfig.DEBUG) return val json = context.assets.open("preview-messages.json").bufferedReader().use { it.readText() } Herald.debugLoadMessages(json) Herald.debugShowInAppMessage("msg_2") } ``` ::: Previewed messages behave like real ones: impressions, clicks and dismissals are queued and sent, and a shown message is recorded in the in-app history. Preview with a test connection and a test user. ## Confirm what reached Herald 1. Send the app to the background or call `flush()`. 2. Confirm the log shows no rejected batch. 3. In Herald, open **Audience > Search users** (admin only) and look up the External ID. The profile shows the attributes and traits written for that user. Herald has no screen for raw SDK events or devices today. If an event seems missing, check that the user is verified: under **Optional** verification, a batch without a token is stored as anonymous and writes nothing to the profile. ## Related - [Troubleshooting](/docs/operations/troubleshooting) - [Error codes](/docs/reference/error-codes) - [Data batching and offline behavior](/docs/concepts/batching-and-offline) Source: https://heraldsdk.com/docs/operations/logging-and-debugging.md --- # Troubleshooting > Symptoms, causes and fixes for the problems teams hit most often with the Herald SDK, from rejected batches to messages that never show. Find the symptom, check the cause, apply the fix. Turn on debug logging first: most causes leave a line in the log. See [Logging and debugging](/docs/operations/logging-and-debugging). ## Data and identity | Symptom | Cause | Fix | |---|---|---| | Log shows `Herald rejected the app key: check the publishable key in configure` and nothing reaches Herald | The app key is wrong, or the connection is not active | Copy the key again from the connection's **Mobile SDK** card and check the connection is active. The SDK keeps the events and sends them on the next launch with the right key. | | 401 only for signed-in users | Verification is **Required** and the user token is missing or wrong | Mint the token on your backend from the exact External ID you pass to `identify`. Call `setUserToken` right after `identify`. | | 401 for every signed-in user after a change on the connection | Someone rotated the ingest token, which invalidates every user token | Re-mint tokens with the new ingest token and deliver them to the apps | | One message sync 401 right after sign-in, then cards appear | `identify` fetched messages before `setUserToken` ran, under **Required** verification | Harmless. Call `setUserToken` immediately after `identify`; it fetches again with the token. | | A session-start in-app message does not show in the first session after sign-in | The session-start trigger ran before the token-authenticated fetch returned the message | Expected; it can show from the next session. | | The user's profile in Herald stays empty | Verification is **Optional** and the batch had no token, so it was stored as anonymous | Call `setUserToken` after `identify` | | `... ignored: ...` in the log | The call broke a limit, such as an empty event name or a 201-character External ID | Fix the call. See [Limits](/docs/reference/limits). | | Email or phone not stored | The value failed the check and that key was dropped (`$email is not a valid email`) | Send a valid address, and phone numbers in E.164 (`+15551234567`) | | Nothing is sent at all | `configure` never ran, or the SDK is disabled | Call `configure` at launch. After `wipeData()`, the SDK stays off until `setEnabled(true)`. | | Calls made at startup are missing | More than 1,000 calls ran before `configure` | Call `configure` earlier, before other SDK calls | | `Event queue full: dropped N oldest event(s)` | Uploads failed for a long time, or a call runs in a tight loop | Check the network and the batch status; remove the loop | ## Content cards and in-app messages | Symptom | Cause | Fix | |---|---|---| | No cards or in-app messages | The device is anonymous or unverified, so the fetch returns empty lists | Identify the user and set a valid user token | | An agent send produced no card for the user | The user had no SDK device on that connection at send time, so the send was suppressed | Make sure the user has opened the app with the SDK at least once, then send again | | A new card appears only after a restart | Cards are fetched at session start and after sign-in | Call `refreshContentCards()` when the user opens your inbox | | In-app messages never show | No presenter is installed (`not shown (no presenter or no active scene)` on iOS) | Call `Herald.useDefaultInAppUI()` (iOS) or `HeraldInAppPresenter.install()` (Android) after `configure` | | A message showed once and never again | Its re-eligibility is `once`. History is kept per user on the device, across restarts and sign-outs. | Expected. `wipeData()` clears the history on a test device. | | A message shows later than its trigger | Another message was up, the 30-second minimum interval had not passed, or the delegate answered later | Expected: pending messages show when they can. Lower `inAppMinimumInterval` in development if needed. | | The iOS delegate is never called | The SDK holds the delegate weakly and it was released | Keep a strong reference to your delegate object | | No in-app messages in one Android screen | The activity is not a `ComponentActivity` | Extend `ComponentActivity` or `AppCompatActivity` | ## Push | Symptom | Cause | Fix | |---|---|---| | No push token stored for the user | Tokens are stored only for identified, verified users | Identify the user and set the user token; the SDK sends the token again after `identify` | | iOS push fails with `DeviceTokenNotForTopic` | The bundle ID on the connection differs from the app's | Fix the bundle ID in the connection's APNs settings | | Android: `Firebase is not initialized; push token not synced` | `google-services.json` is missing or the Google services plugin is not applied | Add both, then rebuild | | Taps do not log opens or open deep links (iOS) | `handleNotificationResponse` is not called, or the notification center delegate is not set | Set `UNUserNotificationCenter.current().delegate` at launch and forward `didReceive` | | Taps do not log opens (Android) | `handleNotificationIntent` is missing from `onCreate` or `onNewIntent` of the launcher activity | Call it in both | | Deep link does nothing on Android (`openUrl failed`) | No activity has an intent filter for the scheme | Add the intent filter | | No image on iOS | No Notification Service Extension, or the image is not HTTPS, is over 10 MB or is not JPEG, PNG, GIF or HEIC | Add the extension with `HeraldNotificationService`; serve a supported image over HTTPS | | Push still arrives after sign-out | The anonymous batch that unbinds the device has not reached Herald yet | Call `flush()` after `reset()` if the app may close right away | | No action buttons on pushes from Herald | The variant has no action buttons, the iOS extension is missing, or `herald-fcm` is not in the Android app | Add buttons in **Delivery options (mobile SDK)** and check the platform setup. See [Rich push](/docs/push-notifications/rich-push#action-buttons). | | New cards and messages wait for the next session | The sync push is not handled, or was sent in the last five minutes | Turn on the Remote notifications background mode and forward the push on iOS. See [Silent push](/docs/push-notifications/silent-push). | ## Still stuck Collect the SDK version, platform and OS version, the debug log from app launch to the problem, and the User ID (shown to your users as Support ID) or the External ID, and the time of a failing call. Then contact your account team. See [Versioning and support](/docs/operations/versioning-and-support). ## Related - [Error codes](/docs/reference/error-codes) - [Logging and debugging](/docs/operations/logging-and-debugging) - [Testing push](/docs/push-notifications/testing) Source: https://heraldsdk.com/docs/operations/troubleshooting.md --- # Versioning and support policy > How SDK versions are numbered, where releases are published, what 0.6.0 does not cover yet, the minimum OS versions, how to get help, and how we intend to handle deprecations. The Herald SDK uses semantic versioning. The current release is 0.6.0. ## Version numbers Versions take the form `MAJOR.MINOR.PATCH`: | Part | Changes when | |---|---| | Major | A release removes or changes public API in a way that breaks existing code | | Minor | A release adds features in a way that keeps existing code working | | Patch | A release fixes bugs without changing the API | iOS and Android share version numbers, and a release ships on both platforms. `Herald.sdkVersion` (iOS) and `Herald.SDK_VERSION` (Android) return the version at runtime, and every batch reports it to Herald. ### Before 1.0 While the major version is 0, the API can still change between minor versions. We intend to list every change that needs work on your side in the [Changelog](/docs/reference/changelog), with the steps to update. Patch releases in the 0.x series are meant for fixes only. ## Where releases are published Each release is a git tag with the version number, such as `0.2.0`, on both source repositories: | Platform | Repository | Install from | |---|---|---| | iOS | `https://github.com/ender1311/herald-ios` | Swift Package Manager | | Android | `https://github.com/ender1311/herald-android` | JitPack (`https://jitpack.io`) | Each repository's releases page carries the notes for that version. [Platform support](/docs/overview/platform-support#install) has the install lines. ## What 0.6.0 does not cover yet Pages that describe a feature that is not built mark it as planned. Today that covers web SDKs, Liquid templating in Herald's own sending, and server-side rate limiting of SDK calls. See [Changelog](/docs/reference/changelog). ## Minimum requirements | | iOS | Android | |---|---|---| | Operating system | iOS 16 | Android 8.0 (API level 26) | | Build tools | Xcode 16, Swift tools 6.0 | Android Gradle Plugin 8, compileSdk 35 | | Push service | APNs | Firebase Cloud Messaging | See [Platform support](/docs/overview/platform-support) for module dependencies. ## Getting help Contact your Herald account team. To speed up a fix, include: - The SDK version, platform and OS version. - The debug log from app launch through the problem (see [Logging and debugging](/docs/operations/logging-and-debugging)). - The User ID (shown to your users as Support ID) or the External ID, and the time of a failing call, and the HTTP status if the log shows one. Do not send user tokens, ingest tokens or push tokens in a support request. ## Deprecation approach This section states how we intend to work. It is not a contractual commitment. - We intend to mark an API as deprecated in a release before we remove it, with a compiler warning and a note in the changelog that names the replacement. - We intend to remove deprecated APIs only in a later minor version while the SDK is below 1.0, and only in a major version from 1.0 on. - We intend to keep the SDK endpoints compatible with every released SDK version that is still in use, so older app versions in your users' hands keep sending data. - When we raise a minimum OS version, we intend to say so in the changelog at least one release ahead. ## Related - [Changelog](/docs/reference/changelog) - [Platform support](/docs/overview/platform-support) - [Troubleshooting](/docs/operations/troubleshooting) Source: https://heraldsdk.com/docs/operations/versioning-and-support.md