insert-affiliate-react-native-sdk 1.1.3 → 1.1.6

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.
@@ -1,23 +1,24 @@
1
1
  import React from "react";
2
- import { Purchase, Subscription } from "react-native-iap";
3
2
  type T_DEEPLINK_IAP_PROVIDER = {
4
3
  children: React.ReactNode;
5
- iapSkus: string[];
6
4
  iapticAppId: string;
7
5
  iapticAppName: string;
8
6
  iapticPublicKey: string;
9
7
  };
8
+ type CustomPurchase = {
9
+ [key: string]: any;
10
+ };
10
11
  type T_DEEPLINK_IAP_CONTEXT = {
11
- iapLoading: boolean;
12
- alreadyPurchased: boolean;
13
- subscriptions: Subscription[];
14
- userPurchase: Purchase | null;
15
12
  referrerLink: string;
16
13
  userId: string;
17
- isIapticValidated: boolean | undefined;
18
- handleBuySubscription: (productId: string, offerToken?: string) => void;
14
+ returnInsertAffiliateIdentifier: () => Promise<string | null>;
15
+ handlePurchaseValidation: (jsonIapPurchase: CustomPurchase) => Promise<boolean>;
19
16
  trackEvent: (eventName: string) => Promise<void>;
17
+ setShortCode: (shortCode: string) => Promise<void>;
18
+ setInsertAffiliateIdentifier: (referringLink: string, completion: (shortLink: string | null) => void) => Promise<void>;
19
+ initialize: (code: string | null) => Promise<void>;
20
+ isInitialized: boolean;
20
21
  };
21
22
  export declare const DeepLinkIapContext: React.Context<T_DEEPLINK_IAP_CONTEXT>;
22
- declare const _default: (props: T_DEEPLINK_IAP_PROVIDER) => React.JSX.Element;
23
- export default _default;
23
+ declare const DeepLinkIapProvider: React.FC<T_DEEPLINK_IAP_PROVIDER>;
24
+ export default DeepLinkIapProvider;
@@ -37,9 +37,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
38
  exports.DeepLinkIapContext = void 0;
39
39
  const react_1 = __importStar(require("react"));
40
- const react_native_iap_1 = require("react-native-iap");
41
- const internal_1 = require("react-native-iap/src/internal");
42
- const react_native_branch_1 = __importDefault(require("react-native-branch"));
43
40
  const react_native_1 = require("react-native");
44
41
  const axios_1 = __importDefault(require("axios"));
45
42
  const async_storage_1 = __importDefault(require("@react-native-async-storage/async-storage"));
@@ -50,25 +47,41 @@ const ASYNC_KEYS = {
50
47
  };
51
48
  // STARTING CONTEXT IMPLEMENTATION
52
49
  exports.DeepLinkIapContext = (0, react_1.createContext)({
53
- iapLoading: false,
54
- alreadyPurchased: false,
55
- isIapticValidated: undefined,
56
- subscriptions: [],
57
- userPurchase: null,
58
50
  referrerLink: "",
59
51
  userId: "",
60
- handleBuySubscription: (productId, offerToken) => { },
52
+ returnInsertAffiliateIdentifier: () => __awaiter(void 0, void 0, void 0, function* () { return ""; }),
53
+ handlePurchaseValidation: (jsonIapPurchase) => __awaiter(void 0, void 0, void 0, function* () { return false; }),
61
54
  trackEvent: (eventName) => __awaiter(void 0, void 0, void 0, function* () { }),
55
+ setShortCode: (shortCode) => __awaiter(void 0, void 0, void 0, function* () { }),
56
+ setInsertAffiliateIdentifier: (referringLink, completion) => __awaiter(void 0, void 0, void 0, function* () { }),
57
+ initialize: (code) => __awaiter(void 0, void 0, void 0, function* () { }),
58
+ isInitialized: false
62
59
  });
