Skip to main content

KLP Android SDK — Integration Guide

Add the loyalty experience to your Android app: install the SDK, initialize it, sign in your user and open the loyalty screen. The SDK runs the loyalty and gamification experience in a secure WebView and also handles session management, real-time notifications (SSE), event logging and deep links from the loyalty screen back into your app.

Requirements: Android 7.0 (API level 24) or later, compileSdk 34 or higher, JDK 17. Examples are in Kotlin; the API can also be called from Java.


Installation​

Add the KLP Maven repository and the dependency. The examples use version 1.0.11; the latest version is listed in maven-metadata.xml.

In settings.gradle.kts:

dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven {
url = uri("https://sdk.kaizentech.net/klp/android")
content { includeGroup("com.klp.sdk") }
}
}
}

In your app module's build.gradle.kts:

dependencies {
implementation("com.klp.sdk:klp-android-sdk:1.0.11")
}

R8 / ProGuard​

You do not need to add any rules. The AAR ships consumer rules that R8 merges into your release build automatically and that keep the SDK's classes.

Be aware that the same consumer rules also tell R8 to remove android.util.Log.d, Log.v, Log.i and Log.w calls. This applies to your whole minified release build, not only to the SDK — use Log.e (or your own logger) for anything you need to see in release builds.

The SDK's manifest (the INTERNET and ACCESS_NETWORK_STATE permissions and the SDK's own activities) is merged into your app automatically. Sources and API docs are published with the artifact, so IDE navigation and inline documentation work without extra setup.


Initializing the SDK​

Call KLP.initialize once, in Application.onCreate():

import android.app.Application
import com.klp.sdk.KLP
import com.klp.sdk.KLPConfig
import com.klp.sdk.KLPEnvironment

class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
val config = KLPConfig.Builder()
.setEnvironment(KLPEnvironment.PROD)
.setDebugMode(BuildConfig.DEBUG) // true only in development builds
.setDebugScreenEnabled(false) // true only in internal test builds
.build()
KLP.initialize(this, config)
}
}
  • Always set the environment. The builder defaults to KLPEnvironment.DEV, which is Kaizen's internal development setup. Use KLPEnvironment.PROD for production and KLPEnvironment.TEST only when Kaizen asks you to test against its test backend.
  • initialize is asynchronous and never throws. The device security checks run on a background thread. Until they pass, KLP.getInstance() throws IllegalStateException. The static methods used in the rest of this guide — KLP.setUser, KLP.setToken, KLP.logout, KLP.setOnRefreshTokenHandler, KLP.logEvent, KLP.getConfig — are safe to call at any time; setUser and setOnRefreshTokenHandler are queued and applied as soon as initialization finishes.
  • Check KLP.isSecurityInitialized() before calling instance methods (KLP.getInstance()…) outside the flows shown below.
  • Repeated calls are ignored. Calls within 500 ms of the previous one are debounced (even with a different config), and once the SDK is initialized further initialize calls do not replace the configuration.

If the security checks fail, the SDK stays unavailable. Check why with KLP.getInitializationError():

KLP.getInitializationError()?.let { error ->
error.getFailedChecks().forEach { check ->
Log.e("KLP", "${check.name}: ${check.errorMessage}")
}
}

The checks are TAMPER_DETECTION, EMULATOR_DETECTION, ROOT_DETECTION, DEBUG_DETECTION (debuggable build or attached debugger), HOOK_DETECTION and CLONE_DETECTION. They are skipped entirely while debugMode is true.

Configuration options​

Builder methodDescription
setEnvironment(KLPEnvironment)Endpoint set: PROD, TEST or DEV. Defaults to DEV — set it explicitly.
setEnvironmentName(String?)Same as above by name (dev, test, prod); null or empty selects prod, any other value throws IllegalArgumentException.
setDebugMode(Boolean)true skips the device security checks and the screenshot protection and enables verbose logging. Development only.
setDebugScreenEnabled(Boolean)true shows the SDK's debug screen and floating debug button, and shows error codes on the error screen. Does not affect the security checks. Internal test builds only.
setTheme(KLPTheme?)Optional startup theme: KLPTheme.LIGHT, DARK or SYSTEM. Omit to follow the system (see Theme and language).
setLanguage(String?)Optional startup language as a BCP-47 tag ("tr", "tr-TR"). Omit to follow the app's configuration.
setLocaleProvider((() -> Locale)?)Optional function that returns your app's current locale. Do not combine with setLanguage.
setColors(KLPColors?)Optional light/dark colours for the SDK's error screen (see Error screen).

Endpoints, trusted domains and certificate pins are managed inside the SDK; there is nothing to configure for them.


User session​

After your user signs in, give the SDK their access token. The user is identified from the token on the backend; the SDK does not take a user ID.

