← ALL POSTS
11 NOVEMBER 2025

AIVA Affiliate Marketing Skill - Complete Implementation Summary

Date Completed: January 2025
Platforms Supported: Shopify, WooCommerce
Integration: HighLevel CRM


Executive Summary

The Affiliate Marketing Skill is a fully automated, platform-agnostic affiliate program management system for AIVA clients. It enables e-commerce businesses (Shopify or WooCommerce) to run sophisticated affiliate programs with zero manual intervention, intelligent commission tracking, and complete CRM integration through HighLevel.

Key Achievement: First-time customers only commission model with bulletproof validation to prevent affiliate fraud.


What This Does for You

For Shopify Clients

Our clients can now run a fully automated affiliate marketing program that:

  1. Automatic Affiliate Onboarding
    • Affiliates register through HighLevel forms or API
    • AIVA automatically generates unique discount codes (e.g., “AF-JILL-SMITH”)
    • Codes are instantly created in Shopify with “new customers only” restrictions
    • Affiliates receive their unique code via email/SMS through HighLevel automation
  2. Intelligent Commission Tracking
    • Every order placed in Shopify is monitored in real-time via webhooks
    • When a customer uses an affiliate code, AIVA checks if they’re a NEW customer (zero previous orders)
    • NEW customers: Commission is tracked and logged to HighLevel
    • EXISTING customers: Attempt is logged but commission is NOT awarded (fraud prevention)
    • All activity is automatically logged as notes on the customer’s HighLevel contact record
  3. Automated Commission Management
    • Commissions are held for a configurable period (default: 30 days) to account for refunds
    • After the hold period, commissions automatically move to “approved” status
    • Affiliate dashboard shows pending, approved, and paid commissions
    • Payment tracking with multiple methods (PayPal, Stripe, Bank Transfer, or Store Credit)
  4. HighLevel CRM Integration
    • Every affiliate referral attempt is logged: ” tried to use affiliate code AF-ABC but this was ignored as they were already a customer”
    • Successful referrals logged: ” was referred by affiliate code AF-ABC. Commission: $15.50.”
    • Affiliates can be managed directly in HighLevel with custom fields
    • Automated workflows can trigger for commission milestones

For WooCommerce Clients

Identical functionality as Shopify with platform-specific implementation:

  1. WooCommerce Coupon Integration
    • Discount codes created as WooCommerce coupons via REST API
    • usage_limit_per_user=1 enforces first-purchase restriction at platform level
    • Individual use coupons (cannot be combined with other discounts)
    • Automatic metadata tagging for AIVA management
  2. Unified Order Webhook
    • Single order.created webhook handles ALL intelligence checks:
      • Cart abandonment tracking
      • Post-purchase upsells
      • Customer lifecycle updates
      • Customer health scoring
      • Affiliate commission tracking
    • No multiple webhooks, no complexity, just one unified intelligence layer
  3. WooCommerce-Specific Features
    • Tracks cart_hash for cart recovery attribution
    • Supports WooCommerce coupon lines (multiple coupons per order)
    • Reads discount amount directly from order data
    • Compatible with all major WooCommerce payment gateways

Business Value for Clients

Revenue Growth

  • Turn customers into salespeople: Existing customers become brand advocates
  • Low-risk customer acquisition: Only pay commissions on actual sales
  • First-purchase only: Prevents abuse, ensures commissions drive NEW revenue
  • Ignores existing customers - if your affliates invite existing customers, no commission is applied

Operational Efficiency

  • Zero manual work: No spreadsheets, no manual tracking, no payment calculations
  • Automated fraud prevention: System automatically blocks repeat-use attempts
  • CRM transparency: All affiliate activity visible in HighLevel contact records

Competitive Advantage

  • Enterprise-level affiliate program at SaaS prices
  • Fully branded: Affiliate codes use client’s custom prefix (e.g., “AF-CLIENT-NAME”)
  • Multi-platform: Works identically across Shopify and WooCommerce

Technical Implementation

Architecture Overview

Platform-Agnostic Design

