insert-affiliate-js-sdk 1.0.2 → 1.2.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
@@ -1,208 +1,498 @@
1
1
  # Insert Affiliate JavaScript SDK
2
2
 
3
- ## Overview
3
+ ![Version](https://img.shields.io/badge/version-1.0.0-brightgreen) ![Platform](https://img.shields.io/badge/platform-Web%20%7C%20Capacitor-blue) ![License](https://img.shields.io/badge/license-MIT-lightgrey)
4
4
 
5
- The **Insert Affiliate JavaScript SDK** brings affiliate tracking to web and hybrid applications, providing seamless integration with the [Insert Affiliate platform](https://insertaffiliate.com). It is fully compatible with Capacitor, making it a great choice for modern cross-platform apps that require affiliate attribution and purchase tracking support.
5
+ The official JavaScript SDK for [Insert Affiliate](https://insertaffiliate.com) - track affiliate-driven purchases on web and hybrid applications.
6
6
 
7
- This SDK is ideal for developers who want to integrate affiliate marketing into their app's monetisation strategy and track purchases via partners like RevenueCat.
7
+ **What does this SDK do?** It connects your web or Capacitor app to Insert Affiliate's platform, enabling you to track which affiliates drive subscriptions and automatically pay them commissions when users make purchases.
8
8
 
9
- ### Features
9
+ ## Table of Contents
10
10
 
11
- - **Unique Device ID**: Creates a unique ID to anonymously associate purchases with users for tracking purposes.
12
- - **Affiliate Identifier Management**: Set and retrieve the affiliate identifier based on user-specific links or short codes.
13
- - **Short Code Support (Beta)**: Allow users to enter affiliate short codes for tracking.
11
+ - [Quick Start (5 Minutes)](#-quick-start-5-minutes)
12
+ - [Essential Setup](#%EF%B8%8F-essential-setup)
13
+ - [1. Initialize the SDK](#1-initialize-the-sdk)
14
+ - [2. Configure Payment Verification](#2-configure-payment-verification)
15
+ - [3. Set Up Deep Linking](#3-set-up-deep-linking)
16
+ - [Verify Your Integration](#-verify-your-integration)
17
+ - [Advanced Features](#-advanced-features)
18
+ - [API Reference](#-api-reference)
19
+ - [Troubleshooting](#-troubleshooting)
20
+ - [Support](#-support)
14
21
 
15
- ### Supported Platforms
16
- - ✅ Capacitor (iOS / Android) – Fully tested
17
- - Web Browsers Tested in modern desktop and mobile browsers
18
- - ⚠️ Other JavaScript Environments – May work, but not officially tested
22
+ ---
23
+
24
+ ## 🚀 Quick Start (5 Minutes)
19
25
 
20
- ## Getting Started
21
- To get started with the Insert Affiliate JavaScript SDK:
26
+ Get up and running with minimal code to validate the SDK works.
22
27
 
23
- 1. [Install the SDK via NPM](#installation)
24
- 2. [Initialise the SDK in your Main Javascript/Typescript File](#basic-usage)
25
- 3. [Set up in-app purchases (Required)](#in-app-purchase-setup-required)
26
- 4. [Set up deep linking (Required)](#deep-link-setup-required)
27
- 5. [Use additional features like short codes and event tracking.](#additional-features)
28
+ ### Prerequisites
28
29
 
30
+ - **Modern web browser** or **Capacitor 4+**
31
+ - **Company Code** from your [Insert Affiliate dashboard](https://app.insertaffiliate.com/settings)
29
32
 
30
- ## Installation
33
+ ### Supported Platforms
31
34
 
32
- Install the Insert Affiliate JavaScript SDK and required plugins:
35
+ | Platform | Status |
36
+ |----------|--------|
37
+ | Capacitor (iOS / Android) | ✅ Fully tested |
38
+ | Web Browsers | ✅ Tested in modern browsers |
39
+ | Other JS Environments | ⚠️ May work, not officially tested |
40
+
41
+ ### Installation
33
42
 
34
43
  ```bash
35
44
  npm install insert-affiliate-js-sdk
36
45
  ```
37
46
 
38
- Then run
47
+ For Capacitor apps, also run:
39
48
  ```bash
40
49
  npx cap sync
41
50
  ```
42
51
 
43
- ## Basic Usage
44
- ### Import the SDKs
52
+ ### Your First Integration
53
+
54
+ ```javascript
55
+ import { InsertAffiliate } from 'insert-affiliate-js-sdk';
56
+
57
+ // Initialize with verbose logging for setup
58
+ await InsertAffiliate.initialize('YOUR_COMPANY_CODE', true);
59
+ ```
60
+
61
+ **Expected Console Output:**
62
+
63
+ ```
64
+ [Insert Affiliate] SDK initialized with company code: YOUR_COMPANY_CODE
65
+ [Insert Affiliate] [VERBOSE] SDK marked as initialized
66
+ ```
67
+
68
+ ✅ **If you see these logs, the SDK is working!** Now proceed to Essential Setup.
69
+
70
+ ⚠️ **Disable verbose logging in production** by setting the second parameter to `false`.
71
+
72
+ ---
73
+
74
+ ## ⚙️ Essential Setup
45
75
 
46
- In your ```main.ts``` or ```main.js``` file:
76
+ Complete these three steps to start tracking affiliate-driven purchases.
77
+
78
+ ### 1. Initialize the SDK
79
+
80
+ Add SDK initialization to your main entry point (`main.ts`, `main.js`, or `App.tsx`):
47
81
 
48
82
  ```javascript
49
83
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
50
- await InsertAffiliate.initialize("your_company_code");
51
84
 
85
+ await InsertAffiliate.initialize('YOUR_COMPANY_CODE');
86
+ ```
87
+
88
+ <details>
89
+ <summary><strong>Advanced Initialization Options</strong> (click to expand)</summary>
90
+
91
+ ```javascript
92
+ // Enable verbose logging for debugging
93
+ await InsertAffiliate.initialize('YOUR_COMPANY_CODE', true);
52
94
  ```
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
95
 
55
- ## 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/)
96
+ **Verbose logging shows:**
97
+ - Initialization process and company code validation
98
+ - Deep link processing and short code detection
99
+ - API communication details
100
+ - Storage operations
101
+
102
+ </details>
103
+
104
+ ---
58
105
 
59
- ### Option 1: RevenueCat Integration
106
+ ### 2. Configure Payment Verification
60
107
 
61
- #### Code Setup
62
- 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.
108
+ **Choose the payment method(s) that match your platform:**
63
109
 
64
- 2. **Modify Initialisation Code** - Update the file where you initialise your deep linking (e.g., Branch.io) and RevenueCat to include a call to ```InsertAffiliate.returnInsertAffiliateIdentifier()```. This ensures that the Insert Affiliate identifier is passed to RevenueCat every time the app starts or a deep link is clicked.
110
+ | Method | Best For | Setup Guide |
111
+ |--------|----------|-------------|
112
+ | [**RevenueCat**](#option-1-revenuecat) | Mobile IAP (iOS/Android) | [View](#option-1-revenuecat) |
113
+ | [**Stripe**](#option-2-stripe) | Web-based payments | [View](#option-2-stripe) |
114
+ | [**Both**](#hybrid-apps) | Hybrid apps with mobile + web payments | Set up both |
65
115
 
66
- 3. **Implementation Example**
116
+ <details open>
117
+ <summary><h4>Option 1: RevenueCat</h4></summary>
118
+
119
+ For mobile in-app purchases via Capacitor.
120
+
121
+ **Step 1: Code Setup**
67
122
 
68
123
  ```javascript
69
124
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
70
125
  import { Purchases } from '@revenuecat/purchases-capacitor';
71
126
 
72
127
  window.addEventListener('DOMContentLoaded', async () => {
73
- await Purchases.configure({ apiKey: 'your_revcat_api_key' });
74
-
75
- const affiliateIdentifier = await InsertAffiliate.returnInsertAffiliateIdentifier();
76
-
77
- if (affiliateIdentifier) {
78
- await Purchases.setAttributes({ insert_affiliate: affiliateIdentifier });
79
- }
128
+ await InsertAffiliate.initialize('YOUR_COMPANY_CODE');
129
+ await Purchases.configure({ apiKey: 'YOUR_REVENUECAT_API_KEY' });
130
+
131
+ const affiliateIdentifier = await InsertAffiliate.returnInsertAffiliateIdentifier();
132
+
133
+ if (affiliateIdentifier) {
134
+ await Purchases.setAttributes({ insert_affiliate: affiliateIdentifier });
135
+ }
136
+ });
137
+ ```
138
+
139
+ **Step 2: Webhook Setup**
140
+
141
+ 1. In RevenueCat, [create a new webhook](https://www.revenuecat.com/docs/integrations/webhooks)
142
+ 2. Configure webhook settings:
143
+ - **Webhook URL**: `https://api.insertaffiliate.com/v1/api/revenuecat-webhook`
144
+ - **Event Type**: "All events"
145
+ 3. In your [Insert Affiliate dashboard](https://app.insertaffiliate.com/settings):
146
+ - Set **In-App Purchase Verification** to `RevenueCat`
147
+ - Copy the `RevenueCat Webhook Authentication Header` value
148
+ 4. Paste the authentication header into RevenueCat's **Authorization header** field
149
+
150
+ ✅ **RevenueCat setup complete!**
151
+
152
+ </details>
153
+
154
+ <details>
155
+ <summary><h4>Option 2: Stripe</h4></summary>
156
+
157
+ For web-based subscriptions and payments.
158
+
159
+ **Step 1: Connect Stripe Account**
160
+
161
+ 1. Go to your [Insert Affiliate dashboard settings](https://app.insertaffiliate.com/settings)
162
+ 2. Select **Stripe** as your verification method
163
+ 3. Click **Connect with Stripe** to authorize via Stripe Connect
164
+
165
+ **Step 2: Pass Affiliate Data to Checkout**
166
+
167
+ ```javascript
168
+ import { InsertAffiliate } from 'insert-affiliate-js-sdk';
169
+
170
+ const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
171
+ const companyId = await InsertAffiliate.returnCompanyId();
172
+
173
+ const response = await fetch('/create-checkout-session', {
174
+ method: 'POST',
175
+ headers: { 'Content-Type': 'application/json' },
176
+ body: JSON.stringify({
177
+ priceId: 'price_xxxxx',
178
+ insertAffiliate: affiliateId,
179
+ insertAffiliateCompanyId: companyId,
180
+ successUrl: window.location.origin + '/success',
181
+ cancelUrl: window.location.origin + '/canceled',
182
+ }),
183
+ });
184
+ ```
185
+
186
+ **Step 3: Store in Stripe Metadata (Backend)**
187
+
188
+ ```javascript
189
+ const session = await stripe.checkout.sessions.create({
190
+ mode: 'subscription',
191
+ line_items: [{ price: priceId, quantity: 1 }],
192
+ metadata: {
193
+ insertAffiliate: insertAffiliate || '',
194
+ insertAffiliateCompanyId: insertAffiliateCompanyId || '',
195
+ },
196
+ subscription_data: {
197
+ metadata: {
198
+ insertAffiliate: insertAffiliate || '',
199
+ insertAffiliateCompanyId: insertAffiliateCompanyId || '',
200
+ },
201
+ },
202
+ success_url: successUrl,
203
+ cancel_url: cancelUrl,
80
204
  });
81
205
  ```
82
206
 
83
- #### Webhook Setup
207
+ 📖 **[View complete Stripe integration guide →](docs/stripe-integration.md)**
208
+
209
+ Includes:
210
+ - Stripe Billing with RevenueCat
211
+ - RevenueCat Web Billing integration
212
+ - RevenueCat Web Purchase Links
213
+ - Callback-based integration
84
214
 
85
- Next, you must setup a webhook to allow us to communicate directly with RevenueCat to track affiliate purchases.
215
+ **Stripe setup complete!**
86
216
 
87
- 1. Go to RevenueCat and [create a new webhook](https://www.revenuecat.com/docs/integrations/webhooks)
217
+ </details>
88
218
 
89
- 2. Configure the webhook with these settings:
90
- - Webhook URL: `https://api.insertaffiliate.com/v1/api/revenuecat-webhook`
91
- - Authorization header: Use the value from your Insert Affiliate dashboard (you'll get this in step 4)
92
- - Set "Event Type" to "All events"
219
+ ---
93
220
 
94
- 3. In your [Insert Affiliate dashboard settings](https://app.insertaffiliate.com/settings):
95
- - Navigate to the verification settings
96
- - Set the in-app purchase verification method to `RevenueCat`
221
+ ### 3. Set Up Deep Linking
97
222
 
98
- 4. Back in your Insert Affiliate dashboard:
99
- - Locate the `RevenueCat Webhook Authentication Header` value
100
- - Copy this value
101
- - Paste it as the Authorization header value in your RevenueCat webhook configuration
223
+ **Deep linking lets affiliates share unique links that track users to your app/website.**
102
224
 
225
+ | Provider | Best For | Complexity |
226
+ |----------|----------|------------|
227
+ | [**Insert Links**](#option-1-insert-links-automatic) | Simplest setup, no 3rd party | Simple |
228
+ | [**Branch.io**](#option-2-branchio) | Robust attribution | Medium |
229
+ | [**AppsFlyer**](#option-3-appsflyer) | Enterprise analytics | Medium |
103
230
 
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
- ```
231
+ <details open>
232
+ <summary><h4>Option 1: Insert Links (Automatic)</h4></summary>
111
233
 
112
- ### Deep Linking with Branch.io
113
- To set up deep linking with Branch.io, follow these steps:
234
+ Insert Links is Insert Affiliate's built-in deep linking - no configuration needed for web.
114
235
 
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:
236
+ The SDK automatically:
237
+ 1. Detects `insertAffiliate` parameter from URLs
238
+ 2. Validates and stores the affiliate identifier
239
+ 3. Triggers callbacks when affiliate changes
119
240
 
241
+ **That's it!** Just initialize the SDK and affiliate links work automatically.
242
+
243
+ Learn more: [Insert Links Documentation](https://docs.insertaffiliate.com/insert-links)
244
+
245
+ </details>
246
+
247
+ <details>
248
+ <summary><h4>Option 2: Branch.io</h4></summary>
249
+
250
+ **For web redirects:** Configure your Branch.io Quick Links to redirect to your web URL with the affiliate parameter:
251
+
252
+ ```
253
+ https://yourwebsite.com/checkout?insertAffiliate={affiliateShortCode}
254
+ ```
255
+
256
+ **For Capacitor apps:** Use the Branch.io Capacitor plugin:
120
257
 
121
258
  ```javascript
122
- import { BranchDeepLinks, BranchInitEvent } from 'capacitor-branch-deep-links';
259
+ import { BranchDeepLinks } from 'capacitor-branch-deep-links';
123
260
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
124
261
 
125
- let branchInitialised = false;
126
-
127
- async function setUpBranchListener() {
128
- if (branchInitialised) return;
129
- branchInitialised = true;
130
-
131
- try {
132
- await BranchDeepLinks.addListener('init', async (event: BranchInitEvent) => {
133
- const clicked = event?.referringParams?.['+clicked_branch_link'];
134
- const referringLink = event?.referringParams?.['~referring_link'];
135
-
136
- if (clicked && referringLink) {
137
- await InsertAffiliate.setInsertAffiliateIdentifier(referringLink);
138
- }
139
- });
140
-
141
- BranchDeepLinks.addListener('initError', (error: any) => {
142
- console.error('Branch init error:', error);
143
- });
144
- } catch (err) {
145
- console.error('Error setting up Branch listener:', err);
146
- }
147
- }
262
+ BranchDeepLinks.addListener('init', async (event) => {
263
+ const clicked = event?.referringParams?.['+clicked_branch_link'];
264
+ const referringLink = event?.referringParams?.['~referring_link'];
148
265
 
266
+ if (clicked && referringLink) {
267
+ await InsertAffiliate.setInsertAffiliateIdentifier(referringLink);
268
+ }
269
+ });
149
270
  ```
150
271
 
151
- ## Additional Features
272
+ 📖 **[View complete deep linking guide →](docs/deep-linking-web.md)**
273
+
274
+ </details>
275
+
276
+ <details>
277
+ <summary><h4>Option 3: AppsFlyer</h4></summary>
278
+
279
+ Configure your AppsFlyer OneLinks to redirect to your web URL with the affiliate parameter:
280
+
281
+ ```
282
+ https://yourwebsite.com/checkout?insertAffiliate={affiliateShortCode}
283
+ ```
152
284
 
153
- ### 1. Event Tracking (Beta)
285
+ The SDK automatically detects `insertAffiliate` from the URL and attributes the payment.
154
286
 
155
- Insert Affiliate now includes a beta feature for event tracking. Use event tracking to log key user actions such as signups, purchases, or referrals. This is useful for:
156
- - Understanding user behaviour.
157
- - Measuring the effectiveness of marketing campaigns.
158
- - Incentivising affiliates for designated actions being taken by the end users, rather than just in app purchases (i.e. pay an affilaite for each signup).
287
+ 📖 **[View complete deep linking guide →](docs/deep-linking-web.md)**
159
288
 
160
- At this stage, we cannot guarantee that this feature is fully resistant to tampering or manipulation.
289
+ </details>
161
290
 
162
- #### Using `trackEvent`
291
+ ---
163
292
 
164
- To track an event, use the `trackEvent` function. Make sure to set an affiliate identifier first; otherwise, event tracking won’t work. Here’s an example:
293
+ ## Verify Your Integration
294
+
295
+ ### Integration Checklist
296
+
297
+ - [ ] **SDK Initializes**: Check console for `SDK initialized with company code` log
298
+ - [ ] **Affiliate Detected**: Visit your site with `?insertAffiliate=TEST123` and verify it's captured
299
+ - [ ] **Payment Tracked**: Make a test purchase and verify it appears in Insert Affiliate dashboard
300
+
301
+ ### Testing URL Parameters
302
+
303
+ Visit your app with an affiliate parameter:
304
+ ```
305
+ https://yourwebsite.com?insertAffiliate=TEST123
306
+ ```
307
+
308
+ Check the affiliate was captured:
309
+ ```javascript
310
+ const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
311
+ console.log('Detected affiliate:', affiliateId); // Should output: TEST123
312
+ ```
313
+
314
+ ### Common Setup Issues
315
+
316
+ | Issue | Solution |
317
+ |-------|----------|
318
+ | "Company code not set" | Ensure `initialize()` is called before other SDK methods |
319
+ | Affiliate not detected | Check URL parameter is exactly `insertAffiliate` (case-sensitive) |
320
+ | Payment not tracked | Verify Stripe/RevenueCat webhook is configured correctly |
321
+
322
+ ---
323
+
324
+ ## 🔧 Advanced Features
325
+
326
+ <details>
327
+ <summary><h3>Event Tracking (Beta)</h3></summary>
328
+
329
+ Track custom events beyond purchases to incentivize affiliates for specific actions.
165
330
 
166
331
  ```javascript
167
332
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
168
333
 
169
- async function trackSignupEvent() {
170
- try {
171
- await InsertAffiliate.trackEvent('your_event_name_here');
172
- } catch (error) {
173
- console.error('❌ Failed to track event:', error);
174
- }
334
+ // Track a signup event (affiliate identifier must be set first)
335
+ await InsertAffiliate.trackEvent('user_signup');
336
+ ```
337
+
338
+ **Use Cases:**
339
+ - Pay affiliates for signups instead of purchases
340
+ - Track trial starts or content unlocks
341
+
342
+ </details>
343
+
344
+ <details>
345
+ <summary><h3>Short Codes</h3></summary>
346
+
347
+ Short codes are unique, 3-25 character alphanumeric identifiers that affiliates can share (e.g., "SAVE20" in a TikTok description).
348
+
349
+ **Validate and Store Short Code:**
350
+
351
+ ```javascript
352
+ const isValid = await InsertAffiliate.setShortCode('SAVE20');
353
+
354
+ if (isValid) {
355
+ alert('Affiliate code applied!');
356
+
357
+ // Check for associated offer
358
+ const offerCode = await InsertAffiliate.getOfferCode();
359
+ if (offerCode) {
360
+ alert(`You unlocked: ${offerCode}`);
361
+ }
362
+ } else {
363
+ alert('Invalid affiliate code');
364
+ }
365
+ ```
366
+
367
+ **Get Affiliate Details Without Setting:**
368
+
369
+ ```javascript
370
+ const details = await InsertAffiliate.getAffiliateDetails('SAVE20');
371
+
372
+ if (details) {
373
+ console.log('Affiliate Name:', details.affiliateName);
374
+ console.log('Short Code:', details.affiliateShortCode);
375
+ console.log('Deep Link:', details.deeplinkUrl);
175
376
  }
176
377
  ```
177
378
 
178
- ### 2. Short Codes (Beta)
379
+ Learn more: [Short Codes Documentation](https://docs.insertaffiliate.com/short-codes)
179
380
 
180
- ### What are Short Codes?
381
+ </details>
181
382
 
182
- Short codes are unique, 3 to 25 character alphanumeric identifiers that affiliates can use to promote products or subscriptions. These codes are ideal for influencers or partners, making them easier to share than long URLs.
383
+ <details>
384
+ <summary><h3>Affiliate Change Callback</h3></summary>
183
385
 
184
- **Example Use Case**: An influencer promotes a subscription with the short code "JOIN123456" within their TikTok video's description. When users enter this code within your app during sign-up or before purchase, the app tracks the subscription back to the influencer for commission payouts.
386
+ Get notified when the affiliate identifier changes:
185
387
 
186
- For more information, visit the [Insert Affiliate Short Codes Documentation](https://docs.insertaffiliate.com/short-codes).
388
+ ```javascript
389
+ InsertAffiliate.setInsertAffiliateIdentifierChangeCallback((identifier) => {
390
+ if (identifier) {
391
+ console.log('Affiliate changed:', identifier);
392
+
393
+ // Update UI
394
+ document.getElementById('affiliate-banner').style.display = 'block';
187
395
 
188
- ### Setting a Short Code
396
+ // Track in analytics
397
+ analytics.track('affiliate_link_clicked', { identifier });
398
+ }
399
+ });
189
400
 
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.
401
+ // Clear callback when done
402
+ InsertAffiliate.setInsertAffiliateIdentifierChangeCallback(null);
403
+ ```
191
404
 
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
405
+ </details>
196
406
 
407
+ ---
197
408
 
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:
409
+ ## 📖 API Reference
410
+
411
+ ### Core Methods
412
+
413
+ | Method | Description | Returns |
414
+ |--------|-------------|---------|
415
+ | `initialize(companyCode, verbose?)` | Initialize the SDK | `Promise<void>` |
416
+ | `returnInsertAffiliateIdentifier(ignoreTimeout?)` | Get current affiliate identifier | `Promise<string \| null>` |
417
+ | `returnCompanyId()` | Get company ID | `Promise<string \| null>` |
418
+ | `setInsertAffiliateIdentifier(link)` | Set affiliate from deep link | `Promise<string \| null>` |
419
+ | `setShortCode(code)` | Validate and store short code | `Promise<boolean>` |
420
+ | `getAffiliateDetails(code)` | Get affiliate info without storing | `Promise<AffiliateDetails \| null>` |
421
+ | `trackEvent(eventName)` | Track custom event | `Promise<void>` |
422
+ | `getOfferCode()` | Get offer code modifier | `Promise<string \| null>` |
423
+ | `setInsertAffiliateIdentifierChangeCallback(fn)` | Set change callback | `void` |
424
+
425
+ <details>
426
+ <summary><strong>Detailed Method Documentation</strong></summary>
427
+
428
+ #### `returnInsertAffiliateIdentifier(ignoreTimeout?)`
429
+
430
+ Retrieves the current affiliate identifier.
431
+
432
+ **Parameters:**
433
+ - `ignoreTimeout` (optional, boolean): Set to `true` to get identifier even if attribution window expired
434
+
435
+ **Returns:** `Promise<string | null>`
200
436
 
201
437
  ```javascript
202
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
438
+ // Respects attribution window
439
+ const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
440
+
441
+ // Ignores attribution window
442
+ const affiliateIdAlways = await InsertAffiliate.returnInsertAffiliateIdentifier(true);
443
+ ```
444
+
445
+ #### `returnCompanyId()`
446
+
447
+ Retrieves the company ID used during initialization.
448
+
449
+ **Returns:** `Promise<string | null>`
450
+
451
+ ```javascript
452
+ const companyId = await InsertAffiliate.returnCompanyId();
453
+ ```
203
454
 
204
- // Example: user entered this in a form
205
- const userEnteredCode = 'B3SC6VRRKQ';
455
+ </details>
206
456
 
207
- InsertAffiliate.setShortCode(userEnteredCode);
457
+ ---
458
+
459
+ ## 🔍 Troubleshooting
460
+
461
+ ### Initialization Issues
462
+
463
+ **Error:** "Company code not set"
464
+ - **Solution:** Call `initialize()` before any other SDK methods
465
+
466
+ ### Deep Linking Issues
467
+
468
+ **Problem:** Affiliate parameter not detected
469
+ - **Solution:** Ensure parameter name is exactly `insertAffiliate` (case-sensitive)
470
+ - Initialize SDK before URL parameters are processed
471
+
472
+ ### Payment Tracking Issues
473
+
474
+ **Problem:** Purchases not appearing in dashboard
475
+ - **Solution:** Verify webhook configuration in Stripe/RevenueCat
476
+ - Check both `insertAffiliate` and `insertAffiliateCompanyId` are in metadata
477
+
478
+ ### Verbose Logging
479
+
480
+ Enable detailed logs to diagnose issues:
481
+
482
+ ```javascript
483
+ await InsertAffiliate.initialize('YOUR_COMPANY_CODE', true);
208
484
  ```
485
+
486
+ ---
487
+
488
+ ## 📚 Support
489
+
490
+ - **Documentation**: [docs.insertaffiliate.com](https://docs.insertaffiliate.com)
491
+ - **Stripe Integration Guide**: [docs/stripe-integration.md](docs/stripe-integration.md)
492
+ - **Deep Linking Guide**: [docs/deep-linking-web.md](docs/deep-linking-web.md)
493
+ - **Dashboard**: [app.insertaffiliate.com](https://app.insertaffiliate.com)
494
+ - **Issues**: [GitHub Issues](https://github.com/Insert-Affiliate/insert-affiliate-js-sdk/issues)
495
+
496
+ ---
497
+
498
+ **Need help?** Check our [documentation](https://docs.insertaffiliate.com) or [contact support](https://app.insertaffiliate.com/help).