Skip to main content

KLP Flutter SDK — Integration Guide

Add the loyalty experience to your Flutter app: install the SDK, initialize it, sign in your user and open the loyalty screen — full screen or embedded as a widget. The package wraps the native KLP iOS and Android SDKs behind one Dart API, so your app needs no platform code.

import 'package:klp_flutter_sdk/klp_flutter_sdk.dart';

Every call goes through the Klp.instance singleton.


1. Adding the SDK to Your Project​

Requirements​

Minimum
Flutter3.27.0
Dart3.6.0
iOS15.0
Xcode26.2
AndroidAPI 24 (Android 7.0)
Android Gradle Plugin8.2.1
Java17

Add the dependency​

In your app's pubspec.yaml:

dependencies:
klp_flutter_sdk:
hosted: https://sdk.kaizentech.net/klp/flutter
version: ^1.0.5

Then run:

flutter pub get

Developer machines and CI need outbound HTTPS to sdk.kaizentech.net, not routed through a TLS-inspecting proxy. No token or login is needed. The Dart package, the native iOS binary and the Android library all come from that one host.

Commit pubspec.lock. ^1.0.5 accepts compatible updates on flutter pub upgrade; use version: 1.0.5 to pin exactly.

If KLP provided a brand-specific wrapper package for you, depend on that package instead. It brings in klp_flutter_sdk at the version it was tested with; do not declare both. The platform steps below still apply.

iOS setup​

This release uses the native KLP iOS SDK (KLPSDK) 1.0.10.

  • Swift Package Manager on (the default in current Flutter versions): nothing to do.

  • Swift Package Manager off (flutter config --no-enable-swift-package-manager, or an older Flutter where it is not on by default): add this line to ios/Podfile inside your target block:

    pod 'KLPSDK', :podspec => 'https://sdk.kaizentech.net/klp/ios/KLPSDK/1.0.10/KLPSDK.podspec.json'

    Then run:

    cd ios && pod install && cd ..

    Open Runner.xcworkspace, not Runner.xcodeproj. Without the line, pod install stops with Unable to find a specification for KLPSDK. Keep the version in the URL at 1.0.10 for this release — it must match the version the plugin depends on.

Not sure which one you use? Swift Package Manager is on if ios/Runner.xcodeproj/project.pbxproj contains FlutterGeneratedPluginSwiftPackage. Having a Podfile does not mean it is off: other plugins can still need CocoaPods.

Make sure ios/Podfile declares platform :ios, '15.0' or higher.

Android setup​