Factory Pattern Implementation:

  • IDiscountCodeServiceFactory creates platform-specific discount services
  • ShopifyDiscountCodeService handles Shopify Price Rules API (2-step: rule + code)
  • WooCommerceDiscountCodeService handles WooCommerce Coupons API (1-step)
  • AffiliateService uses factory to dynamically select correct implementation

Unified Webhook Architecture:

  • ONE webhook endpoint per platform handles ALL e-commerce intelligence
  • Webhook processes happen sequentially in a single handler:
    1. Cart recovery tracking
    2. Post-purchase upsell generation
    3. Customer lifecycle classification
    4. Customer health scoring
    5. Affiliate commission tracking (with new customer validation)

Database Schema

Affiliates Table:

- Id (Guid, PK)
- ClientId (Guid, FK to Clients)
- FirstName, LastName, Email, Phone
- AffiliateCode (unique, indexed)
- Status (Active, Suspended, Terminated)
- TotalCommissionEarned, TotalCommissionPaid
- PreferredPaymentMethod, PaymentEmail, PaymentDetails
- CreatedAt, UpdatedAt, LastSaleAt, LastPaymentAt

AffiliateSales Table:

- Id (Guid, PK)
- AffiliateId (Guid, FK to Affiliates)
- ClientId (Guid, FK to Clients)
- PlatformOrderId, PlatformOrderNumber
- CustomerEmail, CustomerName
- OrderDate, OrderTotal, DiscountAmount
- CommissionAmount, CommissionStatus (Pending, Approved, Reversed, Paid)
- PaymentId (Guid?, FK to AffiliatePayments)
- CommissionApprovedAt, CommissionPaidAt
- CreatedAt

AffiliatePayments Table:

- Id (Guid, PK)
- AffiliateId (Guid, FK to Affiliates)
- ClientId (Guid, FK to Clients)
- PaymentAmount, PaymentMethod
- PaymentReference (e.g., PayPal transaction ID)
- PaymentDate
- SalesPaidCount (number of sales included in this payment)
- Notes
- CreatedAt

Key Services & Files

Core Services

  • Services/Affiliates/IAffiliateService.cs - Interface defining affiliate operations
  • Services/Affiliates/AffiliateService.cs - Core business logic (900+ lines)
    • Affiliate registration and code generation
    • Commission calculation (respects rate & cap)
    • New customer validation via e-commerce platform APIs
    • HighLevel logging for all affiliate activity
    • Payment processing and tracking
    • Performance analytics

Platform-Specific Services

  • Services/Affiliates/IDiscountCodeService.cs - Platform-agnostic interface
  • Services/Affiliates/IDiscountCodeServiceFactory.cs - Factory interface
  • Services/Affiliates/DiscountCodeServiceFactory.cs - Factory implementation
  • Services/Affiliates/ShopifyDiscountCodeService.cs - Shopify implementation
  • Services/Affiliates/WooCommerceDiscountCodeService.cs - WooCommerce implementation

Webhook Controllers

  • Controllers/ShopifyEcommerceWebhookController.cs
    • POST /api/webhooks/shopify/ecommerce/checkout-created - Cart abandonment
    • POST /api/webhooks/shopify/ecommerce/order-created - Unified intelligence + affiliate tracking
  • Controllers/WooCommerceEcommerceWebhookController.cs
    • POST /api/webhooks/woocommerce/ecommerce/order-created - Unified intelligence + affiliate tracking

Security & Fraud Prevention

  1. New Customer Validation (Bulletproof)
    • Queries e-commerce platform API for customer order count
    • IsNewCustomerAsync() returns true ONLY if order count = 0
    • Check happens BEFORE commission is recorded
    • Logged attempts by existing customers for audit trail
  2. Platform-Level Enforcement
    • Shopify: once_per_customer=true on discount codes
    • WooCommerce: usage_limit_per_user=1 on coupons
    • Double-layer protection: platform + AIVA validation
  3. Commission Hold Period
    • 30-day default hold before commissions approved
    • Accounts for refunds, chargebacks, cancellations
    • Automatic approval via background job after hold expires
    • Can be reversed manually if order refunded
  4. Webhook Verification
    • Shopify webhooks verified via HMAC signature
    • WooCommerce webhooks use custom client ID header
    • All webhooks rate-limited to prevent abuse