// After login
KLP.setUser(
accessToken = "access_token",
nameInitials = "GA" // optional, shown as the avatar in the loyalty screen
)

// On logout
KLP.logout()

setUser returns immediately; the session is activated in the background. Pass a KLPSetUserCallback to learn the result — it is called exactly once, on the main thread:

KLP.setUser("access_token", "GA", null) { activated ->
if (activated) {
// KLP.isInitialized() is now true: launch() works, the widget can be shown, SSE is running.
} else {
// Activation failed, the feature is turned off for this user, the call was superseded
// by a newer setUser/logout, or the device security checks failed.
}
}
  • KLP.isInitialized() returns true only after a successful activation in which the backend reported the feature as visible for this user. Until then launch does nothing.
  • Call setUser on every app start once you have a valid access token for the signed-in user, and again when the account changes. After a process restart the SDK is not active until setUser has completed. Calling it again is safe: the previous session is closed and activation runs again with the new token.
  • The session (access token, session id) is kept in memory only and is never written to disk, so it ends when the app process ends.
  • If activation fails, the stored session is cleared. Recover with a new setUser call (not setToken).
  • nameInitials is trimmed, whitespace is removed, and it is cut to 3 upper-case characters.
  • KLP.logout() also cancels a setUser call that is still waiting for initialization. Call it before switching users.

Refreshing the access token​

Two ways, and you normally want the first one.

1. Let the SDK ask you (recommended). Register a handler that returns a fresh token. It works in one of two modes, chosen by whether you give the SDK an expiry:

  • Proactive — you pass an expiry (setUser(expiresAt = …), setToken(…, expiryTimeMillis) or RefreshedToken.expiresAt). A minute before the token expires, every request that uses it is held, your handler is called, the new token is stored and the request continues.
  • Reactive — no expiry (it is optional). The SDK does no time arithmetic. When a service answers 401_Token, the original request is held, your handler is called and the request is resent with the new token — the user never notices.

A 401_Token is handled the same way in proactive mode too (clock skew, early revocation).

import com.klp.sdk.KLP
import com.klp.sdk.security.RefreshedToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

// In Application.onCreate(), right after KLP.initialize(...)
KLP.setOnRefreshTokenHandler {
val token = withContext(Dispatchers.IO) { myAuthService.refreshAccessToken() }
// expiresAt is optional: pass it for proactive mode, omit it for reactive mode.
RefreshedToken(accessToken = token.value, expiresAt = token.expiresAtMillis)
}

// Clear it:
KLP.setOnRefreshTokenHandler(null)
  • Expiry values are absolute epoch milliseconds (System.currentTimeMillis() units) — not seconds and not a time-to-live. A returned expiresAt must be at least 60 seconds in the future; otherwise the refresh is rejected and the stored token is not changed.
  • The handler is a suspend function. Move blocking I/O off the calling thread (withContext(Dispatchers.IO), as above).
  • Asked at most once at a time. If several requests need a refresh together, your handler is called once and the others wait for the same result.
  • 30 second timeout. If the handler throws, times out or returns an empty token, the waiting request fails. The SDK never continues silently with an expired token.
  • Covers the loyalty screen, SSE and logEvent. Each of them checks the token before using it.
  • Retried once per request. After a 401_Token the request is resent at most once.
  • Loop protection. After 3 consecutive refresh attempts that did not end with the backend accepting the new token, the SDK stops calling the handler. The count resets when a retried request gets a non-401 answer, and when you call setUser, setToken with a new token, or logout.
  • Inert without a session. Before setUser and after logout the handler is never called.
  • When the token cannot be refreshed (handler failed, loop protection tripped, or no handler registered and the backend answered 401_Token) the loyalty screen shows "Your session has expired". The embedded component shows it without buttons; the full-screen loyalty screen shows a "Close" button only.

2. Push a new token yourself. If your app refreshes on its own schedule, call setToken to update the token the SDK uses for subsequent requests — without re-running the activation and SSE setup that setUser does:

val updated: Boolean = KLP.setToken(
accessToken = "new_access_token",
expiryTimeMillis = null // optional, absolute epoch millis
)
  • Returns false (no-op) if the SDK is not initialized, there is no active session, or accessToken is blank. Passing null as the expiry clears any previous expiry (reactive mode).
  • Thread-safe: you can call it from any thread, also while requests are in flight.
  • Both paths write through the same storage, so mixing them is safe.

Late setToken. If the "session expired" screen is already showing and you then supply a valid token with setToken (or setUser), the loyalty screen reloads from the start. Normally the token should arrive before it expires; this is only a recovery path.


Launching the loyalty screen​

launch opens the loyalty WebView as a full-screen activity. It requires an active session (KLP.isInitialized()); otherwise the call is ignored.

