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 | |
|---|---|
| Flutter | 3.27.0 |
| Dart | 3.6.0 |
| iOS | 15.0 |
| Xcode | 26.2 |
| Android | API 24 (Android 7.0) |
| Android Gradle Plugin | 8.2.1 |
| Java | 17 |
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 toios/Podfileinside yourtargetblock: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, notRunner.xcodeproj. Without the line,pod installstops withUnable to find a specification for KLPSDK. Keep the version in the URL at1.0.10for 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:
minSdkinandroid/app/build.gradle(.kts)is24or higher.- The Android Gradle Plugin (
com.android.applicationinandroid/settings.gradle(.kts)) is8.2.1or newer. Apps created from the Flutter 3.27 template pin an older AGP and fail withUnsupported class file major versionor 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
| Field | Type | Default | Description |
|---|---|---|---|
environment | KlpEnvironment | prod | dev, test or prod. The default is prod, so an omitted value can never ship a test backend. Use test for development and staging builds. |
debugMode | bool | false | Verbose 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. |
showDebugScreen | bool | false | Shows a floating button that opens the SDK debug interface. Does not switch the security checks off. Keep false in release builds. |
theme | KlpTheme? | null | Starting theme. null follows the device. See Theme and Language. |
language | String? | null | Starting language as a BCP-47 tag (tr, tr-TR). null, empty or blank leaves the default (the device language). |
colors | KlpColors? | null | Colours 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();
setUsercompletes when the native session activation has finished.truemeans loyalty is available for this user.falsemeans it is not: activation failed, the feature is switched off for this user, or a newersetUser/logoutreplaced 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. setUserandlogoutcan be called beforeinitializehas finished: asetUsercall is held and runs once the security checks pass, andlogoutcancels a held call. So do notawaitsetUserbefore your owninitializecall — the two would wait on each other.- Use
setUseronly when the user changes; calllogouton 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.expiresAtmust 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
setUseror afterlogout. 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, asetTokenwith a new token, orlogout— 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 latersetTokenwith 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);
setTokenonly swaps the stored token. UnlikesetUserit does not re-run session activation or restart the real-time stream, so it is safe to call on every refresh.expiryDateis 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 throwsKLP_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 (nosetUser, activation failed, or the feature is switched off for this user). Nothing opens. - Throws
KlpNotInitializedExceptionbeforeinitializehas completed. - Throws
KlpPlatformExceptionwithKLP_LAUNCH_ERRORwhen there is nothing to present from: no visible view controller on iOS, no foregroundActivityon 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}'),
);
}
}
| Parameter | Type | Description |
|---|---|---|
path | String? | Route inside the loyalty app, same as the launch argument. |
keepAlive | bool | Default true. Keeps the native WebView across remounts (see below). |
onWebViewCreated | void Function(KlpWebViewController)? | Called once the native view exists, with a controller for goBack() / reload(). |
gestureRecognizers | Set<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. |
errorBuilder | KlpWebViewErrorBuilder? | Draws your own error screen over the native one. See Error screen. |
onError | void 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
pathchange, - the theme changes — Android only; on iOS the running page restyles live,
- on Android, the host
Activityis 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
| Stream | Payload | Description |
|---|---|---|
onEvent | KlpEventPayload | General events from the loyalty WebView |
onRewardEarned | KlpReward | The user earned a reward |
onError | KlpErrorPayload | A non-fatal SDK error, e.g. a failed session activation |
onSecurityError | KlpSecurityCheckResult | A security check failed after initialization |
onSseEffects | List<KlpSseEffect> | Real-time gamification effects (see below) |
onDeepLink | KlpDeepLink | Navigation request from the loyalty WebView (see Deep Links) |
onWebViewClosed | void | The loyalty WebView was closed |
onWebViewLoadState | KlpWebViewLoadEvent | Load state of an embedded KlpWebView |
onThemeChanged | KlpThemeChanged | Theme changed |
onLanguageChanged | KlpLanguageChanged | Language 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
| Field | Type | Description |
|---|---|---|
id | String | Reward identifier |
name | String | Display name |
description | String | Description; empty when the backend supplied none |
value | double | Point value |
type | String | Reward category |
imageUrl | String? | Artwork URL |
earnedAt | DateTime? | When it was earned |
KlpEventPayload
| Field | Type | Description |
|---|---|---|
type | String | Event name defined by the loyalty backend |
data | String? | Raw payload as JSON text |
timestamp | DateTime? | When the native SDK emitted the event |
dataAsMap | Map<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
| Field | Type | Description |
|---|---|---|
id | String | Effect identifier |
ruleName | String? | Backend rule that produced the effect |
detail | KlpSseEffectDetail | Typed payload |
missionId | String? | Related mission — Android only, null on iOS |
levelId | String? | Related level — Android only, null on iOS |
actionType | String? | 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).
7. Deep Links
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.
});
| Field | Type | Description |
|---|---|---|
url | String | Full URL as received |
scheme | String | Scheme, always lowercased |
host | String? | Host; null for scheme-only links |
path | String | Path; empty when the URL has none |
queryParameters | Map<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:inKlpInitializeConfig, and callsetTheme/setLanguageonly 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.systemkeeps following the device by itself; resolving it tolight/darkin 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}');
}
}
| Type | Codes | Raised when |
|---|---|---|
KlpSecurityException | KLP_INIT_SECURITY_ERROR, KLP_SECURITY_ERROR | A mandatory device-integrity check failed. failedChecks lists which (result holds the full KlpSecurityCheckResult). |
KlpInitializationException | KLP_INIT_ERROR, KLP_INIT_TIMEOUT | initialize failed, or did not reach a security verdict in time (isTimeout, Android). |
KlpNotInitializedException | KLP_NOT_INITIALIZED | A method that needs initialization was called before initialize completed (see API Reference). |
KlpPlatformException | KLP_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_RESPONSE | Any 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.
| Code | Meaning | Retryable |
|---|---|---|
KLP_AUTH_TOKEN_INVALID | Backend 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_EXPIRED | Challenge rejected (401_Challenge) after a forced refresh and one retry. Device/app-bound, not the user's session | No — a new token does not help |
KLP_AUTH_SIGNATURE_REJECTED | Challenge proof rejected. On Android usually an app whose package name + signing certificate SHA-256 is not registered with KLP | No — a build/registration problem |
KLP_AUTH_FAILED | Unexpected failure in the challenge/verify flow | Yes |
KLP_CONFIG_UNAUTHORIZED | The configuration call answered 401_Token — the access token was rejected. Same "session expired" screen | No — setUser with a new token |
KLP_CONFIG_UNREACHABLE | Configuration request never completed (network, timeout, TLS) | Yes |
KLP_CONFIG_REJECTED | Configuration request rejected or answered unusably | Yes |
KLP_CONFIG_DISABLED | The backend switched the loyalty feature off for this user | Not a failure — hide your loyalty entry point |
KLP_NOT_INITIALIZED | initialize never ran, or failed | No |
KLP_SESSION_MISSING | No session: no setUser, logged out, or the token is gone | No |
KLP_SECURITY_FAILED | Device-integrity checks failed | No |
KLP_SECURITY_URL_BLOCKED | Navigation off the allowlist, or a non-https scheme | No |
KLP_APP_VERSION_UNSUPPORTED | The KLP panel no longer supports this app version. The screen asks for an update | No — ship an app update |
KLP_SDK_VERSION_UNSUPPORTED | The KLP panel no longer supports this SDK version. The screen asks for an update | No — ship an app update with a newer SDK |
KLP_PAGE_HTTP_ERROR | Page request returned 4xx/5xx — Android only; on iOS the page shows whatever the server returned | Yes |
KLP_PAGE_LOAD_FAILED | Page could not load: network, DNS, TLS/pinning, cancellation | Yes |
KLP_UNKNOWN | Unclassified, or a code newer than this SDK version | Yes (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:
setTokendoes nothing — it updates a token in place and returnsfalsewhen there is no session. It refreshes a live session; it cannot revive a dead one.setUserwith 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:
KlpWebViewErrorKind | Codes | What to do |
|---|---|---|
disabled | KLP_CONFIG_DISABLED | Hide the loyalty surface; nothing failed |
session | KLP_AUTH_TOKEN_INVALID, KLP_CONFIG_UNAUTHORIZED, KLP_SESSION_MISSING, KLP_NOT_INITIALIZED | setUser with a newly obtained token |
transient | KLP_AUTH_FAILED, KLP_CONFIG_UNREACHABLE, KLP_CONFIG_REJECTED, KLP_PAGE_HTTP_ERROR, KLP_PAGE_LOAD_FAILED, any unknown code | Offer a retry |
blocked | KLP_AUTH_CHALLENGE_EXPIRED, KLP_AUTH_SIGNATURE_REJECTED, KLP_SECURITY_FAILED, KLP_SECURITY_URL_BLOCKED, KLP_APP_VERSION_UNSUPPORTED, KLP_SDK_VERSION_UNSUPPORTED | Nothing 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 field | Used for |
|---|---|
backgroundColor | Screen background |
primaryColor | Retry button background |
textColor | Title; 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.
initializethrowsKlpSecurityExceptionwhen a mandatory check fails.isDeviceSecure()returns the overall verdict;performSecurityChecks()returns each check. Both re-run the full check set on every call — useisInitialized()to decide whether to show a loyalty entry point.onSecurityErrorreports 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 noopenDebugScreen()call.debugMode: trueswitches 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/symbolsflutter 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/setTokenis 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
logEventattributes.
Report suspected vulnerabilities privately to the KLP integration team, not in public issues.
11. Common Errors
| Symptom | Cause | Fix |
|---|---|---|
pub get cannot find klp_flutter_sdk | The hosted: URL is mistyped, or the machine cannot reach the host | Copy 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 mismatch | A TLS-inspecting proxy rewrites the download | Exclude sdk.kaizentech.net from TLS interception. Do not work around the checksum. |
pod install: Unable to find a specification for KLPSDK | The Podfile line is missing (Swift Package Manager off) | Add the pod 'KLPSDK', … line from iOS setup. |
Android cannot resolve com.klp.sdk:klp-android-sdk | The KLP Maven repository is not used, or not reachable | Check network access; if your settings restrict repositories, add it as shown in Android setup. |
Android build fails with Unsupported class file major version | Android Gradle Plugin older than 8.2.1 | Raise com.android.application to 8.2.1 or newer. |
KlpPlatformException: plugin is not registered (MissingPluginException) | Stale build | flutter 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). |
KlpNotInitializedException | A method that needs initialization ran before initialize completed | await Klp.instance.initialize(...) first. |
launch() returns false | No active session: no setUser, activation failed, or the feature is off for this user | Call setUser first and check its result; watch onError for the reason. |
KLP_LAUNCH_ERROR | No visible view controller (iOS) or foreground Activity (Android) | Call launch() from a mounted, visible screen, after the first frame. |
KLP_INVALID_ARGUMENT | Empty access token (setUser, setToken) or empty event name (logEvent) | Pass non-empty values. |
KLP_INIT_TIMEOUT | The security handshake did not finish in time | Treat it as a failed security check. Do not continue into sensitive flows. |
KlpSecurityException on a physical device | The device failed an integrity check | Expected on rooted/jailbroken/hooked devices and emulators. Test on an unmodified device; use debugMode: true only for simulator development. |
setToken returns false | No 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.
| Method | Returns | Before initialize | Description |
|---|---|---|---|
initialize(config) | Future<bool> | — | Initialize the native SDK and run the security checks |
isInitialized() | Future<bool> | allowed | Whether loyalty is live: checks passed, setUser activated a session and the feature is visible for this user. A cheap state read |
getVersionInfo() | Future<KlpVersionInfo> | allowed | Plugin and native SDK versions |
getConfig() | Future<Map<String, Object?>?> | allowed | Backend 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> | allowed | Swap in a refreshed token; false when there is no session |
setOnRefreshTokenHandler(handler) | Future<bool> | allowed | Let 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> | throws | Open the loyalty screen; false without an active session |
logEvent(eventName, [attributes]) | Future<bool> | throws | Send a business event |
setTheme(theme) | Future<bool> | throws | KlpTheme.system, light or dark |
setLanguage(languageTag) | Future<bool> | throws | BCP-47 tag; null / blank follows the device |
getAppearance() | Future<KlpAppearance> | throws | Current theme and language |
isDeviceSecure() | Future<bool> | throws | Device-integrity verdict |
performSecurityChecks() | Future<KlpSecurityCheckResult> | throws | Result of each check |
openDebugScreen() | Future<bool> | throws | Open 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
KLPSDKPodfile 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) andgetConfig(). setUsernow 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.