Commission Calculation Formula

Commission = MIN(
    OrderTotal × CommissionRate,
    CommissionCap
) - DiscountAmount × DiscountCommissionImpact

Example:

  • Order Total: $100
  • Commission Rate: 15%
  • Commission Cap: $50
  • Discount Amount: $10
  • Discount Impact: 0% (affiliate still gets commission on full order)

Result: $15.00 commission


Client Configuration

Each client has the following settings in the Clients table:

// Affiliate Program Settings
public bool EnableAffiliateProgram { get; set; } = false;
public string AffiliateCodePrefix { get; set; } = "AF"; // e.g., "AF-JILL-SMITH"
public decimal AffiliateCommissionRate { get; set; } = 10.0m; // 10%
public decimal AffiliateCommissionCap { get; set; } = 100.0m; // Max $100 per sale
public decimal AffiliateCustomerDiscountRate { get; set; } = 15.0m; // 15% discount for customers
public int AffiliateCommissionHoldDays { get; set; } = 30; // Hold for 30 days before approval

Background Jobs (Hangfire)

Recurring Jobs:

  1. Commission Approval - Runs daily at 3 AM UTC
    • Approves all commissions that have passed hold period
    • Updates commission status from “Pending” → “Approved”
    • Logs approval to HighLevel contact notes
  2. Performance Reports - Runs weekly on Monday at 9 AM UTC
    • Generates affiliate performance summaries
    • Emails top performers and clients with analytics
    • Identifies underperforming affiliates for outreach

HighLevel Integration Details

Contact Notes Format

Successful Referral (New Customer):

Tim Thomas was referred by affiliate code AF-JILL-SMITH. Commission: $15.50.

Blocked Referral (Existing Customer):

Tim Thomas tried to use affiliate code AF-JILL-SMITH but this was ignored as an affiliate referral as they were already a customer (have previous orders).

Custom Contact Fields (Recommended)

Clients can add these custom fields in HighLevel:

  • affiliate_code - The affiliate code the contact used
  • affiliate_commission_earned - Total commission generated
  • referred_by_affiliate - Boolean flag
  • affiliate_referral_date - Date of first affiliate referral

Workflow Automation Examples

Trigger: Contact uses affiliate code (successful referral)
Actions:

  1. Tag contact as “Affiliate Referral”
  2. Add to “VIP Customers” segment
  3. Send thank you email with exclusive offer
  4. Notify affiliate via SMS of successful referral

API Endpoints (For Future Affiliate Portal)

The affiliate service exposes these operations (not yet HTTP endpoints, but ready for API layer):

POST   /api/affiliates/register          - Register new affiliate
GET    /api/affiliates/{id}               - Get affiliate details
GET    /api/affiliates/{id}/performance   - Get performance summary
GET    /api/affiliates/{id}/sales         - Get all sales
GET    /api/affiliates/{id}/commissions   - Get commission breakdown
POST   /api/affiliates/{id}/payments      - Record payment
PUT    /api/affiliates/{id}/status        - Update status (suspend/activate)
GET    /api/affiliates/code/{code}        - Get affiliate by code

Testing Checklist

Shopify + HighLevel

  • Register affiliate → Code created in Shopify
  • New customer uses code → Commission tracked
  • Existing customer uses code → Commission NOT tracked, logged to HighLevel
  • Commission approved after 30 days
  • Payment recorded and sales marked as paid
  • Suspend affiliate → Code deactivated in Shopify
  • Reactivate affiliate → Code reactivated in Shopify

WooCommerce + HighLevel

  • Register affiliate → Coupon created in WooCommerce
  • New customer uses coupon → Commission tracked
  • Existing customer uses coupon → Commission NOT tracked, logged to HighLevel
  • Commission approved after 30 days
  • Payment recorded and sales marked as paid
  • Suspend affiliate → Coupon deactivated in WooCommerce
  • Reactivate affiliate → Coupon reactivated in WooCommerce

