Overview
Retainza is a customer engagement platform — Email, Push, In-App messages, deep-link navigation and conditional sends. You integrate it into your app with a small SDK (or by calling the HTTP API directly).
Every integration is the same three steps:
- Install the SDK with your platform's package manager.
- Initialize it with
baseUrl(your Retainza server) and apublicKey. - Sign your users: pass a
userHashfrom your server with each user id, or turn signed identity off while you build.
Keys & base URL
Two kinds of keys
| Key | Prefix | Use it in |
|---|---|---|
| Public key | pk_… | Client apps (mobile, web) — identify, track, register push. Safe to ship. |
Why you always pass a base URL
The SDK is just code — it knows how to talk to Retainza, but not where your server lives. Every company runs Retainza at a different address, so the address can never be baked into a shared package. You pass it in when you initialize the SDK.
Platform support
The JavaScript/TypeScript SDK covers React Native/Expo, web and Node (npm). The native Swift SDK installs with SPM or CocoaPods, the Kotlin SDK from Maven Central, and the Flutter (Dart) SDK from pub.dev. Any platform can also call the HTTP API directly — an SDK is only a convenience wrapper.
| Platform | Language | Package manager | SDK |
|---|---|---|---|
| React Native / Expo, Web, Node | JavaScript / TypeScript | npm | Available |
| iOS (native) | Swift | SPM, CocoaPods | Available |
| Android (native) | Kotlin | Gradle (Maven Central) | Available |
| Flutter | Dart | pub.dev | Available |
Install & configure
Pick your platform. Every one is the same two steps — install, then initialize with your base URL and key.
# React Native / Expo
npm install @retainza/react-native
# Web: npm install @retainza/sdk-core
# Node: npm install @retainza/sdk-node// App.tsx
import AsyncStorage from "@react-native-async-storage/async-storage";
import Constants from "expo-constants";
import { Retainza } from "@retainza/react-native";
Retainza.init({
publicKey: process.env.EXPO_PUBLIC_ENGAGE_PUBLIC_KEY, // "pk_..."
userProvider: () => currentUser?.id, // optional
appVersion: Constants.expoConfig?.version, // → app_version attribute
storage: AsyncStorage, // offline queue + install_date
debug: __DEV__, // silent in production
});Next: the React Native guide takes it from here — identify, track, push and in-app, in order.
// Xcode → File → Add Package Dependencies… → paste:
https://github.com/appunik-retainza/ios-sdk
// or Package.swift:
.package(url: "https://github.com/appunik-retainza/ios-sdk.git", from: "1.1.0")// App / AppDelegate — the module is RetainzaSDK
import RetainzaSDK
try? Retainza.start(with: RetainzaConfig(
publicKey: "pk_test_…", // pk_live_… in release builds
userProvider: { AuthStore.shared.userId }
))Next: the iOS guide takes it from here — identify, track, push and in-app, in order.
# Podfile
pod 'RetainzaSDK', '~> 1.1'
# then
pod installimport RetainzaSDK
try? Retainza.start(with: RetainzaConfig(
publicKey: "pk_test_…",
userProvider: { AuthStore.shared.userId }
))Next: the iOS guide takes it from here — identify, track, push and in-app, in order.
// app/build.gradle.kts
dependencies {
implementation("com.retainza:retainza-android:1.0.0")
}// Application.onCreate()
import com.retainza.sdk.Retainza
import com.retainza.sdk.RetainzaConfig
Retainza.start(
this,
RetainzaConfig(
publicKey = BuildConfig.RETAINZA_KEY, // pk_test_… / pk_live_… per build type
userProvider = { AuthStore.userId },
),
)Next: the Android guide takes it from here — identify, track, push and in-app, in order.
# pubspec.yaml
dependencies:
retainza_flutter: ^1.0.0
# then
flutter pub get// main.dart
import 'package:flutter/widgets.dart';
import 'package:retainza_flutter/retainza_flutter.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
Retainza.init(
publicKey: const String.fromEnvironment('RETAINZA_PK'), // pk_test_… / pk_live_…
);
runApp(const MyApp());
}
// then Retainza.instance.identify(...), .track(...)Next: the Flutter guide takes it from here — identify, track, push and in-app, in order.
Using the SDK
Once initialized, the client exposes a small surface (shown here in JS/TS — native SDKs mirror it):
Identify a user
await Retainza.get().identify("user-123", {
plan: "pro",
signupSource: "web",
}, { email: "sam@acme.com", locale: "en" });Track an event
await Retainza.get().track("workout_completed", { minutes: 32 });Register for push
// obtain the device token from your push provider (e.g. FCM), then:
await Retainza.get().registerPush(fcmToken, "android"); // or "ios"Update a few attributes
setAttributes is a patch: it sends only the keys you pass and the server merges them, so unrelated attributes (country, tz, anything your app set earlier) are left alone.
await Retainza.get().setAttributes({ plan: "pro" });
// optionally for another user:
await Retainza.get().setAttributes({ plan: "pro" }, "user-123");In-app messages
Mount one component near your app root. That is the entire in-app integration — the SDK ships the renderer, so your app carries no layout, styling or ack code for it, and a template you design in the dashboard looks the same in every app that installs the SDK.
// app/_layout.tsx
import { RetainzaInApp } from "@retainza/react-native/ui";
import { usePathname } from "expo-router";
<RetainzaInApp
currentScreen={usePathname()} // optional "where to show" gate
blockedScreenPrefixes={["/(auth)", "/onboarding"]} // never interrupt these
/>It owns polling, the message queue (one at a time, the rest stay pending), the shown / clicked / dismissed acks that feed Analytics, and CTA deep links. A blocked screen leaves a message pending rather than consuming it, so nothing is lost.
Layouts
A native message is a list of slots — image/video, header, title, body and up to three buttons — arranged in whatever order the layout names. The catalog in the builder (“Image, Text & Button”, “Image only”, “Image & 2 Buttons”…) is just preset slot lists, so a new layout never needs an app release. Your app renders all of them with the one component above.
Each button carries its own action: give it a screen and it deep-links there and reports clicked; leave the screen blank and it closes the message and reports dismissed.
Overriding the look
Adopting the renderer is not all-or-nothing. Replace one presentation and keep the machinery, or take over rendering entirely:
<RetainzaInApp presentations={{ banner: MyBanner }} /> // just the banner
<RetainzaInApp render={(msg, { onCta, onDismiss }) => (
<MyOwnSheet message={msg} onPrimary={onCta} onClose={onDismiss} />
)} />Deep links from a CTA
Retainza.get().onNavigate((route) => router.push(route.screen));Full method list
| Method | Notes |
|---|---|
| identify(userId, attrs?, profile?) | Upsert a profile. The third argument is reserved identity — firstName, lastName, email, phone, gender, birthdate, locale — mapped to snake_case attributes for you. Default attributes ride along on every call. |
| setPushPermission(status, userId?) | "authorized" | "denied" | "provisional" | "undetermined". The SDK never prompts; report what your app already knows. A denied user keeps a valid token and receives nothing. |
| setDeviceInfo(info) | Device model/manufacturer from whichever device library you use. The React Native wrapper calls this from the `device` init option. |
| startSession() / endSession() | Foreground / background. Wired to AppState automatically unless autoSession is false. 30-minute timeout: a quick return resumes rather than counting again. |
| setConsent({ analytics, marketing }) | With requireConsent, nothing is sent until analytics is true. marketing does not gate transport — it is stored for campaign targeting. |
| optOut() / optIn() | Hard stop, clears the queue. Deliberately not persisted — your app owns the consent UI, so re-assert on each launch. |
| setAttributes(attrs, userId?) | Partial update — sends only what you pass; the server merges. |
| track(event, props?, userId?) | Stamps the event time client-side, so a queued event keeps its real timestamp. |
| addToCollection(collection, item, userId?) | One-to-many data — a user's challenges, badges, saved searches. Takes either a bare id string (`"lagos_10k"`) or an object with fields (`{ id, status, progress }`); the two interoperate, so a later write with fields patches the same item. `id` is yours and is the merge key: writing it twice updates in place, which is what makes a replayed offline write safe. Fields you omit are preserved. Items are flat — strings, numbers, booleans, null. |
| removeFromCollection(collection, id, userId?) | Remove one item. An id that is not there is a no-op, not an error. |
| setCollection(collection, items, userId?) | Replace the whole list; `[]` clears it. Accepts id strings or objects. Use it when your app already holds the full list; use addToCollection for incremental changes. |
| registerPush(token, platform, userId?) | Never queued — a stale token is worse than a missing one. |
| ackInApp(msgId, action, userId?) | "shown" | "clicked" | "dismissed". |
| ackPush(msgId, action, userId?) | "delivered" | "opened" — the only source of push delivery data. |
| reset() | Call on logout. Clears identity, session counters, the offline queue and in-app polling. |
| flushQueue() / queueSize() | Drain or inspect the offline queue. |
| getBaseUrl() / setBaseUrl(url) / clearBaseUrl() | Runtime backend switching in dev builds. |
| testConnection() | GET /health — for a “test connection” button on a dev screen. |
| onNavigate(h) | Register your router, for CTA deep links. |
| onSelfHandledInApp(h) | Receive selfhandled campaigns and render them yourself. The handle carries markShown/markClicked/markDismissed — send them or the campaign's funnel stays empty. |
| onInApp(h) | Low-level — <RetainzaInApp /> registers this for you. Only one handler exists, so setting it yourself takes delivery away from the component. |
| fetchPendingInApp(userId?) | One poll for queued in-app messages. Handled for you by <RetainzaInApp />. |
| startInAppPolling({ intervalMs, userId }) | Low-level polling loop; returns a stop function. |
| deliverInApp(msg) / resolveRoute(route) | Hand a message to the renderer / a route to the router. |
| parseRetainzaPush(data) | Standalone function: is this FCM payload ours? Returns null if not. |
Signed identity
Your public key is compiled into your app, so anyone who unpacks the app has it. By itself that is enough to act as any of your users: overwrite their profile and the email your campaigns go to, register a device for their pushes, or read their pending in-app messages. Signed identity closes that. Your server vouches for each user id, and Retainza refuses calls that claim an id without that proof.
How it works
- In the dashboard, open API keys and create an identity secret for the environment. It is shown once. Keep it with your other server secrets.
- When a user signs in, your server computes a signature of their user id with that secret and returns it to the app with the rest of the session.
- The app passes it to
identify. The SDK sends it with every call it makes for that user.
1. Sign the user id on your server
The signature is hex(HMAC-SHA256(identitySecret, userId)): 64 lowercase hex characters. With the Node SDK:
import { signUserId } from "@retainza/sdk-node";
const userHash = signUserId(process.env.RETAINZA_IDENTITY_SECRET, user.id);
// return userHash to the app with the rest of the sessionAny language with an HMAC function produces the same value:
import hmac, hashlib
user_hash = hmac.new(secret.encode(), user_id.encode(), hashlib.sha256).hexdigest()$userHash = hash_hmac('sha256', $userId, $secret);mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(userID))
userHash := hex.EncodeToString(mac.Sum(nil))2. Pass it to the SDK
On every launch, alongside the user id:
await Retainza.get().identify(user.id, attributes, profile, { userHash });try await Retainza.shared?.identify(user.id, userHash: userHash)Retainza.client?.identify(user.id, userHash = userHash)await Retainza.instance.identify(user.id, userHash: userHash);If you do not call identify at that point (for example you use a userProvider), set it directly with setUserHash(userHash).
- The signature is sent with every call for that user id, and never with any other id.
- It is kept in memory, not written to device storage on its own, so pass it again on each launch. Events queued while offline keep the signature they were made with and still verify when they are sent later.
reset()clears it. Identifying a different user without a signature clears it too.- An app that passes no signature behaves exactly as before.
3. Turn it on in stages
| Mode | What the API does |
|---|---|
| Off | Takes the user id on trust. Where projects created before this change start. |
| Monitor | Checks signatures and counts signed, unsigned and wrongly signed calls. Refuses nothing. |
| Enforce | Answers 401 to a call made with the public key that has no valid signature for the user id it names. Where new projects start. |
Ship an app version that sends the signature, switch the environment to Monitor, and watch the unsigned count fall as your users update. Switch to Enforce when it is at or near zero. Going back to Monitor is immediate if you need to.
What is checked, and what is not
- Checked: calls made with a public key to identify, track, collections, push token registration and removal, in-app pending and both ack routes.
- Not checked: calls made with a secret key. That is your server, which is the party doing the vouching.
- Each environment has its own secret and its own mode. Sandbox and Production are independent.
- A signature is tied to one user id. Someone who obtains a user's signature can act as that user only, until you replace the secret.
- It does not cover people who are not signed in (there is no server to vouch for them), and it does not stop a signed-in user sending made-up events about themselves.
Replacing the secret
Replace it from the same screen. The previous secret keeps working for 7 days, so signatures your apps already hold stay valid while your server moves to the new one. If a secret has leaked, replace it with no grace period: every signature made with the old one stops working at once, and users get a new one at their next sign-in.
Without the SDK
Send the signature in the X-Engage-User-Hash header. A refused call answers 401 identity_required (no header) or 401 identity_invalid (wrong signature for that user id).
curl -X POST https://api.retainza.com/v1/identify \
-H "authorization: Bearer pk_..." \
-H "x-engage-user-hash: 5ef80dc2a802d7fc..." \
-H "content-type: application/json" \
-d '{"userId":"user-123","attributes":{"plan":"pro"}}'Custom HTML messages
The four native templates cover most sends and should stay your default — they render as real native views, cost nothing to show, and match your app's look. When the layout itself is the point, pick the Custom HTML presentation instead and design the whole message in the dashboard.
Your document renders in a sandboxed WebView inside a native shell (popup, bottom sheet or full screen), so it keeps the backdrop, safe-area padding and dismiss behaviour of a normal message. No app code is needed — the same <RetainzaInApp /> renders it.
Talking to the app
A document gets exactly three verbs. They run the same code path as a native template's buttons, so the funnel in Analytics reads identically whichever presentation a campaign uses.
<button onclick="engage.cta({ screen: '/(tabs)/shop', kv: { id: '42' } })">Shop</button>
<button onclick="engage.dismiss()">Not now</button>
<button onclick="engage.track('variant_b_tapped')">Tell me more</button>engage.cta(route?)— reports clicked, then deep-links if you pass a route.engage.dismiss()— reports dismissed and closes.engage.track(event, props?)— a custom event, e.g. which variant was tapped.
What a document may and may not do
- Allowed: inline
<style>and<script>, https images, data URIs,{{variables}}. - Blocked on the device: remote scripts,
fetch/XHR,<iframe>,<object>,<embed>,<base>and meta-refresh — a strict CSP and an opaque origin see to it. - Rejected on save: anything over 64 KB, and the tags above. The document is sent on every in-app poll, so size is bandwidth for every user.
Falling back
react-native-webview is an optional peer. If it is not installed, or a document fails to render, the SDK shows the native popup built from the campaign's title, body and CTA instead. That is why those fields stay required for an HTML message — without them the campaign would simply vanish on those devices.
npx expo install react-native-webview # enables HTML in-app messagesSelf-handled messages
The escape hatch: pick the Self-handled presentation and Retainza delivers the payload without drawing anything. Your app renders it with its own design system, and keeps the targeting, scheduling and analytics that every other campaign gets.
It is the last resort, not the first. A native layout needs no app code and no release; this needs both. Reach for it when the message has to be part of your own UI — a card inside a feed, a themed sheet — rather than an overlay on top of it.
Retainza.get().onSelfHandledInApp((msg) => {
setPromo(msg); // your own component draws it
});
// in that component:
useEffect(() => promo.markShown(), []); // counts as delivered
<Button onPress={() => promo.markClicked()} /> // acks clicked, then deep-links
<Close onPress={() => promo.markDismissed()} />Default attributes
The SDK attaches these to every identify, so they never go stale. Anything you pass yourself wins — if your app sets country from a billing address, the SDK will not overwrite it.
| Attribute | Set by | Notes |
|---|---|---|
| language | SDK (Intl) | ISO-639-1, e.g. "en". |
| country | SDK (Intl) | ISO-3166-1 alpha-2 from the device locale, e.g. "IN". Powers geo targeting. Locale, not GPS — no permission involved. |
| tz | SDK (Intl) | IANA, e.g. "Asia/Kolkata". Powers user-local scheduling. |
| sdk_version | SDK | The SDK build, for debugging an integration. |
| platform | React Native SDK | "ios" | "android" | "web", from Platform.OS. |
| os_name / os_version | React Native SDK | From React Native itself. |
| device_model / device_manufacturer | Your app | Only when you pass `device` at init — the SDK takes no dependency on a device library. |
| app_version | React Native SDK | Whatever you pass as appVersion to init. |
| install_date | React Native SDK | Stamped once into your storage adapter on first run. |
| session_count | SDK sessions | Lifetime sessions. Also first_session_at, last_session_at and session_duration_total. |
| push_permission | Your app | setPushPermission(). The difference between having a token and being reachable. |
| first_name, last_name, email, phone, gender, birthdate | Your app | Reserved identity. Only ever what you pass to identify — the SDK never collects PII on its own. |
| consent_marketing / consent_analytics | Your app | setConsent(). |
| last_active | Backend | Refreshed on every identify and track. |
import AsyncStorage from "@react-native-async-storage/async-storage";
import Constants from "expo-constants";
import { Retainza } from "@retainza/react-native";
Retainza.init({
publicKey: process.env.EXPO_PUBLIC_ENGAGE_PUBLIC_KEY,
appVersion: Constants.expoConfig?.version, // → app_version
storage: AsyncStorage, // → install_date + offline queue
});
// platform and install_date resolve asynchronously; await this before the
// very first identify if you need them on that call.
await Retainza.ready();Offline & logout
The offline queue
track and identify are queued when a request fails with a network error or a 5xx, then replayed oldest-first. A 4xx is not queued — it would fail forever and block everything behind it.
- Capacity 100 (
maxQueuedEvents); the oldest events are dropped on overflow. - Order is preserved — a flush stops at the first failure rather than skipping ahead.
- Each event carries its original timestamp, so a delayed flush does not distort analytics or misfire a time-based condition.
- With a
storageadapter the queue survives an app restart. Without one it is memory-only: it survives a network blip, not a relaunch. registerPushis never queued.
Reset on logout
export async function signOut() {
await auth().signOut();
await Retainza.get().reset(); // clears identity, queue and polling
}reset() is a client-side identity clear, not a data deletion — the server-side profile is untouched. It also clears the user's signed identity. For a GDPR erasure use DELETE /v1/users/:id. If you supplied a userProvider, remember it belongs to your app: the SDK will keep using whatever it returns.
Debug & troubleshooting
Debug mode
debug: true logs every request, poll, ack and swallowed error. With debug off the SDK writes nothing to the console. Values are never logged — only attribute and property key names, and only a prefix of the public key.
Retainza.init({
publicKey: "pk_…",
debug: __DEV__, // silent in production
logger: (level, msg, meta) => Sentry.addBreadcrumb({ level, message: msg, data: meta }),
});Changing the backend URL without a rebuild
The base URL is normally inlined into your bundle at build time, so a backend hostname change disconnects every installed build until you ship a new one. In dev builds the SDK can be pointed somewhere else at runtime, highest priority first: stored override → config.baseUrl → EXPO_PUBLIC_ENGAGE_BASE_URL.
const client = Retainza.get();
await client.setBaseUrl("https://your-tunnel.example.dev/v1");
const { ok, status } = await client.testConnection(); // GET /health
await client.clearBaseUrl(); // back to the built-in URLChanging EXPO_PUBLIC_* does not invalidate a release build
Clear both caches and rebuild:
rm -rf android/app/build/generated/assets/createBundleReleaseJsAndAssets \
android/app/build/intermediates/assets/release
rm -rf "$TMPDIR"/metro-*
npx expo run:android --variant releaseThen verify the value actually made it into the bundle before trusting the build:
grep -a -c 'api.retainza.com' \
android/app/build/generated/assets/createBundleReleaseJsAndAssets/index.android.bundle
# 0 means the old bundle is still in place — clear the caches again.Push notifications
- In the dashboard, add an FCM (Android) or APNs (iOS) connection under Connections.
- In your app, get the device push token and call
registerPush(token, platform). - Send a push from Campaigns; watch delivery in Notifications.
Deep links & screens
A campaign's screen is an expo-router path in your app. Retainza does not know your navigation — it carries the path and any parameters, and your app resolves them.
What Retainza puts in the push
Alongside the usual notification block, every Retainza push carries a data block. Every key is prefixed engage_ so it cannot collide with another push SDK in the same app (a third-party SDK, your own notifications), and every value is a string — that is an FCM requirement.
{
"notification": { "title": "…", "body": "…" },
"data": {
"engage_msg_id": "<campaignId>:<runId>:push:<userId>",
"engage_campaign": "<campaignId>",
"engage_route": "/(tabs)/challenges", // optional
"engage_params": "{"id":"42"}" // optional, JSON string
}
}Handling it
Use parseRetainzaPush(data) from the SDK in every Firebase handler. It returns null for anything that is not an Retainza push, so other SDKs pass through untouched.
import messaging from "@react-native-firebase/messaging";
import { parseRetainzaPush } from "@retainza/sdk-core";
// Tapped while backgrounded → report the open, then navigate.
messaging().onNotificationOpenedApp(async (remote) => {
const push = parseRetainzaPush(remote?.data);
if (!push) return; // not ours — leave it alone
await engage.ackPush(push.msgId, "opened");
if (push.route) router.push({ pathname: push.route.screen, params: push.route.kv ?? {} });
});
// Foreground → report delivery, but do NOT navigate: nobody tapped anything.
messaging().onMessage(async (remote) => {
const push = parseRetainzaPush(remote?.data);
if (push) await engage.ackPush(push.msgId, "delivered");
});Why acks matter
FCM gives no delivery receipt. delivered and opened for push exist only because the device reports them via POST /v1/push/ack. Without those calls the funnel stops at sent. Status is monotonic, so acks arriving out of order never move a delivery backwards, and an unknown message id is accepted silently — telemetry must never break the app.
The screen catalog
The campaign builder offers a dropdown of known screens instead of a free-text path. That list lives in one constant, dashboard/src/lib/screenCatalog.ts — it is your app's config, not platform truth. Add a screen there and it appears for every campaign; a Custom… option always remains for anything not yet listed.
export const SCREEN_CATALOG: ScreenTarget[] = [
{ label: "Home", path: "/(tabs)/home" },
{ label: "Challenge", path: "/challenge/[id]", params: ["id"] },
// …add your own
];HTTP API reference
No SDK required — the backend is plain HTTP + JSON. Authenticate the ingest routes with your public key from the app, or with your secret key from your own backend: they accept either, so your server and your app are co-equal write paths. Use that when the truth lives on your server — plan tier, entitlements, anything the app never sees. Management routes below are driven from this portal.
Never ship a secret key in an app. It reaches campaigns, segments and billing, and anyone who unzips your binary has it.
curl -X POST https://api.retainza.com/v1/identify \
-H "authorization: Bearer pk_..." \
-H "content-type: application/json" \
-d '{"userId":"user-123","attributes":{"plan":"pro"}}'If an environment enforces signed identity, calls made with the public key must also carry X-Engage-User-Hash. Calls made with a secret key never need it.
Ingest routes (public key from the app, or secret key from your backend)
- POST
/v1/identifyidentify - POST
/v1/tracktrack - POST
/v1/collectionscollections - POST
/v1/tokentoken - DELETE
/v1/tokentokenDelete - POST
/v1/inapp/ackinappAck - GET
/v1/inapp/pendinginappPending - POST
/v1/push/ackpushAck
Management routes (this portal only)
- GET
/v1/projectsprojectsList - POST
/v1/projectsprojectsCreate - POST
/v1/campaignscampaignsUpsert - GET
/v1/campaignscampaignsList - POST
/v1/campaigns/:id/activatecampaignActivate - POST
/v1/campaigns/:id/pausecampaignPause - POST
/v1/sendsend - POST
/v1/segmentssegmentsUpsert - GET
/v1/segments/:id/countsegmentCount - POST
/v1/connectionsconnectionsUpsert - GET
/v1/connectionsconnectionsList - GET
/v1/usageusage - GET
/v1/billingbilling - POST
/v1/billing/checkoutbillingCheckout - POST
/v1/billing/upgrade-checkoutbillingUpgradeCheckout - POST
/v1/billing/previewbillingPreview - POST
/v1/billing/changebillingChange - POST
/v1/billing/portalbillingPortal - GET
/v1/analytics/campaigns/:idanalytics - POST
/v1/scheduler/tickschedulerTick - GET
/v1/users/:iduserView - GET
/v1/users/:id/exportuserExport - DELETE
/v1/users/:iduserErase