// Home screen
KLP.getInstance().launch(activity)

// A specific path (e.g. rewards)
KLP.getInstance().launch(activity, "rewards")

// Extra query parameters for the loyalty web app
KLP.getInstance().launch(activity, mapOf("source" to "home_banner"))
  • Leading and trailing / in path are optional; the SDK handles concatenation.
  • The SDK adds the current language, theme and the user's initials to the page itself.
  • The screen is shown in portrait orientation. The system back button goes back in the web history first and closes the screen when there is nothing left.
  • The screen closes when the web content asks for it or when a deep link is opened from it (see Deep links).

Embedding the WebView as a component​

When the loyalty screen should live inside your own layout — a tab, a bottom sheet, a page in your navigation — create the embedded component instead. KLPEmbeddedWebView is a FrameLayout with the same security setup, session headers and live notification updates as the full-screen variant.

fun createEmbeddedWebView(
activity: Activity,
path: String? = null, // null → home screen
listener: KLPEmbeddedWebViewListener? = null
): KLPEmbeddedWebView

You do not have to wait for setUser to finish. If you create the component while the session is still being activated, it shows its own loader and loads the page as soon as the session is ready. If there is no session to wait for (setUser never called, logged out, or the feature is turned off for this user), it shows its own error or maintenance state instead of throwing. Only KLP.getInstance() itself throws, before initialization has finished.

import com.klp.sdk.KLP
import com.klp.sdk.ui.KLPEmbeddedWebView
import com.klp.sdk.ui.KLPEmbeddedWebViewListener

class LoyaltyActivity : AppCompatActivity() {

private lateinit var loyaltyView: KLPEmbeddedWebView

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_loyalty)

loyaltyView = KLP.getInstance().createEmbeddedWebView(
activity = this,
path = null, // or "rewards"
listener = object : KLPEmbeddedWebViewListener {
override fun onCloseRequested() {
// The web content asked to close. You decide: switch tab, pop the screen, hide it.
finish()
}

override fun onPageLoadError(message: String, code: String) {
// `code` is a stable KLP_* error code; `message` is diagnostic text only.
}
}
)
findViewById<FrameLayout>(R.id.loyalty_container).addView(
loyaltyView,
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
)
}

override fun onResume() { super.onResume(); loyaltyView.onResume() }
override fun onPause() { loyaltyView.onPause(); super.onPause() }
override fun onDestroy() { loyaltyView.destroy(); super.onDestroy() }
}

KLPEmbeddedWebViewListener callbacks, all on the main thread:

CallbackWhen
onCloseRequested()Required. The web content asked to be closed. The SDK never removes the component itself.
onPageLoadStarted()The loader is visible: waiting for session activation or loading the page.
onPageLoadFinished()The page has loaded and is visible.
onPageLoadError(message, code)The component switched to its error view. Decide with code (see Error codes); treat unknown codes as a generic error. message is diagnostic text, not for users.

Lifecycle​

The component has no activity of its own, so you drive it. Skipping these calls leaves the WebView running in the background and stops live updates.

CallWhen
onResume()The component becomes visible/active. Resumes the WebView and starts receiving live notification updates.
onPause()The component loses visibility (screen paused, tab switched away).
destroy()The component is removed for good. Later calls are ignored.
retry(): BooleanStarts loading again, e.g. from your own error UI. Returns false if the component cannot retry (destroyed, or the security checks failed).

Detaching and re-attaching the view (tab switch, RecyclerView reuse) is safe — the WebView is not destroyed.

Keeping it alive across mounts​

If the component sits in one of your main tabs, holding it in a field is usually not enough: most navigation setups (Fragment replace, Navigation Compose, cross-platform views) throw the host away on every tab switch, so createEmbeddedWebView runs again and the loyalty app loads from scratch.

Use the reuse pair instead, and the SDK hands the same component back on the next mount, with its page, JavaScript state, scroll position and history intact:

fun acquireEmbeddedWebView(
activity: Activity,
path: String? = null,
listener: KLPEmbeddedWebViewListener? = null
): KLPEmbeddedWebView

fun releaseEmbeddedWebView(view: KLPEmbeddedWebView)
fun invalidateEmbeddedWebViewCache()

acquireEmbeddedWebView is a drop-in replacement for createEmbeddedWebView, and releaseEmbeddedWebView replaces destroy() entirely — it pauses and detaches the component when it can be reused and destroys it when it cannot. Call both on the main thread.

@Composable
fun LoyaltyTab(modifier: Modifier = Modifier) {
val activity = LocalContext.current as Activity
val view = remember { KLP.getInstance().acquireEmbeddedWebView(activity) }

DisposableEffect(Unit) {
view.onResume()
onDispose { KLP.getInstance().releaseEmbeddedWebView(view) }
}

AndroidView(modifier = modifier, factory = { view })
}