63
- const DeepLinkIapProvider = ({ children, iapSkus, iapticAppId, iapticAppName, iapticPublicKey, }) => {
64
- // LOCAL STATES
65
- const [iapLoading, setIapLoading] = (0, react_1.useState)(false);
66
- const [alreadyPurchased, setAlreadyPurchased] = (0, react_1.useState)(false);
67
- const [isIapticValidated, setIapticValidated] = (0, react_1.useState)(undefined);
68
- const [userPurchase, setUserPurchase] = (0, react_1.useState)(null);
60
+ const DeepLinkIapProvider = ({ children, iapticAppId, iapticAppName, iapticPublicKey, }) => {
69
61
  const [referrerLink, setReferrerLink] = (0, react_1.useState)("");
70
62
  const [userId, setUserId] = (0, react_1.useState)("");
71
- const { connected, purchaseHistory, getPurchaseHistory, getSubscriptions, subscriptions, finishTransaction, currentPurchase, currentPurchaseError, } = (0, react_native_iap_1.useIAP)();
63
+ const [companyCode, setCompanyCode] = (0, react_1.useState)(null);
64
+ const [isInitialized, setIsInitialized] = (0, react_1.useState)(false);
65
+ const initialize = (code) => __awaiter(void 0, void 0, void 0, function* () {
66
+ if (isInitialized) {
67
+ console.error("[Insert Affiliate] SDK is already initialized.");
68
+ return;
69
+ }
70
+ if (code && code.trim() !== "") {
71
+ setCompanyCode(code);
72
+ setIsInitialized(true);
73
+ console.log(`[Insert Affiliate] SDK initialized with company code: ${code}`);
74
+ }
75
+ else {
76
+ console.warn("[Insert Affiliate] SDK initialized without a company code.");
77
+ setIsInitialized(true);
78
+ }
79
+ });
80
+ const reset = () => {
81
+ setCompanyCode(null);
82
+ setIsInitialized(false);
83
+ console.log("[Insert Affiliate] SDK has been reset.");
84
+ };
72
85
  // ASYNC FUNCTIONS
73
86
  const saveValueInAsync = (key, value) => __awaiter(void 0, void 0, void 0, function* () {
74
87
  yield async_storage_1.default.setItem(key, value);
@@ -112,6 +125,15 @@ const DeepLinkIapProvider = ({ children, iapSkus, iapticAppId, iapticAppName, ia
112
125
  break;
113
126
  }
114
127
  };
128
+ const returnInsertAffiliateIdentifier = () => __awaiter(void 0, void 0, void 0, function* () {
129
+ try {
130
+ return `${referrerLink}-${userId}`;
131
+ }
132
+ catch (error) {
133
+ errorLog(`ERROR ~ returnInsertAffiliateIdentifier: ${error}`);
134
+ return null;
135
+ }
136
+ });
115
137
  // GENERATING UNIQUE USER ID
116
138
  const generateUserID = () => {
117
139
  const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
@@ -122,82 +144,114 @@ const DeepLinkIapProvider = ({ children, iapSkus, iapticAppId, iapticAppName, ia
122
144
  }
123
145
  return uniqueId;
124
146
  };
125
- // BRANCH IMPLEMENTATION
126
- (0, react_1.useEffect)(() => {
127
- const branchSubscription = react_native_branch_1.default.subscribe((_a) => __awaiter(void 0, [_a], void 0, function* ({ error, params }) {
128
- if (error) {
129
- errorLog(`branchSubscription: ${JSON.stringify(error)}`, "error");
147
+ // Helper function to determine if a link is a short code
148
+ const isShortCode = (referringLink) => {
149
+ // Example check: short codes are less than 10 characters
150
+ return referringLink.length < 10;
151
+ };
152
+ const setInsertAffiliateIdentifier = (referringLink, completion) => __awaiter(void 0, void 0, void 0, function* () {
153
+ try {
154
+ setUserID();
155
+ if (!referringLink) {
156
+ console.warn("[Insert Affiliate] Referring link is invalid.");
157
+ storeInsertAffiliateIdentifier({ link: referringLink });
158
+ completion(null);
130
159
  return;
131
160
  }
132
- else if (!params) {
133
- errorLog(`branchSubscription: params does not exits`, "warn");
161
+ if (!isInitialized || !companyCode) {
162
+ console.error("[Insert Affiliate] SDK is not initialized. Please initialize the SDK with a valid company code.");
163
+ completion(null);
134
164
  return;
135
165
  }
136
- else if (!params["+clicked_branch_link"]) {
137
- errorLog(`branchSubscription: Not a branch link`, "warn");
166
+ if (!companyCode || companyCode.trim() === "") {
167
+ console.error("[Insert Affiliate] Company code is not set. Please initialize the SDK with a valid company code.");
168
+ completion(null);
138
169
  return;
139
170
  }
140
- else {
141
- if (params["~referring_link"]) {
142
- setReferrerLink(params["~referring_link"]);
143
- const userId = generateUserID();
144
- setUserId(userId);
145
- yield saveValueInAsync(ASYNC_KEYS.USER_ID, userId);
146
- yield saveValueInAsync(ASYNC_KEYS.REFERRER_LINK, params["~referring_link"]);
147
- }
148
- else
149
- errorLog(`branchSubscription: Params does't have referring_link`, "warn");
171
+ // Check if referring link is already a short code, if so save it and stop here.
172
+ if (isShortCode(referringLink)) {
173
+ console.log("[Insert Affiliate] Referring link is already a short code.");
174
+ storeInsertAffiliateIdentifier({ link: referringLink });
175
+ completion(referringLink);
176
+ return;
150
177
  }
151
- }));
152
- return () => {
153
- if (branchSubscription) {
154
- branchSubscription();
178
+ // 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
179
+ // Encode the referring link
180
+ const encodedAffiliateLink = encodeURIComponent(referringLink);
181
+ if (!encodedAffiliateLink) {
182
+ console.error("[Insert Affiliate] Failed to encode affiliate link.");
183
+ storeInsertAffiliateIdentifier({ link: referringLink });
184
+ completion(null);
185
+ return;
155
186
  }
156
- };
157
- }, []);
158
- // IN APP PURCHASE IMPLEMENTATION STARTS
159
- /**
160
- * This function is responsisble to
161
- * fetch the subscriptions
162
- */
163
- const handleGetSubscriptions = () => __awaiter(void 0, void 0, void 0, function* () {
164
- try {
165
- yield getSubscriptions({ skus: iapSkus });
166
- }
167
- catch (error) {
168
- errorLog(`handleGetSubscriptions: ${error}`, "error");
169
- }
170
- });
171
- /**
172
- * This function is responsible to
173
- * fetch the purchase history
174
- */
175
- const handleGetPurchaseHistory = () => __awaiter(void 0, void 0, void 0, function* () {
176
- try {
177
- yield getPurchaseHistory();
178
- if (purchaseHistory.length > 0) {
179
- setAlreadyPurchased(true);
180
- setUserPurchase(currentPurchase ? currentPurchase : null);
187
+ // Create the request URL
188
+ const urlString = `http://api.insertaffiliate.com/V1/convert-deep-link-to-short-link?companyId=${companyCode}&deepLinkUrl=${encodedAffiliateLink}`;
189
+ const response = yield axios_1.default.get(urlString, {
190
+ headers: {
191
+ "Content-Type": "application/json",
192
+ },
193
+ });
194
+ // Call to the backend for the short code and save the resolse in valid
195
+ if (response.status === 200 && response.data.shortLink) {
196
+ const shortLink = response.data.shortLink;
197
+ console.log("[Insert Affiliate] Short link received:", shortLink);
198
+ storeInsertAffiliateIdentifier({ link: shortLink });
199
+ completion(shortLink);
200
+ }
201
+ else {
202
+ console.warn("[Insert Affiliate] Unexpected response format.");
203
+ storeInsertAffiliateIdentifier({ link: referringLink });
204
+ completion(null);
181
205
  }
182
206
  }
183
207
  catch (error) {
184
- errorLog(`handleGetPurchaseHistory: ${error}`, "error");
208
+ console.error("[Insert Affiliate] Error:", error);
209
+ completion(null);
185
210
  }
186
211
  });
187
- // Effect to fetch IAP subscriptions + purchase history
188
- (0, react_1.useEffect)(() => {
189
- const fetchIapEssentials = () => __awaiter(void 0, void 0, void 0, function* () {
190
- try {
191
- yield handleGetSubscriptions();
192
- yield handleGetPurchaseHistory();
212
+ function setUserID() {
213
+ return __awaiter(this, void 0, void 0, function* () {
214
+ let userId = yield getValueFromAsync(ASYNC_KEYS.USER_ID);
215
+ if (!userId) {
216
+ userId = generateUserID();
217
+ yield saveValueInAsync(ASYNC_KEYS.USER_ID, userId);
218
+ setUserId(userId);
193
219
  }
194
- catch (error) {
195
- errorLog(`fetchIapEssentials: ${error}`);
220
+ });
221
+ }
222
+ function setShortCode(shortCode) {
223
+ return __awaiter(this, void 0, void 0, function* () {
224
+ setUserID();
225
+ // Capitalise the shortcode
226
+ const capitalisedShortCode = shortCode.toUpperCase();
227
+ // Ensure the short code is exactly 10 characters long
228
+ if (capitalisedShortCode.length !== 10) {
229
+ console.error("[Insert Affiliate] Error: Short code must be exactly 10 characters long.");
230
+ return;
231
+ }
232
+ // Check if the short code contains only letters and numbers
233
+ const isValidShortCode = /^[a-zA-Z0-9]+$/.test(capitalisedShortCode);
234
+ if (!isValidShortCode) {
235
+ console.error("[Insert Affiliate] Error: Short code must contain only letters and numbers.");
236
+ return;
237
+ }
238
+ // If all checks pass, set the Insert Affiliate Identifier
239
+ yield storeInsertAffiliateIdentifier({ link: capitalisedShortCode });
240
+ if (referrerLink) {
241
+ console.log(`[Insert Affiliate] Successfully set affiliate identifier: ${referrerLink}`);
196
242
  }
243
+ else {
244
+ console.error("[Insert Affiliate] Failed to set affiliate identifier.");
245
+ }
246
+ });
247
+ }
248
+ function storeInsertAffiliateIdentifier(_a) {
249
+ return __awaiter(this, arguments, void 0, function* ({ link }) {
250
+ console.log(`[Insert Affiliate] Storing affiliate identifier: ${link}`);
251
+ yield saveValueInAsync(ASYNC_KEYS.REFERRER_LINK, link);
252
+ setReferrerLink(link);
197
253
  });
198
- if (connected)
199
- fetchIapEssentials();
200
- }, [connected]);
254
+ }
201
255
  const handlePurchaseValidation = (jsonIapPurchase) => __awaiter(void 0, void 0, void 0, function* () {
202
256
  try {
203
257
  const baseRequestBody = {
@@ -225,7 +279,7 @@ const DeepLinkIapProvider = ({ children, iapSkus, iapticAppId, iapticAppName, ia
225
279
  const requestBody = Object.assign(Object.assign({}, baseRequestBody), { transaction });
226
280
  if (userId && referrerLink) {
227
281
  requestBody.additionalData = {
228
- applicationUsername: `${referrerLink}/${userId}`,
282
+ applicationUsername: `${referrerLink}-${userId}`,
229
283
  };
230
284
  }
231
285
  // Send validation request to server
@@ -240,11 +294,11 @@ const DeepLinkIapProvider = ({ children, iapSkus, iapticAppId, iapticAppName, ia
240
294
  });
241
295
  if (response.status === 200) {
242
296
  console.log("Validation successful:", response.data);
243
- setIapticValidated(true);
297
+ return true;
244
298
  }
245
299
  else {
246
300
  console.error("Validation failed:", response.data);
247
- setIapticValidated(false);
301
+ return false;
248
302
  }
249
303
  }
250
304
  catch (error) {
@@ -254,58 +308,7 @@ const DeepLinkIapProvider = ({ children, iapSkus, iapticAppId, iapticAppName, ia
254
308
  else {
255
309
  console.error(`handlePurchaseValidation Unknown Error: ${JSON.stringify(error)}`);
256
310
  }
257
- setIapticValidated(false);
258
- }
259
- });
260
- (0, react_1.useEffect)(() => {
261
- const checkCurrentPurchase = () => __awaiter(void 0, void 0, void 0, function* () {
262
- try {
263
- if (currentPurchase === null || currentPurchase === void 0 ? void 0 : currentPurchase.productId) {
264
- setUserPurchase(currentPurchase);
265
- yield handlePurchaseValidation(currentPurchase);
266
- yield finishTransaction({
267
- purchase: currentPurchase,
268
- isConsumable: true,
269
- });
270
- yield saveValueInAsync(ASYNC_KEYS.USER_PURCHASE, JSON.stringify(currentPurchase));
271
- setIapLoading(false);
272
- }
273
- }
274
- catch (error) {
275
- setIapLoading(false);
276
- errorLog(`checkCurrentPurchase: ${error}`, "error");
277
- }
278
- });
279
- checkCurrentPurchase();
280
- }, [currentPurchase, finishTransaction]);
281
- (0, react_1.useEffect)(() => {
282
- const checkCurrentPurchaseError = () => __awaiter(void 0, void 0, void 0, function* () {
283
- if (currentPurchaseError) {
284
- setIapLoading(false);
285
- errorLog(`checkCurrentPurchaseError: ${currentPurchaseError.message}`, "error");
286
- }
287
- });
288
- checkCurrentPurchaseError();
289
- }, [currentPurchaseError]);
290
- /**
291
- * Function is responsible to
292
- * buy a subscription
293
- * @param {string} productId
294
- * @param {string} [offerToken]
295
- */
296
- const handleBuySubscription = (productId, offerToken) => __awaiter(void 0, void 0, void 0, function* () {
297
- if (internal_1.isPlay && !offerToken) {
298
- console.warn(`There are no subscription Offers for selected product (Only requiered for Google Play purchases): ${productId}`);
299
- }
300
- try {
301
- setIapLoading(true);
302
- yield (0, react_native_iap_1.requestSubscription)(Object.assign({ sku: productId }, (offerToken && {
303
- subscriptionOffers: [{ sku: productId, offerToken }],
304
- })));
305
- }
306
- catch (error) {
307
- setIapLoading(false);
308
- errorLog(`handleBuySubscription: ${error}`, "error");
311
+ return false;
309
312
  }
310
313
  });
311
314
  const trackEvent = (eventName) => __awaiter(void 0, void 0, void 0, function* () {
@@ -316,7 +319,7 @@ const DeepLinkIapProvider = ({ children, iapSkus, iapticAppId, iapticAppName, ia
316
319
  }
317
320
  const payload = {
318
321
  eventName,
319
- deepLinkParam: `${referrerLink}/${userId}`, // Similar to Swift SDK
322
+ deepLinkParam: `${referrerLink}/${userId}`,
320
323
  };
321
324
  const response = yield axios_1.default.post("https://api.insertaffiliate.com/v1/trackEvent", payload, {
322
325
  headers: { "Content-Type": "application/json" },
@@ -333,21 +336,16 @@ const DeepLinkIapProvider = ({ children, iapSkus, iapticAppId, iapticAppName, ia
333
336
  return Promise.reject(error);
334
337
  }
335
338
  });
336
- (0, react_1.useEffect)(() => {
337
- return () => {
338
- (0, react_native_iap_1.endConnection)();
339
- };
340
- }, []);
341
339
  return (react_1.default.createElement(exports.DeepLinkIapContext.Provider, { value: {
342
- iapLoading,
343
- alreadyPurchased,
344
- isIapticValidated,
345
- subscriptions,
346
- userPurchase,
347
340
  referrerLink,
348
341
  userId,
349
- handleBuySubscription,
342
+ setShortCode,
343
+ returnInsertAffiliateIdentifier,
344
+ handlePurchaseValidation,
350
345
  trackEvent,
346
+ setInsertAffiliateIdentifier,
347
+ initialize,
348
+ isInitialized
351
349
  } }, children));
352
350
  };
353
- exports.default = (0, react_native_iap_1.withIAPContext)(DeepLinkIapProvider);
351
+ exports.default = DeepLinkIapProvider;
@@ -1,12 +1,14 @@
1
1
  declare const useDeepLinkIapProvider: () => {
2
- alreadyPurchased: boolean;
3
- handleBuySubscription: (productId: string, offerToken?: string) => void;
4
- iapLoading: boolean;
5
2
  referrerLink: string;
6
- subscriptions: import("react-native-iap").Subscription[];
7
3
  userId: string;
8
- isIapticValidated: boolean | undefined;
9
- userPurchase: import("react-native-iap").Purchase | null;
4
+ handlePurchaseValidation: (jsonIapPurchase: {
5
+ [key: string]: any;
6
+ }) => Promise<boolean>;
7
+ returnInsertAffiliateIdentifier: () => Promise<string | null>;
10
8
  trackEvent: (eventName: string) => Promise<void>;
9
+ setShortCode: (shortCode: string) => Promise<void>;
10
+ setInsertAffiliateIdentifier: (referringLink: string, completion: (shortLink: string | null) => void) => Promise<void>;
11
+ initialize: (code: string | null) => Promise<void>;
12
+ isInitialized: boolean;
11
13
  };
12
14
  export default useDeepLinkIapProvider;
@@ -3,17 +3,17 @@ 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 { alreadyPurchased, handleBuySubscription, iapLoading, referrerLink, isIapticValidated, subscriptions, userId, userPurchase, trackEvent, } = (0, react_1.useContext)(DeepLinkIapProvider_1.DeepLinkIapContext);
6
+ const { referrerLink, userId, handlePurchaseValidation, returnInsertAffiliateIdentifier, trackEvent, setShortCode, setInsertAffiliateIdentifier, initialize, isInitialized } = (0, react_1.useContext)(DeepLinkIapProvider_1.DeepLinkIapContext);
7
7
  return {
8
- alreadyPurchased,
9
- handleBuySubscription,
10
- iapLoading,
11
8
  referrerLink,
12
- subscriptions,
13
9
  userId,
14
- isIapticValidated,
15
- userPurchase,
16
- trackEvent
10
+ handlePurchaseValidation,
11
+ returnInsertAffiliateIdentifier,
12
+ trackEvent,
13
+ setShortCode,
14
+ setInsertAffiliateIdentifier,
15
+ initialize,
16
+ isInitialized
17
17
  };
18
18
  };
19
19
  exports.default = useDeepLinkIapProvider;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "insert-affiliate-react-native-sdk",
3
- "version": "1.1.3",
3
+ "version": "1.1.6",
4
4
  "description": "A package that will give context having implementation of react-native-branch and react-native-iap and iaptic validate api.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",