insert-affiliate-js-sdk 1.0.2 → 1.1.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.
package/README.md CHANGED
@@ -52,11 +52,56 @@ await InsertAffiliate.initialize("your_company_code");
52
52
  ```
53
53
  - Replace `{{ your_company_code }}` with the unique company code associated with your Insert Affiliate account. You can find this code in your dashboard under [Settings](http://app.insertaffiliate.com/settings).
54
54
 
55
+ ### Verbose Logging (Optional)
56
+
57
+ By default, the SDK operates with minimal logging to avoid cluttering the console. However, you can enable verbose logging to see detailed information about SDK operations. This is particularly useful for debugging during development or testing.
58
+
59
+ #### Enable Verbose Logging
60
+
61
+ ```javascript
62
+ import { InsertAffiliate } from 'insert-affiliate-js-sdk';
63
+
64
+ // Enable verbose logging (second parameter)
65
+ await InsertAffiliate.initialize("your_company_code", true);
66
+ ```
67
+
68
+ **When verbose logging is enabled, you'll see detailed logs with the `[Insert Affiliate] [VERBOSE]` prefix that show:**
69
+
70
+ - **Initialization Process**: SDK startup, company code validation, storage operations
71
+ - **Data Management**: User ID generation, referrer link storage, company code state management
72
+ - **Deep Link Processing**: Input validation, short code detection, API conversion process
73
+ - **API Communication**: Request/response details for all server calls
74
+ - **Event Tracking**: Event parameters, payload construction, success/failure status
75
+ - **Purchase Operations**: Transaction storage, token validation, webhook processing
76
+
77
+ **Example verbose output:**
78
+ ```
79
+ [Insert Affiliate] [VERBOSE] Starting SDK initialization...
80
+ [Insert Affiliate] [VERBOSE] Company code provided: Yes
81
+ [Insert Affiliate] [VERBOSE] Verbose logging enabled
82
+ [Insert Affiliate] SDK initialized with company code: your-company-code
83
+ [Insert Affiliate] [VERBOSE] Company code saved to storage
84
+ [Insert Affiliate] [VERBOSE] SDK marked as initialized
85
+ ```
86
+
87
+ **Benefits of verbose logging:**
88
+ - **Debug Deep Linking Issues**: See exactly what links are being processed and how they're converted
89
+ - **Monitor API Communication**: Track all server requests, responses, and error details
90
+ - **Identify Storage Problems**: Understand storage read/write operations and state management
91
+ - **Performance Insights**: Monitor async operation timing and identify bottlenecks
92
+ - **Integration Troubleshooting**: Quickly identify configuration or setup issues
93
+
94
+ ⚠️ **Important**: Disable verbose logging in production builds to avoid exposing sensitive debugging information and to optimize performance.
95
+
55
96
  ## In-App Purchase Setup [Required]
56
- Insert Affiliate requires a Receipt Verification platform to validate in-app purchases. You must choose **one** of our supported partners:
57
- - [RevenueCat](https://www.revenuecat.com/)
58
97
 
59
- ### Option 1: RevenueCat Integration
98
+ Insert Affiliate requires a receipt verification platform to validate purchases. Choose the integration method(s) that match your platform:
99
+
100
+ - **Mobile In-App Purchases (iOS/Android) or RevenueCat Web Payments**: Use [RevenueCat](https://www.revenuecat.com/)
101
+ - **Web-Based Payments**: Use [Stripe](https://stripe.com/)
102
+ - **Hybrid Apps**: If your app supports both native mobile purchases AND web payments, set up both integrations
103
+
104
+ ### Mobile In-App Purchases: RevenueCat Integration
60
105
 
61
106
  #### Code Setup
62
107
  1. **Install RevenueCat SDK** - First, complete the set up of the relevant [RevenueCat SDK](https://www.revenuecat.com/docs/getting-started/installation) to set up in-app purchases and subscriptions.
@@ -100,44 +145,391 @@ Next, you must setup a webhook to allow us to communicate directly with RevenueC
100
145
  - Copy this value
101
146
  - Paste it as the Authorization header value in your RevenueCat webhook configuration
102
147
 
148
+ ## Web-Based Payments: Stripe Integration
149
+
150
+ For web-based subscriptions and payments using Stripe, you'll need to connect your Stripe account and pass the Insert Affiliate identifier and company ID to Stripe's metadata during checkout.
151
+
152
+ **📚 For complete setup instructions, see: [Stripe Web-Based Transactions Documentation](https://docs.insertaffiliate.com/stripe-web-based-transactions)**
153
+
154
+ #### Setup Steps
155
+
156
+ 1. **Connect Your Stripe Account (Required First Step)**
157
+
158
+ Before integrating the SDK code, you must connect your Stripe account to Insert Affiliate:
159
+
160
+ - Go to your [Insert Affiliate dashboard settings](https://app.insertaffiliate.com/settings)
161
+ - Navigate to the payment verification settings
162
+ - Select **Stripe** as your verification method
163
+ - Click **Connect with Stripe** to authorize the connection via Stripe Connect
164
+ - Once connected, Insert Affiliate will automatically receive your Stripe events
165
+
166
+ 2. **Retrieve the Affiliate Identifier and Company ID**
167
+
168
+ Before creating a Stripe checkout session, retrieve the current affiliate identifier and company ID from the Insert Affiliate SDK:
169
+
170
+ ```javascript
171
+ import { InsertAffiliate } from 'insert-affiliate-js-sdk';
172
+
173
+ const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
174
+ const companyId = await InsertAffiliate.returnCompanyId();
175
+ ```
176
+
177
+ 3. **Pass to Your Backend**
178
+
179
+ When calling your backend to create a Stripe checkout session, include both the affiliate identifier and company ID:
180
+
181
+ ```javascript
182
+ const response = await fetch('https://your-backend.com/create-checkout-session', {
183
+ method: 'POST',
184
+ headers: {
185
+ 'Content-Type': 'application/json',
186
+ },
187
+ body: JSON.stringify({
188
+ priceId: 'price_xxxxx',
189
+ insertAffiliate: affiliateId,
190
+ insertAffiliateCompanyId: companyId,
191
+ successUrl: window.location.origin + '/success',
192
+ cancelUrl: window.location.origin + '/canceled',
193
+ }),
194
+ });
195
+ ```
196
+
197
+ 4. **Store in Stripe Metadata (Backend)**
198
+
199
+ In your backend, when creating the Stripe checkout session, store both the affiliate identifier and company ID in the session metadata and subscription metadata:
200
+
201
+ ```javascript
202
+ const stripe = require('stripe')('sk_test_xxxxx');
203
+
204
+ app.post('/create-checkout-session', async (req, res) => {
205
+ const { priceId, insertAffiliate, insertAffiliateCompanyId, successUrl, cancelUrl } = req.body;
206
+
207
+ const session = await stripe.checkout.sessions.create({
208
+ mode: 'subscription',
209
+ line_items: [{
210
+ price: priceId,
211
+ quantity: 1,
212
+ }],
213
+ metadata: {
214
+ insertAffiliate: insertAffiliate || '',
215
+ insertAffiliateCompanyId: insertAffiliateCompanyId || '',
216
+ },
217
+ subscription_data: {
218
+ metadata: {
219
+ insertAffiliate: insertAffiliate || '',
220
+ insertAffiliateCompanyId: insertAffiliateCompanyId || '',
221
+ },
222
+ },
223
+ success_url: successUrl,
224
+ cancel_url: cancelUrl,
225
+ });
226
+
227
+ res.json({ sessionId: session.id });
228
+ });
229
+ ```
230
+
231
+ **Required Metadata Fields:**
232
+ - `insertAffiliate`: The affiliate's short code
233
+ - `insertAffiliateCompanyId`: Your Insert Affiliate company ID
234
+
235
+ Both fields are required for proper affiliate attribution and commission tracking. Once you've connected your Stripe account via Stripe Connect (Step 1), Insert Affiliate will automatically receive all Stripe events and read these metadata fields to credit affiliates.
236
+
237
+ ### Stripe Billing with RevenueCat
238
+
239
+ If you're using RevenueCat's [Stripe Billing](https://www.revenuecat.com/docs/web/integrations/stripe), you can track affiliate conversions through Insert Affiliate while using RevenueCat for subscription management.
240
+
241
+ **Prerequisites:**
242
+ - You must host your own web checkout page where Stripe Checkout is embedded (Insert Affiliate SDK needs to run on your page)
243
+ - Follow RevenueCat's [Stripe integration guide](https://www.revenuecat.com/docs/web/integrations/stripe) to set up the RevenueCat-Stripe connection
244
+
245
+ **Integration:**
246
+
247
+ Simply follow the same **[Stripe Integration steps above](#web-based-payments-stripe-integration)**, which includes:
248
+ 1. Connecting your Stripe account via Stripe Connect in the Insert Affiliate dashboard
249
+ 2. Installing the SDK on your checkout page
250
+ 3. Passing the affiliate metadata to Stripe
251
+
252
+ That's it! Since you've connected your Stripe account via Stripe Connect, Insert Affiliate will automatically receive all Stripe events. RevenueCat handles subscription management, while Insert Affiliate handles affiliate attribution through the Stripe metadata.
253
+
254
+ ### RevenueCat Web Billing Integration
255
+
256
+ If you're using [RevenueCat's Web SDK with Web Billing](https://www.revenuecat.com/docs/web/web-billing/overview), you can track affiliate conversions by passing UTM parameters as purchase metadata.
257
+
258
+ **Prerequisites:**
259
+ - RevenueCat Web SDK installed and configured
260
+ - RevenueCat Web Billing set up with Stripe
261
+ - Insert Affiliate SDK initialized on your page
262
+ - Connecting your Stripe account via Stripe Connect in the Insert Affiliate dashboard as described [above](#web-based-payments-stripe-integration)
263
+
264
+ **Integration Steps:**
265
+
266
+ 1. **Install and Initialize Both SDKs**
267
+
268
+ ```javascript
269
+ import { InsertAffiliate } from 'insert-affiliate-js-sdk';
270
+ import { Purchases } from '@revenuecat/purchases-js';
271
+
272
+ // Initialize Insert Affiliate SDK
273
+ await InsertAffiliate.initialize('your_company_code');
274
+
275
+ // Initialize RevenueCat Web SDK
276
+ const purchases = Purchases.configure('your_revenuecat_web_api_key');
277
+ ```
278
+
279
+ 2. **Retrieve Affiliate Information and Pass as Metadata During Purchase**
280
+
281
+ Before making a purchase, retrieve the current affiliate identifier and company ID from the Insert Affiliate SDK, then pass them as UTM parameters in the RevenueCat purchase metadata:
282
+
283
+ ```javascript
284
+ // Get the current affiliate identifier and company ID
285
+ // Use ignoreTimeout: true to get the identifier even if attribution window expired
286
+ const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier(true);
287
+ const companyId = await InsertAffiliate.returnCompanyId();
288
+
289
+ console.log('Affiliate ID:', affiliateId || 'none');
290
+ console.log('Company ID:', companyId || 'none');
291
+
292
+ // Prepare metadata with UTM parameters for RevenueCat Web Billing
293
+ const metadata: Record<string, string> = {};
294
+
295
+ if (affiliateId && affiliateId !== 'none') {
296
+ metadata.utm_source = 'insertAffiliate';
297
+ metadata.utm_medium = companyId || 'none';
298
+ metadata.utm_campaign = affiliateId;
299
+ }
300
+
301
+ console.log('Purchase metadata:', JSON.stringify(metadata, null, 2));
302
+
303
+ // Get offerings and select a package
304
+ const offerings = await purchases.getOfferings();
305
+ const selectedPackage = offerings.current?.availablePackages[0];
306
+
307
+ if (!selectedPackage) {
308
+ console.error('No packages available');
309
+ return;
310
+ }
311
+
312
+ // Make the purchase with metadata
313
+ const { customerInfo } = await purchases.purchase({
314
+ rcPackage: selectedPackage,
315
+ metadata: metadata,
316
+ });
317
+
318
+ console.log('Purchase successful!');
319
+ console.log('Active entitlements:', Object.keys(customerInfo.entitlements.active));
320
+ ```
321
+
322
+ **Important Notes:**
323
+ - Always call `returnInsertAffiliateIdentifier()` and `returnCompanyId()` **before** initiating the purchase
324
+ - Only include UTM parameters in metadata if an affiliate identifier exists
325
+ - The metadata will be sent with the purchase and available in RevenueCat webhook events
326
+
327
+
328
+ **UTM Parameter Mapping:**
329
+ - `utm_source`: Always set to `'insertAffiliate'` to identify Insert Affiliate conversions
330
+ - `utm_medium`: Your Insert Affiliate company ID
331
+ - `utm_campaign`: The affiliate's identifier
332
+
333
+ ## RevenueCat Web Purchase Links
334
+
335
+ If you are using [**RevenueCat Web Purchase Links**](https://www.revenuecat.com/docs/web/web-billing/web-purchase-links) for online campaigns (such as email marketing, social media, or affiliate promotions), you must append the following UTM parameters to ensure proper affiliate tracking:
336
+
337
+ - **utm_source**
338
+ - **utm_medium**
339
+ - **utm_campaign**
340
+
341
+ These parameters allow Insert Affiliate to track and attribute web-based purchases correctly.
342
+
343
+ ### Example
344
+
345
+ If your RevenueCat Web Purchase Link is:
346
+
347
+ ```text
348
+ https://pay.rev.cat/sandbox/viqxbcoudyfaeaae/
349
+ ```
350
+
351
+ You should append:
352
+ ```text
353
+ ?utm_source=insertAffiliate&utm_medium={insertAffiliateCompanyId}&utm_campaign={insertAffiliateUtmCampaign}
354
+ ```
355
+
356
+ #### Full Example With Parameters
357
+ ```text
358
+ https://pay.rev.cat/sandbox/viqxbcoudyfaeaxa/?utm_source=insertAffiliate&utm_medium=12345&utm_campaign=AFF123
359
+ ```
360
+
361
+ Where:
362
+ - utm_source=insertAffiliate
363
+ - utm_medium={insertAffiliateCompanyId} → your unique Insert Affiliate company ID
364
+ - utm_campaign={insertAffiliateShortCode} → the affiliate’s short code
365
+
366
+ Once the user opens this URL, the Insert Affiliate SDK automatically processes the UTM parameters and attributes the resulting purchase to the correct affiliate.
367
+
368
+ ## Configuring Deep Links for Web-Based Payments
369
+ Use this section to configure Branch.io, AppsFlyer, or Insert Links so that your deep links correctly pass the insertAffiliate parameter to your web checkout.
370
+
371
+ ### Branch.io – Web Redirect Setup
372
+
373
+ Use these steps if you're using [Branch.io](https://docs.insertaffiliate.com/branch) Quick Links to send users to your web-hosted payment page.
374
+
375
+ ### Creating a Branch.io Quick Link for Stripe Checkout:
376
+
377
+ 1. **Create a new Quick Link** in your Branch.io dashboard
378
+ 2. Go to the **Redirects** section.
379
+ 3. **Select "Web URL"** as the redirect destination
380
+ 4. **Configure the URL** to point to your web app hosting the Stripe payment form:
381
+ - Enter your web app's URL
382
+ - Append the parameter: `?insertAffiliate={affiliateShortCode}`
383
+ - Replace `{affiliateShortCode}` with the actual [short code](https://docs.insertaffiliate.com/short-codes) of the affiliate you're creating the link for
384
+
385
+ **Example:**
386
+ ```
387
+ https://yourwebsite.com?insertAffiliate=ABC123
388
+ ```
389
+
390
+ Once the user arrives on your site, the Insert Affiliate SDK automatically detects insertAffiliate and attributes the payment.
391
+
392
+ For more details, see the [Short Codes documentation](https://docs.insertaffiliate.com/short-codes).
393
+
394
+ ### AppsFlyer – Web Redirect Setup
395
+
396
+ Use these steps if you're using [AppsFlyer](https://docs.insertaffiliate.com/appsflyer) OneLinks to send users to your Stripe or RevenueCat web checkout flow.
397
+
398
+ ### Creating an AppsFlyer OneLink for Stripe Checkout
399
+ 1. **Create a new OneLink** in your AppsFlyer dashboard
400
+ 2. Open the link configuration settings
401
+ 3. Under **"When link is clicked on desktop web page"**, set the redirect URL
402
+ 4. Enter your web app’s checkout URL.
403
+ 5. Append the parameter: `?insertAffiliate={affiliateShortCode}`
404
+ - Replace `{affiliateShortCode}` with the actual [short code](https://docs.insertaffiliate.com/short-codes) of the affiliate you're creating the link for
405
+
406
+ **Example:**
407
+ ```
408
+ https://yourwebsite.com?insertAffiliate=ABC123
409
+ ```
410
+
411
+ The Insert Affiliate SDK will automatically detect the parameter and attribute the resulting payment.
412
+
413
+ For more details, see the [Short Codes documentation](https://docs.insertaffiliate.com/short-codes).
414
+
415
+ ### Insert Links – Web Automatic Configuration
416
+
417
+ If you're using [**Insert Links**](https://docs.insertaffiliate.com/insert-links) (Insert Affiliate’s built-in deep linking solution), you don’t need to configure anything for web payments.
418
+
419
+ Insert Links automatically:
420
+ 1. Adds the `insertAffiliate` parameter
421
+ 2. Detects and processes attribution in your web app
422
+ 3. Tracks the payment to the correct affiliate
103
423
 
104
- ## Deep Link Setup [Required]
105
- Insert Affiliate requires a Deep Linking platform to create links for your affiliates. Our platform works with **any** deep linking provider, and you only need to follow these steps:
106
- 1. **Create a deep link** in your chosen third-party platform and pass it to our dashboard when an affiliate signs up.
107
- 2. **Handle deep link clicks** in your app by passing the clicked link:
108
- ```javascript
109
- InsertAffiliate.setInsertAffiliateIdentifier(data["~referring_link"]);
110
- ```
424
+ No extra setup, no redirects to configure — just initialise the SDK and you're done.
111
425
 
112
- ### Deep Linking with Branch.io
113
- To set up deep linking with Branch.io, follow these steps:
426
+ Learn more in our[Insert Links documentation](https://docs.insertaffiliate.com/insert-links).
114
427
 
115
- 1. Create a deep link in Branch and pass it to our dashboard when an affiliate signs up.
116
- - Example: [Create Affiliate](https://docs.insertaffiliate.com/create-affiliate).
117
- 2. Modify Your Deep Link Handling
118
- - After setting up your Branch integration, add the following code to initialise the Insert Affiliate SDK in your iOS app:
428
+ ## Using the Callback for Automatic Integration
119
429
 
430
+ The SDK provides a callback that fires whenever the affiliate identifier changes.
431
+ This makes it easy to automatically update your UI, analytics, or checkout flow.
432
+
433
+ #### Example: Storing Affiliate Identifier for Checkout
434
+
435
+ ```javascript
436
+ import { InsertAffiliate } from 'insert-affiliate-js-sdk';
437
+
438
+ // Track the current affiliate identifier
439
+ let currentAffiliateId = null;
440
+
441
+ InsertAffiliate.setInsertAffiliateIdentifierChangeCallback((identifier) => {
442
+ if (identifier) {
443
+ console.log('Affiliate identifier changed:', identifier);
444
+ currentAffiliateId = identifier;
445
+ }
446
+ });
447
+
448
+ // Later, when creating a Stripe checkout session
449
+ const companyId = await InsertAffiliate.returnCompanyId();
450
+
451
+ const response = await fetch('https://your-backend.com/create-checkout-session', {
452
+ method: 'POST',
453
+ headers: { 'Content-Type': 'application/json' },
454
+ body: JSON.stringify({
455
+ priceId: 'price_xxxxx',
456
+ insertAffiliate: currentAffiliateId,
457
+ insertAffiliateCompanyId: companyId,
458
+ successUrl: window.location.origin + '/success',
459
+ cancelUrl: window.location.origin + '/canceled',
460
+ }),
461
+ });
462
+ ```
463
+
464
+ #### Example: Updating the UI When an Affiliate Link Is Clicked
465
+
466
+ ```javascript
467
+ import { InsertAffiliate } from 'insert-affiliate-js-sdk';
468
+
469
+ // Update the UI when the affiliate identifier changes
470
+ InsertAffiliate.setInsertAffiliateIdentifierChangeCallback((identifier) => {
471
+ if (identifier) {
472
+ console.log('Affiliate identifier changed:', identifier);
473
+
474
+ const banner = document.getElementById('affiliate-banner');
475
+ if (banner) {
476
+ banner.textContent = 'You used a special affiliate link!';
477
+ banner.style.display = 'block';
478
+ }
479
+
480
+ analytics.track('affiliate_link_clicked', { identifier });
481
+ }
482
+ });
483
+ ```
484
+
485
+ **Benefits of using the callback:**
486
+ - Automatically captures affiliate identifiers
487
+ - No need for manual checks
488
+ - Ensures attribution is always up-to-date
489
+ - Perfect for handling dynamic user flows
490
+ - Enables custom UI updates and analytics events
491
+
492
+ **To clear the callback:**
493
+ ```javascript
494
+ InsertAffiliate.setInsertAffiliateIdentifierChangeCallback(null);
495
+ ```
496
+
497
+ ## Capacitor/Hybrid App Deep Link Handling
498
+
499
+ If your app uses Branch.io via Capacitor, you may want to manually capture the referring link.
500
+ Here’s an example using the Branch.io Capacitor Plugin:
501
+
502
+ #### Example with Branch.io Capacitor Plugin
120
503
 
121
504
  ```javascript