The kept component lives in memory only, for the lifetime of the process. It is dropped — so the next acquireEmbeddedWebView loads fresh — when:

  • the app process ends (a relaunch always loads fresh),
  • the session changes (setUser, logout),
  • the language, the theme, the user's initials or the path change,
  • the host activity is recreated (rotation, process restore) or is finishing,
  • the security checks fail — a broken component is never kept.

Call invalidateEmbeddedWebViewCache() to force a fresh load yourself, e.g. behind a "refresh" action. A component that is mounted at that moment keeps running (you would otherwise be left with a blank WebView on screen) and is destroyed when you release it.

One caveat: reuse assumes at most one live component per path at a time. A view has only one parent, so mounting a second one for the same path while the first is still on screen moves it to the second mount and blanks the first. If you genuinely need two at once, create the secondary one with createEmbeddedWebView and destroy() it yourself.

Back navigation​

Give the web content the back press first, then fall back to your own handling:

onBackPressedDispatcher.addCallback(this) {
if (!loyaltyView.goBack()) finish()
}

goBack() returns false when there is no web history; canGoBack() lets you show or hide your own back button. Both return false after destroy().

Jetpack Compose​

@Composable
fun LoyaltyScreen(path: String? = null, modifier: Modifier = Modifier) {
val activity = LocalContext.current as Activity
val view = remember { KLP.getInstance().createEmbeddedWebView(activity, path) }

DisposableEffect(Unit) {
view.onResume()
onDispose { view.onPause(); view.destroy() }
}

AndroidView(modifier = modifier, factory = { view })
}

For a screen the user leaves and comes back to, use the keep-alive pair above so the page is not reloaded every time. Guard these composables with KLP.isSecurityInitialized() if they can be shown before initialization has finished.

Notes​

  • Screenshot protection: unless debugMode is on, the SDK sets FLAG_SECURE on the host activity's window, so your whole screen is protected against screenshots and screen recording. The flag stays set after destroy().
  • Keep one instance visible at a time. Real-time notification updates go to the most recently resumed KLP WebView.
  • Deep links do not close the component. They are delivered to KLPEventListener.onDeepLinkReceived and never trigger onCloseRequested(); navigation is your decision.
  • The web app is told it is embedded and renders without its own full-screen chrome. Let the component fill its container edge to edge; the SDK passes the safe-area insets to the page.
  • Loader and error states (including a "Try again" button for transient errors) are rendered by the component itself. Its error view has no "Close" button.

Event logging​

Send events to the platform while a user session is active (after setUser). Without a session the call is silently ignored.

KLP.logEvent("LogIn")
KLP.logEvent("MoneyTransfer", mapOf(
"Quantity" to 10,
"TransferAmount" to 1250.75
))

KLP.logEncryptedEvent("LogIn")
KLP.logEncryptedEvent("MoneyTransfer", mapOf(
"Quantity" to 10,
"Currency" to "TRY"
))
  • Both are fire-and-forget; attributes is a Map<String, Any>?.
  • logEncryptedEvent has the same signature and requirements. The event name and each attribute value are encrypted (RSA-OAEP-SHA256) before they are sent; attribute keys stay in plain text. Use it for events that carry sensitive values. Values are sent as strings: strings as-is, booleans as "true"/"false", everything else as JSON.
  • Event names and attribute keys must match what is configured for your organization in KLP.

Event listener (optional)​

The default behaviour — including the SDK's own notification UI — is enough for most apps. Set a KLPEventListener for custom flows. onEventReceived and onRewardEarned must be implemented; every other method has a default.

import com.klp.sdk.KLPEventListener
import com.klp.sdk.bridge.KLPEvent
import com.klp.sdk.bridge.KLPReward
import com.klp.sdk.security.SecurityCheckResult
import com.klp.sdk.sse.KLPSSEEffect

class LoyaltyListener : KLPEventListener {

// Event sent by the loyalty web content (event.type, event.data as a JSON string)
override fun onEventReceived(event: KLPEvent) {}

// Reward earned inside the loyalty screen
override fun onRewardEarned(reward: KLPReward) {
Log.e("KLP", "Reward: ${reward.name} (${reward.value})")
}

// Real-time effects from the server (points, mission progress, ...).
// Return true to suppress the SDK's notification UI and handle it yourself.
override fun onSSEEffectsReceived(effects: List<KLPSSEEffect>): Boolean = false

// Deep link requested from the loyalty screen (see Deep links)
override fun onDeepLinkReceived(uri: String): Boolean = false

// Device security check failed while opening the loyalty screen
override fun onSecurityError(result: SecurityCheckResult) {}

// Loyalty screen error (for example a blocked navigation)
override fun onError(error: Exception) {}
}

