API

A comprehensive API for tracking affiliate orders, calculating commissions, and managing partner relationships in your affiliate program.

Overview

The Affiliate Order Tracking API enables seamless integration of affiliate tracking into your e-commerce platform. When a customer makes a purchase using an affiliate code, this API records the order, creates or updates customer records, calculates commissions based on partner settings, and tracks affiliate program statistics.

Authentication

All API requests require authentication using your API key.

API Key RequiredInclude the Y-API-Key header in all requests. You can find your API key in the dashboard settings under Settings > API.

Endpoint Details

POST https://yaplet.com/api/affiliates/track/{affiliate_code}

Records a new affiliate order and calculates commission based on partner settings. Creates or updates customer records and partner statistics. Returns success: false for invalid affiliate codes (normal behavior).

Base URL: https://yaplet.com/api/affiliates/track/YOUR_AFFILIATE_CODE

Important: Replace YOUR_AFFILIATE_CODE with the actual affiliate partner's coupon code. If the code is invalid, the API returns success: false (this is expected behavior, not an error).

Request Structure

Headers

{
  "Content-Type": "application/json",
  "Y-API-Key": "YOUR_API_KEY"
}

Request Body

{
  "order_id": "order_12345",           // Required - Unique order identifier
  "total_amount": 100.0,                // Required - Order total in decimal format
  "customer": {                         // Required
    "email": "[email protected]",    // Required - Customer email address
    "name": "John Doe",
    "customer_id": "cust_12345",
    "customer_metadata": {
      "source": "website",
      "campaign": "summer2024"
    }
  },
  "commission": 10.0,                   // Optional - Custom commission amount
  "notes": "First order from customer",
  "timestamp": 1640995200000,           // Optional - Order timestamp (milliseconds)
  "product": {                          // Optional
    "id": "prod_123",
    "name": "Premium Plan",
    "category": "subscription"
  },
  "metadata": {                         // Optional
    "campaign_id": "camp_123",
    "utm_source": "facebook"
  }
}

Response Examples

Successful Tracking (Valid Affiliate Code)

Status: 200 OK

{
  "success": true,
  "data": {
    "commission_id": "comm_123456789",
    "partner_id": "partner_123",
    "customer_id": "customer_456",
    "commission_amount": 10.0,
    "order_id": "order_12345",
    "affiliate_code": "AFFILIATE_CODE"
  }
}

Invalid Affiliate Code

Status: 200 OK

{
  "success": false,
  "message": "No approved affiliate partner found for coupon code: AFFILIATE_CODE"
}
Invalid affiliate codes return success: false with a 200 status code. This is normal behavior and indicates the code was not found in the system.

Commission Calculation

Commissions are calculated automatically based on partner settings and the following priority rules:

Calculation Priority

  1. Partner Override: If partner has ignore_product_rate = true and has a rate set, partner rate is always used
  2. Custom Commission: If commission amount is provided in the API request, that amount is used
  3. Partner Rate: If partner has a rate set (and ignore_product_rate is false), partner rate is used
  4. No Commission: If none of the above conditions are met, commission = 0

Rate Types

Percentage Rate

commission = total_amount * (rate.value / 100)

Example: $100 order × 10% = $10 commission

Fixed Rate

commission = rate.value

Example: $5 commission per order

Code Examples

const response = await fetch('https://yaplet.com/api/affiliates/track/YOUR_AFFILIATE_CODE', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Y-API-Key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
        "order_id": "order_12345",           // Required
        "total_amount": 100.0,                // Required
        "customer": {                         // Required
            "email": "[email protected]",  // Required
            "name": "John Doe",
            "customer_id": "cust_12345",
            "customer_metadata": {
                "source": "website",
                "campaign": "summer2024"
            }
        },
        "commission": 10.0,
        "notes": "First order from customer",
        "timestamp": 1640995200000,
        "product": {
            "id": "prod_123",
            "name": "Premium Plan",
            "category": "subscription"
        },
        "metadata": {
            "campaign_id": "camp_123",
            "utm_source": "facebook"
        }
    })
});

const result = await response.json();
console.log('Response:', result);

Field Reference

Required Fields

FieldTypeDescription
order_idstringUnique identifier for the order. Used to prevent duplicate commissions and for tracking purposes.
total_amountnumberTotal order amount in decimal format. Used for commission calculation and revenue tracking.
customer.emailstringCustomer email address. Required for customer identification and tracking repeat purchases.
Y-API-KeyheaderAPI authentication key. Must be included in request headers for security validation.

Optional Fields

FieldTypeDefaultDescription
timestampnumberCurrent timestampOrder timestamp in milliseconds. If not provided, current server time will be used. Accepts both seconds (10 digits) and milliseconds (13 digits).
commissionnumberCalculated from partner rateCustom commission amount. If not provided, will be calculated based on partner rate settings.
notesstringnullAdditional notes about the order or commission.
customer.namestringEmail prefix (part before @)Customer full name for display purposes.
customer.customer_idstringnullExternal customer ID from your system for cross-reference.
customer.customer_metadataobjectEmpty object {}Additional customer data like source, campaign, etc.
productobjectEmpty object {}Product information including ID, name, category, etc. Stored for reporting purposes.
metadataobjectEmpty object {}Additional order metadata like campaign IDs, UTM parameters, etc.

URL Parameters

ParameterDescription
affiliate_codeReplace YOUR_AFFILIATE_CODE with the actual affiliate partner's coupon code. If the code is invalid or doesn't exist, the API will return success: false (this is normal behavior, not an error).

Error Handling

Common Error Codes

CodeMessageDescription
401API key is required / Invalid API keyMissing or invalid Y-API-Key header
403UnauthorizedUser does not have permission to use this API
400Affiliate code is required in URLMissing affiliate code in URL path
400order_id and total_amount are requiredMissing required fields in request body
400Customer with email is requiredMissing customer object or customer.email field
400Both customer and partner information are required to create a commissionMissing customer or partner data for commission creation
409Order {order_id} has already been tracked for this organizationDuplicate order detection - this order has already been processed
500Internal server errorServer error during processing
Duplicate PreventionThe API prevents duplicate commissions for the same order ID within your organization. If you attempt to track the same order multiple times, you'll receive a 409 error.

Integration Best Practices

  1. Validate Affiliate Codes: Always check if the affiliate code exists before sending tracking requests
  2. Handle Invalid Codes: Expect success: false responses for invalid codes - this is normal behavior
  3. Prevent Duplicates: Use unique order IDs to avoid duplicate commission tracking
  4. Include Customer Data: Provide customer email at minimum for proper tracking
  5. Use Timestamps: Include order timestamps for accurate reporting
  6. Monitor Rate Limits: Implement proper error handling and retry logic

Support

For additional support or questions about the Affiliate API, please contact our support team or refer to the API settings in your dashboard.