UNPKG

gomarketme-react-native-expo

Version:

Affiliate Marketing for Expo-Based iOS and Android Apps.

390 lines 17.4 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SaleDistribution = exports.Affiliate = exports.Campaign = exports.GoMarketMeAffiliateMarketingData = void 0; const react_native_1 = require("react-native"); const axios_1 = __importDefault(require("axios")); const Application = __importStar(require("expo-application")); const expo_constants_1 = __importDefault(require("expo-constants")); const Device = __importStar(require("expo-device")); const Localization = __importStar(require("expo-localization")); const expo_iap_1 = require("expo-iap"); const async_storage_1 = __importDefault(require("@react-native-async-storage/async-storage")); class GoMarketMeAffiliateMarketingData { constructor(campaign, affiliate, saleDistribution, affiliateCampaignCode, deviceId, offerCode) { this.campaign = campaign; this.affiliate = affiliate; this.saleDistribution = saleDistribution; this.affiliateCampaignCode = affiliateCampaignCode; this.deviceId = deviceId; this.offerCode = offerCode; } static fromJson(json) { if (!json || Object.keys(json).length === 0) return null; return new GoMarketMeAffiliateMarketingData(Campaign.fromJson(json.campaign), Affiliate.fromJson(json.affiliate), SaleDistribution.fromJson(json.sale_distribution), json.affiliate_campaign_code || '', json.device_id || '', json.offer_code); } } exports.GoMarketMeAffiliateMarketingData = GoMarketMeAffiliateMarketingData; class Campaign { constructor(id, name, status, type, publicLinkUrl) { this.id = id; this.name = name; this.status = status; this.type = type; this.publicLinkUrl = publicLinkUrl; } static fromJson(json) { return new Campaign((json === null || json === void 0 ? void 0 : json.id) || '', (json === null || json === void 0 ? void 0 : json.name) || '', (json === null || json === void 0 ? void 0 : json.status) || '', (json === null || json === void 0 ? void 0 : json.type) || '', json === null || json === void 0 ? void 0 : json.public_link_url); } } exports.Campaign = Campaign; class Affiliate { constructor(id, firstName, lastName, countryCode, instagramAccount, tiktokAccount, xAccount) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.countryCode = countryCode; this.instagramAccount = instagramAccount; this.tiktokAccount = tiktokAccount; this.xAccount = xAccount; } static fromJson(json) { return new Affiliate((json === null || json === void 0 ? void 0 : json.id) || '', (json === null || json === void 0 ? void 0 : json.first_name) || '', (json === null || json === void 0 ? void 0 : json.last_name) || '', (json === null || json === void 0 ? void 0 : json.country_code) || '', (json === null || json === void 0 ? void 0 : json.instagram_account) || '', (json === null || json === void 0 ? void 0 : json.tiktok_account) || '', (json === null || json === void 0 ? void 0 : json.x_account) || ''); } } exports.Affiliate = Affiliate; class SaleDistribution { constructor(platformPercentage, affiliatePercentage) { this.platformPercentage = platformPercentage; this.affiliatePercentage = affiliatePercentage; } static fromJson(json) { return new SaleDistribution((json === null || json === void 0 ? void 0 : json.platform_percentage) || '', (json === null || json === void 0 ? void 0 : json.affiliate_percentage) || ''); } } exports.SaleDistribution = SaleDistribution; class GoMarketMe { constructor() { this.sdkType = 'ReactNativeExpo'; this.sdkVersion = '4.0.3'; this.sdkInitializedKey = 'GOMARKETME_SDK_INITIALIZED'; this.sdkInitializationUrl = 'https://4v9008q1a5.execute-api.us-west-2.amazonaws.com/prod/v1/sdk-initialization'; this.systemInfoUrl = 'https://4v9008q1a5.execute-api.us-west-2.amazonaws.com/prod/v1/mobile/system-info'; this.eventUrl = 'https://4v9008q1a5.execute-api.us-west-2.amazonaws.com/prod/v1/event'; this._affiliateCampaignCode = ''; this._deviceId = ''; this._packageName = ''; } static getInstance() { if (!GoMarketMe.instance) GoMarketMe.instance = new GoMarketMe(); return GoMarketMe.instance; } initialize(apiKey) { return __awaiter(this, void 0, void 0, function* () { var _a; try { const isSDKInitialized = yield this._isSDKInitialized(); if (!isSDKInitialized) yield this._postSDKInitialization(apiKey); this._packageName = (_a = Application.applicationId) !== null && _a !== void 0 ? _a : ''; const systemInfo = yield this._getSystemInfo(); this.affiliateMarketingData = yield this._postSystemInfo(systemInfo, apiKey); yield this._addListeners(apiKey); this._fetchExistingPurchases(apiKey).catch(e => { console.log('Error in background purchase fetch:', e); }); } catch (e) { console.log('Error initializing GoMarketMe:', e); } }); } removeListeners() { var _a, _b, _c, _d; try { (_b = (_a = this._purchaseUpdateUnsub) === null || _a === void 0 ? void 0 : _a.remove) === null || _b === void 0 ? void 0 : _b.call(_a); (_d = (_c = this._purchaseErrorUnsub) === null || _c === void 0 ? void 0 : _c.remove) === null || _d === void 0 ? void 0 : _d.call(_c); } catch (e) { console.log('Error removing listeners:', e); } } _addListeners(apiKey) { return __awaiter(this, void 0, void 0, function* () { if (!this._purchaseUpdateUnsub) { this._purchaseUpdateUnsub = (0, expo_iap_1.purchaseUpdatedListener)((purchase) => __awaiter(this, void 0, void 0, function* () { try { yield this._fetchConsolidatedPurchases([purchase], apiKey); } catch (e) { console.log('purchaseUpdated error:', e); } })); } if (!this._purchaseErrorUnsub) { this._purchaseErrorUnsub = (0, expo_iap_1.purchaseErrorListener)((error) => { console.log('purchaseErrorListener:', error); }); } }); } _getLanguageCode() { return Localization.getLocales()[0].languageTag; } _getSystemInfo() { return __awaiter(this, void 0, void 0, function* () { const deviceData = react_native_1.Platform.OS === 'ios' ? yield this._readIosDeviceInfo() : yield this._readAndroidDeviceInfo(); this._deviceId = deviceData['deviceId'] || ''; const devicePixelRatio = react_native_1.PixelRatio.get(); const dimension = react_native_1.Dimensions.get('window'); return { device_info: deviceData, window_info: { devicePixelRatio, width: dimension.width * devicePixelRatio, height: dimension.height * devicePixelRatio, }, time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone, language_code: this._getLanguageCode(), sdk_type: this.sdkType, sdk_version: this.sdkVersion, package_name: this._packageName, is_production: yield this._isProduction() }; }); } _postSDKInitialization(apiKey) { return __awaiter(this, void 0, void 0, function* () { try { const res = yield axios_1.default.post(this.sdkInitializationUrl, {}, { headers: { 'x-api-key': apiKey }, }); if (res.status === 200) yield this._markSDKAsInitialized(); } catch (e) { console.log('Error posting SDK initialization:', e); } }); } _postSystemInfo(data, apiKey) { return __awaiter(this, void 0, void 0, function* () { try { const res = yield axios_1.default.post(this.systemInfoUrl, data, { headers: { 'x-api-key': apiKey }, }); if (res.status === 200) { const obj = GoMarketMeAffiliateMarketingData.fromJson(res.data); if (obj) this._affiliateCampaignCode = obj.affiliateCampaignCode; return obj; } } catch (e) { console.log('Error posting system info:', e); } return null; }); } _readAndroidDeviceInfo() { return __awaiter(this, void 0, void 0, function* () { let androidId = react_native_1.Platform.OS === 'android' ? yield Application.getAndroidId() : ''; let systemName = Device.osName; let systemVersion = Device.osVersion; let brand = Device.brand; let model = Device.modelName; let manufacturer = Device.manufacturer; let isEmulator = !Device.isDevice; return { deviceId: androidId, _deviceId: androidId, _uniqueId: androidId, brand: brand, model: model, manufacturer: manufacturer, systemName: systemName, systemVersion: systemVersion, isEmulator: isEmulator }; }); } _readIosDeviceInfo() { return __awaiter(this, void 0, void 0, function* () { let deviceId = react_native_1.Platform.OS === 'ios' ? yield Application.getIosIdForVendorAsync() : ''; let systemName = Device.osName; let systemVersion = Device.osVersion; let brand = Device.brand; let model = Device.modelName; let manufacturer = Device.manufacturer; return { deviceId: deviceId, _deviceId: deviceId, brand: brand, model: model, manufacturer: manufacturer, systemName: systemName, systemVersion: systemVersion, }; }); } _fetchConsolidatedPurchases(purchases, apiKey) { return __awaiter(this, void 0, void 0, function* () { for (const purchase of purchases) { const receipt = purchase.purchaseToken; if (!receipt) continue; const data = this._serializePurchaseDetails(purchase); data.products = []; const pid = data.productID || ''; if (pid) { try { const products = yield (0, expo_iap_1.fetchProducts)({ skus: [pid] }); if (products && products.length) { for (const p of products) { data.products.push(this._serializeProductDetails(p)); } } } catch (e) { console.warn('Error fetching products:', e); } } yield this._sendEventToServer(JSON.stringify(data), 'purchase_product', apiKey); } }); } _sendEventToServer(body, eventType, apiKey) { return __awaiter(this, void 0, void 0, function* () { try { yield axios_1.default.post(this.eventUrl, body, { headers: { 'x-affiliate-campaign-code': this._affiliateCampaignCode, 'x-device-id': this._deviceId, 'x-event-type': eventType, 'x-product-type': react_native_1.Platform.OS, 'x-source-name': react_native_1.Platform.OS === 'android' ? 'google_play' : 'app_store', 'x-api-key': apiKey, }, }); console.log(`${eventType} sent successfully`); } catch (e) { console.log(`Error sending ${eventType}:`, e); } }); } _serializePurchaseDetails(purchase) { return { packageName: this._packageName, productID: purchase.productId, purchaseID: purchase.id, transactionDate: purchase.transactionDate, verificationData: { localVerificationData: purchase.purchaseToken, source: react_native_1.Platform.OS === 'android' ? 'google_play' : 'app_store', }, }; } _serializeProductDetails(product) { return { packageName: this._packageName, productID: product.id, productTitle: product.title, productDescription: product.description, productPrice: product.displayPrice, productRawPrice: product.price || '', productCurrencyCode: product.currency, }; } _markSDKAsInitialized() { return __awaiter(this, void 0, void 0, function* () { yield async_storage_1.default.setItem(this.sdkInitializedKey, 'true'); }); } _isSDKInitialized() { return __awaiter(this, void 0, void 0, function* () { const val = yield async_storage_1.default.getItem(this.sdkInitializedKey); return val === 'true'; }); } _isProduction() { return __awaiter(this, void 0, void 0, function* () { try { const appOwnership = expo_constants_1.default.appOwnership; const executionEnvironment = expo_constants_1.default.executionEnvironment; const isStoreBuild = appOwnership === null && executionEnvironment === 'standalone' && !!Application.applicationId && !__DEV__; return isStoreBuild; } catch (error) { console.warn('Error determining production status:', error); return false; } }); } _fetchExistingPurchases(apiKey) { return __awaiter(this, void 0, void 0, function* () { try { const purchases = yield (0, expo_iap_1.getAvailablePurchases)(); if (purchases && purchases.length > 0) { yield this._fetchConsolidatedPurchases(purchases, apiKey); } } catch (e) { console.log('Error fetching existing purchases on app open:', e); } }); } } exports.default = GoMarketMe.getInstance(); //# sourceMappingURL=index.js.map