initializeSdk static method
Implementation
static Future<Map<String, dynamic>> initializeSdk(
InitializeSdkProps args) async {
try {
final mid = args.mid;
final environment = args.environment;
final kcMerchantId = args.kcMerchantId ?? '';
final kcMerchantToken = args.kcMerchantToken ?? '';
final isSnowplowTrackingEnabled = args.isSnowplowTrackingEnabled ?? true;
final mode = args.mode ?? (kDebugMode ? 'debug' : 'release');
await getConfig();
// callback function for analytics
final Function analyticsCallback = args.onAnalytics ?? () {};
// Create settings with defaults, then merge with provided settings
final settingsWithDefaults = Settings(
enableKwikPass: args.settings?.enableKwikPass ?? true,
enableCheckout: args.settings?.enableCheckout ?? true,
);
final enableKwikPass = settingsWithDefaults.enableKwikPass;
final enableCheckout = settingsWithDefaults.enableCheckout;
// await Logger().log(
// 'SDK Initialized',
// data: jsonEncode({
// 'mid': mid,
// 'environment': environment.name,
// }),
// );
await Future.wait([
cacheInstance.setValue(
cdnConfigInstance.getKeys(StorageKeyKeys.gkMode)!,
mode.toString(),
),
cacheInstance.setValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkEnvironmentKey)!, environment.name),
cacheInstance.setValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkMerchantIdKey)!, mid),
cacheInstance.setValue(cdnConfigInstance.getKeys(StorageKeyKeys.kcMerchantId)!, kcMerchantId),
cacheInstance.setValue(cdnConfigInstance.getKeys(StorageKeyKeys.kcMerchantToken)!, kcMerchantToken),
cacheInstance.setValue(
cdnConfigInstance.getKeys(StorageKeyKeys.kcNotificationEventUrl)!,
SdkConfig.getNotifEventsUrl(environment.name),
),
cacheInstance.setValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkKPEnabled)!, enableKwikPass.toString()),
cacheInstance.setValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkCheckoutEnabled)!, enableCheckout.toString()),
]);
if (enableKwikPass == false) {
return {'message': 'Initialization Successful without kwikpass'};
}
cacheInstance.setValue(
cdnConfigInstance.getKeys(StorageKeyKeys.isSnowplowTrackingEnabled)!,
isSnowplowTrackingEnabled.toString(),
);
await DioClient().initialize(args.environment.name);
final gokwik = DioClient().getClient();
gokwik.options.headers[cdnConfigInstance.getHeader(APIHeaderKeys.gkMerchantId)!] = mid;
gokwik.options.headers[cdnConfigInstance.getHeader(APIHeaderKeys.kpSdkPlatform)!] = 'flutter';
gokwik.options.headers[cdnConfigInstance.getHeader(APIHeaderKeys.kpSdkVersion)!] = KPSdkVersion.version;
// await Logger().log(
// 'SDK Initialized',
// data: jsonEncode({
// 'mid': mid,
// 'environment': environment.name,
// }),
// );
final results = await Future.wait([
cacheInstance.getValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkRequestIdKey)!),
cacheInstance.getValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkAccessTokenKey)!),
cacheInstance.getValue(cdnConfigInstance.getKeys(StorageKeyKeys.checkoutAccessTokenKey)!),
]);
final accessToken = results[1];
final checkoutAccessToken = results[2];
if (accessToken != null) {
gokwik.options.headers[cdnConfigInstance.getHeader(APIHeaderKeys.gkAccessToken)!] = accessToken;
}
if (checkoutAccessToken != null) {
gokwik.options.headers[cdnConfigInstance.getHeader(APIHeaderKeys.checkoutAccessToken)!] =
checkoutAccessToken;
}
final result = await checkKwikpassHealth();
// await getBrowserToken();
if(result.isSuccess) {
final healthData = result.getDataOrThrow();
if(healthData?.isKwikpassHealthy == false){
throw Exception('Kwikpass is unhealthy');
}
}
final merchantConfig = await initializeMerchant(mid, environment.name);
if (merchantConfig.isSuccess) {
final merchantConfigData = merchantConfig.getDataOrThrow();
if (merchantConfigData?.platform != null) {
final platform =
merchantConfigData!.platform.toString().toLowerCase();
await cacheInstance.setValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkMerchantTypeKey)!, platform);
}
final hostName = getHostName(merchantConfigData!.host);
await cacheInstance.setValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkMerchantUrlKey)!, hostName);
}
await SnowplowClient.initializeSnowplowClient(args);
final deviceInfo = DeviceInfoPlugin();
String osVersion = 'Unknown';
String deviceModel = 'Unknown';
String deviceId = 'Unknown';
if (Platform.isAndroid) {
final androidInfo = await deviceInfo.androidInfo;
osVersion = 'Android ${androidInfo.version.release}';
deviceModel = androidInfo.model;
deviceId = androidInfo.id;
} else if (Platform.isIOS) {
final iosInfo = await deviceInfo.iosInfo;
osVersion = 'iOS ${iosInfo.systemVersion}';
deviceModel = iosInfo.model;
deviceId = iosInfo.identifierForVendor ?? 'Unknown';
}
final packageInfo = await PackageInfo.fromPlatform();
// ignore: deprecated_member_use
final window = WidgetsBinding.instance.window;
final screenSize = window.physicalSize;
final screenResolution =
'${screenSize.width.toInt()}x${screenSize.height.toInt()}';
final deviceInfoDetails = {
cdnConfigInstance.getKeys(StorageKeyKeys.gkDeviceModel)!: deviceModel,
cdnConfigInstance.getKeys(StorageKeyKeys.gkAppDomain)!: packageInfo.packageName,
cdnConfigInstance.getKeys(StorageKeyKeys.gkOperatingSystem)!: osVersion,
cdnConfigInstance.getKeys(StorageKeyKeys.gkDeviveId)!: deviceId,
cdnConfigInstance.getKeys(StorageKeyKeys.gkDeviceUniqueId)!: deviceId,
cdnConfigInstance.getKeys(StorageKeyKeys.gkGoogleAnalyticsId)!: deviceId,
cdnConfigInstance.getKeys(StorageKeyKeys.gkGoogleAdId)!: '',
cdnConfigInstance.getKeys(StorageKeyKeys.gkAppVersion)!: packageInfo.version,
cdnConfigInstance.getKeys(StorageKeyKeys.gkAppVersionCode)!: packageInfo.buildNumber,
cdnConfigInstance.getKeys(StorageKeyKeys.gkScreenResolution)!: screenResolution,
cdnConfigInstance.getKeys(StorageKeyKeys.gkCarrierInfo)!: 'Unknown',
cdnConfigInstance.getKeys(StorageKeyKeys.gkBatteryStatus)!: 'Unknown',
cdnConfigInstance.getKeys(StorageKeyKeys.gkLanguage)!: Intl.getCurrentLocale(),
cdnConfigInstance.getKeys(StorageKeyKeys.gkTimeZone)!: DateTime.now().timeZoneName,
};
try {
final advertisingInfo = await AdvertisingInfo.getAdvertisingInfo();
if (advertisingInfo.id != null) {
deviceInfoDetails[cdnConfigInstance.getKeys(StorageKeyKeys.gkGoogleAdId)!] = advertisingInfo.id!;
}
} catch (e) {
deviceInfoDetails[cdnConfigInstance.getKeys(StorageKeyKeys.gkGoogleAdId)!] = "";
}
await cacheInstance.setValue(
cdnConfigInstance.getKeys(StorageKeyKeys.gkDeviceInfo)!,
jsonEncode(deviceInfoDetails),
);
// await sendGoogleAdIdentification();
final requestId = results[0];
if (requestId != null) {
gokwik.options.headers[cdnConfigInstance.getHeader(APIHeaderKeys.kpRequestId)!] = requestId;
gokwik.options.headers[cdnConfigInstance.getHeader(APIHeaderKeys.gkRequestId)!] = requestId;
}
// Check for MoEngage tracking configuration
// final isMoEngageTracking = merchantConfig.isSuccess &&
// merchantConfig.getDataOrThrow()?.thirdPartyServiceProviders
// .where((item) => item.name == 'mo_engage' && item.type == 'analytics')
// .length == 1;
// // Check for WebEngage tracking configuration
// final isWebEngageTracking = merchantConfig.isSuccess &&
// merchantConfig.getDataOrThrow()?.thirdPartyServiceProviders
// .where((item) => item.name == 'web_engage' && item.type == 'analytics')
// .length == 1;
// Get verified user data and track identified user event
final verifiedUserJson =
await cacheInstance.getValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkVerifiedUserKey)!);
if (verifiedUserJson != null) {
final verifiedUser = jsonDecode(verifiedUserJson);
if (verifiedUser['email'] != null && verifiedUser['phone'] != null) {
analyticsCallback(
cdnConfigInstance.getAnalyticsEvent(AnalyticsEventKeys.appIdentifiedUser)!,
{
'phone': verifiedUser['phone']?.toString() ?? "",
'email': verifiedUser['email']?.toString() ?? "",
'customer_id': verifiedUser['shopifyCustomerId']?.toString() ?? "",
},
);
}
}
return {'message': 'Initialization Successful'};
} catch (error) {
if (error is Failure) {
throw handleApiError(error);
}
throw handleApiError(error);
}
}