insert-affiliate-js-sdk 1.1.0 → 1.3.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,231 @@
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
+ // Full initialization with all options
93
+ await InsertAffiliate.initialize(
94
+ 'YOUR_COMPANY_CODE', // Company code (required)
95
+ true, // Enable verbose logging (optional, default: false)
96
+ 86400000, // Attribution timeout in milliseconds (optional, e.g., 24 hours)
97
+ true // Prevent affiliate transfer (optional, default: false)
98
+ );
85
99
  ```
86
100
 
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
101
+ **Parameters:**
102
+ - `companyCode` (required): Your Insert Affiliate company code
103
+ - `verboseLogging` (optional): Enable detailed console logs for debugging
104
+ - `affiliateAttributionActiveTime` (optional): Time in milliseconds before attribution expires (e.g., `86400000` for 24 hours)
105
+ - `preventAffiliateTransfer` (optional): When `true`, prevents a new affiliate link from overwriting an existing affiliate attribution (defaults to `false`)
106
+ - Use this to ensure the first affiliate who acquired the user always gets credit
107
+ - New affiliate links will be silently ignored if the user already has an affiliate
108
+
109
+ **Verbose logging shows:**
110
+ - Initialization process and company code validation
111
+ - Deep link processing and short code detection
112
+ - API communication details
113
+ - Storage operations
93
114
 
94
- ⚠️ **Important**: Disable verbose logging in production builds to avoid exposing sensitive debugging information and to optimize performance.
115
+ </details>
95
116
 
96
- ## In-App Purchase Setup [Required]
117
+ ---
97
118
 
98
- Insert Affiliate requires a receipt verification platform to validate purchases. Choose the integration method(s) that match your platform:
119
+ ### 2. Configure Payment Verification
99
120
 
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
121
+ **Choose the payment method(s) that match your platform:**
103
122
 
104
- ### Mobile In-App Purchases: RevenueCat Integration
123
+ | Method | Best For | Setup Guide |
124
+ |--------|----------|-------------|
125
+ | [**RevenueCat**](#option-1-revenuecat) | Mobile IAP (iOS/Android) | [View](#option-1-revenuecat) |
126
+ | [**Stripe**](#option-2-stripe) | Web-based payments | [View](#option-2-stripe) |
127
+ | [**Both**](#hybrid-apps) | Hybrid apps with mobile + web payments | Set up both |
105
128
 
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.
129
+ <details open>
130
+ <summary><h4>Option 1: RevenueCat</h4></summary>
108
131
 
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.
132
+ For mobile in-app purchases via Capacitor.
110
133
 
111
- 3. **Implementation Example**
134
+ **Step 1: Code Setup**
112
135
 
113
136
  ```javascript
114
137
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
115
138
  import { Purchases } from '@revenuecat/purchases-capacitor';
116
139
 
117
140
  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 });
141
+ await InsertAffiliate.initialize(
142
+ 'YOUR_COMPANY_CODE',
143
+ false, // verbose logging
144
+ 86400000, // 24 hour attribution timeout (optional)
145
+ true // prevent affiliate transfer (optional)
146
+ );
147
+ await Purchases.configure({ apiKey: 'YOUR_REVENUECAT_API_KEY' });
148
+
149
+ // Set up callback for when affiliate identifier changes
150
+ // Note: Use preventAffiliateTransfer in initialize() to block affiliate changes in the SDK
151
+ InsertAffiliate.setInsertAffiliateIdentifierChangeCallback(async (identifier, offerCode) => {
152
+ if (!identifier) return;
153
+
154
+ // Ensure RevenueCat subscriber exists before setting attributes
155
+ const customerInfo = await Purchases.getCustomerInfo();
156
+
157
+ // OPTIONAL: Prevent attribution for existing subscribers
158
+ // Uncomment to ensure affiliates only earn from users they actually brought:
159
+ // const hasActiveEntitlement = Object.keys(customerInfo.entitlements.active).length > 0;
160
+ // if (hasActiveEntitlement) return; // User already subscribed, don't attribute
161
+
162
+ // Get expiry timestamp for RevenueCat targeting
163
+ const expiryTimestamp = await InsertAffiliate.getAffiliateExpiryTimestamp();
164
+
165
+ // Set attributes for RevenueCat
166
+ const attributes = {
167
+ insert_affiliate: identifier,
168
+ insert_timedout: expiryTimestamp?.toString() || '',
169
+ };
170
+
171
+ // Add offer code for RevenueCat Targeting (if available)
172
+ if (offerCode) {
173
+ attributes.affiliateOfferCode = offerCode;
124
174
  }
175
+
176
+ await Purchases.setAttributes(attributes);
177
+ await Purchases.syncAttributesAndOfferingsIfNeeded();
178
+ });
125
179
  });
