insert_affiliate_flutter_sdk 1.4.0 copy "insert_affiliate_flutter_sdk: ^1.4.0" to clipboard
insert_affiliate_flutter_sdk: ^1.4.0 copied to clipboard

PlatformAndroid

A Flutter SDK for integrating affiliate tracking and in-app purchases for the Insert Affiliate Platform.

Insert Affiliate Flutter SDK #

Version Flutter Platform

The official Flutter SDK for Insert Affiliate - track affiliate-driven in-app purchases and reward your partners automatically.

What does this SDK do? It connects your Flutter app to Insert Affiliate's platform, enabling you to track which affiliates drive subscriptions and automatically pay them commissions when users make in-app purchases.

Table of Contents #


πŸš€ Quick Start (5 Minutes) #

Get up and running with minimal code to validate the SDK works before tackling IAP and deep linking setup.

Prerequisites #

Installation #

Add to your pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  insert_affiliate_flutter_sdk: <latest_version>
  shared_preferences: <latest_version>
  http: <latest_version>

Then run:

flutter pub get

Your First Integration #

import 'package:flutter/material.dart';
import 'package:insert_affiliate_flutter_sdk/insert_affiliate_flutter_sdk.dart';

late final InsertAffiliateFlutterSDK insertAffiliateSdk;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize Insert Affiliate SDK
  insertAffiliateSdk = InsertAffiliateFlutterSDK(
    companyCode: "YOUR_COMPANY_CODE",  // Get from https://app.insertaffiliate.com/settings
    verboseLogging: true,               // Enable for setup debugging
  );

  runApp(MyApp());
}

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 removing the verboseLogging: true parameter.


βš™οΈ Essential Setup #

Complete these three required steps to start tracking affiliate-driven purchases.

1. Initialize the SDK #

You've already done basic initialization above. Here are additional options:

Advanced Initialization Options (click to expand)
insertAffiliateSdk = InsertAffiliateFlutterSDK(
  companyCode: "YOUR_COMPANY_CODE",
  verboseLogging: true,              // Enable detailed debugging logs
  insertLinksEnabled: true,          // Enable Insert Links (built-in deep linking)
  insertLinksClipboardEnabled: true, // Enable clipboard attribution (triggers permission prompt)
  attributionTimeout: 604800,        // 7 days attribution timeout in seconds
);

Parameters:

  • verboseLogging: Shows detailed logs for debugging (disable in production)
  • insertLinksEnabled: Set to true if using Insert Links, false if using Branch/AppsFlyer
  • insertLinksClipboardEnabled: Enables clipboard-based attribution for Insert Links
  • attributionTimeout: How long affiliate attribution lasts in seconds (0 = never expires)

2. Configure In-App Purchase Verification #

Insert Affiliate requires a receipt verification method to validate purchases. Choose ONE of the following:

Method Best For Setup Time Complexity
RevenueCat Most developers, managed infrastructure ~10 min Simple
Adapty Paywall A/B testing, analytics ~10 min Simple
Iaptic Custom requirements, direct control ~15 min Medium
App Store Direct No 3rd party fees (iOS) ~20 min Medium
Google Play Direct No 3rd party fees (Android) ~20 min Medium

Option 1: RevenueCat (Recommended)

Step 1: Code Setup

Complete the RevenueCat Flutter SDK installation first, then:

import 'package:purchases_flutter/purchases_flutter.dart';
import 'package:insert_affiliate_flutter_sdk/insert_affiliate_flutter_sdk.dart';

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _initializeAsyncDependencies();
  }

  Future<void> _initializeAsyncDependencies() async {
    // Initialize RevenueCat
    await Purchases.configure(PurchasesConfiguration("YOUR_REVENUECAT_API_KEY"));

    // Handle affiliate identifier
    handleAffiliateIdentifier();
  }

  void handleAffiliateIdentifier() {
    insertAffiliateSdk.returnInsertAffiliateIdentifier().then((value) {
      if (value != null && value.isNotEmpty) {
        Purchases.setAttributes({"insert_affiliate": value});
      }
    });
  }
}

Step 2: Webhook Setup

  1. In RevenueCat, create a new webhook
  2. Configure webhook settings:
    • Webhook URL: https://api.insertaffiliate.com/v1/api/revenuecat-webhook
    • Event Type: "All events"
  3. In your Insert Affiliate dashboard:
    • Set In-App Purchase Verification to RevenueCat
    • Copy the RevenueCat Webhook Authentication Header value
  4. Paste the authentication header into RevenueCat's Authorization header field