Cross-Platform

  • Client with Shopify → Uses Shopify discount service
  • Client with WooCommerce → Uses WooCommerce discount service
  • Multi-client setup (one Shopify, one WooCommerce) → Both work independently

Future Enhancements

Phase 2 (Q1 2026)

  • Affiliate portal (React app) with self-service dashboard
  • Tiered commission structures (bronze/silver/gold affiliates)
  • Recurring commission for subscription products
  • Lifetime value tracking (credit affiliate for all future purchases)

Phase 3 (Q1 2026)

  • Multi-level marketing (MLM) support
  • Custom commission rules per product
  • Affiliate recruitment bonuses
  • Advanced analytics and leaderboards

Phase 4 (Q1 2026)

  • BigCommerce support
  • Magento support
  • API-first headless commerce support

Migration Path for Existing Affiliate Programs

For clients with existing affiliate programs, AIVA can import:

  1. Affiliate List
    • CSV import with email, name, existing code
    • AIVA will sync codes to Shopify/WooCommerce
    • Historical commission data imported as reference (not paid)
  2. Historical Sales
    • Import past sales for reporting (marked as “paid”)
    • Maintains accurate lifetime value metrics
    • Does not affect current commission calculations
  3. Payment History
    • Import payment records for complete audit trail
    • Links to imported sales data
    • Provides full transparency to affiliates

Success Metrics

AIVA clients using the Affiliate Marketing Skill can track:

  1. Affiliate Performance
    • Total affiliates registered
    • Active affiliates (made at least one sale)
    • Top 10 performers by commission earned
    • Average commission per affiliate
  2. Revenue Impact
    • Total revenue from affiliate sales
    • Average order value (affiliate vs non-affiliate)
    • Customer lifetime value (affiliate-referred vs organic)
    • Cost of customer acquisition via affiliates
  3. Program Health
    • New affiliate signups per month
    • Affiliate churn rate
    • Average time to first sale (per affiliate)
    • Commission approval time
    • Payment processing time

Support & Documentation

For Clients:

  • Affiliate program setup guide (HighLevel forms, automation workflows)
  • Webhook configuration instructions (Shopify/WooCommerce)
  • Best practices for affiliate recruitment
  • Commission structure recommendations

For Affiliates:

  • How to use your unique code
  • Commission terms and conditions
  • Payment schedules and methods
  • Performance tracking

For AIVA Team:

  • Technical architecture documentation
  • API reference for affiliate service
  • Database schema and relationships
  • Troubleshooting guide

Conclusion

The AIVA Affiliate Marketing Skill is a production-ready, enterprise-grade affiliate program automation system that works seamlessly across Shopify and WooCommerce. It eliminates manual affiliate management, prevents fraud through intelligent validation, and provides complete transparency through HighLevel CRM integration.

Key Differentiators:

  • ✅ Platform-agnostic (Shopify + WooCommerce)
  • ✅ Zero-latency commission tracking (real-time webhooks)
  • ✅ Bulletproof fraud prevention (new customer validation)
  • ✅ Full CRM integration (HighLevel contact notes)
  • ✅ Automated payment tracking
  • ✅ Enterprise features at SaaS pricing

This is a game-changing feature for AIVA clients looking to scale their e-commerce businesses through word-of-mouth marketing and affiliate partnerships.


Implementation Team: Claude Code + Tim Thomas
Technology Stack: .NET 8, Entity Framework Core, SQL Server, Hangfire, Shopify REST API, WooCommerce REST API, HighLevel REST API
Lines of Code: ~2,500 across 12 files
Build Status: ✅ 0 Errors, 73 Warnings (pre-existing)
Time to build: 1hr (would have taken a human dev team weeks or months 2 years ago)

Want this working on your store? Aiva does the sales, marketing and service work - in your voice, around the clock.
Get Aiva