insert-affiliate-js-sdk 1.1.0 → 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,189 +1,178 @@
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)
32
+
33
+ ### Supported Platforms
29
34
 
30
- ## Installation
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 |
31
40
 
32
- Install the Insert Affiliate JavaScript SDK and required plugins:
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
45
-
46
- In your ```main.ts``` or ```main.js``` file:
52
+ ### Your First Integration
47
53
 
48
54
  ```javascript
49
55
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
50
- await InsertAffiliate.initialize("your_company_code");
51
56
 
57
+ // Initialize with verbose logging for setup
58
+ await InsertAffiliate.initialize('YOUR_COMPANY_CODE', true);
52
59
  ```
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
60
 
55
- ### Verbose Logging (Optional)
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
56
75
 
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.
76
+ Complete these three steps to start tracking affiliate-driven purchases.
58
77
 
59
- #### Enable Verbose Logging
78
+ ### 1. Initialize the SDK
79
+
80
+ Add SDK initialization to your main entry point (`main.ts`, `main.js`, or `App.tsx`):
60
81
 
61
82
  ```javascript
62
83
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
63
84
 
64
- // Enable verbose logging (second parameter)
65
- await InsertAffiliate.initialize("your_company_code", true);
85
+ await InsertAffiliate.initialize('YOUR_COMPANY_CODE');
66
86
  ```
67
87
 
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
88
+ <details>
89
+ <summary><strong>Advanced Initialization Options</strong> (click to expand)</summary>
76
90
 
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
91
+ ```javascript
92
+ // Enable verbose logging for debugging
93
+ await InsertAffiliate.initialize('YOUR_COMPANY_CODE', true);
85
94
  ```
86
95
 
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
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
93
101
 
94
- ⚠️ **Important**: Disable verbose logging in production builds to avoid exposing sensitive debugging information and to optimize performance.
102
+ </details>
95
103
 
96
- ## In-App Purchase Setup [Required]
104
+ ---
97
105
 
98
- Insert Affiliate requires a receipt verification platform to validate purchases. Choose the integration method(s) that match your platform:
106
+ ### 2. Configure Payment Verification
99
107
 
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
108
+ **Choose the payment method(s) that match your platform:**
103
109
 
104
- ### Mobile In-App Purchases: RevenueCat Integration
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 |
105
115
 
106
- #### Code Setup
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.
116
+ <details open>
117
+ <summary><h4>Option 1: RevenueCat</h4></summary>
108
118
 
109
- 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.
119
+ For mobile in-app purchases via Capacitor.
110
120
 
111
- 3. **Implementation Example**
121
+ **Step 1: Code Setup**
112
122
 
113
123
  ```javascript
114
124
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
115
125
  import { Purchases } from '@revenuecat/purchases-capacitor';
116
126
 
117
127
  window.addEventListener('DOMContentLoaded', async () => {
118
- await Purchases.configure({ apiKey: 'your_revcat_api_key' });
119
-
120
- const affiliateIdentifier = await InsertAffiliate.returnInsertAffiliateIdentifier();
121
-
122
- if (affiliateIdentifier) {
123
- await Purchases.setAttributes({ insert_affiliate: affiliateIdentifier });
124
- }
125
- });
126
- ```
127
-
128
- #### Webhook Setup
129
-
130
- Next, you must setup a webhook to allow us to communicate directly with RevenueCat to track affiliate purchases.
128
+ await InsertAffiliate.initialize('YOUR_COMPANY_CODE');
129
+ await Purchases.configure({ apiKey: 'YOUR_REVENUECAT_API_KEY' });
131
130
 