βœ… RevenueCat setup complete!

Option 2: Adapty

Step 1: Install Adapty SDK

Add to your pubspec.yaml:

dependencies:
  adapty_flutter: ^3.2.1

Then run:

flutter pub get

Complete the Adapty Flutter SDK installation for any additional platform-specific setup.

Step 2: Code Setup

import 'package:flutter/material.dart';
import 'package:adapty_flutter/adapty_flutter.dart';
import 'package:insert_affiliate_flutter_sdk/insert_affiliate_flutter_sdk.dart';

late final InsertAffiliateFlutterSDK insertAffiliateSdk;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize Insert Affiliate SDK
  insertAffiliateSdk = InsertAffiliateFlutterSDK(
    companyCode: "YOUR_COMPANY_CODE",
  );

  runApp(MyApp());
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _initializeSDKs();
  }

  Future<void> _initializeSDKs() async {
    // Initialize Adapty
    await Adapty().activate(
      configuration: AdaptyConfiguration(apiKey: 'YOUR_ADAPTY_PUBLIC_KEY')
        ..withLogLevel(AdaptyLogLevel.verbose),
    );

    // Set up callback for affiliate identifier changes
    insertAffiliateSdk.setInsertAffiliateIdentifierChangeCallback((identifier) async {
      if (identifier != null && identifier.isNotEmpty) {
        await _updateAdaptyWithAffiliateId(identifier);
      }
    });

    // Check for existing affiliate identifier
    final existingId = await insertAffiliateSdk.returnInsertAffiliateIdentifier();
    if (existingId != null && existingId.isNotEmpty) {
      await _updateAdaptyWithAffiliateId(existingId);
    }
  }

  Future<void> _updateAdaptyWithAffiliateId(String affiliateId) async {
    final builder = AdaptyProfileParametersBuilder()
      ..setCustomStringAttribute(affiliateId, 'insert_affiliate');
    await Adapty().updateProfile(builder.build());
  }
}

Step 3: Ensure Attribution Before Purchase

Future<void> _makePurchase(AdaptyPaywallProduct product) async {
  // Always ensure affiliate ID is set before purchase
  final affiliateId = await insertAffiliateSdk.returnInsertAffiliateIdentifier();
  if (affiliateId != null && affiliateId.isNotEmpty) {
    final builder = AdaptyProfileParametersBuilder()
      ..setCustomStringAttribute(affiliateId, 'insert_affiliate');
    await Adapty().updateProfile(builder.build());
  }

  // Now make the purchase
  final result = await Adapty().makePurchase(product: product);
  // Handle result...
}

Step 4: Webhook Setup

  1. In your Insert Affiliate dashboard:

    • Set In-App Purchase Verification to Adapty
    • Copy the Adapty Webhook URL
    • Copy the Adapty Webhook Authorization Header value
  2. In the Adapty Dashboard:

    • Navigate to Integrations β†’ Webhooks
    • Set Production URL to the webhook URL from Insert Affiliate
    • Set Sandbox URL to the same webhook URL
    • Paste the authorization header value into Authorization header value
    • Enable these options:
      • Exclude historical events
      • Send attribution
      • Send trial price
      • Send user attributes
    • Save the configuration

Step 5: Verify Integration

To confirm the affiliate identifier is set correctly:

  1. Go to app.adapty.io/profiles/users
  2. Find the test user who made a purchase
  3. Look for insert_affiliate in Custom attributes with format: {SHORT_CODE}-{UUID}

βœ… Adapty setup complete!

Option 3: Iaptic

Step 1: Code Setup

Complete the In App Purchase Flutter Library setup first:

import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:insert_affiliate_flutter_sdk/insert_affiliate_flutter_sdk.dart';

class _MyAppState extends State<MyApp> {
  final InAppPurchase _iap = InAppPurchase.instance;

  void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) async {
    for (var purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.purchased) {
        final jsonIapPurchase = {
          'transactionReceipt': purchaseDetails.verificationData.localVerificationData,
          'orderId': purchaseDetails.purchaseID,
          'purchaseToken': purchaseDetails.verificationData.serverVerificationData,
          'signature': purchaseDetails.verificationData.localVerificationData,
          'applicationUsername': await insertAffiliateSdk.returnInsertAffiliateIdentifier(),
        };

        await insertAffiliateSdk.validatePurchaseWithIapticAPI(
          jsonIapPurchase,
          "YOUR_IAPTIC_APP_ID",
          "YOUR_IAPTIC_APP_NAME",
          "YOUR_IAPTIC_PUBLIC_KEY"
        );
      }
    }
  }
}