Register it once the SDK is initialized — the setUser callback is a convenient place:

// Keep a strong reference: the SDK holds the listener weakly.
private val loyaltyListener = LoyaltyListener()

fun onLoggedIn(accessToken: String, initials: String?) {
KLP.setUser(accessToken, initials, null) { _ ->
if (KLP.isSecurityInitialized()) {
KLP.getInstance().setEventListener(loyaltyListener)
}
}
}

removeEventListener() unregisters it. Real-time notification callbacks are delivered on the main thread.


Links in the loyalty screen that use a custom URL scheme (anything other than http/https) are not loaded in the WebView. The SDK hands them to onDeepLinkReceived instead. Links on notification buttons that are not loyalty-screen paths arrive here too.

override fun onDeepLinkReceived(uri: String): Boolean {
val parsed = Uri.parse(uri)
if (parsed.scheme != "com.mycompany.myapp") return false
// navigate to the target screen
return true
}
  • Return true when you handled the link. Return false (or set no listener) and the SDK tries to open the URI with a system ACTION_VIEW intent; if nothing can handle it, nothing happens.
  • The full-screen loyalty screen closes after a deep link either way, so your target screen comes to the front. The embedded component stays where it is.
  • Prefer reverse-domain scheme names (e.g. com.mycompany.myapp).

If you rely on the false path, or want the same links to open your app from outside, declare the scheme on your activity (launchMode="singleTop" recommended) and handle it in onCreate / onNewIntent:

<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="com.mycompany.myapp" />
</intent-filter>

Links to other https sites that the loyalty screen is allowed to open are opened in the user's default browser.


Real-time notifications (SSE)​

After a successful setUser, the SDK keeps a server-sent events connection open. It disconnects when your app goes to the background and reconnects when it returns to the foreground.

Default UI. For each notification the SDK shows its own toast or bottom sheet; several notifications in one message are combined into one list sheet. Which events appear as toasts and which are not shown at all is configured on the KLP side. Notifications that arrived while the user was away are shown once per session, after activation. While a loyalty screen is open and loaded, the page shows the notification itself and the SDK does not show its native UI.

Reading the raw effects. onSSEEffectsReceived receives every message's effects. Each KLPSSEEffect has id, name, missionId, levelId, ruleId, ruleName and a detail; check which of its fields is non-null:

detail fieldTypeUseful fields
giveLoyaltyProgramPointKLPSSEPointDetailpoint, reason, organizationLoyaltyProgramId
increaseMissionProgressKLPSSEProgressDetailmissionId, value, target, total, completed, claimType
increaseLevelProgressKLPSSEProgressDetaillevelId, value, target, total, completed
override fun onSSEEffectsReceived(effects: List<KLPSSEEffect>): Boolean {
effects.forEach { effect ->
effect.detail?.giveLoyaltyProgramPoint?.let { refreshPointsBadge(it.point) }
}
return false // keep the SDK's notification UI
}

Returning true suppresses all of the SDK's notification UI for that message, including the rendered notification content, which this callback does not pass to you.

KLP.getInstance().getSSEConnectionState() returns CONNECTED, CONNECTING or DISCONNECTED for diagnostics.


Theme and language​

Theme​

The SDK follows the system night mode by default. The KLP theme is used for the loyalty screen, the widget and the error screen; an open loyalty page is updated live when it changes.

For the starting value, pass it in the config — it is applied during initialize, so nothing has to run afterwards:

KLPConfig.Builder()
.setEnvironment(KLPEnvironment.PROD)
.setTheme(if (isDark) KLPTheme.DARK else KLPTheme.LIGHT)
.build()

If your app sets its own theme — Jetpack Compose MaterialTheme, an in-app theme switch — tell the SDK whenever it changes (Compose does not update Configuration):

if (KLP.isSecurityInitialized()) {
KLP.getInstance().setTheme(isDark) // null → follow the system again
}

Language​

The SDK follows your app's configuration language by default and passes it to the loyalty web app and the KLP backend.

  • KLPConfig.Builder().setLanguage("tr") — startup language, applied during initialize.
  • KLPConfig.Builder().setLocaleProvider { … } — the SDK reads your locale from this function. Changes are not observed; call setLocale when the language changes.
  • KLP.getInstance().setLocale(locale) — call it whenever the user changes the app language; setLocale(null) reverts to the app's configuration.

With an active session, a language change reconnects the real-time (SSE) stream in the new language and saves the user's language on the backend, so notifications produced while the app is closed use it too. Call logout() before switching users.

Error screen​

