insert-affiliate-js-sdk
v1.3.0
Published
  
Readme
Insert Affiliate JavaScript SDK
The official JavaScript SDK for Insert Affiliate - track affiliate-driven purchases on web and hybrid applications.
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.
Table of Contents
- Quick Start (5 Minutes)
- Essential Setup
- Verify Your Integration
- Advanced Features
- API Reference
- Troubleshooting
- Support
🚀 Quick Start (5 Minutes)
Get up and running with minimal code to validate the SDK works.
Prerequisites
- Modern web browser or Capacitor 4+
- Company Code from your Insert Affiliate dashboard
Supported Platforms
| Platform | Status | |----------|--------| | Capacitor (iOS / Android) | ✅ Fully tested | | Web Browsers | ✅ Tested in modern browsers | | Other JS Environments | ⚠️ May work, not officially tested |
Installation
npm install insert-affiliate-js-sdkFor Capacitor apps, also run:
npx cap syncYour First Integration
import { InsertAffiliate } from 'insert-affiliate-js-sdk';
// Initialize with verbose logging for setup
await InsertAffiliate.initialize('YOUR_COMPANY_CODE', true);Expected Console Output:
[Insert Affiliate] SDK initialized with company code: YOUR_COMPANY_CODE
[Insert Affiliate] [VERBOSE] SDK marked as initialized✅ If you see these logs, the SDK is working! Now proceed to Essential Setup.
⚠️ Disable verbose logging in production by setting the second parameter to false.
⚙️ Essential Setup
Complete these three steps to start tracking affiliate-driven purchases.
1. Initialize the SDK
Add SDK initialization to your main entry point (main.ts, main.js, or App.tsx):
import { InsertAffiliate } from 'insert-affiliate-js-sdk';
await InsertAffiliate.initialize('YOUR_COMPANY_CODE');// Full initialization with all options
await InsertAffiliate.initialize(
'YOUR_COMPANY_CODE', // Company code (required)
true, // Enable verbose logging (optional, default: false)
86400000, // Attribution timeout in milliseconds (optional, e.g., 24 hours)
true // Prevent affiliate transfer (optional, default: false)
);Parameters:
companyCode(required): Your Insert Affiliate company codeverboseLogging(optional): Enable detailed console logs for debuggingaffiliateAttributionActiveTime(optional): Time in milliseconds before attribution expires (e.g.,86400000for 24 hours)preventAffiliateTransfer(optional): Whentrue, prevents a new affiliate link from overwriting an existing affiliate attribution (defaults tofalse)- Use this to ensure the first affiliate who acquired the user always gets credit
- New affiliate links will be silently ignored if the user already has an affiliate
Verbose logging shows:
- Initialization process and company code validation
- Deep link processing and short code detection
- API communication details
- Storage operations
2. Configure Payment Verification
Choose the payment method(s) that match your platform:
| Method | Best For | Setup Guide | |--------|----------|-------------| | RevenueCat | Mobile IAP (iOS/Android) | View | | Stripe | Web-based payments | View | | Both | Hybrid apps with mobile + web payments | Set up both |
For mobile in-app purchases via Capacitor.
Step 1: Code Setup
import { InsertAffiliate } from 'insert-affiliate-js-sdk';
import { Purchases } from '@revenuecat/purchases-capacitor';
window.addEventListener('DOMContentLoaded', async () => {
await InsertAffiliate.initialize(
'YOUR_COMPANY_CODE',
false, // verbose logging
86400000, // 24 hour attribution timeout (optional)
true // prevent affiliate transfer (optional)
);
await Purchases.configure({ apiKey: 'YOUR_REVENUECAT_API_KEY' });
// Set up callback for when affiliate identifier changes
// Note: Use preventAffiliateTransfer in initialize() to block affiliate changes in the SDK
InsertAffiliate.setInsertAffiliateIdentifierChangeCallback(async (identifier, offerCode) => {
if (!identifier) return;
// Ensure RevenueCat subscriber exists before setting attributes
const customerInfo = await Purchases.getCustomerInfo();
// OPTIONAL: Prevent attribution for existing subscribers
// Uncomment to ensure affiliates only earn from users they actually brought:
// const hasActiveEntitlement = Object.keys(customerInfo.entitlements.active).length > 0;
// if (hasActiveEntitlement) return; // User already subscribed, don't attribute
// Get expiry timestamp for RevenueCat targeting
const expiryTimestamp = await InsertAffiliate.getAffiliateExpiryTimestamp();
// Set attributes for RevenueCat
const attributes = {
insert_affiliate: identifier,
insert_timedout: expiryTimestamp?.toString() || '',
};
// Add offer code for RevenueCat Targeting (if available)
if (offerCode) {
attributes.affiliateOfferCode = offerCode;
}
await Purchases.setAttributes(attributes);
await Purchases.syncAttributesAndOfferingsIfNeeded();
});
});Using RevenueCat Targeting (Recommended)
RevenueCat Targeting automatically shows different offerings based on the affiliateOfferCode attribute. Simply display offerings.current:
const offerings = await Purchases.getOfferings();
const currentOffering = offerings.current;
// RevenueCat targeting automatically shows the correct offering based on affiliateOfferCodeStep 2: Webhook Setup
- In RevenueCat, create a new webhook
- Configure webhook settings:
- Webhook URL:
https://api.insertaffiliate.com/v1/api/revenuecat-webhook - Event Type: "All events"
- Webhook URL:
- In your Insert Affiliate dashboard:
- Set In-App Purchase Verification to
RevenueCat - Copy the
RevenueCat Webhook Authentication Headervalue
- Set In-App Purchase Verification to
- Paste the authentication header into RevenueCat's Authorization header field
✅ RevenueCat setup complete!
For web-based subscriptions and payments.
Step 1: Connect Stripe Account
- Go to your Insert Affiliate dashboard settings
- Select Stripe as your verification method
- Click Connect with Stripe to authorize via Stripe Connect
Step 2: Pass Affiliate Data to Checkout
import { InsertAffiliate } from 'insert-affiliate-js-sdk';
const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
const companyId = await InsertAffiliate.returnCompanyId();
const response = await fetch('/create-checkout-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
priceId: 'price_xxxxx',
insertAffiliate: affiliateId,
insertAffiliateCompanyId: companyId,
successUrl: window.location.origin + '/success',
cancelUrl: window.location.origin + '/canceled',
}),
});Step 3: Store in Stripe Metadata (Backend)
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
line_items: [{ price: priceId, quantity: 1 }],
metadata: {
insertAffiliate: insertAffiliate || '',
insertAffiliateCompanyId: insertAffiliateCompanyId || '',
},
subscription_data: {
metadata: {
insertAffiliate: insertAffiliate || '',
insertAffiliateCompanyId: insertAffiliateCompanyId || '',
},
},
success_url: successUrl,
cancel_url: cancelUrl,
});📖 View complete Stripe integration guide →
Includes:
- Stripe Billing with RevenueCat
- RevenueCat Web Billing integration
- RevenueCat Web Purchase Links
- Callback-based integration
✅ Stripe setup complete!
3. Set Up Deep Linking
Deep linking lets affiliates share unique links that track users to your app/website.
| Provider | Best For | Complexity | |----------|----------|------------| | Insert Links | Simplest setup, no 3rd party | Simple | | Branch.io | Robust attribution | Medium | | AppsFlyer | Enterprise analytics | Medium |
Insert Links is Insert Affiliate's built-in deep linking - no configuration needed for web.
The SDK automatically:
- Detects
insertAffiliateparameter from URLs - Validates and stores the affiliate identifier
- Triggers callbacks when affiliate changes
That's it! Just initialize the SDK and affiliate links work automatically.
Learn more: Insert Links Documentation
For web redirects: Configure your Branch.io Quick Links to redirect to your web URL with the affiliate parameter:
https://yourwebsite.com/checkout?insertAffiliate={affiliateShortCode}For Capacitor apps: Use the Branch.io Capacitor plugin:
import { BranchDeepLinks } from 'capacitor-branch-deep-links';
import { InsertAffiliate } from 'insert-affiliate-js-sdk';
BranchDeepLinks.addListener('init', async (event) => {
const clicked = event?.referringParams?.['+clicked_branch_link'];
const referringLink = event?.referringParams?.['~referring_link'];
if (clicked && referringLink) {
await InsertAffiliate.setInsertAffiliateIdentifier(referringLink);
}
});📖 View complete deep linking guide →
Configure your AppsFlyer OneLinks to redirect to your web URL with the affiliate parameter:
https://yourwebsite.com/checkout?insertAffiliate={affiliateShortCode}The SDK automatically detects insertAffiliate from the URL and attributes the payment.
📖 View complete deep linking guide →
✅ Verify Your Integration
Integration Checklist
- [ ] SDK Initializes: Check console for
SDK initialized with company codelog - [ ] Affiliate Detected: Visit your site with
?insertAffiliate=TEST123and verify it's captured - [ ] Payment Tracked: Make a test purchase and verify it appears in Insert Affiliate dashboard
Testing URL Parameters
Visit your app with an affiliate parameter:
https://yourwebsite.com?insertAffiliate=TEST123Check the affiliate was captured:
const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
console.log('Detected affiliate:', affiliateId); // Should output: TEST123Common Setup Issues
| Issue | Solution |
|-------|----------|
| "Company code not set" | Ensure initialize() is called before other SDK methods |
| Affiliate not detected | Check URL parameter is exactly insertAffiliate (case-sensitive) |
| Payment not tracked | Verify Stripe/RevenueCat webhook is configured correctly |
🔧 Advanced Features
Track custom events beyond purchases to incentivize affiliates for specific actions.
import { InsertAffiliate } from 'insert-affiliate-js-sdk';
// Track a signup event (affiliate identifier must be set first)
await InsertAffiliate.trackEvent('user_signup');Use Cases:
- Pay affiliates for signups instead of purchases
- Track trial starts or content unlocks
Short codes are unique, 3-25 character alphanumeric identifiers that affiliates can share (e.g., "SAVE20" in a TikTok description).
Validate and Store Short Code:
const isValid = await InsertAffiliate.setShortCode('SAVE20');
if (isValid) {
alert('Affiliate code applied!');
// Check for associated offer
const offerCode = await InsertAffiliate.getOfferCode();
if (offerCode) {
alert(`You unlocked: ${offerCode}`);
}
} else {
alert('Invalid affiliate code');
}Get Affiliate Details Without Setting:
const details = await InsertAffiliate.getAffiliateDetails('SAVE20');
if (details) {
console.log('Affiliate Name:', details.affiliateName);
console.log('Short Code:', details.affiliateShortCode);
console.log('Deep Link:', details.deeplinkUrl);
}Learn more: Short Codes Documentation
Get notified when the affiliate identifier changes:
InsertAffiliate.setInsertAffiliateIdentifierChangeCallback((identifier, offerCode) => {
if (identifier) {
console.log('Affiliate changed:', identifier);
console.log('Offer code:', offerCode || 'none');
// Update UI
document.getElementById('affiliate-banner').style.display = 'block';
// Track in analytics
analytics.track('affiliate_link_clicked', { identifier, offerCode });
}
});
// Clear callback when done
InsertAffiliate.setInsertAffiliateIdentifierChangeCallback(null);Callback Parameters:
identifier(string | null): The full affiliate identifier (shortCode-userId)offerCode(string | null): The offer code associated with this affiliate (if any)
Prevent Affiliate Transfer
By default, clicking a new affiliate link will overwrite any existing attribution. Enable preventAffiliateTransfer to lock the first affiliate:
await InsertAffiliate.initialize(
"YOUR_COMPANY_CODE",
false, // verboseLogging
604800, // 7-day attribution timeout
true // preventAffiliateTransfer - locks first affiliate
);How it works:
- When enabled, once a user is attributed to an affiliate, that attribution is locked
- New affiliate links will not overwrite the existing attribution
- The callback still fires with the existing affiliate data (not the new one)
- Useful for preventing "affiliate stealing" where users click competitor links
Learn more: Prevent Affiliate Transfer Documentation
📖 API Reference
Core Methods
| Method | Description | Returns |
|--------|-------------|---------|
| initialize(companyCode, verbose?, timeout?, preventTransfer?) | Initialize the SDK | Promise<void> |
| returnInsertAffiliateIdentifier(ignoreTimeout?) | Get current affiliate identifier | Promise<string \| null> |
| returnCompanyId() | Get company ID | Promise<string \| null> |
| setInsertAffiliateIdentifier(link) | Set affiliate from deep link | Promise<string \| null> |
| setShortCode(code) | Validate and store short code | Promise<boolean> |
| getAffiliateDetails(code) | Get affiliate info without storing | Promise<AffiliateDetails \| null> |
| trackEvent(eventName) | Track custom event | Promise<void> |
| getOfferCode() | Get offer code modifier | Promise<string \| null> |
| getAffiliateExpiryTimestamp() | Get Unix timestamp (ms) when attribution expires | Promise<number \| null> |
| getAffiliateStoredDate() | Get ISO date string when affiliate was stored | Promise<string \| null> |
| isAffiliateAttributionValid() | Check if attribution is still valid | Promise<boolean> |
| setInsertAffiliateIdentifierChangeCallback(fn) | Set change callback | void |
returnInsertAffiliateIdentifier(ignoreTimeout?)
Retrieves the current affiliate identifier.
Parameters:
ignoreTimeout(optional, boolean): Set totrueto get identifier even if attribution window expired
Returns: Promise<string | null>
// Respects attribution window
const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
// Ignores attribution window
const affiliateIdAlways = await InsertAffiliate.returnInsertAffiliateIdentifier(true);returnCompanyId()
Retrieves the company ID used during initialization.
Returns: Promise<string | null>
const companyId = await InsertAffiliate.returnCompanyId();🔍 Troubleshooting
Initialization Issues
Error: "Company code not set"
- Solution: Call
initialize()before any other SDK methods
Deep Linking Issues
Problem: Affiliate parameter not detected
- Solution: Ensure parameter name is exactly
insertAffiliate(case-sensitive) - Initialize SDK before URL parameters are processed
Payment Tracking Issues
Problem: Purchases not appearing in dashboard
- Solution: Verify webhook configuration in Stripe/RevenueCat
- Check both
insertAffiliateandinsertAffiliateCompanyIdare in metadata
Verbose Logging
Enable detailed logs to diagnose issues:
await InsertAffiliate.initialize('YOUR_COMPANY_CODE', true);📚 Support
- Documentation: docs.insertaffiliate.com
- Stripe Integration Guide: docs/stripe-integration.md
- Deep Linking Guide: docs/deep-linking-web.md
- Dashboard: app.insertaffiliate.com
- Issues: GitHub Issues
Need help? Check our documentation or contact support.