Step 2: Webhook Setup

  1. In Insert Affiliate settings:
    • Set verification method to Iaptic
    • Copy the Iaptic Webhook URL and Iaptic Webhook Sandbox URL
  2. In Iaptic Settings:
    • Paste the Webhook URLs into corresponding fields
    • Click Save Settings
  3. Complete Iaptic App Store Server Notifications setup
  4. Complete Iaptic Google Play Notifications setup

βœ… Iaptic setup complete!

Option 4: App Store Direct

Step 1: Visit our docs and complete the App Store Server Notifications setup.

Step 2: Implementing Purchases

import 'dart:io';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:insert_affiliate_flutter_sdk/insert_affiliate_flutter_sdk.dart';

void _buySubscription(ProductDetails product) async {
  String? appAccountToken;
  if (Platform.isIOS) {
    appAccountToken = await insertAffiliateSdk.returnUserAccountTokenAndStoreExpectedTransaction();
  }

  final purchaseParam = PurchaseParam(
    productDetails: product,
    applicationUserName: appAccountToken,
  );

  _iap.buyNonConsumable(purchaseParam: purchaseParam);
}

βœ… App Store Direct setup complete!

Option 5: Google Play Direct

Step 1: Visit our docs and complete the RTDN setup.

Step 2: Implementing Purchases

import 'dart:io';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_android/in_app_purchase_android.dart';
import 'package:insert_affiliate_flutter_sdk/insert_affiliate_flutter_sdk.dart';

void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) async {
  for (var purchaseDetails in purchaseDetailsList) {
    if (purchaseDetails.status == PurchaseStatus.purchased) {
      if (Platform.isAndroid && purchaseDetails is GooglePlayPurchaseDetails) {
        final purchaseToken = purchaseDetails.billingClientPurchase.purchaseToken;
        if (purchaseToken.isNotEmpty) {
          await insertAffiliateSdk.storeExpectedStoreTransaction(purchaseToken);
        }
      }
      InAppPurchase.instance.completePurchase(purchaseDetails);
    }
  }
}

βœ… Google Play Direct setup complete!


3. Set Up Deep Linking #

Deep linking lets affiliates share unique links that track users to your app. Choose ONE deep linking provider:

Provider Best For Complexity Setup Guide
Insert Links Simple setup, no 3rd party Simple View
Branch.io Robust attribution, deferred deep linking Medium View
AppsFlyer Enterprise analytics, comprehensive attribution Medium View

Option 1: Insert Links

Insert Links is Insert Affiliate's built-in deep linking solution.

Step 1: Complete the Insert Links setup in the dashboard.

Step 2: Initialize with Insert Links enabled

insertAffiliateSdk = InsertAffiliateFlutterSDK(
  companyCode: "YOUR_COMPANY_CODE",
  verboseLogging: true,
  insertLinksEnabled: true,
  insertLinksClipboardEnabled: true,
);

Step 3: Set up deep link handling with app_links

Add to pubspec.yaml:

dependencies:
  app_links: ^6.3.2
import 'package:app_links/app_links.dart';
import 'package:insert_affiliate_flutter_sdk/insert_affiliate_flutter_sdk.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  insertAffiliateSdk = InsertAffiliateFlutterSDK(
    companyCode: "YOUR_COMPANY_CODE",
    insertLinksEnabled: true,
    insertLinksClipboardEnabled: true,
  );

  // Set up callback for affiliate identifier changes
  insertAffiliateSdk.setInsertAffiliateIdentifierChangeCallback((identifier) async {
    if (identifier != null) {
      // For RevenueCat:
      // await Purchases.setAttributes({"insert_affiliate": identifier});

      // For Adapty:
      // final builder = AdaptyProfileParametersBuilder()
      //   ..setCustomStringAttribute(identifier, 'insert_affiliate');
      // await Adapty().updateProfile(builder.build());

      // For Apphud:
      // await Apphud.setUserProperty(key: "insert_affiliate", value: identifier, setOnce: false);
    }
  });

  // Set up deep link listener
  _setupDeepLinkListener();

  runApp(MyApp());
}

void _setupDeepLinkListener() async {
  final appLinks = AppLinks();

  // Check for initial link
  final initialLink = await appLinks.getInitialLink();
  if (initialLink != null) {
    await insertAffiliateSdk.handleDeepLink(initialLink.toString());
  }

  // Listen for incoming links
  appLinks.uriLinkStream.listen((Uri uri) async {
    await insertAffiliateSdk.handleDeepLink(uri.toString());
  });
}