132
- 1. Go to RevenueCat and [create a new webhook](https://www.revenuecat.com/docs/integrations/webhooks)
131
+ const affiliateIdentifier = await InsertAffiliate.returnInsertAffiliateIdentifier();
133
132
 
134
- 2. Configure the webhook with these settings:
135
- - Webhook URL: `https://api.insertaffiliate.com/v1/api/revenuecat-webhook`
136
- - Authorization header: Use the value from your Insert Affiliate dashboard (you'll get this in step 4)
137
- - Set "Event Type" to "All events"
138
-
139
- 3. In your [Insert Affiliate dashboard settings](https://app.insertaffiliate.com/settings):
140
- - Navigate to the verification settings
141
- - Set the in-app purchase verification method to `RevenueCat`
142
-
143
- 4. Back in your Insert Affiliate dashboard:
144
- - Locate the `RevenueCat Webhook Authentication Header` value
145
- - Copy this value
146
- - Paste it as the Authorization header value in your RevenueCat webhook configuration
133
+ if (affiliateIdentifier) {
134
+ await Purchases.setAttributes({ insert_affiliate: affiliateIdentifier });
135
+ }
136
+ });
137
+ ```
147
138
 
148
- ## Web-Based Payments: Stripe Integration
139
+ **Step 2: Webhook Setup**
149
140
 
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.
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
151
149
 
152
- **📚 For complete setup instructions, see: [Stripe Web-Based Transactions Documentation](https://docs.insertaffiliate.com/stripe-web-based-transactions)**
150
+ **RevenueCat setup complete!**
153
151
 
154
- #### Setup Steps
152
+ </details>
155
153
 
156
- 1. **Connect Your Stripe Account (Required First Step)**
154
+ <details>
155
+ <summary><h4>Option 2: Stripe</h4></summary>
157
156
 
158
- Before integrating the SDK code, you must connect your Stripe account to Insert Affiliate:
157
+ For web-based subscriptions and payments.
159
158
 
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
159
+ **Step 1: Connect Stripe Account**
165
160
 
166
- 2. **Retrieve the Affiliate Identifier and Company ID**
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
167
164
 
168
- Before creating a Stripe checkout session, retrieve the current affiliate identifier and company ID from the Insert Affiliate SDK:
165
+ **Step 2: Pass Affiliate Data to Checkout**
169
166
 
170
167
  ```javascript
171
168
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
172
169
 
173
170
  const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
174
171
  const companyId = await InsertAffiliate.returnCompanyId();
175
- ```
176
172
 
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', {
173
+ const response = await fetch('/create-checkout-session', {
183
174
  method: 'POST',
184
- headers: {
185
- 'Content-Type': 'application/json',
186
- },
175
+ headers: { 'Content-Type': 'application/json' },
187
176
  body: JSON.stringify({
188
177
  priceId: 'price_xxxxx',
189
178
  insertAffiliate: affiliateId,
@@ -194,585 +183,316 @@ const response = await fetch('https://your-backend.com/create-checkout-session',
194
183
  });
195
184
  ```
196
185
 
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:
186
+ **Step 3: Store in Stripe Metadata (Backend)**
200
187
 
201
188
  ```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
- }],
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: {
213
197
  metadata: {
214
198
  insertAffiliate: insertAffiliate || '',
215
199
  insertAffiliateCompanyId: insertAffiliateCompanyId || '',
216
200
  },
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 });
201
+ },
202
+ success_url: successUrl,
203
+ cancel_url: cancelUrl,
228
204
  });
229
205
  ```
230
206
 
231
- **Required Metadata Fields:**
232
- - `insertAffiliate`: The affiliate's short code
233
- - `insertAffiliateCompanyId`: Your Insert Affiliate company ID
207
+ 📖 **[View complete Stripe integration guide →](docs/stripe-integration.md)**
234
208
 
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.
209
+ Includes:
210
+ - Stripe Billing with RevenueCat
211
+ - RevenueCat Web Billing integration
212
+ - RevenueCat Web Purchase Links
213
+ - Callback-based integration
236
214
 
237
- ### Stripe Billing with RevenueCat
215
+ **Stripe setup complete!**
238
216
 
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.
217
+ </details>
240
218
 
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
219
+ ---
244
220
 
245
- **Integration:**
221
+ ### 3. Set Up Deep Linking
246
222
 
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
223
+ **Deep linking lets affiliates share unique links that track users to your app/website.**
251
224
 
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.
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 |
253
230
 
254
- ### RevenueCat Web Billing Integration
231
+ <details open>
232
+ <summary><h4>Option 1: Insert Links (Automatic)</h4></summary>
255
233
 
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.
234
+ Insert Links is Insert Affiliate's built-in deep linking - no configuration needed for web.
257
235
 
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)
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
263
240
 