When the loyalty screen (full screen or embedded) cannot load, the SDK shows its own native, white-label error screen over the WebView area: a warning glyph, a generic title and body ("We could not connect!" / "Check your connection and try again."), a "Try again" button and a "Close" button. No host code is needed.

  • Colours come from KLPConfig.colors (setColors). Values are ARGB colour ints; omitted fields use the defaults:

    TokenDark defaultLight defaultOverride
    Background#0B0E14#FFFFFFbackgroundColor
    Primary (buttons, glyph)#0670D4#0670D4primaryColor
    Title#FFFFFF#0F172AtextColor
    Body / labels#94A3B8#64748BtextColor at 64% alpha
    KLPConfig.Builder()
    .setEnvironment(KLPEnvironment.PROD)
    .setColors(
    KLPColors(
    light = KLPColorSet(primaryColor = Color.parseColor("#006B4D")),
    dark = KLPColorSet(backgroundColor = Color.BLACK)
    )
    )
    .build()
  • Colours can also come from the backend: the statusScreenColors key of your app's configuration in the KLP panel — { "light": { "backgroundColor", "primaryColor", "textColor" }, "dark": { … } }, values #RRGGBB or #AARRGGBB, every field optional. Per field the backend wins over KLPConfig.colors, which wins over the defaults.

  • Light/dark follows the KLP theme (see Theme).

  • Language follows the KLP language: tr* → Turkish, anything else → English. To change the copy, define the same string resources in your app's values-en/strings.xml and values-tr/strings.xml: klp_error_title, klp_error_body, klp_error_retry, klp_error_close, klp_error_blocked_title, klp_error_blocked_body, klp_session_expired_title, klp_session_expired_body, klp_maintenance_title, klp_maintenance_body, klp_update_required_title, klp_update_required_body.

  • "Try again" is shown only for transient failures. The embedded component never shows "Close".

  • The feature turned off for this user (KLP_CONFIG_DISABLED) is not an error. The embedded component shows a maintenance variant instead — gear glyph, "This feature is not available right now" / "Please check back later.", no buttons. launch does not open at all in this state.

  • Unsupported version. When the backend no longer supports your app version (KLP_APP_VERSION_UNSUPPORTED) or the SDK version (KLP_SDK_VERSION_UNSUPPORTED), the SDK behaves as if it was never initialized and the embedded component shows "Update required" without a retry button.

  • Session expired (KLP_AUTH_TOKEN_INVALID, KLP_CONFIG_UNAUTHORIZED): "Your session has expired!" without a retry button — see Refreshing the access token.

  • Security failures (every code of kind BLOCKED in Error codes) show a generic security message — "For security reasons this feature is currently unavailable." — never the reason itself.

  • The error code (tap to copy) and the technical detail are shown only when setDebugScreenEnabled(true). End users never see internal identifiers.


Loyalty entry widget and your own entry points​

KLPWidgetView​

A ready-made entry card that opens the loyalty screen on tap. Its texts follow the KLP language and its colours follow the KLP theme.

<com.klp.sdk.ui.KLPWidgetView
android:layout_width="match_parent"
android:layout_height="wrap_content" />
@Composable
fun KlpEntryWidget(modifier: Modifier = Modifier) {
AndroidView(modifier = modifier, factory = { KLPWidgetView(it) })
}

The widget checks KLP.isInitialized() when it is created: if the session is not active yet, the view is GONE and takes no space, and it does not appear later on its own. Create (or re-create) it after setUser has completed, for example from the KLPSetUserCallback.

Building your own entry point​

Everything your own banner or button needs is public:

APIPurpose
KLP.getInstance().launch(activity) / launch(activity, path)Open the loyalty screen
KLP.isInitialized()true once setUser has completed and the feature is visible for this user. Hide your entry point while it is false.
KLP.getConfig()Your app's configuration from the KLP panel as a JSONObject (a new copy on every call). null until KLP.isInitialized() is true. The SDK gives the keys no meaning — read and validate only the ones you use.
isDarkTheme() / getThemeMode()Current KLP theme; getThemeMode() returns "system", "light" or "dark"
addThemeChangeListener(ThemeChangeListener) / removeThemeChangeListener(…)Restyle on theme change
getCurrentLocale() / getLanguageTag()Active KLP language (e.g. tr-TR) for your own copy
addLocaleChangeListener(LocaleChangeListener) / removeLocaleChangeListener(…)Refresh your own copy on language change

Theme and locale listeners are held weakly and called on the main thread — keep a reference to them.

val config: JSONObject? = KLP.getConfig()
val imageUrl = config?.optString("bannerUrl")?.takeIf { it.startsWith("https://") }

launch is safe to wire directly to a tap: while the session is not active it does nothing and does not throw.


App signature registration​

Before your app can use the loyalty APIs, Kaizen must register your app's package name and signing-certificate SHA-256. The SDK sends this pair when it activates the session, and the backend accepts it only if the pair is registered for your organization. An unregistered pair fails with KLP_AUTH_SIGNATURE_REJECTED.