126
180
  ```
127
181
 
128
- #### Webhook Setup
129
-
130
- Next, you must setup a webhook to allow us to communicate directly with RevenueCat to track affiliate purchases.
131
-
132
- 1. Go to RevenueCat and [create a new webhook](https://www.revenuecat.com/docs/integrations/webhooks)
182
+ **Using RevenueCat Targeting (Recommended)**
133
183
 
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"
184
+ RevenueCat Targeting automatically shows different offerings based on the `affiliateOfferCode` attribute. Simply display `offerings.current`:
138
185
 
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
186
+ ```javascript
187
+ const offerings = await Purchases.getOfferings();
188
+ const currentOffering = offerings.current;
189
+ // RevenueCat targeting automatically shows the correct offering based on affiliateOfferCode
190
+ ```
147
191
 
148
- ## Web-Based Payments: Stripe Integration
192
+ **Step 2: Webhook Setup**
149
193
 
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.
194
+ 1. In RevenueCat, [create a new webhook](https://www.revenuecat.com/docs/integrations/webhooks)
195
+ 2. Configure webhook settings:
196
+ - **Webhook URL**: `https://api.insertaffiliate.com/v1/api/revenuecat-webhook`
197
+ - **Event Type**: "All events"
198
+ 3. In your [Insert Affiliate dashboard](https://app.insertaffiliate.com/settings):
199
+ - Set **In-App Purchase Verification** to `RevenueCat`
200
+ - Copy the `RevenueCat Webhook Authentication Header` value
201
+ 4. Paste the authentication header into RevenueCat's **Authorization header** field
151
202
 
152
- **📚 For complete setup instructions, see: [Stripe Web-Based Transactions Documentation](https://docs.insertaffiliate.com/stripe-web-based-transactions)**
203
+ **RevenueCat setup complete!**
153
204
 
154
- #### Setup Steps
205
+ </details>
155
206
 
156
- 1. **Connect Your Stripe Account (Required First Step)**
207
+ <details>
208
+ <summary><h4>Option 2: Stripe</h4></summary>
157
209
 
158
- Before integrating the SDK code, you must connect your Stripe account to Insert Affiliate:
210
+ For web-based subscriptions and payments.
159
211
 
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
212
+ **Step 1: Connect Stripe Account**
165
213
 
166
- 2. **Retrieve the Affiliate Identifier and Company ID**
214
+ 1. Go to your [Insert Affiliate dashboard settings](https://app.insertaffiliate.com/settings)
215
+ 2. Select **Stripe** as your verification method
216
+ 3. Click **Connect with Stripe** to authorize via Stripe Connect
167
217
 
168
- Before creating a Stripe checkout session, retrieve the current affiliate identifier and company ID from the Insert Affiliate SDK:
218
+ **Step 2: Pass Affiliate Data to Checkout**
169
219
 
170
220
  ```javascript
171
221
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
172
222
 
173
223
  const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
174
224
  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
225
 
181
- ```javascript
182
- const response = await fetch('https://your-backend.com/create-checkout-session', {
226
+ const response = await fetch('/create-checkout-session', {
183
227
  method: 'POST',
184
- headers: {
185
- 'Content-Type': 'application/json',
186
- },
228
+ headers: { 'Content-Type': 'application/json' },
187
229
  body: JSON.stringify({
188
230
  priceId: 'price_xxxxx',
189
231
  insertAffiliate: affiliateId,
@@ -194,585 +236,345 @@ const response = await fetch('https://your-backend.com/create-checkout-session',
194
236
  });
195
237
  ```
196
238
 
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:
239
+ **Step 3: Store in Stripe Metadata (Backend)**
200
240
 
201
241
  ```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
- }],
242
+ const session = await stripe.checkout.sessions.create({
243
+ mode: 'subscription',
244
+ line_items: [{ price: priceId, quantity: 1 }],
245
+ metadata: {
246
+ insertAffiliate: insertAffiliate || '',
247
+ insertAffiliateCompanyId: insertAffiliateCompanyId || '',
248
+ },
249
+ subscription_data: {
213
250
  metadata: {
214
251
  insertAffiliate: insertAffiliate || '',
215
252
  insertAffiliateCompanyId: insertAffiliateCompanyId || '',
216
253
  },
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 });
254
+ },
255
+ success_url: successUrl,
256
+ cancel_url: cancelUrl,
228
257
  });
229
258
  ```
230
259
 
231
- **Required Metadata Fields:**
232
- - `insertAffiliate`: The affiliate's short code
233
- - `insertAffiliateCompanyId`: Your Insert Affiliate company ID
260
+ 📖 **[View complete Stripe integration guide →](docs/stripe-integration.md)**
234
261
 
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.
262
+ Includes:
263
+ - Stripe Billing with RevenueCat
264
+ - RevenueCat Web Billing integration
265
+ - RevenueCat Web Purchase Links
266
+ - Callback-based integration
236
267
 
237
- ### Stripe Billing with RevenueCat
268
+ **Stripe setup complete!**
238
269
 
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.
270
+ </details>
240
271
 
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
272
+ ---
244
273
 
245
- **Integration:**
274
+ ### 3. Set Up Deep Linking
246
275
 
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
276
+ **Deep linking lets affiliates share unique links that track users to your app/website.**
251
277
 
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.
278
+ | Provider | Best For | Complexity |
279
+ |----------|----------|------------|
280
+ | [**Insert Links**](#option-1-insert-links-automatic) | Simplest setup, no 3rd party | Simple |
281
+ | [**Branch.io**](#option-2-branchio) | Robust attribution | Medium |
282
+ | [**AppsFlyer**](#option-3-appsflyer) | Enterprise analytics | Medium |
253
283
 
254
- ### RevenueCat Web Billing Integration
284
+ <details open>
285
+ <summary><h4>Option 1: Insert Links (Automatic)</h4></summary>
255
286
 
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.
287
+ Insert Links is Insert Affiliate's built-in deep linking - no configuration needed for web.
257
288
 
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)
289
+ The SDK automatically:
290
+ 1. Detects `insertAffiliate` parameter from URLs
291
+ 2. Validates and stores the affiliate identifier
292
+ 3. Triggers callbacks when affiliate changes
263
293
 
264
- **Integration Steps:**
294
+ **That's it!** Just initialize the SDK and affiliate links work automatically.
265
295
 
266
- 1. **Install and Initialize Both SDKs**
296
+ Learn more: [Insert Links Documentation](https://docs.insertaffiliate.com/insert-links)
267
297
 
268
- ```javascript
269
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
270
- import { Purchases } from '@revenuecat/purchases-js';
298
+ </details>
271
299
 
272
- // Initialize Insert Affiliate SDK
273
- await InsertAffiliate.initialize('your_company_code');
300
+ <details>
301
+ <summary><h4>Option 2: Branch.io</h4></summary>
274
302
 
275
- // Initialize RevenueCat Web SDK
276
- const purchases = Purchases.configure('your_revenuecat_web_api_key');
277
- ```
303
+ **For web redirects:** Configure your Branch.io Quick Links to redirect to your web URL with the affiliate parameter:
278
304
 
279
- 2. **Retrieve Affiliate Information and Pass as Metadata During Purchase**
305
+ ```
306
+ https://yourwebsite.com/checkout?insertAffiliate={affiliateShortCode}
307
+ ```
280
308
 
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:
309
+ **For Capacitor apps:** Use the Branch.io Capacitor plugin:
282
310
 
283
311
  ```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];
312
+ import { BranchDeepLinks } from 'capacitor-branch-deep-links';
313
+ import { InsertAffiliate } from 'insert-affiliate-js-sdk';
306
314
 
307
- if (!selectedPackage) {
308
- console.error('No packages available');
309
- return;
310
- }
315
+ BranchDeepLinks.addListener('init', async (event) => {
316
+ const clicked = event?.referringParams?.['+clicked_branch_link'];
317
+ const referringLink = event?.referringParams?.['~referring_link'];
311
318
 
312
- // Make the purchase with metadata
313
- const { customerInfo } = await purchases.purchase({
314
- rcPackage: selectedPackage,
315
- metadata: metadata,
319
+ if (clicked && referringLink) {
320
+ await InsertAffiliate.setInsertAffiliateIdentifier(referringLink);
321
+ }
316
322
  });
317
-
318
- console.log('Purchase successful!');
319
- console.log('Active entitlements:', Object.keys(customerInfo.entitlements.active));
320
323
  ```
321
324
 
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
325
+ 📖 **[View complete deep linking guide →](docs/deep-linking-web.md)**
332
326
 
333
- ## RevenueCat Web Purchase Links
327
+ </details>
334
328
 
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:
329
+ <details>
330
+ <summary><h4>Option 3: AppsFlyer</h4></summary>
336
331
 
337
- - **utm_source**
338
- - **utm_medium**
339
- - **utm_campaign**
332
+ Configure your AppsFlyer OneLinks to redirect to your web URL with the affiliate parameter:
340
333
 
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
334
  ```
350
-
351
- You should append:
352
- ```text
353
- ?utm_source=insertAffiliate&utm_medium={insertAffiliateCompanyId}&utm_campaign={insertAffiliateUtmCampaign}
335
+ https://yourwebsite.com/checkout?insertAffiliate={affiliateShortCode}
354
336
  ```
355
337
 
356
- #### Full Example With Parameters
357
- ```text
358
- https://pay.rev.cat/sandbox/viqxbcoudyfaeaxa/?utm_source=insertAffiliate&utm_medium=12345&utm_campaign=AFF123
359
- ```
338
+ The SDK automatically detects `insertAffiliate` from the URL and attributes the payment.
360
339
 
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
340
+ 📖 **[View complete deep linking guide →](docs/deep-linking-web.md)**
365
341
 
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.
342
+ </details>
367
343
 
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.
344
+ ---
370
345
 
371
- ### Branch.io Web Redirect Setup
346
+ ## Verify Your Integration
372
347
 
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.
348
+ ### Integration Checklist
374
349
 
375
- ### Creating a Branch.io Quick Link for Stripe Checkout:
350
+ - [ ] **SDK Initializes**: Check console for `SDK initialized with company code` log
351
+ - [ ] **Affiliate Detected**: Visit your site with `?insertAffiliate=TEST123` and verify it's captured
352
+ - [ ] **Payment Tracked**: Make a test purchase and verify it appears in Insert Affiliate dashboard
376
353
 
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
354
+ ### Testing URL Parameters
384
355
 
385
- **Example:**
356
+ Visit your app with an affiliate parameter:
386
357
  ```
387
- https://yourwebsite.com?insertAffiliate=ABC123
358
+ https://yourwebsite.com?insertAffiliate=TEST123
388
359
  ```
389
360
 
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
361
+ Check the affiliate was captured:
362
+ ```javascript
363
+ const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
364
+ console.log('Detected affiliate:', affiliateId); // Should output: TEST123
409
365
  ```
410
366
 
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
367
+ ### Common Setup Issues
416
368
 
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.
369
+ | Issue | Solution |
370
+ |-------|----------|
371
+ | "Company code not set" | Ensure `initialize()` is called before other SDK methods |
372
+ | Affiliate not detected | Check URL parameter is exactly `insertAffiliate` (case-sensitive) |
373
+ | Payment not tracked | Verify Stripe/RevenueCat webhook is configured correctly |
418
374
 
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
375
+ ---
423
376
 
424
- No extra setup, no redirects to configure — just initialise the SDK and you're done.
377
+ ## 🔧 Advanced Features
425
378
 
426
- Learn more in our[Insert Links documentation](https://docs.insertaffiliate.com/insert-links).
379
+ <details>
380
+ <summary><h3>Event Tracking (Beta)</h3></summary>
427
381
 
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
382
+ Track custom events beyond purchases to incentivize affiliates for specific actions.
434
383
 
435
384
  ```javascript
436
385
  import { InsertAffiliate } from 'insert-affiliate-js-sdk';
437
386
 
438
- // Track the current affiliate identifier
439
- let currentAffiliateId = null;
387
+ // Track a signup event (affiliate identifier must be set first)
388
+ await InsertAffiliate.trackEvent('user_signup');
389
+ ```
440
390
 
441
- InsertAffiliate.setInsertAffiliateIdentifierChangeCallback((identifier) => {
442
- if (identifier) {
443
- console.log('Affiliate identifier changed:', identifier);
444
- currentAffiliateId = identifier;
445
- }
446
- });
391
+ **Use Cases:**
392
+ - Pay affiliates for signups instead of purchases
393
+ - Track trial starts or content unlocks
447
394
 
448
- // Later, when creating a Stripe checkout session
449
- const companyId = await InsertAffiliate.returnCompanyId();
395
+ </details>
450
396
 
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
- ```
397
+ <details>
398
+ <summary><h3>Short Codes</h3></summary>
463
399
 
464
- #### Example: Updating the UI When an Affiliate Link Is Clicked
400
+ Short codes are unique, 3-25 character alphanumeric identifiers that affiliates can share (e.g., "SAVE20" in a TikTok description).
465
401
 
466
- ```javascript
467
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
402
+ **Validate and Store Short Code:**
468
403
 
469
- // Update the UI when the affiliate identifier changes
470
- InsertAffiliate.setInsertAffiliateIdentifierChangeCallback((identifier) => {
471
- if (identifier) {
472
- console.log('Affiliate identifier changed:', identifier);
404
+ ```javascript
405
+ const isValid = await InsertAffiliate.setShortCode('SAVE20');
473
406
 
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
- }
407
+ if (isValid) {
408
+ alert('Affiliate code applied!');
479
409
 
480
- analytics.track('affiliate_link_clicked', { identifier });
410
+ // Check for associated offer
411
+ const offerCode = await InsertAffiliate.getOfferCode();
412
+ if (offerCode) {
413
+ alert(`You unlocked: ${offerCode}`);
481
414
  }
482
- });
415
+ } else {
416
+ alert('Invalid affiliate code');
417
+ }
483
418
  ```
484
419
 
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
420
+ **Get Affiliate Details Without Setting:**
491
421
 
492
- **To clear the callback:**
493
422
  ```javascript
494
- InsertAffiliate.setInsertAffiliateIdentifierChangeCallback(null);
423
+ const details = await InsertAffiliate.getAffiliateDetails('SAVE20');
424
+
425
+ if (details) {
426
+ console.log('Affiliate Name:', details.affiliateName);
427
+ console.log('Short Code:', details.affiliateShortCode);
428
+ console.log('Deep Link:', details.deeplinkUrl);
429
+ }
495
430
  ```
496
431
 
497
- ## Capacitor/Hybrid App Deep Link Handling
432
+ Learn more: [Short Codes Documentation](https://docs.insertaffiliate.com/short-codes)
498
433
 
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:
434
+ </details>
501
435
 
502
- #### Example with Branch.io Capacitor Plugin
436
+ <details>
437
+ <summary><h3>Affiliate Change Callback</h3></summary>
503
438
 
504
- ```javascript
505
- import { BranchDeepLinks, BranchInitEvent } from 'capacitor-branch-deep-links';
506
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
439
+ Get notified when the affiliate identifier changes:
507
440
 
508
- // Set up callback to automatically capture affiliate identifier when user clicks a link
509
- InsertAffiliate.setInsertAffiliateIdentifierChangeCallback((identifier) => {
441
+ ```javascript
442
+ InsertAffiliate.setInsertAffiliateIdentifierChangeCallback((identifier, offerCode) => {
510
443
  if (identifier) {
511
- console.log('Affiliate identifier changed:', identifier);
512
- console.log('Affiliate attribution captured successfully');
513
- }
514
- });
515
-
516
- let branchInitialised = false;
517
-
518
- async function setUpBranchListener() {
519
- if (branchInitialised) return;
520
- branchInitialised = true;
444
+ console.log('Affiliate changed:', identifier);
445
+ console.log('Offer code:', offerCode || 'none');
521
446
 
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'];
447
+ // Update UI
448
+ document.getElementById('affiliate-banner').style.display = 'block';
526
449
 
527
- if (clicked && referringLink) {
528
- // This will automatically trigger the callback
529
- await InsertAffiliate.setInsertAffiliateIdentifier(referringLink);
530
- }
531
- });
450
+ // Track in analytics
451
+ analytics.track('affiliate_link_clicked', { identifier, offerCode });
452
+ }
453
+ });
532
454
 
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
- }
539
- }
455
+ // Clear callback when done
456
+ InsertAffiliate.setInsertAffiliateIdentifierChangeCallback(null);
540
457
  ```
541
458
 
542
- **Note:** For most web applications, the automatic URL detection method is recommended and requires no additional setup.
543
-
544
- ## Additional Features
459
+ **Callback Parameters:**
460
+ - `identifier` (string | null): The full affiliate identifier (shortCode-userId)
461
+ - `offerCode` (string | null): The offer code associated with this affiliate (if any)
545
462
 
546
- ### 1. Event Tracking (Beta)
463
+ </details>
547
464
 
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).
465
+ ### Prevent Affiliate Transfer
552
466
 
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:
467
+ By default, clicking a new affiliate link will overwrite any existing attribution. Enable `preventAffiliateTransfer` to lock the first affiliate:
558
468
 
559
469
  ```javascript
560
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
561
-
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
- }
568
- }
470
+ await InsertAffiliate.initialize(
471
+ "YOUR_COMPANY_CODE",
472
+ false, // verboseLogging
473
+ 604800, // 7-day attribution timeout
474
+ true // preventAffiliateTransfer - locks first affiliate
475
+ );
569
476
  ```
570
477
 
571
- ### 2. Short Codes (Beta)
478
+ **How it works:**
479
+ - When enabled, once a user is attributed to an affiliate, that attribution is locked
480
+ - New affiliate links will not overwrite the existing attribution
481
+ - The callback still fires with the existing affiliate data (not the new one)
482
+ - Useful for preventing "affiliate stealing" where users click competitor links
572
483
 
573
- ### What are Short Codes?
484
+ Learn more: [Prevent Affiliate Transfer Documentation](https://docs.insertaffiliate.com/prevent-affiliate-transfer)
574
485
 
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.
486
+ ---
576
487
 
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.
488
+ ## 📖 API Reference
578
489
 
579
- For more information, visit the [Insert Affiliate Short Codes Documentation](https://docs.insertaffiliate.com/short-codes).
490
+ ### Core Methods
580
491
 
581
- ### Getting Affiliate Details
492
+ | Method | Description | Returns |
493
+ |--------|-------------|---------|
494
+ | `initialize(companyCode, verbose?, timeout?, preventTransfer?)` | Initialize the SDK | `Promise<void>` |
495
+ | `returnInsertAffiliateIdentifier(ignoreTimeout?)` | Get current affiliate identifier | `Promise<string \| null>` |
496
+ | `returnCompanyId()` | Get company ID | `Promise<string \| null>` |
497
+ | `setInsertAffiliateIdentifier(link)` | Set affiliate from deep link | `Promise<string \| null>` |
498
+ | `setShortCode(code)` | Validate and store short code | `Promise<boolean>` |
499
+ | `getAffiliateDetails(code)` | Get affiliate info without storing | `Promise<AffiliateDetails \| null>` |
500
+ | `trackEvent(eventName)` | Track custom event | `Promise<void>` |
501
+ | `getOfferCode()` | Get offer code modifier | `Promise<string \| null>` |
502
+ | `getAffiliateExpiryTimestamp()` | Get Unix timestamp (ms) when attribution expires | `Promise<number \| null>` |
503
+ | `getAffiliateStoredDate()` | Get ISO date string when affiliate was stored | `Promise<string \| null>` |
504
+ | `isAffiliateAttributionValid()` | Check if attribution is still valid | `Promise<boolean>` |
505
+ | `setInsertAffiliateIdentifierChangeCallback(fn)` | Set change callback | `void` |
582
506
 
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.
507
+ <details>
508
+ <summary><strong>Detailed Method Documentation</strong></summary>
584
509
 
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
510
+ #### `returnInsertAffiliateIdentifier(ignoreTimeout?)`
589
511
 
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
512
+ Retrieves the current affiliate identifier.
594
513
 
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
514
+ **Parameters:**
515
+ - `ignoreTimeout` (optional, boolean): Set to `true` to get identifier even if attribution window expired
600
516
 
601
- #### Example Usage
517
+ **Returns:** `Promise<string | null>`
602
518
 
603
519
  ```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}`);
520
+ // Respects attribution window
521
+ const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
613
522
 
614
- // Update UI with affiliate name
615
- document.getElementById('referrer').textContent = `Referred by: ${details.affiliateName}`;
616
- } else {
617
- console.log('Affiliate not found');
618
- }
523
+ // Ignores attribution window
524
+ const affiliateIdAlways = await InsertAffiliate.returnInsertAffiliateIdentifier(true);
619
525
  ```
620
526
 
621
- ### Setting a Short Code
622
-
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.
630
-
631
- **Short Code Requirements:**
632
- - Between **3 and 25 characters long**
633
- - Contain only **letters and numbers** (alphanumeric characters)
527
+ #### `returnCompanyId()`
634
528
 
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
529
+ Retrieves the company ID used during initialization.
640
530
 
641
- #### Basic Usage
531
+ **Returns:** `Promise<string | null>`
642
532
 
643
533
  ```javascript
644
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
645
-
646
- // Basic usage without validation feedback
647
- await InsertAffiliate.setShortCode('JOIN123');
534
+ const companyId = await InsertAffiliate.returnCompanyId();
648
535
  ```
649
536
 
650
- #### Recommended Usage with Validation Feedback
537
+ </details>
651
538
 
652
- ```javascript
653
- import { InsertAffiliate } from 'insert-affiliate-js-sdk';
539
+ ---
654
540
 
655
- async function handleShortCodeSubmit(userEnteredCode) {
656
- const isValid = await InsertAffiliate.setShortCode(userEnteredCode);
541
+ ## 🔍 Troubleshooting
657
542
 
658
- if (isValid) {
659
- // Show success message
660
- alert('Affiliate code applied successfully!');
543
+ ### Initialization Issues
661
544
 
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
- });
678
- ```
679
-
680
- ## API Reference
545
+ **Error:** "Company code not set"
546
+ - **Solution:** Call `initialize()` before any other SDK methods
681
547
 
682
- ### Core Methods
548
+ ### Deep Linking Issues
683
549
 
684
- #### `returnInsertAffiliateIdentifier()`
550
+ **Problem:** Affiliate parameter not detected
551
+ - **Solution:** Ensure parameter name is exactly `insertAffiliate` (case-sensitive)
552
+ - Initialize SDK before URL parameters are processed
685
553
 
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.
554
+ ### Payment Tracking Issues
687
555
 
688
- **Parameters:**
689
- - `ignoreTimeout` (optional, boolean): Set to `true` to retrieve the identifier even if the attribution window has expired. Default is `false`.
556
+ **Problem:** Purchases not appearing in dashboard
557
+ - **Solution:** Verify webhook configuration in Stripe/RevenueCat
558
+ - Check both `insertAffiliate` and `insertAffiliateCompanyId` are in metadata
690
559
 
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
560
+ ### Verbose Logging
694
561
 
695
- **Example Usage:**
562
+ Enable detailed logs to diagnose issues:
696
563
 
697
564
  ```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
- });
565
+ await InsertAffiliate.initialize('YOUR_COMPANY_CODE', true);
723
566
  ```
724
567
 
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';
568
+ ---
750
569
 
751
- // Initialize the SDK first
752
- await InsertAffiliate.initialize('your_company_code');
570
+ ## 📚 Support
753
571
 
754
- // Later, retrieve the company ID
755
- const companyId = await InsertAffiliate.returnCompanyId();
756
- console.log('Company ID:', companyId); // Output: 'your_company_code'
572
+ - **Documentation**: [docs.insertaffiliate.com](https://docs.insertaffiliate.com)
573
+ - **Stripe Integration Guide**: [docs/stripe-integration.md](docs/stripe-integration.md)
574
+ - **Deep Linking Guide**: [docs/deep-linking-web.md](docs/deep-linking-web.md)
575
+ - **Dashboard**: [app.insertaffiliate.com](https://app.insertaffiliate.com)
576
+ - **Issues**: [GitHub Issues](https://github.com/Insert-Affiliate/insert-affiliate-js-sdk/issues)
757
577
 
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
- ```
578
+ ---
769
579
 
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()`
580
+ **Need help?** Check our [documentation](https://docs.insertaffiliate.com) or [contact support](https://app.insertaffiliate.com/help).