264
- **Integration Steps:**
241
+ **That's it!** Just initialize the SDK and affiliate links work automatically.
265
242
 
266
- 1. **Install and Initialize Both SDKs**
243
+ Learn more: [Insert Links Documentation](https://docs.insertaffiliate.com/insert-links)
267
244
 
268
- ```javascript
269
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
270
- import { Purchases } from '@revenuecat/purchases-js';
245
+ </details>
271
246
 
272
- // Initialize Insert Affiliate SDK
273
- await InsertAffiliate.initialize('your_company_code');
247
+ <details>
248
+ <summary><h4>Option 2: Branch.io</h4></summary>
274
249
 
275
- // Initialize RevenueCat Web SDK
276
- const purchases = Purchases.configure('your_revenuecat_web_api_key');
277
- ```
250
+ **For web redirects:** Configure your Branch.io Quick Links to redirect to your web URL with the affiliate parameter:
278
251
 
279
- 2. **Retrieve Affiliate Information and Pass as Metadata During Purchase**
252
+ ```
253
+ https://yourwebsite.com/checkout?insertAffiliate={affiliateShortCode}
254
+ ```
280
255
 
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:
256
+ **For Capacitor apps:** Use the Branch.io Capacitor plugin:
282
257
 
283
258
  ```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];
259
+ import { BranchDeepLinks } from 'capacitor-branch-deep-links';
260
+ import { InsertAffiliate } from 'insert-affiliate-js-sdk';
306
261
 
307
- if (!selectedPackage) {
308
- console.error('No packages available');
309
- return;
310
- }
262
+ BranchDeepLinks.addListener('init', async (event) => {
263
+ const clicked = event?.referringParams?.['+clicked_branch_link'];
264
+ const referringLink = event?.referringParams?.['~referring_link'];
311
265
 
312
- // Make the purchase with metadata
313
- const { customerInfo } = await purchases.purchase({
314
- rcPackage: selectedPackage,
315
- metadata: metadata,
266
+ if (clicked && referringLink) {
267
+ await InsertAffiliate.setInsertAffiliateIdentifier(referringLink);
268
+ }
316
269
  });
317
-
318
- console.log('Purchase successful!');
319
- console.log('Active entitlements:', Object.keys(customerInfo.entitlements.active));
320
270
  ```
321
271
 
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:
272
+ 📖 **[View complete deep linking guide →](docs/deep-linking-web.md)**
336
273
 
337
- - **utm_source**
338
- - **utm_medium**
339
- - **utm_campaign**
274
+ </details>
340
275
 
341
- These parameters allow Insert Affiliate to track and attribute web-based purchases correctly.
276
+ <details>
277
+ <summary><h4>Option 3: AppsFlyer</h4></summary>
342
278
 
343
- ### Example
279
+ Configure your AppsFlyer OneLinks to redirect to your web URL with the affiliate parameter:
344
280
 
345
- If your RevenueCat Web Purchase Link is:
346
-
347
- ```text
348
- https://pay.rev.cat/sandbox/viqxbcoudyfaeaae/
349
281
  ```
350
-
351
- You should append:
352
- ```text
353
- ?utm_source=insertAffiliate&utm_medium={insertAffiliateCompanyId}&utm_campaign={insertAffiliateUtmCampaign}
282
+ https://yourwebsite.com/checkout?insertAffiliate={affiliateShortCode}
354
283
  ```
355
284
 
356
- #### Full Example With Parameters
357
- ```text
358
- https://pay.rev.cat/sandbox/viqxbcoudyfaeaxa/?utm_source=insertAffiliate&utm_medium=12345&utm_campaign=AFF123
359
- ```
285
+ The SDK automatically detects `insertAffiliate` from the URL and attributes the payment.
360
286
 
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
287
+ 📖 **[View complete deep linking guide →](docs/deep-linking-web.md)**
365
288
 
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.
289
+ </details>
367
290
 
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.
291
+ ---
370
292
 
371
- ### Branch.io Web Redirect Setup
293
+ ## Verify Your Integration
372
294
 
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.
295
+ ### Integration Checklist
374
296
 
375
- ### Creating a Branch.io Quick Link for Stripe Checkout:
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
376
300
 
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
301
+ ### Testing URL Parameters
384
302
 
385
- **Example:**
303
+ Visit your app with an affiliate parameter:
386
304
  ```
387
- https://yourwebsite.com?insertAffiliate=ABC123
305
+ https://yourwebsite.com?insertAffiliate=TEST123
388
306
  ```
389
307
 
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
308
+ Check the affiliate was captured:
309
+ ```javascript
310
+ const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
311
+ console.log('Detected affiliate:', affiliateId); // Should output: TEST123
409
312
  ```
410
313
 
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).
314
+ ### Common Setup Issues
414
315
 