122
505
  import { BranchDeepLinks, BranchInitEvent } from 'capacitor-branch-deep-links';
123
506
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
124
507
 
508
+ // Set up callback to automatically capture affiliate identifier when user clicks a link
509
+ InsertAffiliate.setInsertAffiliateIdentifierChangeCallback((identifier) => {
510
+ if (identifier) {
511
+ console.log('Affiliate identifier changed:', identifier);
512
+ console.log('Affiliate attribution captured successfully');
513
+ }
514
+ });
515
+
125
516
  let branchInitialised = false;
126
517
 
127
518
  async function setUpBranchListener() {
128
519
  if (branchInitialised) return;
129
520
  branchInitialised = true;
130
-
521
+
131
522
  try {
132
523
  await BranchDeepLinks.addListener('init', async (event: BranchInitEvent) => {
133
524
  const clicked = event?.referringParams?.['+clicked_branch_link'];
134
525
  const referringLink = event?.referringParams?.['~referring_link'];
135
-
526
+
136
527
  if (clicked && referringLink) {
528
+ // This will automatically trigger the callback
137
529
  await InsertAffiliate.setInsertAffiliateIdentifier(referringLink);
138
530
  }
139
531
  });
140
-
532
+
141
533
  BranchDeepLinks.addListener('initError', (error: any) => {
142
534
  console.error('Branch init error:', error);
143
535
  });
@@ -145,9 +537,10 @@ async function setUpBranchListener() {
145
537
  console.error('Error setting up Branch listener:', err);
146
538
  }
147
539
  }
148
-
149
540
  ```
150
541
 
542
+ **Note:** For most web applications, the automatic URL detection method is recommended and requires no additional setup.
543
+
151
544
  ## Additional Features
152
545
 
153
546
  ### 1. Event Tracking (Beta)
@@ -185,24 +578,201 @@ Short codes are unique, 3 to 25 character alphanumeric identifiers that affiliat
185
578
 
186
579
  For more information, visit the [Insert Affiliate Short Codes Documentation](https://docs.insertaffiliate.com/short-codes).
187
580
 
581
+ ### Getting Affiliate Details
582
+
583
+ You can retrieve detailed information about an affiliate by their short code or deep link using the `getAffiliateDetails` method. This is useful for displaying affiliate information to users or showing personalized content based on the referrer.
584
+
585
+ **Return Value:** Returns a `Promise<AffiliateDetails | null>`:
586
+ - `affiliateName`: The name of the affiliate
587
+ - `affiliateShortCode`: The affiliate's short code
588
+ - `deeplinkUrl`: The affiliate's deep link URL
589
+
590
+ Returns `null` if:
591
+ - The affiliate code doesn't exist
592
+ - The company code is not initialized
593
+ - There's a network error or API issue
594
+
595
+ **Important Notes:**
596
+ - This method **does not store or set** the affiliate identifier - it only retrieves information
597
+ - Use `setShortCode()` to actually associate an affiliate with a user
598
+ - The method automatically strips UUIDs from codes (e.g., "ABC123-uuid" becomes "ABC123")
599
+ - Works with both short codes and deep link URLs
600
+
601
+ #### Example Usage
602
+
603
+ ```javascript
604
+ import { InsertAffiliate } from 'insert-affiliate-js-sdk';
605
+
606
+ // Get affiliate details for a specific code
607
+ const details = await InsertAffiliate.getAffiliateDetails('JOIN123');
608
+
609
+ if (details) {
610
+ console.log(`Affiliate Name: ${details.affiliateName}`);
611
+ console.log(`Short Code: ${details.affiliateShortCode}`);
612
+ console.log(`Deep Link: ${details.deeplinkUrl}`);
613
+
614
+ // Update UI with affiliate name
615
+ document.getElementById('referrer').textContent = `Referred by: ${details.affiliateName}`;
616
+ } else {
617
+ console.log('Affiliate not found');
618
+ }
619
+ ```
620
+
188
621
  ### Setting a Short Code
189
622
 
190
- Use the `setShortCode` method to associate a short code with an affiliate. This is ideal for scenarios where users enter the code via an input field, pop-up, or similar UI element.
623
+ Use the `setShortCode` method to validate and associate a short code with an affiliate. This is ideal for scenarios where users enter the code via an input field, pop-up, or similar UI element.
624
+
625
+ **Return Value:** Returns a `Promise<boolean>`:
626
+ - Returns **`true`** if the short code exists and was successfully validated and stored
627
+ - Returns **`false`** if the short code does not exist or validation failed
628
+
629
+ This allows you to provide immediate feedback to users about whether their entered code is valid.
191
630
 
192
- Short codes must meet the following criteria:
193
- - Between **3 and 25 characters long**.
194
- - Contain only **letters and numbers** (alphanumeric characters).
195
- - Replace {{ user_entered_short_code }} with the short code the user enters through your chosen input method, i.e. an input field / pop up element
631
+ **Short Code Requirements:**
632
+ - Between **3 and 25 characters long**
633
+ - Contain only **letters and numbers** (alphanumeric characters)
196
634
 
635
+ **Important Notes:**
636
+ - The method validates the short code against the Insert Affiliate API before storing it
637
+ - Validation checks both format (length, alphanumeric) and existence in your affiliate database
638
+ - Short codes are automatically converted to uppercase
639
+ - Use the return value to show success/error messages to your users
197
640
 
198
- #### Example Integration
199
- Below is an example SwiftUI implementation where users can enter a short code, which will be validated and associated with the affiliate's account:
641
+ #### Basic Usage
200
642
 
201
643
  ```javascript
202
644
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
203
645
 
204
- // Example: user entered this in a form
205
- const userEnteredCode = 'B3SC6VRRKQ';
646
+ // Basic usage without validation feedback
647
+ await InsertAffiliate.setShortCode('JOIN123');
648
+ ```
649
+
650
+ #### Recommended Usage with Validation Feedback
651
+
652
+ ```javascript
653
+ import { InsertAffiliate } from 'insert-affiliate-js-sdk';
654
+
655
+ async function handleShortCodeSubmit(userEnteredCode) {
656
+ const isValid = await InsertAffiliate.setShortCode(userEnteredCode);
657
+
658
+ if (isValid) {
659
+ // Show success message
660
+ alert('Affiliate code applied successfully!');
206
661
 
207
- InsertAffiliate.setShortCode(userEnteredCode);
662
+ // Check for associated offer
663
+ const offerCode = await InsertAffiliate.getOfferCode();
664
+ if (offerCode) {
665
+ alert(`You've unlocked a special offer: ${offerCode}`);
666
+ }
667
+ } else {
668
+ // Show error message
669
+ alert('Invalid affiliate code. Please check and try again.');
670
+ }
671
+ }
672
+
673
+ // Example: user clicks submit button
674
+ document.getElementById('submitButton').addEventListener('click', async () => {
675
+ const code = document.getElementById('shortCodeInput').value;
676
+ await handleShortCodeSubmit(code);
677
+ });
208
678
  ```
679
+
680
+ ## API Reference
681
+
682
+ ### Core Methods
683
+
684
+ #### `returnInsertAffiliateIdentifier()`
685
+
686
+ Retrieves the current affiliate identifier that has been set via deep links, URL parameters, or short codes. This is the primary method for getting the affiliate's unique identifier to pass to payment processors or analytics platforms.
687
+
688
+ **Parameters:**
689
+ - `ignoreTimeout` (optional, boolean): Set to `true` to retrieve the identifier even if the attribution window has expired. Default is `false`.
690
+
691
+ **Returns:** `Promise<string | null>`
692
+ - Returns the affiliate identifier if one has been set and is still valid
693
+ - Returns `null` if no affiliate identifier is set or if the attribution window has expired
694
+
695
+ **Example Usage:**
696
+
697
+ ```javascript
698
+ import { InsertAffiliate } from 'insert-affiliate-js-sdk';
699
+
700
+ // Initialize the SDK first
701
+ await InsertAffiliate.initialize('your_company_code');
702
+
703
+ // Later, retrieve the affiliate identifier (respects attribution window)
704
+ const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
705
+ console.log('Affiliate ID:', affiliateId); // Output: 'ABC123' or null
706
+
707
+ // Retrieve even if attribution window expired
708
+ const affiliateIdIgnoreTimeout = await InsertAffiliate.returnInsertAffiliateIdentifier(true);
709
+ console.log('Affiliate ID (ignore timeout):', affiliateIdIgnoreTimeout);
710
+
711
+ // Use with Stripe checkout
712
+ const response = await fetch('/create-checkout-session', {
713
+ method: 'POST',
714
+ headers: { 'Content-Type': 'application/json' },
715
+ body: JSON.stringify({
716
+ priceId: 'price_xxxxx',
717
+ insertAffiliate: affiliateId,
718
+ insertAffiliateCompanyId: await InsertAffiliate.returnCompanyId(),
719
+ successUrl: window.location.origin + '/success',
720
+ cancelUrl: window.location.origin + '/canceled',
721
+ }),
722
+ });
723
+ ```
724
+
725
+ **Use Cases:**
726
+ - **Payment Attribution**: Pass the affiliate ID to Stripe, RevenueCat, or other payment processors
727
+ - **Analytics Tracking**: Include affiliate information in analytics events
728
+ - **Conditional UI**: Show special messaging or discounts when an affiliate link was used
729
+ - **Backend API Calls**: Send affiliate information to your backend for custom tracking
730
+
731
+ **Notes:**
732
+ - The identifier is set when users click affiliate links or enter short codes
733
+ - By default, the identifier expires after the attribution window (configurable in your dashboard)
734
+ - Use `ignoreTimeout: true` if you need the identifier regardless of expiration
735
+ - Returns `null` if no affiliate link has been clicked or short code entered
736
+ - The identifier persists in local storage across sessions
737
+
738
+ #### `returnCompanyId()`
739
+
740
+ Retrieves the company ID that was used during SDK initialization. This is particularly useful when integrating with payment processors like Stripe that require the company ID to be passed as metadata for proper affiliate attribution.
741
+
742
+ **Returns:** `Promise<string | null>`
743
+ - Returns the company ID if the SDK has been initialized
744
+ - Returns `null` if no company ID is available
745
+
746
+ **Example Usage:**
747
+
748
+ ```javascript
749
+ import { InsertAffiliate } from 'insert-affiliate-js-sdk';
750
+
751
+ // Initialize the SDK first
752
+ await InsertAffiliate.initialize('your_company_code');
753
+
754
+ // Later, retrieve the company ID
755
+ const companyId = await InsertAffiliate.returnCompanyId();
756
+ console.log('Company ID:', companyId); // Output: 'your_company_code'
757
+
758
+ // Use with Stripe checkout
759
+ const response = await fetch('/create-checkout-session', {
760
+ method: 'POST',
761
+ headers: { 'Content-Type': 'application/json' },
762
+ body: JSON.stringify({
763
+ priceId: 'price_xxxxx',
764
+ insertAffiliate: await InsertAffiliate.returnInsertAffiliateIdentifier(),
765
+ insertAffiliateCompanyId: companyId,
766
+ }),
767
+ });
768
+ ```
769
+
770
+ **Use Cases:**
771
+ - **Stripe Integration**: Pass the company ID as metadata to Stripe for proper webhook attribution
772
+ - **Backend API Calls**: Include the company ID in API requests for multi-tenant applications
773
+ - **Analytics**: Track which company's affiliate links are being used
774
+
775
+ **Notes:**
776
+ - The company ID is set during SDK initialization and persists in local storage
777
+ - This method retrieves the value from memory first, falling back to storage if needed
778
+ - Returns the same value that was passed to `initialize()`