This release uses the native KLP Android SDK com.klp.sdk:klp-android-sdk:1.0.10. The plugin adds the KLP Maven repository (https://sdk.kaizentech.net/klp/android) to your build itself, so there is normally nothing to do. Check two things:

  • minSdk in android/app/build.gradle(.kts) is 24 or higher.
  • The Android Gradle Plugin (com.android.application in android/settings.gradle(.kts)) is 8.2.1 or newer. Apps created from the Flutter 3.27 template pin an older AGP and fail with Unsupported class file major version or an obsolete source-value error; raise it. Templates from Flutter 3.29 on are already fine.

If your settings.gradle(.kts) restricts repositories to the settings file (dependencyResolutionManagement with RepositoriesMode.PREFER_SETTINGS or FAIL_ON_PROJECT_REPOS), the repository the plugin adds is not used; declare it there:

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

The plugin does not apply its own Kotlin Gradle Plugin and does not constrain your app's Kotlin version.

Verify the installation​

getVersionInfo() is safe before initialize and confirms the plugin is linked:

final KlpVersionInfo info = await Klp.instance.getVersionInfo();
debugPrint('$info');
// KlpVersionInfo(platform: android, nativeSdkVersion: 1.0.10, pluginVersion: 1.0.5)

If it throws a KlpPlatformException saying the plugin is not registered, see Common Errors.


2. Initializing the SDK​

Call initialize once at startup, after WidgetsFlutterBinding.ensureInitialized(). It runs the native device-integrity checks; if they fail, the SDK stays unavailable and you should keep the user out of sensitive loyalty flows.

import 'package:flutter/foundation.dart';
import 'package:klp_flutter_sdk/klp_flutter_sdk.dart';

Future<bool> bootstrapKlp({required bool isDark}) async {
try {
await Klp.instance.initialize(
KlpInitializeConfig(
environment: kReleaseMode ? KlpEnvironment.prod : KlpEnvironment.test,
debugMode: !kReleaseMode, // also switches the security checks off — never in release
showDebugScreen: false,
theme: isDark ? KlpTheme.dark : KlpTheme.light, // optional starting theme
language: 'tr', // optional starting language (BCP-47)
),
);
return true;
} on KlpSecurityException catch (e) {
// The device failed a mandatory integrity check.
for (final KlpSecurityCheck check in e.failedChecks) {
debugPrint('KLP check failed: ${check.name} ${check.errorMessage ?? ''}');
}
return false;
} on KlpInitializationException catch (e) {
// Init failed, or timed out with the security verdict unknown.
debugPrint('KLP init failed (timeout: ${e.isTimeout}): ${e.message}');
return false;
}
}

Both failures are fail-closed: treat a timeout (isTimeout) exactly like a failed check — the device's integrity is unknown.

Configuration fields​

FieldTypeDefaultDescription
environmentKlpEnvironmentproddev, test or prod. The default is prod, so an omitted value can never ship a test backend. Use test for development and staging builds.
debugModeboolfalseVerbose native logging and no device-integrity checks: with true, initialize never throws KlpSecurityException and rooted, jailbroken, emulated or hooked devices are accepted. That is what makes simulator development possible — and why it must be false in release builds.
showDebugScreenboolfalseShows a floating button that opens the SDK debug interface. Does not switch the security checks off. Keep false in release builds.
themeKlpTheme?nullStarting theme. null follows the device. See Theme and Language.
languageString?nullStarting language as a BCP-47 tag (tr, tr-TR). null, empty or blank leaves the default (the device language).
colorsKlpColors?nullColours of the SDK's native error screen. See Error screen.

theme and language only set the starting value, so the loyalty screen opens in your app's theme and language without a setTheme / setLanguage call right after initialize. Keep calling those when the user changes either one later.

Debug tools (test builds only)​

With showDebugScreen: true a floating debug button opens the SDK debug interface (security results, API logs, test actions). You can also open it from code:

await Klp.instance.openDebugScreen();

Do not ship either in production builds.


3. User Session​

After your own sign-in has completed, start the loyalty session with the user's access token. The backend resolves the user from the token; the SDK takes no user id.

// After login
final bool active = await Klp.instance.setUser(session.accessToken);

// On logout
await Klp.instance.logout();
  • setUser completes when the native session activation has finished. true means loyalty is available for this user. false means it is not: activation failed, the feature is switched off for this user, or a newer setUser / logout replaced the call.
  • Activation outcomes never throw, so a loyalty problem cannot break your sign-in. Only an empty token (KLP_INVALID_ARGUMENT) or a bridge failure throws.
  • setUser and logout can be called before initialize has finished: a setUser call is held and runs once the security checks pass, and logout cancels a held call. So do not await setUser before your own initialize call — the two would wait on each other.
  • Use setUser only when the user changes; call logout on sign-out.

Refreshing the access token​

The SDK keeps using the last token it was given. Choose one of two ways to keep it fresh.

1. Let the SDK ask you (recommended). Register a handler once. The SDK calls it whenever it needs a new token, holds the request that needed it, and continues — the user never notices.

await Klp.instance.setOnRefreshTokenHandler(() async {
final session = await myAuth.refreshSession(); // your own refresh call
return KlpRefreshedToken(session.accessToken, expiresAt: session.expiresAt);
});
  • With expiresAt (proactive) the SDK asks shortly (60 s) before the token expires. expiresAt must be at least 60 s in the future, or the refresh counts as failed.
  • Without it (reactive) the SDK asks when a service answers 401_Token, then retries that request once with the new token.
  • The handler is not called before setUser or after logout. Concurrent needs share one call.
  • It has 30 s to answer. A throw, a timeout or an empty token counts as a failed refresh.
  • After 3 refreshes in a row that did not end with a token the backend accepts, the SDK stops calling the handler until setUser, a setToken with a new token, or logout — a handler that keeps returning bad tokens cannot loop.
  • When the token cannot be renewed the user sees the "Your session has expired!" screen (KLP_AUTH_TOKEN_INVALID). A later setToken with a valid token reloads the WebView from its start page.
  • setOnRefreshTokenHandler(null) removes the handler.

2. Push a new token yourself. Without a handler, hand over every token your own refresh flow mints, or the session's backend calls start failing once the old token expires:

final bool accepted =
await Klp.instance.setToken(session.accessToken, expiryDate: session.expiresAt);
  • setToken only swaps the stored token. Unlike setUser it does not re-run session activation or restart the real-time stream, so it is safe to call on every refresh.
  • expiryDate is optional. Omitting it clears a previously known expiry.
  • It returns false — without throwing — when there is no active session; the SDK then keeps the token it had. An empty token throws KLP_INVALID_ARGUMENT.

Backend configuration​

getConfig() returns the configuration set for your app in the KLP panel, as a map. The SDK gives the keys no meaning: read only the keys you have agreed with KLP, and check their types. It is null until isInitialized() is true (that is, after a successful setUser).

final Map<String, Object?>? config = await Klp.instance.getConfig();

4. Opening the Loyalty Screen​

Two ways to show the loyalty experience; both need a successful initialize and an active session from setUser.

Full screen​

await Klp.instance.launch(); // home screen
await Klp.instance.launch('rewards'); // a specific route

launch opens the native loyalty WebView modally, outside your widget tree.

  • Returns false — without throwing — when there is no active session (no setUser, activation failed, or the feature is switched off for this user). Nothing opens.
  • Throws KlpNotInitializedException before initialize has completed.
  • Throws KlpPlatformException with KLP_LAUNCH_ERROR when there is nothing to present from: no visible view controller on iOS, no foreground Activity on Android. Call it from a mounted, visible screen.

An entry-point button should report failures instead of throwing into the widget tree, and ignore a second tap while a call is in flight:

Future<void> openLoyalty() async {
try {
final bool opened = await Klp.instance.launch();
if (!opened) {
// No active loyalty session — hide or disable the entry point.
}
} on KlpException catch (e) {
debugPrint('KLP launch failed: ${e.code} ${e.message}');
}
}

Embedded widget: KlpWebView​

KlpWebView shows the same native loyalty WebView inside your layout — for example as the body of a tab. Security (certificate pinning, token handoff) is identical to launch.

import 'package:flutter/material.dart';
import 'package:klp_flutter_sdk/klp_flutter_sdk.dart';

class LoyaltyTab extends StatelessWidget {
const LoyaltyTab({super.key});


Widget build(BuildContext context) {
return KlpWebView(
path: 'rewards', // optional; null opens the home screen
onError: (KlpWebViewError error) => debugPrint('KLP: ${error.code}'),
);
}
}
ParameterTypeDescription
pathString?Route inside the loyalty app, same as the launch argument.
keepAliveboolDefault true. Keeps the native WebView across remounts (see below).
onWebViewCreatedvoid Function(KlpWebViewController)?Called once the native view exists, with a controller for goBack() / reload().
gestureRecognizersSet<Factory<OneSequenceGestureRecognizer>>?Gestures the platform view claims. Leave null on a static screen; pass recognizers when it sits inside a scrollable ancestor and must win vertical drags.
errorBuilderKlpWebViewErrorBuilder?Draws your own error screen over the native one. See Error screen.
onErrorvoid Function(KlpWebViewError)?Called on every transition into the error state, with the failure classified. Treat repeats as idempotent.

errorStrings and showErrorDiagnostics are still accepted but have no effect.

Mount timing. The widget does not have to wait for setUser to finish: mounted during activation, the native SDK shows its own loader and loads the page once the session is ready. If the view cannot be created at all (no initialize, no setUser, logged out), the failure is reported on Klp.instance.onWebViewLoadState (state error) and Klp.instance.onError instead of being thrown into the widget tree.

Closing. Close requests from the web app (its close button, close deep links) arrive on Klp.instance.onWebViewClosed. The SDK never removes the widget; react by switching tab or popping your route.

Safe area. Do not wrap KlpWebView in a SafeArea; give it the full area. The web app draws its own insets for the notch, status bar and home indicator, and follows size changes — also when your app hides its own app bar or tab bar while the widget is on screen.

On platforms other than Android and iOS the widget only shows a short notice.

Keeping it alive across mounts​

Most tab hosts dispose the subtree they leave, which disposes the platform view with it. With keepAlive: true (the default) the native SDK hands back the same WebView on the next mount — page, scroll position and history intact — so switching tabs does not reload the page.

The kept WebView lives in memory only, for the lifetime of the process. It is dropped, and the next mount loads fresh, when:

  • the app process ends,
  • the session changes (setUser, logout),
  • the language, the user's initials or path change,
  • the theme changes — Android only; on iOS the running page restyles live,
  • on Android, the host Activity is recreated,
  • the security checks fail.

Keep-alive assumes one live KlpWebView per path at a time. A second widget for the same path takes the WebView over and blanks the first; give the second one keepAlive: false.

Back button and loading overlay​

KlpWebViewController.goBack() walks the web history and returns false when the web app is already at its first page — then handle "back" yourself. Klp.instance.onWebViewLoadState reports loading / loaded / error, so you can draw a Flutter loading overlay (which stays smooth while the native loader can stutter on first open). Remove the overlay on both loaded and error, so it never covers the native error screen. On a keep-alive remount the current state is emitted again right after the view is created.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:klp_flutter_sdk/klp_flutter_sdk.dart';

class LoyaltyScreen extends StatefulWidget {
const LoyaltyScreen({super.key});


State<LoyaltyScreen> createState() => _LoyaltyScreenState();
}

class _LoyaltyScreenState extends State<LoyaltyScreen> {
KlpWebViewController? _controller;
StreamSubscription<KlpWebViewLoadEvent>? _loadState;
bool _loading = true;


void initState() {
super.initState();
_loadState = Klp.instance.onWebViewLoadState.listen((KlpWebViewLoadEvent e) {
setState(() => _loading = e.state == KlpWebViewLoadState.loading);
});
}


void dispose() {
_loadState?.cancel();
super.dispose();
}

/// `true` when the web content went one page back.
Future<bool> goBackInLoyalty() async => await _controller?.goBack() ?? false;


Widget build(BuildContext context) {
return Stack(
fit: StackFit.expand,
children: <Widget>[
KlpWebView(onWebViewCreated: (controller) => _controller = controller),
if (_loading) const Center(child: CircularProgressIndicator()),
],
);
}
}

5. Event Logging​

Send business events while a user session is active:

await Klp.instance.logEvent('LogIn');
await Klp.instance.logEvent('MoneyTransfer', {
'amount': 500,
'currency': 'TRY',
});
  • The event name must not be empty (KLP_INVALID_ARGUMENT).
  • Event names and attribute keys must be aligned with KLP according to your business rules.
  • Attributes are sent to the loyalty backend. Do not put personal data or secrets in them unless that is agreed with KLP.

6. Event Streams​

The SDK reports what happens inside the loyalty experience on broadcast streams. Multiple listeners are fine. Cancel your subscriptions when you no longer need them; cancelling every subscription does not shut the SDK down, and a later listen() resumes delivery. Stream errors arrive as KlpException, like method failures — always pass an onError handler. Streams have no replay: an event that arrived before you subscribed is not delivered again.

import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:klp_flutter_sdk/klp_flutter_sdk.dart';

class LoyaltyEvents {
final List<StreamSubscription<Object?>> _subscriptions = <StreamSubscription<Object?>>[];
final ValueNotifier<KlpReward?> latestReward = ValueNotifier<KlpReward?>(null);

void start() {
_subscriptions.addAll(<StreamSubscription<Object?>>[
Klp.instance.onRewardEarned.listen(
(KlpReward reward) => latestReward.value = reward,
onError: _onStreamError,
),
Klp.instance.onError.listen(
(KlpErrorPayload e) => debugPrint('KLP error: ${e.message}'),
onError: _onStreamError,
),
Klp.instance.onSecurityError.listen(
(KlpSecurityCheckResult result) => debugPrint('KLP security: ${result.failedChecks}'),
onError: _onStreamError,
),
]);
}

Future<void> dispose() async {
for (final StreamSubscription<Object?> s in _subscriptions) {
await s.cancel();
}
_subscriptions.clear();
}

void _onStreamError(Object error) {
// `error` is a KlpException.
}
}

Subscribe once at app start rather than per screen, and drive reward UI from a cached value like latestReward instead of a StreamBuilder directly on the stream. Clear the value once the reward has been shown.

Available streams​

StreamPayloadDescription
onEventKlpEventPayloadGeneral events from the loyalty WebView
onRewardEarnedKlpRewardThe user earned a reward
onErrorKlpErrorPayloadA non-fatal SDK error, e.g. a failed session activation
onSecurityErrorKlpSecurityCheckResultA security check failed after initialization
onSseEffectsList<KlpSseEffect>Real-time gamification effects (see below)
onDeepLinkKlpDeepLinkNavigation request from the loyalty WebView (see Deep Links)
onWebViewClosedvoidThe loyalty WebView was closed
onWebViewLoadStateKlpWebViewLoadEventLoad state of an embedded KlpWebView
onThemeChangedKlpThemeChangedTheme changed
onLanguageChangedKlpLanguageChangedLanguage changed

The event names on the underlying channel are available as constants on KlpEventType.

Real-time effects​

By default the SDK shows its own popup for real-time effects (points, mission and level progress). While onSseEffects has a listener, that popup stays hidden and presenting the effects is your job; the popup comes back when the last listener cancels.

Klp.instance.onSseEffects.listen((List<KlpSseEffect> effects) {
for (final KlpSseEffect effect in effects) {
final KlpLoyaltyPointGrant? points = effect.detail.giveLoyaltyProgramPoint;
if (points != null) debugPrint('+${points.point} points');

final KlpProgressUpdate? mission = effect.detail.increaseMissionProgress;
if (mission != null) debugPrint('mission ${(mission.fraction * 100).round()}%');
}
});

Payload reference​

KlpReward

FieldTypeDescription
idStringReward identifier
nameStringDisplay name
descriptionStringDescription; empty when the backend supplied none
valuedoublePoint value
typeStringReward category
imageUrlString?Artwork URL
earnedAtDateTime?When it was earned

KlpEventPayload

FieldTypeDescription
typeStringEvent name defined by the loyalty backend
dataString?Raw payload as JSON text
timestampDateTime?When the native SDK emitted the event
dataAsMapMap<String, Object?>?data decoded as a JSON object; null if absent or not an object. Never throws.

KlpErrorPayload: message (String, never empty) and code (String?). The code is a native diagnostic identifier, not a stable contract — log it, do not branch on it.

KlpSecurityCheckResult: allPassed (bool), checks (List<KlpSecurityCheck> with name, passed, errorMessage) and failedChecks (only the failures).

KlpSseEffect

FieldTypeDescription
idStringEffect identifier
ruleNameString?Backend rule that produced the effect
detailKlpSseEffectDetailTyped payload
missionIdString?Related mission — Android only, null on iOS
levelIdString?Related level — Android only, null on iOS
actionTypeString?Backend action type — Android only, null on iOS

KlpSseEffectDetail carries up to three optional variants — giveLoyaltyProgramPoint (KlpLoyaltyPointGrant: point, reason), increaseMissionProgress and increaseLevelProgress (KlpProgressUpdate: total, target, completed, fraction clamped to 0..1) — and isEmpty when none was present.

KlpWebViewLoadEvent: state (KlpWebViewLoadState.loading, loaded or error), and on error a code (see Error Handling) and a diagnostic message.

KlpThemeChanged: theme (KlpTheme) and resolvedTheme (KlpBrightness). KlpLanguageChanged: languageTag (BCP-47).


Deep links requested from inside the loyalty WebView arrive on onDeepLink, already split into parts on both platforms. Treat every field as untrusted input and validate it against an allowlist before routing:

const Set<String> allowedHosts = <String>{'rewards', 'campaigns'};

Klp.instance.onDeepLink.listen((KlpDeepLink link) {
if (link.scheme != 'myapp') return; // your app's scheme
if (!allowedHosts.contains(link.host)) return;
// Route with link.path and link.queryParameters.
});
FieldTypeDescription
urlStringFull URL as received
schemeStringScheme, always lowercased
hostString?Host; null for scheme-only links
pathStringPath; empty when the URL has none
queryParametersMap<String, String>Decoded query parameters (unmodifiable)

KlpDeepLink.parse(url) builds the same structure from a URL string, without throwing.


8. Theme and Language​

The loyalty experience is native: it does not read your ThemeData or Localizations. It starts on the device theme and language; these calls override them:

await Klp.instance.setTheme(KlpTheme.dark); // system / light / dark
await Klp.instance.setLanguage('tr-TR'); // or 'tr', 'en', 'en-US'
await Klp.instance.setLanguage(null); // back to the device language
  • Set them on every app start. Nothing is stored natively; each process starts from the device setting again. Easiest: pass theme: / language: in KlpInitializeConfig, and call setTheme / setLanguage only when the user changes them later.
  • Set them before opening the loyalty screen. On Android the theme and language go into the WebView URL, so a change made while the page is open does not restyle it; iOS applies it live.
  • Send the preference, not the resolved brightness. KlpTheme.system keeps following the device by itself; resolving it to light / dark in your app pins the SDK to that value.
  • For setLanguage, null, an empty and a blank string all mean "follow the device".

To read the current state, or react to changes:

final KlpAppearance appearance = await Klp.instance.getAppearance();
// appearance.theme — the preference, possibly KlpTheme.system
// appearance.resolvedTheme — the KlpBrightness actually in effect (light / dark)
// appearance.languageTag — e.g. 'tr-TR'

Klp.instance.onThemeChanged.listen((KlpThemeChanged e) => debugPrint('${e.resolvedTheme}'));
Klp.instance.onLanguageChanged.listen((KlpLanguageChanged e) => debugPrint(e.languageTag));

9. Error Handling​

Exceptions​

Every failure — on futures and on streams — is a subtype of the sealed KlpException (code, message, details). Because it is sealed, a switch over it is checked for exhaustiveness:

try {
await Klp.instance.initialize(const KlpInitializeConfig());
} on KlpException catch (error) {
switch (error) {
case KlpSecurityException e:
// Device failed integrity checks (root/jailbreak, emulator, hooking, ...).
for (final KlpSecurityCheck check in e.failedChecks) {
debugPrint('Failed: ${check.name} — ${check.errorMessage}');
}
case KlpInitializationException e:
// Init failed, or timed out with the verdict unknown. Fail closed either way.
debugPrint('Init failed (timeout: ${e.isTimeout})');
case KlpNotInitializedException():
debugPrint('Called before initialize() completed');
case KlpPlatformException e:
debugPrint('${e.code}: ${e.message}');
}
}
TypeCodesRaised when
KlpSecurityExceptionKLP_INIT_SECURITY_ERROR, KLP_SECURITY_ERRORA mandatory device-integrity check failed. failedChecks lists which (result holds the full KlpSecurityCheckResult).
KlpInitializationExceptionKLP_INIT_ERROR, KLP_INIT_TIMEOUTinitialize failed, or did not reach a security verdict in time (isTimeout, Android).
KlpNotInitializedExceptionKLP_NOT_INITIALIZEDA method that needs initialization was called before initialize completed (see API Reference).
KlpPlatformExceptionKLP_INVALID_ARGUMENT, KLP_LAUNCH_ERROR, KLP_SET_USER_ERROR, KLP_SET_TOKEN_ERROR, KLP_LOGOUT_ERROR, KLP_LOG_EVENT_ERROR, KLP_THEME_ERROR, KLP_LANGUAGE_ERROR, KLP_APPEARANCE_ERROR, KLP_DEBUG_SCREEN_ERROR, KLP_INVALID_RESPONSEAny other native failure.

The codes of the first three types, plus KLP_INVALID_RESPONSE, are available as constants on KlpErrorCode (initSecurityError, securityError, initError, initTimeout, notInitialized, invalidResponse).

Loyalty is not your critical path: wrap the calls you make from your own flows so an SDK failure cannot stop them. Catch KlpException, not Exception.

Future<void> onLogin(String accessToken) async {
// ... your own login has already completed
try {
await Klp.instance.setUser(accessToken);
await Klp.instance.logEvent('LogIn');
} on KlpException catch (error) {
debugPrint('KLP skipped: $error'); // log and keep going
}
}

Loyalty screen failures​

A failure while the loyalty page loads has no call of yours to throw from. For an embedded KlpWebView it arrives on KlpWebView.onError and on Klp.instance.onWebViewLoadState as an event with state == KlpWebViewLoadState.error and a stable code. The codes are constants on KlpWebViewErrorCode.

Branch on code, never on message. The message is unlocalized native diagnostic text and changes between versions; the code is the same string on both platforms.

CodeMeaningRetryable
KLP_AUTH_TOKEN_INVALIDBackend 401_Token — the access token is invalid or expired and could not be renewed. The screen reads "Your session has expired!"No — while the page is open: a new token via setToken or setUser (the WebView reloads from the start); after a failed setUser: setUser with a new token
KLP_AUTH_CHALLENGE_EXPIREDChallenge rejected (401_Challenge) after a forced refresh and one retry. Device/app-bound, not the user's sessionNo — a new token does not help
KLP_AUTH_SIGNATURE_REJECTEDChallenge proof rejected. On Android usually an app whose package name + signing certificate SHA-256 is not registered with KLPNo — a build/registration problem
KLP_AUTH_FAILEDUnexpected failure in the challenge/verify flowYes
KLP_CONFIG_UNAUTHORIZEDThe configuration call answered 401_Token — the access token was rejected. Same "session expired" screenNo — setUser with a new token
KLP_CONFIG_UNREACHABLEConfiguration request never completed (network, timeout, TLS)Yes
KLP_CONFIG_REJECTEDConfiguration request rejected or answered unusablyYes
KLP_CONFIG_DISABLEDThe backend switched the loyalty feature off for this userNot a failure — hide your loyalty entry point
KLP_NOT_INITIALIZEDinitialize never ran, or failedNo
KLP_SESSION_MISSINGNo session: no setUser, logged out, or the token is goneNo
KLP_SECURITY_FAILEDDevice-integrity checks failedNo
KLP_SECURITY_URL_BLOCKEDNavigation off the allowlist, or a non-https schemeNo
KLP_APP_VERSION_UNSUPPORTEDThe KLP panel no longer supports this app version. The screen asks for an updateNo — ship an app update
KLP_SDK_VERSION_UNSUPPORTEDThe KLP panel no longer supports this SDK version. The screen asks for an updateNo — ship an app update with a newer SDK
KLP_PAGE_HTTP_ERRORPage request returned 4xx/5xx — Android only; on iOS the page shows whatever the server returnedYes
KLP_PAGE_LOAD_FAILEDPage could not load: network, DNS, TLS/pinning, cancellationYes
KLP_UNKNOWNUnclassified, or a code newer than this SDK versionYes (treated as transient)

Codes are additive: a newer native SDK can report one this version does not know, so always keep a default branch. code can be null when the native SDK underneath predates it; treat that as KLP_UNKNOWN rather than parsing message.

Klp.instance.onWebViewLoadState.listen((KlpWebViewLoadEvent event) async {
if (event.state != KlpWebViewLoadState.error) return;
switch (event.code) {
case KlpWebViewErrorCode.authTokenInvalid:
case KlpWebViewErrorCode.configUnauthorized:
// Refresh through your own auth flow, then setUser() with the NEW token.
final session = await myAuth.refreshSession();
await Klp.instance.setUser(session.accessToken);
case KlpWebViewErrorCode.configDisabled:
hideLoyaltyEntryPoint(); // not a failure
default:
debugPrint('KLP loyalty screen: ${event.code}');
}
});

Recovering from a rejected token. After a failed activation the SDK has already dropped the session, so:

  • setToken does nothing — it updates a token in place and returns false when there is no session. It refreshes a live session; it cannot revive a dead one.
  • setUser with the same token loops — it repeats the activation that was just rejected.

Run your own refresh first, then setUser(newToken). If the refresh fails, the user has to sign in again in your app. KLP_AUTH_CHALLENGE_EXPIRED and KLP_AUTH_SIGNATURE_REJECTED look like session problems but are not: the challenge is bound to the device and the app's signing identity, and a fresh access token does not change them.

Classified errors​

KlpWebView.onError and errorBuilder receive a KlpWebViewError, which groups the codes by what fixes them:

KlpWebViewErrorKindCodesWhat to do
disabledKLP_CONFIG_DISABLEDHide the loyalty surface; nothing failed
sessionKLP_AUTH_TOKEN_INVALID, KLP_CONFIG_UNAUTHORIZED, KLP_SESSION_MISSING, KLP_NOT_INITIALIZEDsetUser with a newly obtained token
transientKLP_AUTH_FAILED, KLP_CONFIG_UNREACHABLE, KLP_CONFIG_REJECTED, KLP_PAGE_HTTP_ERROR, KLP_PAGE_LOAD_FAILED, any unknown codeOffer a retry
blockedKLP_AUTH_CHALLENGE_EXPIRED, KLP_AUTH_SIGNATURE_REJECTED, KLP_SECURITY_FAILED, KLP_SECURITY_URL_BLOCKED, KLP_APP_VERSION_UNSUPPORTED, KLP_SDK_VERSION_UNSUPPORTEDNothing the user can do at runtime

KlpWebViewError exposes code, kind, detail (native diagnostic text, for logs only), isRetryable (only transient) and isUserFacing (everything but disabled). KlpWebViewError.classify(code) gives the kind for a raw code.

Error screen​

When the loyalty page cannot be shown, the native SDK draws its own error screen inside the WebView area — the same screen for launch() and KlpWebView, in the SDK theme and language, with a Try again button only when retrying can help. "Update required" and "feature not available" states use the same screen. The error code and technical detail appear on it only when the SDK runs with debugMode: true. To change its copy you need native code — see the iOS and Android guides.

Its colours are normally set in the KLP panel, so there is nothing to pass. You can also supply colours from the app with KlpInitializeConfig.colors — one KlpColorSet for light and one for dark appearance, picked by the SDK theme. Every field is optional; omitted ones keep the default.

KlpColorSet fieldUsed for
backgroundColorScreen background
primaryColorRetry button background
textColorTitle; body text and diagnostics use it at 64 % opacity
await Klp.instance.initialize(
const KlpInitializeConfig(
colors: KlpColors(
light: KlpColorSet(primaryColor: Color(0xFF0670D4)),
dark: KlpColorSet(backgroundColor: Color(0xFF000000)),
),
),
);

KlpWebView draws no Flutter error screen by default: nothing covers the platform view, so the native screen and its retry stay usable. To draw your own instead, pass errorBuilder. Its widget is stacked over the native screen (so return a full-screen presentation) and gets the KlpWebViewError and an onRetry callback — null when retrying cannot help; do not show a retry button then. KlpWebViewErrorView is a ready-made Material screen you can return from it:

KlpWebView(
errorBuilder: (BuildContext context, KlpWebViewError error, VoidCallback? onRetry) =>
KlpWebViewErrorView(
error: error,
onRetry: onRetry,
strings: KlpWebViewErrorStrings.en.copyWith(retryLabel: 'Reload'), // optional
),
onError: (KlpWebViewError error) => debugPrint('KLP: ${error.code}'), // fires either way
)

KlpWebViewErrorView takes its colours from your app's ColorScheme, shows a title, one line of text, a retry button when onRetry is set and the error is retryable, and the error code (tap to copy). The native diagnostic text appears only with showDiagnostics, which defaults to Flutter's kDebugMode. For disabled it draws nothing unless diagnostics are on, so the native "not available" screen stays visible. Its copy comes in Turkish and English (KlpWebViewErrorStrings.tr / .en), picked from the app locale (KlpWebViewErrorStrings.of); override any field with strings.

Retrying from code​

KlpWebViewController.reload() (from onWebViewCreated) is the native view's own retry. You need it when you draw your own error UI over the platform view and hide the native retry button — an errorBuilder already receives it as onRetry. Remounting the widget is not a substitute: with keepAlive the SDK hands back the same failed view.

reload() returns whether an attempt started (false after a failed security check, or when the view is gone). It re-checks the session and loads the page but does not re-run session activation — for the token codes above a reload ends on KLP_SESSION_MISSING; only setUser with a fresh token recovers those.


10. Security​

Device integrity. During initialize the native SDKs check for jailbreak/root, emulators and simulators, hooking and instrumentation frameworks, an attached debugger and app tampering. These checks run in native code, not in Dart.

  • initialize throws KlpSecurityException when a mandatory check fails.
  • isDeviceSecure() returns the overall verdict; performSecurityChecks() returns each check. Both re-run the full check set on every call — use isInitialized() to decide whether to show a loyalty entry point.
  • onSecurityError reports security failures detected after initialization.

Gate sensitive loyalty actions on a fresh result and degrade gracefully:

final KlpSecurityCheckResult result = await Klp.instance.performSecurityChecks();
if (result.allPassed) {
await Klp.instance.launch();
} else {
// Show a restricted state; result.failedChecks lists what failed.
}

Release builds.

  • environment: KlpEnvironment.prod, debugMode: false, showDebugScreen: false, and no openDebugScreen() call. debugMode: true switches the security checks off entirely.

  • Build with obfuscation and keep the symbol files private — you need them to read crash reports:

    flutter build apk --release --obfuscate --split-debug-info=build/symbols
    flutter build ipa --release --obfuscate --split-debug-info=build/symbols
  • Do not disable App Transport Security (iOS) or allow cleartext traffic (Android) for KLP domains. TLS and certificate pinning are handled by the native SDKs.

Data handling.

  • The SDK needs no API key or credential at runtime.
  • The access token you pass to setUser / setToken is forwarded to the native SDK; the Dart layer does not store it. Do not log it.
  • Do not log SDK payloads (rewards, deep links, tokens) in production.
  • Validate every deep link against an allowlist (see Deep Links).
  • Keep personal data and secrets out of logEvent attributes.

Report suspected vulnerabilities privately to the KLP integration team, not in public issues.


11. Common Errors​

SymptomCauseFix
pub get cannot find klp_flutter_sdkThe hosted: URL is mistyped, or the machine cannot reach the hostCopy the dependency exactly as in section 1. Check curl -I https://sdk.kaizentech.net/klp/flutter/api/packages/klp_flutter_sdk — anything but 200 is a network or egress issue. Allow outbound HTTPS to sdk.kaizentech.net on CI runners too.
Swift Package Manager reports a KLPSDK checksum mismatchA TLS-inspecting proxy rewrites the downloadExclude sdk.kaizentech.net from TLS interception. Do not work around the checksum.
pod install: Unable to find a specification for KLPSDKThe Podfile line is missing (Swift Package Manager off)Add the pod 'KLPSDK', … line from iOS setup.
Android cannot resolve com.klp.sdk:klp-android-sdkThe KLP Maven repository is not used, or not reachableCheck network access; if your settings restrict repositories, add it as shown in Android setup.
Android build fails with Unsupported class file major versionAndroid Gradle Plugin older than 8.2.1Raise com.android.application to 8.2.1 or newer.
KlpPlatformException: plugin is not registered (MissingPluginException)Stale buildflutter clean && flutter pub get, then a full rebuild (not a hot restart). With CocoaPods also run pod install; with Swift Package Manager reset the package caches in Xcode (File ▸ Packages ▸ Reset Package Caches).
KlpNotInitializedExceptionA method that needs initialization ran before initialize completedawait Klp.instance.initialize(...) first.
launch() returns falseNo active session: no setUser, activation failed, or the feature is off for this userCall setUser first and check its result; watch onError for the reason.
KLP_LAUNCH_ERRORNo visible view controller (iOS) or foreground Activity (Android)Call launch() from a mounted, visible screen, after the first frame.
KLP_INVALID_ARGUMENTEmpty access token (setUser, setToken) or empty event name (logEvent)Pass non-empty values.
KLP_INIT_TIMEOUTThe security handshake did not finish in timeTreat it as a failed security check. Do not continue into sensitive flows.
KlpSecurityException on a physical deviceThe device failed an integrity checkExpected on rooted/jailbroken/hooked devices and emulators. Test on an unmodified device; use debugMode: true only for simulator development.
setToken returns falseNo active session (no setUser, logout since, or a failed activation)Use setUser with a fresh token instead.
Loyalty screen shows "Your session has expired!"The token could not be renewed (KLP_AUTH_TOKEN_INVALID)Register setOnRefreshTokenHandler, or pass every new token with setToken.

12. API Reference​

All methods are on Klp.instance.

MethodReturnsBefore initializeDescription
initialize(config)Future<bool>—Initialize the native SDK and run the security checks
isInitialized()Future<bool>allowedWhether loyalty is live: checks passed, setUser activated a session and the feature is visible for this user. A cheap state read
getVersionInfo()Future<KlpVersionInfo>allowedPlugin and native SDK versions
getConfig()Future<Map<String, Object?>?>allowedBackend configuration from the KLP panel; null until isInitialized() is true
setUser(accessToken)Future<bool>allowed (held until init)Start a user session; resolves when activation finishes
setToken(accessToken, {expiryDate})Future<bool>allowedSwap in a refreshed token; false when there is no session
setOnRefreshTokenHandler(handler)Future<bool>allowedLet the SDK ask for new tokens (KlpRefreshTokenHandler, returns KlpRefreshedToken); null removes it
logout()Future<bool>allowed (cancels a held setUser)End the session
launch([path])Future<bool>throwsOpen the loyalty screen; false without an active session
logEvent(eventName, [attributes])Future<bool>throwsSend a business event
setTheme(theme)Future<bool>throwsKlpTheme.system, light or dark
setLanguage(languageTag)Future<bool>throwsBCP-47 tag; null / blank follows the device
getAppearance()Future<KlpAppearance>throwsCurrent theme and language
isDeviceSecure()Future<bool>throwsDevice-integrity verdict
performSecurityChecks()Future<KlpSecurityCheckResult>throwsResult of each check
openDebugScreen()Future<bool>throwsOpen the SDK debug interface (test builds only)

"throws" means KlpNotInitializedException before initialize has completed. None of these methods needs an active user session except launch, so a backend problem does not make them unavailable.

isInitialized() is false until setUser succeeds and can stay false when the feature is switched off for that user — check it after setUser, and again when the session changes.

Version​

Include the getVersionInfo() output in bug reports — the Dart package version alone does not identify the native SDK a build uses:

final KlpVersionInfo info = await Klp.instance.getVersionInfo();
debugPrint('${info.platform} ${info.nativeSdkVersion} ${info.pluginVersion}');

Upgrading from 1.0.3​

  • Change the dependency to the one in section 1; no token or credential setup is needed anymore.
  • Apps with Swift Package Manager off add the KLPSDK Podfile line (iOS setup). Nothing to do otherwise, and nothing on Android unless your Gradle settings restrict repositories.
  • iOS 15 and Xcode 26.2 are the new minimums.
  • New: setOnRefreshTokenHandler (section 3) and getConfig().
  • setUser now resolves with the activation result (true / false); it still never throws for an activation failure.
  • The SDK shows its own error, "session expired", "feature not available" and "update required" screens; failures carry a stable code (see Error Handling).

For questions, contact the KLP integration team.