415
- ### Insert Links Web Automatic Configuration
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 |
416
321
 
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.
322
+ ---
418
323
 
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
324
+ ## 🔧 Advanced Features
423
325
 
424
- No extra setup, no redirects to configure — just initialise the SDK and you're done.
326
+ <details>
327
+ <summary><h3>Event Tracking (Beta)</h3></summary>
425
328
 
426
- Learn more in our[Insert Links documentation](https://docs.insertaffiliate.com/insert-links).
427
-
428
- ## Using the Callback for Automatic Integration
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
329
+ Track custom events beyond purchases to incentivize affiliates for specific actions.
434
330
 
435
331
  ```javascript
436
332
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
437
333
 
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
- });
334
+ // Track a signup event (affiliate identifier must be set first)
335
+ await InsertAffiliate.trackEvent('user_signup');
462
336
  ```
463
337
 
464
- #### Example: Updating the UI When an Affiliate Link Is Clicked
338
+ **Use Cases:**
339
+ - Pay affiliates for signups instead of purchases
340
+ - Track trial starts or content unlocks
465
341
 
466
- ```javascript
467
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
342
+ </details>
468
343
 
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
- }
344
+ <details>
345
+ <summary><h3>Short Codes</h3></summary>
479
346
 
480
- analytics.track('affiliate_link_clicked', { identifier });
481
- }
482
- });
483
- ```
347
+ Short codes are unique, 3-25 character alphanumeric identifiers that affiliates can share (e.g., "SAVE20" in a TikTok description).
484
348
 
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
349
+ **Validate and Store Short Code:**
491
350
 
492
- **To clear the callback:**
493
351
  ```javascript
494
- InsertAffiliate.setInsertAffiliateIdentifierChangeCallback(null);
495
- ```
496
-
497
- ## Capacitor/Hybrid App Deep Link Handling
352
+ const isValid = await InsertAffiliate.setShortCode('SAVE20');
498
353
 
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
503
-
504
- ```javascript
505
- import { BranchDeepLinks, BranchInitEvent } from 'capacitor-branch-deep-links';
506
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
354
+ if (isValid) {
355
+ alert('Affiliate code applied!');
507
356
 
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');
357
+ // Check for associated offer
358
+ const offerCode = await InsertAffiliate.getOfferCode();
359
+ if (offerCode) {
360
+ alert(`You unlocked: ${offerCode}`);
513
361
  }
514
- });
515
-
516
- let branchInitialised = false;
517
-
518
- async function setUpBranchListener() {
519
- if (branchInitialised) return;
520
- branchInitialised = true;
521
-
522
- try {
523
- await BranchDeepLinks.addListener('init', async (event: BranchInitEvent) => {
524
- const clicked = event?.referringParams?.['+clicked_branch_link'];
525
- const referringLink = event?.referringParams?.['~referring_link'];
526
-
527
- if (clicked && referringLink) {
528
- // This will automatically trigger the callback
529
- await InsertAffiliate.setInsertAffiliateIdentifier(referringLink);
530
- }
531
- });
532
-
533
- BranchDeepLinks.addListener('initError', (error: any) => {
534
- console.error('Branch init error:', error);
535
- });
536
- } catch (err) {
537
- console.error('Error setting up Branch listener:', err);
538
- }
362
+ } else {
363
+ alert('Invalid affiliate code');
539
364
  }
540
365
  ```
541
366
 
542
- **Note:** For most web applications, the automatic URL detection method is recommended and requires no additional setup.
543
-
544
- ## Additional Features
545
-
546
- ### 1. Event Tracking (Beta)
547
-
548
- 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:
549
- - Understanding user behaviour.
550
- - Measuring the effectiveness of marketing campaigns.
551
- - 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).
552
-
553
- At this stage, we cannot guarantee that this feature is fully resistant to tampering or manipulation.
554
-
555
- #### Using `trackEvent`
556
-
557
- 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:
367
+ **Get Affiliate Details Without Setting:**
558
368
 
