KLP React Native SDK — Integration Guide
Add the loyalty experience to your React Native app: install the package, initialize it, sign in your user and open the loyalty screen. The package is a bridge to the native iOS and Android SDKs; it works the same way on both platforms.
Requirements: React Native 0.72 or later, React 18 or later, iOS 15 or later (Xcode 26.2 or later), Android API 24 (Android 7.0) or later with JDK 17.
This page describes version 1.1.3 of @kaizen-dev-team/rn-sdk, which uses version 1.0.11
of the native iOS and Android SDKs.
1. Installation
If KLP provided a brand-specific wrapper package for you, install that package instead and follow its instructions.
Configure the registry
Create a .npmrc file in your project root, next to package.json, with this single line:
@kaizen-dev-team:registry=https://sdk.kaizentech.net/klp/npm/
- No credentials or tokens are needed.
- Keep the trailing slash. Without it, npm may not resolve the package.
- Only the
@kaizen-dev-teamscope uses this registry; all other packages still come from your usual registry. - Commit the file. Your CI machines use the same file.
Install the package
yarn add @kaizen-dev-team/rn-sdk
or, with npm:
npm install @kaizen-dev-team/rn-sdk
iOS
The package brings its own pod, KlpRnSdk, which React Native autolinking picks up. The
native KLP iOS SDK is declared through a helper shipped in the package. In your ios/Podfile,
load the helper and call klp_ios_sdk! inside your app target:
require_relative '../node_modules/@kaizen-dev-team/rn-sdk/scripts/klp_pods.rb'
target 'MyApp' do
config = use_native_modules!
klp_ios_sdk!
# ...the rest of your target (use_react_native!, post_install, ...)
end
Then install the pods:
cd ios && pod install
The native SDK version is pinned by the npm package. When you upgrade the npm package, the
native SDK is upgraded with it on the next pod install. Do not add a separate KLPSDK pod
yourself.
Android
No change is needed. Autolinking registers the module, and the module adds the repository for the native KLP Android SDK to your build. The native SDK version is pinned by the npm package.
If your settings.gradle sets repositoriesMode to FAIL_ON_PROJECT_REPOS, Gradle will not
accept the repository the module adds. In that case, add
https://sdk.kaizentech.net/klp/android to the repositories block under
dependencyResolutionManagement yourself.
Build machines and CI
No secrets need to be injected. Your build machines need HTTPS access to sdk.kaizentech.net
for the package install, pod install and the Gradle build. If you use TLS inspection, exclude
this host from it.
2. Initializing the SDK
Call initialize once at app startup, before any other KLP method.
import { KLP } from "@kaizen-dev-team/rn-sdk";
export async function initializeLoyalty(isDark: boolean): Promise<boolean> {
try {
return await KLP.initialize({
environment: __DEV__ ? "test" : "prod",
debugMode: __DEV__, // development only
showDebugScreen: false, // test builds only
theme: isDark ? "dark" : "light", // optional starting theme
language: "tr" // optional starting language
});
} catch (error) {
const code = (error as { code?: string }).code;
if (code === "KLP_INIT_SECURITY_ERROR") {
// The device failed the security checks. The SDK is unavailable.
}
return false;
}
}
The promise resolves to true when the SDK is ready. If it rejects, the SDK is unavailable,
and you should show an appropriate message to the user.
Configuration fields
All fields of KLPInitializeConfig are optional.
| Field | Type | Description |
|---|---|---|
environment | "dev" | "test" | "prod" | Endpoint set. Defaults to "prod". |
debugMode | boolean | Disables the security checks and turns on verbose logging. Development only. Default false. |
showDebugScreen | boolean | Shows the testing aids (debug button and debug screen). Keep disabled in production builds. Default false. |
theme | "system" | "light" | "dark" | Starting theme. Omit it to keep the native default ("system"). |
language | string | Starting language as a BCP-47 tag, for example "tr" or "tr-TR". Omit it to follow the app's language. An empty or blank value counts as not provided. |
colors | KLPColors | White-label colours for the SDK's native error screen. See below. |
theme and language set only the starting value, so the loyalty screen opens in your app's
theme and language without extra calls. When the user changes either one later, call
setTheme or setLanguage (see Theme and language).
An unknown environment or theme value makes initialize reject.
White-label colours
When the loyalty screen cannot load, the native SDK shows its own error screen. Pass colors
to match your brand. Every field is optional, and you can set the colours separately for each
appearance. The SDK picks the set that matches the current theme, or the system appearance when
the theme is "system".
await KLP.initialize({
environment: "prod",
colors: {
light: { backgroundColor: "#FFFFFF", primaryColor: "#0670D4", textColor: "#0F172A" },
dark: { primaryColor: "#0670D4" }
}
});
| Field | Used for |
|---|---|
backgroundColor | Background of the screen |
primaryColor | Retry button |
textColor | Title. Body text uses the same colour at 64% opacity. |
- Values are hex strings, either
#RRGGBBor#AARRGGBB(not case-sensitive). - An omitted or invalid value falls back to the design default. Invalid values never make
initializefail; they are logged whendebugModeis on. - The screen is drawn by the native SDK, so there is no React Native component to render. See the iOS guide for the default colours and the screen's behaviour.
3. User Session
After the user signs in to your app, pass the access token to the SDK. The user is resolved
from the token by the backend, so you do not pass a user ID. When the user signs out, call
logout.
// After login
await KLP.setUser(accessToken);
// Or with the token's expiry time (epoch milliseconds)
await KLP.setUser(accessToken, expiresAt);
// On logout
await KLP.logout();
Refreshing the access token
There are two ways to keep the token fresh. You normally want the first one.
1. Let the SDK ask you (recommended). Register a handler that returns a fresh token. Register
it once at app startup, next to initialize:
import { KLP } from "@kaizen-dev-team/rn-sdk";
import type { KLPRefreshedToken } from "@kaizen-dev-team/rn-sdk";
KLP.setOnRefreshTokenHandler(async (): Promise<KLPRefreshedToken> => {
const token = await myAuthService.refreshAccessToken();
// `expiresAt` (epoch milliseconds) is optional.
return { accessToken: token.value, expiresAt: token.expiresAt };
});
// To stop:
KLP.setOnRefreshTokenHandler(null);
The handler works in one of two modes, depending on whether the SDK knows when the token expires:
- Proactive: you pass an expiry, with
setUser(accessToken, expiresAt), theexpiryDateofsetToken, or theexpiresAtthat your handler returns. A minute before the token expires, requests are held, your handler is called, and the requests continue with the new token. - Reactive: you do not pass an expiry. When a service answers
401_Token, the request is held, your handler is called, and the request is resent with the new token. The user does not notice anything.
How the handler is used:
- One handler at a time. Calling
setOnRefreshTokenHandleragain replaces the previous handler.nullremoves it, and the SDK stops asking for tokens. - Reject the promise to signal a failure. The error message is passed to the native SDK. Do not resolve with an old token instead.
- About 30 seconds. The native SDK stops waiting for an answer after roughly 30 seconds. A slower handler is not cancelled, but its result is ignored.
- Expiry of at least 60 seconds. If you return
expiresAt, it must be at least 60 seconds in the future. - No handler registered. If a service answers
401_Tokenand no handler is registered, the request fails immediately. - Unlike the other
KLPmethods,setOnRefreshTokenHandleris synchronous and returnsvoid.
When the token cannot be refreshed, the loyalty screen shows a "session expired" screen. This
happens when your handler rejects, when the backend rejects 3 refreshed tokens in a row, or when
no handler is registered and a service answers 401_Token. If you later pass a valid token with
setToken or setUser, the loyalty screen reloads from the start.
2. Push a new token yourself. If your app refreshes the token on its own schedule, call
setToken. It replaces the token the SDK uses for later requests, without restarting the
session the way setUser does.
const updated = await KLP.setToken(newAccessToken);
// or with the new expiry (epoch milliseconds)
const updatedWithExpiry = await KLP.setToken(newAccessToken, newExpiresAt);
setToken resolves to false and does nothing when there is no active session or when
accessToken is empty.
4. Launching the Loyalty Screen
// Home screen
await KLP.launch();
// A specific path (e.g. rewards)
await KLP.launch("rewards");
launch opens the loyalty screen full screen over your app. Call it after initialize and
setUser. It rejects with KLP_LAUNCH_ERROR when there is no active screen to present from,
or when the native SDK cannot open the screen.
To react when the user closes the loyalty screen, subscribe with onWebViewClosed
(see Listening to SDK events).
This package opens the loyalty screen only in full screen. It does not provide a component that embeds the loyalty screen inside your own layout.
5. Event Logging
Send business events to the loyalty platform while a user session is active, after setUser.
await KLP.logEvent("LogIn");
await KLP.logEvent("MoneyTransfer", { amount: 500, currency: "TRY" });
For events that carry sensitive values, use logEncryptedEvent. The native SDK encrypts the
event type and each attribute value (RSA-OAEP-SHA256) before sending them.
await KLP.logEncryptedEvent("MoneyTransfer", { amount: 500, currency: "TRY" });
Event names and attribute keys must match what is configured for your application in KLP.
6. Listening to SDK Events
Each on… method returns a subscription. Call remove() on it when you no longer need it, for
example when your component unmounts.
import { useEffect } from "react";
import { KLP } from "@kaizen-dev-team/rn-sdk";
export function useLoyaltyEvents(): void {
useEffect(() => {
const deepLink = KLP.onDeepLink(({ url, host, queryParameters }) => {
// Navigate inside your app
console.log("Deep link:", url, host, queryParameters);
});
const reward = KLP.onRewardEarned((earned) => {
console.log("Reward earned:", earned.name);
});
const closed = KLP.onWebViewClosed(() => {
console.log("Loyalty screen closed");
});
return () => {
deepLink.remove();
reward.remove();
closed.remove();
};
}, []);
}
| Method | Listener receives | When |
|---|---|---|
onDeepLink | KLPDeepLinkPayload | The loyalty screen asks your app to open a deep link. The SDK closes the loyalty screen after it delivers the link. |
onRewardEarned | KLPReward | The user earned a reward. |
onSSEEffects | { effects: Record<string, unknown>[] } | Real-time effects arrived from the server, for example points or mission progress. See below. |
onEventReceived | KLPEventPayload | A generic event arrived from the loyalty screen or the native SDK. |
onWebViewClosed | nothing | The loyalty screen opened by launch was closed. |
onError | { message: string; code?: string } | The native SDK reported an error. code may be absent. |
onSecurityError | KLPSecurityCheckResult | The device failed the security checks. |
onThemeChanged | KLPThemeChangedPayload | The SDK theme changed. |
onLanguageChanged | KLPLanguageChangedPayload | The SDK language changed. |
onSSENotification | KLPSSENotificationPayload | Used by brand-specific wrapper packages. With this package on its own, it does not fire. |
Real-time effects popup. By default the SDK shows real-time effects in its own popup. While
at least one onSSEEffects listener is attached, the SDK does not show the popup, and your app
presents the effects. When you remove the last listener, the SDK shows the popup again. An open
loyalty screen is notified in both cases. onRewardEarned does not affect the popup.
Security failures during startup. When the security checks fail during initialize, the
SDK emits onSecurityError before the initialize promise rejects. To receive the details,
subscribe before you call initialize.
KLPEvents contains the raw native event names. Use the on… methods instead: a raw
subscription to the real-time effects event does not turn off the SDK's popup.
7. Theme and Language
Keep the SDK in sync with your app's theme and language. Otherwise the loyalty screen may look different from the rest of your app.
// When the user changes the theme in your app
await KLP.setTheme("dark"); // "system" | "light" | "dark"
// When the user changes the language in your app
await KLP.setLanguage("en");
// Go back to the default language
await KLP.setLanguage(null);
// Read the current values
const { theme, resolvedTheme, languageTag } = await KLP.getAppearance();
// Get notified about changes
const themeSubscription = KLP.onThemeChanged(({ theme, resolvedTheme }) => {
console.log("Theme:", theme, "shown as", resolvedTheme);
});
const languageSubscription = KLP.onLanguageChanged(({ languageTag }) => {
console.log("Language:", languageTag);
});
resolvedThemeis always"light"or"dark". Whenthemeis"system", it is the system appearance.- To reset the language, pass
null. Do not pass an empty string: on iOS,setLanguagerejects it withKLP_LANGUAGE_ERROR. - When a user session is active, a language change also reconnects the real-time stream in the new language and saves the user's language on the backend. Notifications that are created while the app is closed then use this language too.
- Call
setThemeandsetLanguageafterinitialize. On Android, they have no effect before initialization, andsetThemeresolves tofalse.
8. Security and Diagnostics
const ready = await KLP.isInitialized();
const secure = await KLP.isDeviceSecure();
const result = await KLP.performSecurityChecks();
if (!result.allPassed) {
result.checks
.filter((check) => !check.passed)
.forEach((check) => console.log(check.name, check.errorMessage));
}
- Use
debugMode: falseandshowDebugScreen: falsein production builds. KLP.openDebugScreen()opens the SDK's debug screen on iOS and Android whenshowDebugScreenis on; otherwise it does nothing. Use it only in test builds.
9. API Reference
Import everything from the package root:
import { KLP } from "@kaizen-dev-team/rn-sdk";
import type { KLPInitializeConfig, KLPReward } from "@kaizen-dev-team/rn-sdk";
Methods
| Method | Returns | Description |
|---|---|---|
initialize(config: KLPInitializeConfig) | Promise<boolean> | Initializes the native SDK and runs the security checks. |
setUser(accessToken: string, expiresAt?: number | null) | Promise<boolean> | Starts the user session. expiresAt is in epoch milliseconds. |
setToken(accessToken: string, expiryDate?: number | null) | Promise<boolean> | Replaces the access token. Resolves false when there is no active session or the token is empty. |
setOnRefreshTokenHandler(handler: KLPRefreshTokenHandler | null) | void | Registers or removes the token refresh handler. |
logout() | Promise<boolean> | Ends the user session. |
launch(path?: string) | Promise<boolean> | Opens the loyalty screen, optionally at path. |
logEvent(eventName: string, attributes?: Record<string, unknown>) | Promise<boolean> | Sends an event. |
logEncryptedEvent(eventName: string, attributes?: Record<string, unknown>) | Promise<boolean> | Sends an event with the event type and attribute values encrypted. |
setTheme(theme: KLPTheme) | Promise<boolean> | Sets the theme. |
setLanguage(languageTag: string | null) | Promise<boolean> | Sets the language. null resets it. |
getAppearance() | Promise<KLPAppearanceSnapshot> | Reads the current theme and language. |
isInitialized() | Promise<boolean> | Whether the native SDK is initialized. |
isDeviceSecure() | Promise<boolean> | Whether the device passes the security checks. |
performSecurityChecks() | Promise<KLPSecurityCheckResult> | Runs the security checks and returns each result. |
openDebugScreen() | Promise<boolean> | Opens the debug screen (test builds). |
Event subscriptions
Each method takes a listener and returns { remove(): void }.
| Method | Listener |
|---|---|
onDeepLink | (payload: KLPDeepLinkPayload) => void |
onRewardEarned | (payload: KLPReward) => void |
onSSEEffects | (payload: { effects: Record<string, unknown>[] }) => void |
onEventReceived | (payload: KLPEventPayload) => void |
onWebViewClosed | () => void |
onError | (payload: { message: string; code?: string }) => void |
onSecurityError | (payload: KLPSecurityCheckResult) => void |
onThemeChanged | (payload: KLPThemeChangedPayload) => void |
onLanguageChanged | (payload: KLPLanguageChangedPayload) => void |
onSSENotification | (payload: KLPSSENotificationPayload) => void |
Types
| Type | Shape |
|---|---|
KLPEnvironment | "dev" | "test" | "prod" |
KLPTheme | "system" | "light" | "dark" |
KLPInitializeConfig | { environment?, debugMode?, showDebugScreen?, theme?, language?, colors? } |
KLPColors | { light?: KLPColorSet; dark?: KLPColorSet } |
KLPColorSet | { backgroundColor?: string; primaryColor?: string; textColor?: string } |
KLPRefreshTokenHandler | () => Promise<KLPRefreshedToken> |
KLPRefreshedToken | { accessToken: string; expiresAt?: number | null } |
KLPReward | { id: string; name: string; description: string; imageUrl: string; value: number; type: string; earnedAt: number } (earnedAt in epoch milliseconds) |
KLPDeepLinkPayload | { url: string; scheme?: string; host?: string | null; path?: string; queryParameters?: Record<string, string> } |
KLPEventPayload | { type: string; data: Record<string, unknown> | string; timestamp: number } (timestamp in epoch milliseconds) |
KLPSecurityCheckResult | { allPassed: boolean; checks: KLPSecurityCheck[] } |
KLPSecurityCheck | { name: string; passed: boolean; errorMessage?: string | null } |
KLPAppearanceSnapshot | { theme: KLPTheme; resolvedTheme: "light" | "dark"; languageTag: string } |
KLPThemeChangedPayload | { theme: KLPTheme; resolvedTheme: "light" | "dark" } |
KLPLanguageChangedPayload | { languageTag: string } |
KLPSSENotificationPayload | { messageId: string | null; contents: KLPSSENotificationContent[] } |
KLPPublicApi | The type of the KLP object. |
10. Common Errors
| Condition | Possible cause |
|---|---|
KLP native module is not linked. Check iOS Pods and Android Gradle setup. | The app was not rebuilt after the package was installed, or pod install was not run. Run pod install and rebuild the native app. |
pod install fails with Unable to find a specification for 'KLPSDK' | The Podfile does not load klp_pods.rb or does not call klp_ios_sdk! (see iOS). |
pod install or the Gradle build cannot download the KLP SDK | The build machine cannot reach sdk.kaizentech.net over HTTPS. |
initialize rejects with KLP_INIT_SECURITY_ERROR | The device failed the security checks, for example because it is jailbroken or rooted, a debugger is attached, or the app runs on a simulator or emulator. Use debugMode: true during development. |
initialize rejects with KLP_INIT_ERROR | The configuration is invalid (for example an unknown environment or theme), or the native SDK could not initialize. The error message has the details. |
launch rejects with KLP_LAUNCH_ERROR | There is no active screen to present from, or the native SDK could not open the loyalty screen. The error message has the details. |
launch does nothing | The SDK is not ready yet. Call launch after initialize has resolved and setUser has been called. |
logEvent has no effect | setUser was not called, or the session has no access token. |
setToken resolves false | There is no active session, or the token is empty. Call setUser first. |
| The loyalty screen shows "session expired" | The token could not be refreshed. Check that your refresh handler resolves with a token that the KLP backend accepts. |
For questions, contact the KLP integration team.