gomarketme-react-native
Version:
Affiliate Marketing for React Native-Based iOS and Android Apps.
604 lines (603 loc) • 30.1 kB
JavaScript
"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 (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__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 __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
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;
var react_native_1 = require("react-native");
var react_native_device_info_1 = __importDefault(require("react-native-device-info"));
var get_user_locale_1 = __importDefault(require("get-user-locale"));
var async_storage_1 = __importDefault(require("@react-native-async-storage/async-storage"));
var RNIap = __importStar(require("react-native-iap"));
var axios_1 = __importDefault(require("axios"));
var GoMarketMeAffiliateMarketingData = /** @class */ (function () {
function GoMarketMeAffiliateMarketingData(campaign, affiliate, saleDistribution, affiliateCampaignCode, deviceId, offerCode) {
this.campaign = campaign;
this.affiliate = affiliate;
this.saleDistribution = saleDistribution;
this.affiliateCampaignCode = affiliateCampaignCode;
this.deviceId = deviceId;
this.offerCode = offerCode;
}
GoMarketMeAffiliateMarketingData.fromJson = function (json) {
// Check if the json is an empty object
if (Object.keys(json).length === 0) {
return null; // Return null or undefined, depending on your preference
}
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);
};
return GoMarketMeAffiliateMarketingData;
}());
exports.GoMarketMeAffiliateMarketingData = GoMarketMeAffiliateMarketingData;
var Campaign = /** @class */ (function () {
function Campaign(id, name, status, type, publicLinkUrl) {
this.id = id;
this.name = name;
this.status = status;
this.type = type;
this.publicLinkUrl = publicLinkUrl;
}
Campaign.fromJson = function (json) {
return new Campaign(json.id || '', json.name || '', json.status || '', json.type || '', json.public_link_url);
};
return Campaign;
}());
exports.Campaign = Campaign;
var Affiliate = /** @class */ (function () {
function Affiliate(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;
}
Affiliate.fromJson = function (json) {
return new Affiliate(json.id || '', json.first_name || '', json.last_name || '', json.country_code || '', json.instagram_account || '', json.tiktok_account || '', json.x_account || '');
};
return Affiliate;
}());
exports.Affiliate = Affiliate;
var SaleDistribution = /** @class */ (function () {
function SaleDistribution(platformPercentage, affiliatePercentage) {
this.platformPercentage = platformPercentage;
this.affiliatePercentage = affiliatePercentage;
}
SaleDistribution.fromJson = function (json) {
return new SaleDistribution(json.platform_percentage || '', json.affiliate_percentage || '');
};
return SaleDistribution;
}());
exports.SaleDistribution = SaleDistribution;
var GoMarketMe = /** @class */ (function () {
function GoMarketMe() {
this.sdkType = 'ReactNative';
this.sdkVersion = '2.0.0';
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 = '';
this._getTimeZone = function () {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
};
}
GoMarketMe.getInstance = function () {
if (!GoMarketMe.instance) {
GoMarketMe.instance = new GoMarketMe();
}
return GoMarketMe.instance;
};
GoMarketMe.prototype.initialize = function (apiKey) {
return __awaiter(this, void 0, void 0, function () {
var isSDKInitialized, systemInfo, _a, e_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_b.trys.push([0, 7, , 8]);
return [4 /*yield*/, this._isSDKInitialized()];
case 1:
isSDKInitialized = _b.sent();
if (!!isSDKInitialized) return [3 /*break*/, 3];
return [4 /*yield*/, this._postSDKInitialization(apiKey)];
case 2:
_b.sent();
_b.label = 3;
case 3:
this._packageName = react_native_device_info_1.default.getBundleId();
return [4 /*yield*/, this._getSystemInfo()];
case 4:
systemInfo = _b.sent();
_a = this;
return [4 /*yield*/, this._postSystemInfo(systemInfo, apiKey)];
case 5:
_a.affiliateMarketingData = _b.sent();
return [4 /*yield*/, this._addListener(apiKey)];
case 6:
_b.sent();
return [3 /*break*/, 8];
case 7:
e_1 = _b.sent();
console.log('Error initializing GoMarketMe:', e_1);
return [3 /*break*/, 8];
case 8: return [2 /*return*/];
}
});
});
};
GoMarketMe.prototype._addListener = function (apiKey) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
try {
RNIap.purchaseUpdatedListener(function (purchase) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._fetchConsolidatedPurchases([purchase], apiKey)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); });
RNIap.purchaseErrorListener(function (error) {
console.log('Purchase error:', error);
});
}
catch (e) {
console.log('Error setting up IAP listeners:', e);
}
return [2 /*return*/];
});
});
};
GoMarketMe.prototype._getSystemInfo = function () {
return __awaiter(this, void 0, void 0, function () {
var deviceData, _a, _b, devicePixelRatio, dimension, windowData;
var _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_b = (_a = react_native_1.Platform).select;
_c = {};
return [4 /*yield*/, this._readIosDeviceInfo()];
case 1:
_c.ios = _d.sent();
return [4 /*yield*/, this._readAndroidDeviceInfo()];
case 2:
deviceData = _b.apply(_a, [(_c.android = _d.sent(),
_c)]);
this._deviceId = deviceData['deviceId'];
devicePixelRatio = react_native_1.PixelRatio.get();
dimension = react_native_1.Dimensions.get('window');
windowData = {
devicePixelRatio: devicePixelRatio,
width: dimension.width * devicePixelRatio,
height: dimension.height * devicePixelRatio,
};
return [2 /*return*/, {
device_info: deviceData,
window_info: windowData,
time_zone: this._getTimeZone(),
language_code: this._getLanguageCode(),
}];
}
});
});
};
GoMarketMe.prototype._postSDKInitialization = function (apiKey) {
return __awaiter(this, void 0, void 0, function () {
var response, e_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 5, , 6]);
return [4 /*yield*/, axios_1.default.post(this.sdkInitializationUrl, {}, {
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
},
})];
case 1:
response = _a.sent();
if (!(response.status === 200)) return [3 /*break*/, 3];
return [4 /*yield*/, this._markSDKAsInitialized()];
case 2:
_a.sent();
return [3 /*break*/, 4];
case 3:
console.log('Failed to mark SDK as Initialized. Status code:', response.status);
_a.label = 4;
case 4: return [3 /*break*/, 6];
case 5:
e_2 = _a.sent();
console.log('Error sending SDK information to server:', e_2);
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
});
};
GoMarketMe.prototype._postSystemInfo = function (data, apiKey) {
return __awaiter(this, void 0, void 0, function () {
var output, response, e_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
output = null;
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
data['sdk_type'] = this.sdkType;
data['sdk_version'] = this.sdkVersion;
data['package_name'] = this._packageName;
return [4 /*yield*/, axios_1.default.post(this.systemInfoUrl, data, {
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
},
})];
case 2:
response = _a.sent();
if (response.status === 200) {
output = GoMarketMeAffiliateMarketingData.fromJson(response.data);
if (output != null) {
this._affiliateCampaignCode = output.affiliateCampaignCode;
}
}
else {
console.log('Failed to send system info. Status code:', response.status);
}
return [3 /*break*/, 4];
case 3:
e_3 = _a.sent();
console.log('Error sending system info to server:', e_3);
return [3 /*break*/, 4];
case 4: return [2 /*return*/, output];
}
});
});
};
GoMarketMe.prototype._readAndroidDeviceInfo = function () {
return __awaiter(this, void 0, void 0, function () {
var androidId, uniqueId, deviceId, systemName, systemVersion, brand, model, manufacturer, isEmulator;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, react_native_device_info_1.default.getAndroidId()];
case 1:
androidId = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.getUniqueId()];
case 2:
uniqueId = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.getDeviceId()];
case 3:
deviceId = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.getSystemName()];
case 4:
systemName = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.getSystemVersion()];
case 5:
systemVersion = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.getBrand()];
case 6:
brand = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.getModel()];
case 7:
model = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.getManufacturer()];
case 8:
manufacturer = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.isEmulator()];
case 9:
isEmulator = _a.sent();
return [2 /*return*/, {
deviceId: androidId,
_deviceId: deviceId,
_uniqueId: uniqueId,
systemName: systemName,
systemVersion: systemVersion,
brand: brand,
model: model,
manufacturer: manufacturer,
isEmulator: isEmulator
}];
}
});
});
};
GoMarketMe.prototype._readIosDeviceInfo = function () {
return __awaiter(this, void 0, void 0, function () {
var uniqueId, deviceId, systemName, systemVersion, brand, model, manufacturer, isEmulator;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, react_native_device_info_1.default.getUniqueId()];
case 1:
uniqueId = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.getDeviceId()];
case 2:
deviceId = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.getSystemName()];
case 3:
systemName = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.getSystemVersion()];
case 4:
systemVersion = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.getBrand()];
case 5:
brand = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.getModel()];
case 6:
model = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.getManufacturer()];
case 7:
manufacturer = _a.sent();
return [4 /*yield*/, react_native_device_info_1.default.isEmulator()];
case 8:
isEmulator = _a.sent();
return [2 /*return*/, {
deviceId: uniqueId,
_deviceId: deviceId,
systemName: systemName,
systemVersion: systemVersion,
brand: brand,
model: model,
manufacturer: manufacturer,
isEmulator: isEmulator
}];
}
});
});
};
GoMarketMe.prototype._getLanguageCode = function () {
return (0, get_user_locale_1.default)();
};
GoMarketMe.prototype._fetchConsolidatedPurchases = function (purchaseDetailsList, apiKey) {
return __awaiter(this, void 0, void 0, function () {
var _i, purchaseDetailsList_1, purchase, data, products, _a, products_1, product0, products_3, _b, products_2, product0;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_i = 0, purchaseDetailsList_1 = purchaseDetailsList;
_c.label = 1;
case 1:
if (!(_i < purchaseDetailsList_1.length)) return [3 /*break*/, 8];
purchase = purchaseDetailsList_1[_i];
if (!purchase.transactionReceipt) return [3 /*break*/, 7];
data = this._serializePurchaseDetails(purchase);
data['products'] = [];
if (!(data.productID != '')) return [3 /*break*/, 5];
return [4 /*yield*/, RNIap.getProducts({ skus: [data.productID] })];
case 2:
products = _c.sent();
if (!(products.length > 0)) return [3 /*break*/, 3];
for (_a = 0, products_1 = products; _a < products_1.length; _a++) {
product0 = products_1[_a];
data['products'].push(this._serializeProductDetails(product0));
}
return [3 /*break*/, 5];
case 3: return [4 /*yield*/, RNIap.getSubscriptions({ skus: [data.productID] })];
case 4:
products_3 = _c.sent();
if (products_3.length > 0) {
for (_b = 0, products_2 = products_3; _b < products_2.length; _b++) {
product0 = products_2[_b];
data['products'].push(this._serializeSubscriptionDetails(product0));
}
}
_c.label = 5;
case 5: return [4 /*yield*/, this._sendEventToServer(JSON.stringify(data), 'purchase', apiKey)];
case 6:
_c.sent();
_c.label = 7;
case 7:
_i++;
return [3 /*break*/, 1];
case 8: return [2 /*return*/];
}
});
});
};
GoMarketMe.prototype._sendEventToServer = function (body, eventType, apiKey) {
return __awaiter(this, void 0, void 0, function () {
var response, e_4;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, axios_1.default.post(this.eventUrl, body, {
headers: {
'Content-Type': 'application/json',
'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,
},
})];
case 1:
response = _a.sent();
if (response.status === 200) {
console.log("".concat(eventType, " sent successfully"));
}
else {
console.log("Failed to send ".concat(eventType, ". Status code:"), response.status);
}
return [3 /*break*/, 3];
case 2:
e_4 = _a.sent();
console.log("Error sending ".concat(eventType, " to server:"), e_4);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
});
};
GoMarketMe.prototype._serializePurchaseDetails = function (purchase) {
return {
packageName: this._packageName,
productID: purchase.productId,
purchaseID: purchase.transactionId || '',
transactionDate: purchase.transactionDate || '',
status: react_native_1.Platform.select({
ios: purchase.transactionStateIOS,
android: purchase.purchaseStateAndroid,
}),
verificationData: {
localVerificationData: purchase.transactionReceipt,
serverVerificationData: purchase.transactionReceipt,
source: react_native_1.Platform.OS === 'android' ? 'google_play' : 'app_store',
},
pendingCompletePurchase: '',
error: {},
hashCode: '',
_purchase: purchase
};
};
GoMarketMe.prototype._serializeProductDetails = function (product) {
return {
packageName: this._packageName,
productID: product.productId,
productTitle: product.title,
productDescription: product.description,
productPrice: product.localizedPrice,
productRawPrice: product.price,
productCurrencySymbol: product.localizedPrice.replace('product.price', ''),
productCurrencyCode: product.currency,
hashCode: '',
_product: product
};
};
GoMarketMe.prototype._serializeSubscriptionDetails = function (subscription) {
var _a;
var output = {
productID: subscription.productId,
productTitle: subscription.title,
productDescription: subscription.description,
hashCode: '',
};
if (react_native_1.Platform.OS === 'ios') {
var subscriptionIOS = subscription;
output.productPrice = subscriptionIOS.localizedPrice;
output.productRawPrice = subscriptionIOS.price;
output.productCurrencyCode = subscriptionIOS.currency;
output._subscription = subscriptionIOS;
}
else if (react_native_1.Platform.OS === 'android') {
var subscriptionAndroid = subscription;
if ((_a = subscriptionAndroid.subscriptionOfferDetails) === null || _a === void 0 ? void 0 : _a.length) {
var offerDetails = subscriptionAndroid.subscriptionOfferDetails[0];
var priceAmountMicros = parseInt(offerDetails.pricingPhases.pricingPhaseList[0].priceAmountMicros, 10) || 0;
output.productPrice = offerDetails.pricingPhases.pricingPhaseList[0].formattedPrice;
output.productRawPrice = String(priceAmountMicros / 1000000);
output.productCurrencyCode = offerDetails.pricingPhases.pricingPhaseList[0].priceCurrencyCode;
}
output._subscription = subscriptionAndroid;
}
return output;
};
GoMarketMe.prototype._markSDKAsInitialized = function () {
return __awaiter(this, void 0, void 0, function () {
var e_5;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, async_storage_1.default.setItem(this.sdkInitializedKey, 'true')];
case 1:
_a.sent();
return [2 /*return*/, true];
case 2:
e_5 = _a.sent();
console.log('Failed to save SDK initialization:', e_5);
return [2 /*return*/, false];
case 3: return [2 /*return*/];
}
});
});
};
GoMarketMe.prototype._isSDKInitialized = function () {
return __awaiter(this, void 0, void 0, function () {
var value, e_6;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, async_storage_1.default.getItem(this.sdkInitializedKey)];
case 1:
value = _a.sent();
return [2 /*return*/, value === 'true'];
case 2:
e_6 = _a.sent();
console.log('Failed to load SDK initialization:', e_6);
return [2 /*return*/, false];
case 3: return [2 /*return*/];
}
});
});
};
return GoMarketMe;
}());
exports.default = GoMarketMe.getInstance();