559
369
  ```javascript
560
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
370
+ const details = await InsertAffiliate.getAffiliateDetails('SAVE20');
561
371
 
562
- async function trackSignupEvent() {
563
- try {
564
- await InsertAffiliate.trackEvent('your_event_name_here');
565
- } catch (error) {
566
- console.error('❌ Failed to track event:', error);
567
- }
372
+ if (details) {
373
+ console.log('Affiliate Name:', details.affiliateName);
374
+ console.log('Short Code:', details.affiliateShortCode);
375
+ console.log('Deep Link:', details.deeplinkUrl);
568
376
  }
569
377
  ```
570
378
 
571
- ### 2. Short Codes (Beta)
572
-
573
- ### What are Short Codes?
574
-
575
- 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.
576
-
577
- **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.
578
-
579
- For more information, visit the [Insert Affiliate Short Codes Documentation](https://docs.insertaffiliate.com/short-codes).
379
+ Learn more: [Short Codes Documentation](https://docs.insertaffiliate.com/short-codes)
580
380
 
581
- ### Getting Affiliate Details
381
+ </details>
582
382
 
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.
383
+ <details>
384
+ <summary><h3>Affiliate Change Callback</h3></summary>
584
385
 
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
386
+ Get notified when the affiliate identifier changes:
602
387
 
603
388
  ```javascript
604
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
389
+ InsertAffiliate.setInsertAffiliateIdentifierChangeCallback((identifier) => {
390
+ if (identifier) {
391
+ console.log('Affiliate changed:', identifier);
605
392
 
606
- // Get affiliate details for a specific code
607
- const details = await InsertAffiliate.getAffiliateDetails('JOIN123');
393
+ // Update UI
394
+ document.getElementById('affiliate-banner').style.display = 'block';
608
395
 
609
- if (details) {
610
- console.log(`Affiliate Name: ${details.affiliateName}`);
611
- console.log(`Short Code: ${details.affiliateShortCode}`);
612
- console.log(`Deep Link: ${details.deeplinkUrl}`);
396
+ // Track in analytics
397
+ analytics.track('affiliate_link_clicked', { identifier });
398
+ }
399
+ });
613
400
 
614
- // Update UI with affiliate name
615
- document.getElementById('referrer').textContent = `Referred by: ${details.affiliateName}`;
616
- } else {
617
- console.log('Affiliate not found');
618
- }
401
+ // Clear callback when done
402
+ InsertAffiliate.setInsertAffiliateIdentifierChangeCallback(null);
619
403
  ```
620
404
 
621
- ### Setting a Short Code
405
+ </details>
622
406
 
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.
407
+ ---
624
408
 
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
409
+ ## 📖 API Reference
628
410
 
629
- This allows you to provide immediate feedback to users about whether their entered code is valid.
411
+ ### Core Methods
630
412
 
631
- **Short Code Requirements:**
632
- - Between **3 and 25 characters long**
633
- - Contain only **letters and numbers** (alphanumeric characters)
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` |
634
424
 
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
425
+ <details>
426
+ <summary><strong>Detailed Method Documentation</strong></summary>
640
427
 
641
- #### Basic Usage
428
+ #### `returnInsertAffiliateIdentifier(ignoreTimeout?)`
642
429
 
643
- ```javascript
644
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
430
+ Retrieves the current affiliate identifier.
645
431
 
646
- // Basic usage without validation feedback
647
- await InsertAffiliate.setShortCode('JOIN123');
648
- ```
432
+ **Parameters:**
433
+ - `ignoreTimeout` (optional, boolean): Set to `true` to get identifier even if attribution window expired
649
434
 
650
- #### Recommended Usage with Validation Feedback
435
+ **Returns:** `Promise<string | null>`
651
436
 
652
437
  ```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!');
661
-
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
- }
438
+ // Respects attribution window
439
+ const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
672
440
 
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
- });
441
+ // Ignores attribution window
442
+ const affiliateIdAlways = await InsertAffiliate.returnInsertAffiliateIdentifier(true);
678
443
  ```
679
444
 
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.
445
+ #### `returnCompanyId()`
687
446
 
688
- **Parameters:**
689
- - `ignoreTimeout` (optional, boolean): Set to `true` to retrieve the identifier even if the attribution window has expired. Default is `false`.
447
+ Retrieves the company ID used during initialization.
690
448
 
691
449
  **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
450
 
697
451
  ```javascript