βœ… Insert Links setup complete!

Option 2: Branch.io

Key Integration Steps:

  1. Install and configure Flutter Branch SDK
  2. Listen for Branch deep link events with FlutterBranchSdk.listSession()
  3. Extract ~referring_link from Branch callback
  4. Pass to Insert Affiliate SDK using setInsertAffiliateIdentifier()
import 'package:flutter_branch_sdk/flutter_branch_sdk.dart';
import 'package:insert_affiliate_flutter_sdk/insert_affiliate_flutter_sdk.dart';

_branchStreamSubscription = FlutterBranchSdk.listSession().listen((data) {
  if (data.containsKey("+clicked_branch_link") && data["+clicked_branch_link"] == true) {
    insertAffiliateSdk.setInsertAffiliateIdentifier(data["~referring_link"]);

    // For RevenueCat: Update attributes
    insertAffiliateSdk.returnInsertAffiliateIdentifier().then((value) {
      if (value != null) {
        Purchases.setAttributes({"insert_affiliate": value});
      }
    });
  }
});

πŸ“– View complete Branch.io integration guide β†’

Option 3: AppsFlyer

Key Integration Steps:

  1. Install and configure AppsFlyer Flutter SDK
  2. Listen for onDeepLinking and onInstallConversionData callbacks
  3. Pass deep link value to Insert Affiliate SDK using setInsertAffiliateIdentifier()
import 'package:appsflyer_sdk/appsflyer_sdk.dart';
import 'package:insert_affiliate_flutter_sdk/insert_affiliate_flutter_sdk.dart';

_appsflyerSdk.onDeepLinking((deepLinkResult) async {
  if (deepLinkResult.status == Status.FOUND) {
    final deepLinkValue = deepLinkResult.deepLink?.deepLinkValue;
    if (deepLinkValue != null) {
      await insertAffiliateSdk.setInsertAffiliateIdentifier(deepLinkValue);

      // For RevenueCat: Update attributes
      final affiliateId = await insertAffiliateSdk.returnInsertAffiliateIdentifier();
      if (affiliateId != null) {
        Purchases.setAttributes({"insert_affiliate": affiliateId});
      }
    }
  }
});

πŸ“– View complete AppsFlyer integration guide β†’


βœ… Verify Your Integration #

Integration Checklist #

  • ❌ SDK Initializes: Check console for SDK initialized with company code log
  • ❌ Affiliate Identifier Stored: Click a test affiliate link and verify identifier is stored
  • ❌ Purchase Tracked: Make a test purchase and verify it appears in Insert Affiliate dashboard

Testing Commands #

# Test deep link (Android Emulator)
adb shell am start -W -a android.intent.action.VIEW -d "https://your-deep-link-url/abc123"

# Test deep link (iOS Simulator)
xcrun simctl openurl booted "https://your-deep-link-url/abc123"

Check Stored Affiliate Identifier #

final affiliateId = await insertAffiliateSdk.returnInsertAffiliateIdentifier();
print('Current affiliate ID: $affiliateId');

Common Setup Issues #

Issue Solution
"Company code is not set" Ensure SDK is initialized before calling other methods
"No affiliate identifier found" User must click an affiliate link before making a purchase
Deep link opens browser instead of app Verify URL schemes in Info.plist (iOS) and AndroidManifest.xml (Android)
Purchase not tracked Check webhook configuration in IAP verification platform

πŸ”§ Advanced Features #

Event Tracking (Beta)

Track custom events beyond purchases to incentivize affiliates for specific actions.

ElevatedButton(
  onPressed: () {
    insertAffiliateSdk.trackEvent(eventName: "user_signup")
      .then((_) => print('Event tracked successfully!'))
      .catchError((error) => print('Error: $error'));
  },
  child: Text("Track Signup"),
);

Use Cases:

  • Pay affiliates for signups instead of purchases
  • Track trial starts, content unlocks, or other conversions

Short Codes

Short codes are unique, 3-25 character alphanumeric identifiers that affiliates can share.

Validate and Store Short Code:

final isValid = await insertAffiliateSdk.setShortCode('SAVE20');