Do this before go-live, and before any QA against a non-development backend.

What to submit​

FieldDescriptionExample
Package nameThe shipped applicationIdcom.example.loyaltyapp
Signature (SHA-256)SHA-256 of the app signing certificate, lowercase hex, no colons, no prefix4c821267ac26cfc1fd4a5479c9ac2249a3248114cbcd40d554bfe624b86360d0

Submit one row per signing identity you will use — for example the debug certificate for internal QA and the Play app signing key for production.

RuleCorrectIncorrect
EncodingLowercase hexadecimalBase64
SeparatorsNoneAA:BB:CC:...
PrefixNonesha256:, sha256/
Length64 charactersTruncated or padded values
SourceSigning certificate of the APK/AAB that runs on the deviceFirebase SHA-1, an SSL pin (sha256/...=), the upload key when Play re-signs

How to get the value​

Recommended — ask the SDK. Install a build signed the way you will distribute it and log the value. This is exactly what your app sends at runtime:

if (KLP.isSecurityInitialized()) {
Log.e("KLP", "packageId = $packageName")
Log.e("KLP", "signature = ${KLP.getInstance().getCurrentAppSignatureHash()}")
}

Log.e is used on purpose: the SDK's consumer rules remove Log.d/v/i/w from minified release builds. Use a release or Play-distributed build for production registration — a debug build reports the debug certificate.

From a signed APK (no keystore password needed):

apksigner verify --print-certs app-release.apk \
| awk '/SHA-256 digest:/{print $NF}'

From your keystore — only when the same certificate ends up on the device (see Play App Signing below):

keytool -list -v \
-keystore /path/to/your.keystore \
-alias 'YOUR_ALIAS' \
-storepass 'YOUR_STORE_PASSWORD' \
| awk -F'SHA256: ' '/SHA256:/{print tolower($2)}' \
| tr -d ':'

For local debug builds the keystore is ~/.android/debug.keystore with alias androiddebugkey and password android. If keytool prints nothing, run it without the pipe first — the alias or password is usually wrong.

From Gradle — run ./gradlew signingReport, find SHA-256 under the relevant variant, remove all : and lower-case it.

Google Play App Signing​

Most Play apps use Play App Signing, and it is the most common source of failure.

KeyWho holds itUsed for
Upload keyYou (local keystore)Signing the AAB you upload to Play Console
App signing keyGoogle PlayRe-signing what users download

On a device that installed your app from Play (including internal testing tracks), the certificate is Google's app signing key, not your upload key. To register it:

  1. Open Google Play Console.
  2. Select your app → Setup → App integrity / App signing.
  3. Copy the SHA-256 certificate fingerprint under App signing key certificate.
  4. Remove the colons and lower-case it.
  5. Submit it with your package name.

The upload key is the right value only when Play does not re-sign your build — direct installs, some CI artifacts, and debug or internal builds outside Play.

BuildCertificateRegister?
Local debugDebug keystoreYes, if QA uses debug builds against a shared backend
Local release / CI APKYour release keystoreYes, if those builds talk to the backend outside Play
Play production / testingApp signing key from Play ConsoleAlways for store-distributed apps

You may register several signatures for the same package name. Changing the package name or rotating the signing key requires a new registration.

Before you send the values​

  • The package name matches the shipped applicationId exactly (watch for flavor suffixes and applicationIdSuffix).
  • Each signature is 64-character lowercase hex without colons.
  • Play builds use the app signing key SHA-256, not only the upload key.
  • Debug and release hashes are listed separately and labelled with their environment.
Package name: com.example.loyaltyapp

Production (Play App Signing key) SHA-256:
4c821267ac26cfc1fd4a5479c9ac2249a3248114cbcd40d554bfe624b86360d0

Optional — debug SHA-256 (local QA only):
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

If verification still fails, log getCurrentAppSignatureHash() on the failing install and compare it with what you registered; check whether that install came from Play, a sideload or a debug build. A keystore hash that differs from the SDK value on a Play install is expected when Play App Signing is on — register the Play Console value.


Security and diagnostics​

AreaWhat the SDK does
App signatureServer-side challenge/verify with package name + signing-certificate SHA-256
IntegrityTamper, hooking-framework and clone/dual-app detection
Runtime environmentRoot, emulator and debugger detection
TransportHTTPS only, certificate pinning, allow-listed domains
StorageEncrypted storage for tokens and session data
ScreenScreenshot and screen-recording protection (FLAG_SECURE); skipped while debugMode is on

No security setup is needed on your side beyond app signature registration. Use setDebugMode(false) and setDebugScreenEnabled(false) in production builds.