698
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
452
+ const companyId = await InsertAffiliate.returnCompanyId();
453
+ ```
699
454
 
700
- // Initialize the SDK first
701
- await InsertAffiliate.initialize('your_company_code');
455
+ </details>
702
456
 
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
457
+ ---
706
458
 
707
- // Retrieve even if attribution window expired
708
- const affiliateIdIgnoreTimeout = await InsertAffiliate.returnInsertAffiliateIdentifier(true);
709
- console.log('Affiliate ID (ignore timeout):', affiliateIdIgnoreTimeout);
459
+ ## 🔍 Troubleshooting
710
460
 
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
- ```
461
+ ### Initialization Issues
724
462
 
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
463
+ **Error:** "Company code not set"
464
+ - **Solution:** Call `initialize()` before any other SDK methods
737
465
 
738
- #### `returnCompanyId()`
466
+ ### Deep Linking Issues
739
467
 
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.
468
+ **Problem:** Affiliate parameter not detected
469
+ - **Solution:** Ensure parameter name is exactly `insertAffiliate` (case-sensitive)
470
+ - Initialize SDK before URL parameters are processed
741
471
 
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
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
745
477
 
746
- **Example Usage:**
478
+ ### Verbose Logging
479
+
480
+ Enable detailed logs to diagnose issues:
747
481
 
748
482
  ```javascript
749
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
483
+ await InsertAffiliate.initialize('YOUR_COMPANY_CODE', true);
484
+ ```
750
485
 
751
- // Initialize the SDK first
752
- await InsertAffiliate.initialize('your_company_code');
486
+ ---
753
487
 
754
- // Later, retrieve the company ID
755
- const companyId = await InsertAffiliate.returnCompanyId();
756
- console.log('Company ID:', companyId); // Output: 'your_company_code'
488
+ ## 📚 Support
757
489
 
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
- ```
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)
769
495
 
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()`
496
+ ---
497
+
498
+ **Need help?** Check our [documentation](https://docs.insertaffiliate.com) or [contact support](https://app.insertaffiliate.com/help).