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:
- 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
- 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
- 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)
- 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:
- WooCommerce Coupon Integration
- Discount codes created as WooCommerce coupons via REST API
usage_limit_per_user=1enforces first-purchase restriction at platform level- Individual use coupons (cannot be combined with other discounts)
- Automatic metadata tagging for AIVA management
- Unified Order Webhook
- Single
order.createdwebhook 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
- Single
- WooCommerce-Specific Features
- Tracks
cart_hashfor 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
- Tracks
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:
IDiscountCodeServiceFactorycreates platform-specific discount servicesShopifyDiscountCodeServicehandles Shopify Price Rules API (2-step: rule + code)WooCommerceDiscountCodeServicehandles WooCommerce Coupons API (1-step)AffiliateServiceuses 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:
- Cart recovery tracking
- Post-purchase upsell generation
- Customer lifecycle classification
- Customer health scoring
- 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 operationsServices/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 interfaceServices/Affiliates/IDiscountCodeServiceFactory.cs- Factory interfaceServices/Affiliates/DiscountCodeServiceFactory.cs- Factory implementationServices/Affiliates/ShopifyDiscountCodeService.cs- Shopify implementationServices/Affiliates/WooCommerceDiscountCodeService.cs- WooCommerce implementation
Webhook Controllers
Controllers/ShopifyEcommerceWebhookController.csPOST /api/webhooks/shopify/ecommerce/checkout-created- Cart abandonmentPOST /api/webhooks/shopify/ecommerce/order-created- Unified intelligence + affiliate tracking
Controllers/WooCommerceEcommerceWebhookController.csPOST /api/webhooks/woocommerce/ecommerce/order-created- Unified intelligence + affiliate tracking
Security & Fraud Prevention
- 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
- Platform-Level Enforcement
- Shopify:
once_per_customer=trueon discount codes - WooCommerce:
usage_limit_per_user=1on coupons - Double-layer protection: platform + AIVA validation
- Shopify:
- 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
- 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:
- 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
- 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 usedaffiliate_commission_earned- Total commission generatedreferred_by_affiliate- Boolean flagaffiliate_referral_date- Date of first affiliate referral
Workflow Automation Examples
Trigger: Contact uses affiliate code (successful referral)
Actions:
- Tag contact as “Affiliate Referral”
- Add to “VIP Customers” segment
- Send thank you email with exclusive offer
- 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:
- Affiliate List
- CSV import with email, name, existing code
- AIVA will sync codes to Shopify/WooCommerce
- Historical commission data imported as reference (not paid)
- Historical Sales
- Import past sales for reporting (marked as “paid”)
- Maintains accurate lifetime value metrics
- Does not affect current commission calculations
- 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:
- Affiliate Performance
- Total affiliates registered
- Active affiliates (made at least one sale)
- Top 10 performers by commission earned
- Average commission per affiliate
- 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
- 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)