Optional diagnostics (instance methods via KLP.getInstance() unless marked static):

APIReturns
KLP.getVersion() (static)The embedded SDK version, e.g. 1.0.11
KLP.isSecurityInitialized() (static)Whether initialization finished and the security checks passed
KLP.getInitializationError() (static)The SecurityException from initialization, or null
getInitialSecurityCheckResult()The checks run during initialization (null in debug mode)
performSecurityChecks() / isDeviceSecure()Runs the device checks (again)
isDeviceCloneFree() / checkCloneAsync { … }Clone/dual-app check, synchronous or with a callback
getCurrentAppSignatureHash()The signing-certificate SHA-256 the SDK sends
getSSEConnectionState()CONNECTED, CONNECTING or DISCONNECTED
KLP.openDebugScreen(activity) (static)Opens the SDK debug screen — only when setDebugScreenEnabled(true)

Common errors​

ConditionPossible cause
IllegalStateException: KLP SDK is not initializedKLP.getInstance() was called before initialization finished, or the security checks failed. Use the static methods (KLP.setUser, …) or check KLP.isSecurityInitialized() first.
Security checks failedRooted device, emulator, debuggable build, attached debugger, hooking framework, clone/dual app, or an app installed by an installer other than Google Play, Huawei AppGallery, Samsung Galaxy Store or a direct install. Read KLP.getInitializationError(); use setDebugMode(true) during development.
launch does nothing / widget not visibleThe session is not active: setUser was not called on this app start, its activation failed, or the feature is turned off for this user. Check the KLPSetUserCallback result and KLP.isInitialized().
The app talks to the wrong backendsetEnvironment(...) was not set; the builder defaults to KLPEnvironment.DEV.
logEvent has no effectNo user session (setUser was not called), or the token could not be refreshed.
KLP_AUTH_SIGNATURE_REJECTEDThe package name + signing-certificate SHA-256 of this build is not registered. See App signature registration.
"Your session has expired" screenThe backend rejected the access token and it could not be refreshed. Register a refresh handler, or call setToken/setUser with a valid token.
Listener callbacks stop arrivingThe listener was garbage-collected — the SDK holds it weakly. Keep a strong reference.
Your Log.d/Log.i lines are missing in releaseThe SDK's consumer R8 rules remove Log.d/v/i/w calls from minified builds.

Error codes​

The embedded component reports these codes through onPageLoadError(message, code); the constants are in com.klp.sdk.model.KLPWebViewErrorCode. KLPWebViewErrorKind.of(code) maps a code to what you should do (isRetryable, isUserFacing). New codes may be added — treat unknown ones as a generic error.

CodeKindMeaning
KLP_CONFIG_DISABLEDDISABLEDThe feature is turned off for this user. Not an error — hide your entry point.
KLP_AUTH_TOKEN_INVALIDSESSIONThe access token was rejected (401_Token) and could not be refreshed.
KLP_CONFIG_UNAUTHORIZEDSESSIONThe configuration request was rejected as unauthorized.
KLP_SESSION_MISSINGSESSIONNo active session: setUser not called, logged out, or no access token.
KLP_NOT_INITIALIZEDSESSIONinitialize was not called or did not complete.
KLP_AUTH_CHALLENGE_EXPIREDBLOCKEDThe challenge token expired and a forced refresh did not help.
KLP_AUTH_SIGNATURE_REJECTEDBLOCKEDSignature verification rejected — usually an unregistered package name + SHA-256.
KLP_SECURITY_FAILEDBLOCKEDThe device security checks failed.
KLP_SECURITY_URL_BLOCKEDBLOCKEDNavigation to a non-allowed or non-HTTPS address was blocked.
KLP_APP_VERSION_UNSUPPORTEDBLOCKEDThis app version is no longer supported.
KLP_SDK_VERSION_UNSUPPORTEDBLOCKEDThis KLP SDK version is no longer supported.
KLP_AUTH_FAILEDTRANSIENTUnexpected error during challenge/verify.
KLP_CONFIG_UNREACHABLETRANSIENTThe configuration request did not complete (network, timeout, TLS).
KLP_CONFIG_REJECTEDTRANSIENTThe configuration request failed (400 or unexpected status).
KLP_PAGE_HTTP_ERRORTRANSIENTThe page request returned HTTP 4xx/5xx.
KLP_PAGE_LOAD_FAILEDTRANSIENTThe page could not load (network, DNS, TLS/pinning).
KLP_UNKNOWNTRANSIENTUnclassified error.

For SESSION codes the remedy is a new access token passed with setUser; BLOCKED codes are not fixed by retrying or by a new token.


Version​

Read the embedded SDK version with KLP.getVersion().


Copyright © 2024 KLP. All rights reserved. For questions, contact the KLP integration team.