insert-affiliate-react-native-sdk 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "WebFetch(domain:github.com)"
5
+ ],
6
+ "deny": []
7
+ }
8
+ }
@@ -8,6 +8,7 @@ type CustomPurchase = {
8
8
  type T_DEEPLINK_IAP_CONTEXT = {
9
9
  referrerLink: string;
10
10
  userId: string;
11
+ iOSOfferCode: string | null;
11
12
  returnInsertAffiliateIdentifier: () => Promise<string | null>;
12
13
  validatePurchaseWithIapticAPI: (jsonIapPurchase: CustomPurchase, iapticAppId: string, iapticAppName: string, iapticPublicKey: string) => Promise<boolean>;
13
14
  returnUserAccountTokenAndStoreExpectedTransaction: () => Promise<string | null>;
@@ -15,7 +16,7 @@ type T_DEEPLINK_IAP_CONTEXT = {
15
16
  trackEvent: (eventName: string) => Promise<void>;
16
17
  setShortCode: (shortCode: string) => Promise<void>;
17
18
  setInsertAffiliateIdentifier: (referringLink: string) => Promise<void | string>;
18
- initialize: (code: string | null) => Promise<void>;
19
+ initialize: (code: string | null, verboseLogging?: boolean) => Promise<void>;
19
20
  isInitialized: boolean;
20
21
  };
21
22
  export declare const DeepLinkIapContext: React.Context<T_DEEPLINK_IAP_CONTEXT>;
@@ -46,11 +46,13 @@ const ASYNC_KEYS = {
46
46
  USER_ID: '@app_user_id',
47
47
  COMPANY_CODE: '@app_company_code',
48
48
  USER_ACCOUNT_TOKEN: '@app_user_account_token',
49
+ IOS_OFFER_CODE: '@app_ios_offer_code',
49
50
  };
50
51
  // STARTING CONTEXT IMPLEMENTATION
51
52
  exports.DeepLinkIapContext = (0, react_1.createContext)({
52
53
  referrerLink: '',
53
54
  userId: '',
55
+ iOSOfferCode: null,
54
56
  returnInsertAffiliateIdentifier: () => __awaiter(void 0, void 0, void 0, function* () { return ''; }),
55
57
  validatePurchaseWithIapticAPI: (jsonIapPurchase, iapticAppId, iapticAppName, iapticPublicKey) => __awaiter(void 0, void 0, void 0, function* () { return false; }),
56
58
  returnUserAccountTokenAndStoreExpectedTransaction: () => __awaiter(void 0, void 0, void 0, function* () { return ''; }),
@@ -58,7 +60,7 @@ exports.DeepLinkIapContext = (0, react_1.createContext)({
58
60
  trackEvent: (eventName) => __awaiter(void 0, void 0, void 0, function* () { }),
59
61
  setShortCode: (shortCode) => __awaiter(void 0, void 0, void 0, function* () { }),
60
62
  setInsertAffiliateIdentifier: (referringLink) => __awaiter(void 0, void 0, void 0, function* () { }),
61
- initialize: (code) => __awaiter(void 0, void 0, void 0, function* () { }),
63
+ initialize: (code, verboseLogging) => __awaiter(void 0, void 0, void 0, function* () { }),
62
64
  isInitialized: false,
63
65
  });
64
66
  const DeepLinkIapProvider = ({ children, }) => {
@@ -66,8 +68,16 @@ const DeepLinkIapProvider = ({ children, }) => {
66
68
  const [userId, setUserId] = (0, react_1.useState)('');
67
69
  const [companyCode, setCompanyCode] = (0, react_1.useState)(null);
68
70
  const [isInitialized, setIsInitialized] = (0, react_1.useState)(false);
71
+ const [verboseLogging, setVerboseLogging] = (0, react_1.useState)(false);
72
+ const [iOSOfferCode, setIOSOfferCode] = (0, react_1.useState)(null);
69
73
  // MARK: Initialize the SDK
70
- const initialize = (companyCode) => __awaiter(void 0, void 0, void 0, function* () {
74
+ const initialize = (companyCode_1, ...args_1) => __awaiter(void 0, [companyCode_1, ...args_1], void 0, function* (companyCode, verboseLogging = false) {
75
+ setVerboseLogging(verboseLogging);
76
+ if (verboseLogging) {
77
+ console.log('[Insert Affiliate] [VERBOSE] Starting SDK initialization...');
78
+ console.log('[Insert Affiliate] [VERBOSE] Company code provided:', companyCode ? 'Yes' : 'No');
79
+ console.log('[Insert Affiliate] [VERBOSE] Verbose logging enabled');
80
+ }
71
81
  if (isInitialized) {
72
82
  console.error('[Insert Affiliate] SDK is already initialized.');
73
83
  return;
@@ -77,10 +87,17 @@ const DeepLinkIapProvider = ({ children, }) => {
77
87
  yield saveValueInAsync(ASYNC_KEYS.COMPANY_CODE, companyCode);
78
88
  setIsInitialized(true);
79
89
  console.log(`[Insert Affiliate] SDK initialized with company code: ${companyCode}`);
90
+ if (verboseLogging) {
91
+ console.log('[Insert Affiliate] [VERBOSE] Company code saved to AsyncStorage');
92
+ console.log('[Insert Affiliate] [VERBOSE] SDK marked as initialized');
93
+ }
80
94
  }
81
95
  else {
82
96
  console.warn('[Insert Affiliate] SDK initialized without a company code.');
83
97
  setIsInitialized(true);
98
+ if (verboseLogging) {
99
+ console.log('[Insert Affiliate] [VERBOSE] No company code provided, SDK initialized in limited mode');
100
+ }
84
101
  }
85
102
  });
86
103
  // EFFECT TO FETCH USER ID AND REF LINK
@@ -88,28 +105,49 @@ const DeepLinkIapProvider = ({ children, }) => {
88
105
  (0, react_1.useEffect)(() => {
89
106
  const fetchAsyncEssentials = () => __awaiter(void 0, void 0, void 0, function* () {
90
107
  try {
108
+ verboseLog('Loading stored data from AsyncStorage...');
91
109
  const uId = yield getValueFromAsync(ASYNC_KEYS.USER_ID);
92
110
  const refLink = yield getValueFromAsync(ASYNC_KEYS.REFERRER_LINK);
111
+ const companyCodeFromStorage = yield getValueFromAsync(ASYNC_KEYS.COMPANY_CODE);
112
+ const storedIOSOfferCode = yield getValueFromAsync(ASYNC_KEYS.IOS_OFFER_CODE);
113
+ verboseLog(`User ID found: ${uId ? 'Yes' : 'No'}`);
114
+ verboseLog(`Referrer link found: ${refLink ? 'Yes' : 'No'}`);
115
+ verboseLog(`Company code found: ${companyCodeFromStorage ? 'Yes' : 'No'}`);
116
+ verboseLog(`iOS Offer Code found: ${storedIOSOfferCode ? 'Yes' : 'No'}`);
93
117
  if (uId && refLink) {
94
118
  setUserId(uId);
95
119
  setReferrerLink(refLink);
120
+ verboseLog('User ID and referrer link restored from storage');
121
+ }
122
+ if (companyCodeFromStorage) {
123
+ setCompanyCode(companyCodeFromStorage);
124
+ verboseLog('Company code restored from storage');
125
+ }
126
+ if (storedIOSOfferCode) {
127
+ setIOSOfferCode(storedIOSOfferCode);
128
+ verboseLog('iOS Offer Code restored from storage');
96
129
  }
97
130
  }
98
131
  catch (error) {
99
132
  errorLog(`ERROR ~ fetchAsyncEssentials: ${error}`);
133
+ verboseLog(`Error loading from AsyncStorage: ${error}`);
100
134
  }
101
135
  });
102
136
  fetchAsyncEssentials();
103
137
  }, []);
104
138
  function generateThenSetUserID() {
105
139
  return __awaiter(this, void 0, void 0, function* () {
140
+ verboseLog('Getting or generating user ID...');
106
141
  let userId = yield getValueFromAsync(ASYNC_KEYS.USER_ID);
107
142
  if (!userId) {
143
+ verboseLog('No existing user ID found, generating new one...');
108
144
  userId = generateUserID();
109
145
  setUserId(userId);
110
146
  yield saveValueInAsync(ASYNC_KEYS.USER_ID, userId);
147
+ verboseLog(`Generated and saved new user ID: ${userId}`);
111
148
  }
112
149
  else {
150
+ verboseLog(`Found existing user ID: ${userId}`);
113
151
  setUserId(userId);
114
152
  }
115
153
  return userId;
@@ -140,6 +178,29 @@ const DeepLinkIapProvider = ({ children, }) => {
140
178
  const clearAsyncStorage = () => __awaiter(void 0, void 0, void 0, function* () {
141
179
  yield async_storage_1.default.clear();
142
180
  });
181
+ // Helper function to get company code from state or storage
182
+ const getActiveCompanyCode = () => __awaiter(void 0, void 0, void 0, function* () {
183
+ verboseLog('Getting active company code...');
184
+ let activeCompanyCode = companyCode;
185
+ verboseLog(`Company code in React state: ${activeCompanyCode || 'empty'}`);
186
+ if (!activeCompanyCode || (activeCompanyCode.trim() === '' && activeCompanyCode !== null)) {
187
+ verboseLog('Company code not in state, checking AsyncStorage...');
188
+ activeCompanyCode = yield getValueFromAsync(ASYNC_KEYS.COMPANY_CODE);
189
+ verboseLog(`Company code in AsyncStorage: ${activeCompanyCode || 'empty'}`);
190
+ if (activeCompanyCode) {
191
+ // Update state for future use
192
+ setCompanyCode(activeCompanyCode);
193
+ verboseLog('Updated React state with company code from storage');
194
+ }
195
+ }
196
+ return activeCompanyCode;
197
+ });
198
+ // Helper function for verbose logging
199
+ const verboseLog = (message) => {
200
+ if (verboseLogging) {
201
+ console.log(`[Insert Affiliate] [VERBOSE] ${message}`);
202
+ }
203
+ };
143
204
  // Helper function to log errors
144
205
  const errorLog = (message, type) => {
145
206
  switch (type) {
@@ -156,9 +217,9 @@ const DeepLinkIapProvider = ({ children, }) => {
156
217
  };
157
218
  // MARK: Short Codes
158
219
  const isShortCode = (referringLink) => {
159
- // Short codes are less than 10 characters
160
- const isValidCharacters = /^[a-zA-Z0-9]+$/.test(referringLink);
161
- return isValidCharacters && referringLink.length < 25 && referringLink.length > 3;
220
+ // Short codes are 3-25 characters and can include underscores
221
+ const isValidCharacters = /^[a-zA-Z0-9_]+$/.test(referringLink);
222
+ return isValidCharacters && referringLink.length >= 3 && referringLink.length <= 25;
162
223
  };
163
224
  function setShortCode(shortCode) {
164
225
  return __awaiter(this, void 0, void 0, function* () {
@@ -207,12 +268,32 @@ const DeepLinkIapProvider = ({ children, }) => {
207
268
  ;
208
269
  });
209
270
  // MARK: Return Insert Affiliate Identifier
271
+ // Instead of just reading React state
210
272
  const returnInsertAffiliateIdentifier = () => __awaiter(void 0, void 0, void 0, function* () {
211
273
  try {
212
- return `${referrerLink}-${userId}`;
274
+ verboseLog('Getting insert affiliate identifier...');
275
+ verboseLog(`React state - referrerLink: ${referrerLink || 'empty'}, userId: ${userId || 'empty'}`);
276
+ // Try React state first
277
+ if (referrerLink && userId) {
278
+ const identifier = `${referrerLink}-${userId}`;
279
+ verboseLog(`Found identifier in React state: ${identifier}`);
280
+ return identifier;
281
+ }
282
+ verboseLog('React state empty, checking AsyncStorage...');
283
+ // Fallback to async storage if React state is empty
284
+ const storedLink = yield getValueFromAsync(ASYNC_KEYS.REFERRER_LINK);
285
+ const storedUserId = yield getValueFromAsync(ASYNC_KEYS.USER_ID);
286
+ verboseLog(`AsyncStorage - storedLink: ${storedLink || 'empty'}, storedUserId: ${storedUserId || 'empty'}`);
287
+ if (storedLink && storedUserId) {
288
+ const identifier = `${storedLink}-${storedUserId}`;
289
+ verboseLog(`Found identifier in AsyncStorage: ${identifier}`);
290
+ return identifier;
291
+ }
292
+ verboseLog('No affiliate identifier found in state or storage');
293
+ return null;
213
294
  }
214
295
  catch (error) {
215
- errorLog(`ERROR ~ returnInsertAffiliateIdentifier: ${error}`);
296
+ verboseLog(`Error getting affiliate identifier: ${error}`);
216
297
  return null;
217
298
  }
218
299
  });
@@ -220,64 +301,77 @@ const DeepLinkIapProvider = ({ children, }) => {
220
301
  function setInsertAffiliateIdentifier(referringLink) {
221
302
  return __awaiter(this, void 0, void 0, function* () {
222
303
  console.log('[Insert Affiliate] Setting affiliate identifier.');
304
+ verboseLog(`Input referringLink: ${referringLink}`);
223
305
  try {
306
+ verboseLog('Generating or retrieving user ID...');
224
307
  const customerID = yield generateThenSetUserID();
225
308
  console.log('[Insert Affiliate] Completed generateThenSetUserID within setInsertAffiliateIdentifier.');
309
+ verboseLog(`Customer ID: ${customerID}`);
226
310
  if (!referringLink) {
227
311
  console.warn('[Insert Affiliate] Referring link is invalid.');
228
- let heldReferrerLinkBeforeAsyncStateUpdate = referrerLink;
312
+ verboseLog('Referring link is empty or invalid, storing as-is');
229
313
  yield storeInsertAffiliateIdentifier({ link: referringLink });
230
- return `${heldReferrerLinkBeforeAsyncStateUpdate}-${customerID}`;
314
+ return `${referringLink}-${customerID}`;
231
315
  }
232
- if (!companyCode || (companyCode.trim() === '' && companyCode !== null)) {
233
- let companyCodeFromStorage = yield getValueFromAsync(ASYNC_KEYS.COMPANY_CODE);
234
- if (companyCodeFromStorage !== null) {
235
- setCompanyCode(companyCodeFromStorage);
236
- }
237
- else {
238
- console.error('[Insert Affiliate] Company code is not set. Please initialize the SDK with a valid company code.');
239
- return;
240
- }
316
+ // Get company code from state or storage
317
+ verboseLog('Getting company code...');
318
+ const activeCompanyCode = yield getActiveCompanyCode();
319
+ verboseLog(`Active company code: ${activeCompanyCode || 'Not found'}`);
320
+ if (!activeCompanyCode) {
321
+ console.error('[Insert Affiliate] Company code is not set. Please initialize the SDK with a valid company code.');
322
+ verboseLog('Company code missing, cannot proceed with API call');
323
+ return;
241
324
  }
242
325
  // Check if referring link is already a short code, if so save it and stop here.
326
+ verboseLog('Checking if referring link is already a short code...');
243
327
  if (isShortCode(referringLink)) {
244
328
  console.log('[Insert Affiliate] Referring link is already a short code.');
245
- let heldReferrerLinkBeforeAsyncStateUpdate = referrerLink;
329
+ verboseLog('Link is already a short code, storing directly');
246
330
  yield storeInsertAffiliateIdentifier({ link: referringLink });
247
- return `${heldReferrerLinkBeforeAsyncStateUpdate}-${customerID}`;
331
+ return `${referringLink}-${customerID}`;
248
332
  }
333
+ verboseLog('Link is not a short code, will convert via API');
249
334
  // If the code is not already a short code, encode it raedy to send to our endpoint to return the short code. Save it before making the call in case something goes wrong
250
335
  // Encode the referring link
336
+ verboseLog('Encoding referring link for API call...');
251
337
  const encodedAffiliateLink = encodeURIComponent(referringLink);
252
338
  if (!encodedAffiliateLink) {
253
339
  console.error('[Insert Affiliate] Failed to encode affiliate link.');
254
- let heldReferrerLinkBeforeAsyncStateUpdate = referrerLink;
340
+ verboseLog('Failed to encode link, storing original');
255
341
  yield storeInsertAffiliateIdentifier({ link: referringLink });
256
- return `${heldReferrerLinkBeforeAsyncStateUpdate}-${customerID}`;
342
+ return `${referringLink}-${customerID}`;
257
343
  }
258
344
  // Create the request URL
259
- const urlString = `https://api.insertaffiliate.com/V1/convert-deep-link-to-short-link?companyId=${companyCode}&deepLinkUrl=${encodedAffiliateLink}`;
345
+ const urlString = `https://api.insertaffiliate.com/V1/convert-deep-link-to-short-link?companyId=${activeCompanyCode}&deepLinkUrl=${encodedAffiliateLink}`;
260
346
  console.log('[Insert Affiliate] urlString .', urlString);
347
+ verboseLog('Making API request to convert deep link to short code...');
261
348
  const response = yield axios_1.default.get(urlString, {
262
349
  headers: {
263
350
  'Content-Type': 'application/json',
264
351
  },
265
352
  });
353
+ verboseLog(`API response status: ${response.status}`);
266
354
  // Call to the backend for the short code and save the resolse in valid
267
355
  if (response.status === 200 && response.data.shortLink) {
268
356
  const shortLink = response.data.shortLink;
269
357
  console.log('[Insert Affiliate] Short link received:', shortLink);
358
+ verboseLog(`Successfully converted to short link: ${shortLink}`);
359
+ verboseLog('Storing short link to AsyncStorage...');
360
+ yield storeInsertAffiliateIdentifier({ link: shortLink });
361
+ verboseLog('Short link stored successfully');
270
362
  return `${shortLink}-${customerID}`;
271
363
  }
272
364
  else {
273
365
  console.warn('[Insert Affiliate] Unexpected response format.');
274
- let heldReferrerLinkBeforeAsyncStateUpdate = referrerLink;
366
+ verboseLog(`Unexpected API response. Status: ${response.status}, Data: ${JSON.stringify(response.data)}`);
367
+ verboseLog('Storing original link as fallback');
275
368
  yield storeInsertAffiliateIdentifier({ link: referringLink });
276
- return `${heldReferrerLinkBeforeAsyncStateUpdate}-${customerID}`;
369
+ return `${referringLink}-${customerID}`;
277
370
  }
278
371
  }
279
372
  catch (error) {
280
373
  console.error('[Insert Affiliate] Error:', error);
374
+ verboseLog(`Error in setInsertAffiliateIdentifier: ${error}`);
281
375
  }
282
376
  });
283
377
  }
@@ -285,8 +379,14 @@ const DeepLinkIapProvider = ({ children, }) => {
285
379
  function storeInsertAffiliateIdentifier(_a) {
286
380
  return __awaiter(this, arguments, void 0, function* ({ link }) {
287
381
  console.log(`[Insert Affiliate] Storing affiliate identifier: ${link}`);
382
+ verboseLog(`Updating React state with referrer link: ${link}`);
288
383
  setReferrerLink(link);
384
+ verboseLog(`Saving referrer link to AsyncStorage...`);
289
385
  yield saveValueInAsync(ASYNC_KEYS.REFERRER_LINK, link);
386
+ verboseLog(`Referrer link saved to AsyncStorage successfully`);
387
+ // Automatically fetch and store offer code for any affiliate identifier
388
+ verboseLog('Attempting to fetch offer code for stored affiliate identifier...');
389
+ yield retrieveAndStoreOfferCode(link);
290
390
  });
291
391
  }
292
392
  const validatePurchaseWithIapticAPI = (jsonIapPurchase, iapticAppId, iapticAppName, iapticPublicKey) => __awaiter(void 0, void 0, void 0, function* () {
@@ -350,23 +450,29 @@ const DeepLinkIapProvider = ({ children, }) => {
350
450
  }
351
451
  });
352
452
  const storeExpectedStoreTransaction = (purchaseToken) => __awaiter(void 0, void 0, void 0, function* () {
353
- if (!companyCode || (companyCode.trim() === '' && companyCode !== null)) {
453
+ verboseLog(`Storing expected store transaction with token: ${purchaseToken}`);
454
+ const activeCompanyCode = yield getActiveCompanyCode();
455
+ if (!activeCompanyCode) {
354
456
  console.error("[Insert Affiliate] Company code is not set. Please initialize the SDK with a valid company code.");
457
+ verboseLog("Cannot store transaction: no company code available");
355
458
  return;
356
459
  }
357
460
  const shortCode = yield returnInsertAffiliateIdentifier();
358
461
  if (!shortCode) {
359
462
  console.error("[Insert Affiliate] No affiliate identifier found. Please set one before tracking events.");
463
+ verboseLog("Cannot store transaction: no affiliate identifier available");
360
464
  return;
361
465
  }
466
+ verboseLog(`Company code: ${activeCompanyCode}, Short code: ${shortCode}`);
362
467
  // Build JSON payload
363
468
  const payload = {
364
469
  UUID: purchaseToken,
365
- companyCode,
470
+ companyCode: activeCompanyCode,
366
471
  shortCode,
367
472
  storedDate: new Date().toISOString(), // ISO8601 format
368
473
  };
369
474
  console.log("[Insert Affiliate] Storing expected transaction: ", payload);
475
+ verboseLog("Making API call to store expected transaction...");
370
476
  try {
371
477
  const response = yield fetch("https://api.insertaffiliate.com/v1/api/app-store-webhook/create-expected-transaction", {
372
478
  method: "POST",
@@ -375,53 +481,139 @@ const DeepLinkIapProvider = ({ children, }) => {
375
481
  },
376
482
  body: JSON.stringify(payload),
377
483
  });
484
+ verboseLog(`API response status: ${response.status}`);
378
485
  if (response.ok) {
379
486
  console.info("[Insert Affiliate] Expected transaction stored successfully.");
487
+ verboseLog("Expected transaction stored successfully on server");
380
488
  }
381
489
  else {
382
490
  const errorText = yield response.text();
383
491
  console.error(`[Insert Affiliate] Failed to store expected transaction with status code: ${response.status}. Response: ${errorText}`);
492
+ verboseLog(`API error response: ${errorText}`);
384
493
  }
385
494
  }
386
495
  catch (error) {
387
496
  console.error(`[Insert Affiliate] Error storing expected transaction: ${error}`);
497
+ verboseLog(`Network error storing transaction: ${error}`);
388
498
  }
389
499
  });
390
500
  // MARK: Track Event
391
501
  const trackEvent = (eventName) => __awaiter(void 0, void 0, void 0, function* () {
392
502
  try {
393
- if (!companyCode || (companyCode.trim() === '' && companyCode !== null)) {
503
+ verboseLog(`Tracking event: ${eventName}`);
504
+ const activeCompanyCode = yield getActiveCompanyCode();
505
+ if (!activeCompanyCode) {
394
506
  console.error("[Insert Affiliate] Company code is not set. Please initialize the SDK with a valid company code.");
507
+ verboseLog("Cannot track event: no company code available");
395
508
  return Promise.resolve();
396
509
  }
397
- console.log("track event called with - companyCode: ", companyCode);
510
+ console.log("track event called with - companyCode: ", activeCompanyCode);
398
511
  if (!referrerLink || !userId) {
399
512
  console.warn('[Insert Affiliate] No affiliate identifier found. Please set one before tracking events.');
513
+ verboseLog("Cannot track event: no affiliate identifier available");
400
514
  return Promise.resolve();
401
515
  }
516
+ const deepLinkParam = `${referrerLink}-${userId}`;
517
+ verboseLog(`Deep link param: ${deepLinkParam}`);
402
518
  const payload = {
403
519
  eventName,
404
- deepLinkParam: `${referrerLink}-${userId}`,
405
- companyId: companyCode,
520
+ deepLinkParam: deepLinkParam,
521
+ companyId: activeCompanyCode,
406
522
  };
523
+ verboseLog(`Track event payload: ${JSON.stringify(payload)}`);
524
+ verboseLog("Making API call to track event...");
407
525
  const response = yield axios_1.default.post('https://api.insertaffiliate.com/v1/trackEvent', payload, {
408
526
  headers: { 'Content-Type': 'application/json' },
409
527
  });
528
+ verboseLog(`Track event API response status: ${response.status}`);
410
529
  if (response.status === 200) {
411
530
  console.log('[Insert Affiliate] Event tracked successfully');
531
+ verboseLog("Event tracked successfully on server");
412
532
  }
413
533
  else {
414
534
  console.error(`[Insert Affiliate] Failed to track event with status code: ${response.status}`);
535
+ verboseLog(`Track event API error: status ${response.status}, response: ${JSON.stringify(response.data)}`);
415
536
  }
416
537
  }
417
538
  catch (error) {
418
539
  console.error('[Insert Affiliate] Error tracking event:', error);
540
+ verboseLog(`Network error tracking event: ${error}`);
419
541
  return Promise.reject(error);
420
542
  }
421
543
  });
544
+ const fetchOfferCode = (affiliateLink) => __awaiter(void 0, void 0, void 0, function* () {
545
+ try {
546
+ const activeCompanyCode = yield getActiveCompanyCode();
547
+ if (!activeCompanyCode) {
548
+ verboseLog('Cannot fetch offer code: no company code available');
549
+ return null;
550
+ }
551
+ const encodedAffiliateLink = encodeURIComponent(affiliateLink);
552
+ const url = `https://api.insertaffiliate.com/v1/affiliateReturnOfferCode/${activeCompanyCode}/${encodedAffiliateLink}`;
553
+ verboseLog(`Fetching offer code from: ${url}`);
554
+ const response = yield axios_1.default.get(url);
555
+ if (response.status === 200) {
556
+ const offerCode = response.data;
557
+ // Check for specific error strings from API
558
+ if (typeof offerCode === 'string' && (offerCode.includes("errorofferCodeNotFound") ||
559
+ offerCode.includes("errorAffiliateoffercodenotfoundinanycompany") ||
560
+ offerCode.includes("errorAffiliateoffercodenotfoundinanycompanyAffiliatelinkwas") ||
561
+ offerCode.includes("Routenotfound"))) {
562
+ console.warn(`[Insert Affiliate] Offer code not found or invalid: ${offerCode}`);
563
+ verboseLog(`Offer code not found or invalid: ${offerCode}`);
564
+ return null;
565
+ }
566
+ const cleanedOfferCode = cleanOfferCode(offerCode);
567
+ verboseLog(`Successfully fetched and cleaned offer code: ${cleanedOfferCode}`);
568
+ return cleanedOfferCode;
569
+ }
570
+ else {
571
+ console.error(`[Insert Affiliate] Failed to fetch offer code. Status code: ${response.status}, Response: ${JSON.stringify(response.data)}`);
572
+ verboseLog(`Failed to fetch offer code. Status code: ${response.status}, Response: ${JSON.stringify(response.data)}`);
573
+ return null;
574
+ }
575
+ }
576
+ catch (error) {
577
+ console.error('[Insert Affiliate] Error fetching offer code:', error);
578
+ verboseLog(`Error fetching offer code: ${error}`);
579
+ return null;
580
+ }
581
+ });
582
+ const retrieveAndStoreOfferCode = (affiliateLink) => __awaiter(void 0, void 0, void 0, function* () {
583
+ try {
584
+ verboseLog(`Attempting to retrieve and store offer code for: ${affiliateLink}`);
585
+ const offerCode = yield fetchOfferCode(affiliateLink);
586
+ if (offerCode && offerCode.length > 0) {
587
+ // Store in both AsyncStorage and state
588
+ yield saveValueInAsync(ASYNC_KEYS.IOS_OFFER_CODE, offerCode);
589
+ setIOSOfferCode(offerCode);
590
+ verboseLog(`Successfully stored offer code: ${offerCode}`);
591
+ console.log('[Insert Affiliate] Offer code retrieved and stored successfully');
592
+ }
593
+ else {
594
+ verboseLog('No valid offer code found to store');
595
+ // Clear stored offer code if none found
596
+ yield saveValueInAsync(ASYNC_KEYS.IOS_OFFER_CODE, '');
597
+ setIOSOfferCode(null);
598
+ }
599
+ }
600
+ catch (error) {
601
+ console.error('[Insert Affiliate] Error retrieving and storing offer code:', error);
602
+ verboseLog(`Error in retrieveAndStoreOfferCode: ${error}`);
603
+ }
604
+ });
605
+ const removeSpecialCharacters = (offerCode) => {
606
+ // Remove special characters, keep only alphanumeric and underscores
607
+ return offerCode.replace(/[^a-zA-Z0-9_]/g, '');
608
+ };
609
+ const cleanOfferCode = (offerCode) => {
610
+ // Remove special characters, keep only alphanumeric
611
+ return removeSpecialCharacters(offerCode);
612
+ };
422
613
  return (react_1.default.createElement(exports.DeepLinkIapContext.Provider, { value: {
423
614
  referrerLink,
424
615
  userId,
616
+ iOSOfferCode,
425
617
  setShortCode,
426
618
  returnInsertAffiliateIdentifier,
427
619
  storeExpectedStoreTransaction,
@@ -10,7 +10,8 @@ declare const useDeepLinkIapProvider: () => {
10
10
  trackEvent: (eventName: string) => Promise<void>;
11
11
  setShortCode: (shortCode: string) => Promise<void>;
12
12
  setInsertAffiliateIdentifier: (referringLink: string) => Promise<void | string>;
13
- initialize: (code: string | null) => Promise<void>;
13
+ initialize: (code: string | null, verboseLogging?: boolean) => Promise<void>;
14
14
  isInitialized: boolean;
15
+ iOSOfferCode: string | null;
15
16
  };
16
17
  export default useDeepLinkIapProvider;
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const react_1 = require("react");
4
4
  const DeepLinkIapProvider_1 = require("./DeepLinkIapProvider");
5
5
  const useDeepLinkIapProvider = () => {
6
- const { referrerLink, userId, validatePurchaseWithIapticAPI, storeExpectedStoreTransaction, returnUserAccountTokenAndStoreExpectedTransaction, returnInsertAffiliateIdentifier, trackEvent, setShortCode, setInsertAffiliateIdentifier, initialize, isInitialized } = (0, react_1.useContext)(DeepLinkIapProvider_1.DeepLinkIapContext);
6
+ const { referrerLink, userId, validatePurchaseWithIapticAPI, storeExpectedStoreTransaction, returnUserAccountTokenAndStoreExpectedTransaction, returnInsertAffiliateIdentifier, trackEvent, setShortCode, setInsertAffiliateIdentifier, initialize, isInitialized, iOSOfferCode, } = (0, react_1.useContext)(DeepLinkIapProvider_1.DeepLinkIapContext);
7
7
  return {
8
8
  referrerLink,
9
9
  userId,
@@ -15,7 +15,8 @@ const useDeepLinkIapProvider = () => {
15
15
  setShortCode,
16
16
  setInsertAffiliateIdentifier,
17
17
  initialize,
18
- isInitialized
18
+ isInitialized,
19
+ iOSOfferCode,
19
20
  };
20
21
  };
21
22
  exports.default = useDeepLinkIapProvider;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "insert-affiliate-react-native-sdk",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "A package for connecting with the Insert Affiliate Platform to add app based affiliate marketing.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",