if (isValid) {
  showDialog(
    context: context,
    builder: (context) => AlertDialog(
      title: Text('Success'),
      content: Text('Affiliate code applied!'),
    ),
  );
} else {
  showDialog(
    context: context,
    builder: (context) => AlertDialog(
      title: Text('Error'),
      content: Text('Invalid affiliate code'),
    ),
  );
}

Get Affiliate Details Without Setting:

final details = await insertAffiliateSdk.getAffiliateDetails('SAVE20');

if (details != null) {
  print('Affiliate Name: ${details.affiliateName}');
  print('Short Code: ${details.affiliateShortCode}');
  print('Deep Link: ${details.deeplinkUrl}');
}

Learn more: Short Codes Documentation

Dynamic Offer Codes / Discounts

Automatically apply discounts or trials when users come from specific affiliates.

How It Works:

  1. Configure an offer code modifier in your dashboard (e.g., _oneWeekFree)
  2. SDK automatically fetches and stores the modifier when affiliate identifier is set
  3. Use the modifier to construct dynamic product IDs

Quick Example:

String? offerCode = await insertAffiliateSdk.getStoredOfferCode();

final baseProductId = "oneMonthSubscription";
final dynamicProductId = offerCode != null
    ? '$baseProductId$offerCode'  // e.g., "oneMonthSubscription_oneWeekFree"
    : baseProductId;

// Use dynamicProductId when fetching/purchasing products

πŸ“– View complete Dynamic Offer Codes guide β†’

Attribution Timeout Control

Control how long affiliate attribution remains active.

Set Timeout During Initialization:

insertAffiliateSdk = InsertAffiliateFlutterSDK(
  companyCode: "YOUR_COMPANY_CODE",
  attributionTimeout: 604800, // 7 days in seconds
);

Runtime Updates:

// Set 7-day timeout
await insertAffiliateSdk.setAffiliateAttributionTimeout(604800);

// Disable timeout (never expires)
await insertAffiliateSdk.setAffiliateAttributionTimeout(0);

// Check if attribution is still valid
final isValid = await insertAffiliateSdk.isAffiliateAttributionValid();

// Get when attribution was stored
final storedDate = await insertAffiliateSdk.getAffiliateStoredDate();

Common Timeout Values:

  • 1 day: 86400
  • 7 days: 604800 (recommended)
  • 30 days: 2592000
  • No timeout: 0 (default)

Bypass Timeout for Testing:

// Get identifier even if attribution has expired
final identifier = await insertAffiliateSdk.returnInsertAffiliateIdentifier(ignoreTimeout: true);

Affiliate Change Callback

Get notified when the affiliate identifier changes:

insertAffiliateSdk.setInsertAffiliateIdentifierChangeCallback((identifier) {
  if (identifier != null) {
    print('Affiliate changed: $identifier');

    // Update your IAP platform
    Purchases.setAttributes({"insert_affiliate": identifier});
  }
});

πŸ” Troubleshooting #

Initialization Issues #

Error: "Company code is not set"

  • Cause: SDK not initialized or method called before initialization
  • Solution: Initialize SDK in main() before runApp()

Deep Linking Issues #

Problem: Deep link opens browser instead of app

  • Cause: Missing or incorrect URL scheme configuration
  • Solution:
    • iOS: Add URL scheme to Info.plist and configure associated domains
    • Android: Add intent filters to AndroidManifest.xml

Problem: "No affiliate identifier found"

  • Cause: User hasn't clicked an affiliate link yet
  • Solution: Test with simulator/emulator using adb shell or xcrun simctl openurl

Purchase Tracking Issues #

Problem: Purchases not appearing in dashboard

  • Cause: Webhook not configured or affiliate identifier not passed to IAP platform
  • Solution:
    • Verify webhook URL and authorization headers
    • For RevenueCat: Confirm insert_affiliate attribute is set before purchase
    • Enable verbose logging and check console for errors

Verbose Logging #

Enable detailed logs during development:

insertAffiliateSdk = InsertAffiliateFlutterSDK(
  companyCode: "YOUR_COMPANY_CODE",
  verboseLogging: true,
);

πŸ“š Support #


Need help? Check our documentation or contact support.

2
likes
130
points
170
downloads

Publisher

unverified uploader

Weekly Downloads

A Flutter SDK for integrating affiliate tracking and in-app purchases for the Insert Affiliate Platform.

Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (license)

Dependencies

android_play_install_referrer, connectivity_plus, device_info_plus, flutter, http, in_app_purchase, in_app_purchase_storekit, package_info_plus, shared_preferences, url_launcher

More

Packages that depend on insert_affiliate_flutter_sdk