Skip to main content

Before You Start

Understanding the Affelios API

Before integrating with the Affelios API, it’s important to understand how to interact with our platform programmatically.

Developer Resources

Visit the Developers tab in the documentation to access comprehensive resources for API integration, including:
  • API authentication methods
  • Available endpoints and data structures
  • Request/response examples
  • SDKs and code samples
  • Testing tools and playground

API Reference

For complete endpoint documentation, visit the API Reference section where you can find all available endpoints, request/response schemas, and interactive examples for every API operation.
The Developers tab provides everything you need to understand how to authenticate, make requests, and handle responses when integrating with the Affelios API. The API Reference contains detailed documentation for all available endpoints.

Setting Up Custom Integration

Step 1: Configure Brand Integration Settings

1

Access Brand Settings

Navigate to the “Brands” page in your Affelios dashboard and click the three dots next to your brand, then select “Integration Settings”.
2

Select Custom Integration

Choose “Custom” from the available integration methods for REST API integration.
3

Configure API Settings

Set up your API configuration as needed.
The “Custom” integration option enables you to use the full REST API capabilities for programmatic access to all platform features.
Once your custom integration is set up, you’ll need to capture click keys from affiliate tracking links to properly attribute conversions.

Understanding Click Keys

Click keys are unique identifiers that link conversions back to specific affiliates. When a user clicks an affiliate’s tracking link, a click key is generated and should be captured for proper attribution.
1

Understand Click Key Generation

Learn how click keys are generated in our Attribution documentation to understand the technical details of the attribution process.
2

Learn About Tracking Links

Review our Tracking Links guide to understand how affiliate tracking links work and how click keys are passed through the system.
3

Implement Click Key Capture

Modify your application to capture the click key parameter from affiliate tracking links and store it for use in conversion tracking.
Important: Without proper click key capture and attribution, conversions cannot be properly credited to affiliates. Ensure your integration captures click keys from all affiliate tracking links.

Click Key Capture Example

Here’s a practical example of how to capture click keys from affiliate tracking links:
// Capture click key from URL parameters
function captureClickKey() {
  const urlParams = new URLSearchParams(window.location.search);
  
  // Check for common click key parameter names
  const clickKey = urlParams.get('btag') || 
                   urlParams.get('clickId') || 
                   urlParams.get('clickkey') ||
                   urlParams.get('affiliate_id');
  
  if (clickKey) {
    // Store in cookie for 30 days (matching Affelios attribution window)
    document.cookie = `affiliate_click_key=${clickKey}; max-age=${30 * 24 * 60 * 60}; path=/`;
    console.log('Click key captured:', clickKey);
  }
}

// Call on page load
document.addEventListener('DOMContentLoaded', captureClickKey);

// Function to retrieve stored click key
function getStoredClickKey() {
  const cookies = document.cookie.split(';');
  for (let cookie of cookies) {
    const [name, value] = cookie.trim().split('=');
    if (name === 'affiliate_click_key') {
      return value;
    }
  }
  return null;
}

// Use during registration/purchase
async function submitRegistration(userData) {
  const clickKey = getStoredClickKey();
  
  const registrationData = {
    ...userData,
    affiliateClickKey: clickKey // Include with user data
  };
  
  // Submit to your backend
  const response = await fetch('/api/register', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(registrationData)
  });
  
  return response.json();
}
Storage Recommendations:
  • Store click keys in both cookies and server-side sessions for reliability
  • Use a 30-day expiration to match Affelios’ attribution window
  • Always include the click key when submitting user registrations or purchases
  • Store click keys in your database alongside user and transaction records

Step 3: Send Customer Records to Affelios

When a new customer registers in your system, you need to send their information to Affelios using the Customer API endpoint.

Customer API Endpoint

POST /api/v1/customer - Creates a new customer item in Affelios with tracking information for proper attribution.

Required Fields

Based on the API reference, the following fields are required:
  • externalId - Your internal customer ID
  • brandId - The Affelios brand ID for your program
  • clickKey - The click key captured from the affiliate tracking link

Customer Creation Example

Here’s how to send customer data to Affelios when they register:
// Send customer to Affelios when they register
async function createAffeliosCustomer(customerData, clickKey) {
  const affeliosCustomer = {
    externalId: customerData.id, // Your internal customer ID
    brandId: process.env.AFFELIOS_BRAND_ID, // Your Affelios brand ID
    clickKey: clickKey, // Captured from tracking link
    username: customerData.username,
    registrationDate: new Date().toISOString(),
    country_code: customerData.countryCode
  };

  try {
    const response = await fetch('https://platform.affelios.com/api/v1/customer', {
      method: 'POST',
      headers: {
        'X-Api-Key': process.env.AFFELIOS_API_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(affeliosCustomer)
    });

    if (!response.ok) {
      throw new Error(`Affelios API error: ${response.status} ${response.statusText}`);
    }

    const result = await response.json();
    console.log('Customer created in Affelios:', result.id);
    return result;
  } catch (error) {
    console.error('Failed to create customer in Affelios:', error);
    throw error;
  }
}

// Integration with your registration process
async function handleUserRegistration(userData) {
  // 1. Create user in your system
  const newUser = await createUserInYourSystem(userData);
  
  // 2. Get stored click key
  const clickKey = getStoredClickKey();
  
  // 3. Send to Affelios if click key exists
  if (clickKey) {
    try {
      await createAffeliosCustomer(newUser, clickKey);
    } catch (error) {
      // Log error but don't fail registration
      console.error('Affelios integration failed:', error);
    }
  }
  
  return newUser;
}
GDPR Compliance: Avoid sending any personally identifiable information (PII) to Affelios to comply with GDPR regulations. Only send anonymized data such as:
  • externalId (your internal customer ID)
  • clickKey (for attribution)
  • country_code (if necessary for compliance)
  • registrationDate (if necessary for tracking)
Do NOT send: names, email addresses, phone numbers, IP addresses, or any other personal data.
Important Notes:
  • Always include the clickKey when creating customers to ensure proper attribution
  • The externalId should be your internal customer ID for reference
  • The brandId is your specific Affelios brand/program ID
  • Registration should not fail if Affelios API is unavailable - log errors but continue
  • Store the Affelios customer ID returned in the response for future reference
  • Ensure GDPR compliance by only sending anonymized data

Step 4: Plan Transaction Aggregation Strategy

For high-volume systems, consider how frequently you want to send transactions to Affelios, as each transaction incurs a cost.

Transaction Cost Consideration

Affelios charges per transaction, so real-time transaction processing can become costly for high-volume systems. Consider aggregating transactions to optimize costs.Learn more about how Affelios charges work and see detailed pricing information at Affelios Pricing.
Volume Assessment: Before choosing your strategy, assess your transaction volume:
  • < 10,000 transactions/month: Consider real-time processing
  • > 10,000 transactions/month: Consider daily batching

Aggregation Strategies

Best for: Low to medium volume systems
  • Send each transaction immediately to Affelios
  • Provides real-time attribution and reporting
  • Higher cost but maximum accuracy
  • Suitable for systems with < 10,000 transactions/month
Best for: High volume systems
  • Aggregate transactions by customer over a time window (e.g., daily, hourly)
  • Send aggregated data at predetermined intervals
  • Significantly reduces API costs
  • Recommended for systems with > 10,000 transactions/month
Best for: Mixed volume systems
  • Real-time for high-value transactions
  • Batch processing for low-value/frequent transactions
  • Balance between cost and accuracy
  • Customize based on transaction value thresholds

Implementation Examples

// Real-time transaction processing
async function processTransactionRealtime(transactionData, customerId) {
  const affeliosTransaction = {
    externalId: transactionData.id,
    externalCustomerId: customerId,
    externalBrandId: process.env.AFFELIOS_BRAND_ID,
    type: 'deposit', // or 'revenue', 'withdrawal', etc.
    grossRevenue: transactionData.amount,
    transactionDate: new Date().toISOString()
  };

  return await sendToAffelios('/api/v1/transaction', affeliosTransaction);
}

// Batch transaction processing
async function processTransactionsBatch(transactions) {
  // Group transactions by customer
  const groupedTransactions = groupBy(transactions, 'customerId');
  
  for (const [customerId, customerTransactions] of Object.entries(groupedTransactions)) {
    // Aggregate transaction data
    const aggregatedData = {
      externalCustomerId: customerId,
      externalBrandId: process.env.AFFELIOS_BRAND_ID,
      grossRevenue: customerTransactions.reduce((sum, t) => sum + t.amount, 0),
      transactionCount: customerTransactions.length,
      transactionDate: new Date().toISOString()
    };

             await sendToAffelios('/api/v1/transaction/bulk', aggregatedData);
  }
}

// Scheduled batch processing (run every hour)
setInterval(async () => {
  const pendingTransactions = await getPendingTransactions();
  if (pendingTransactions.length > 0) {
    await processTransactionsBatch(pendingTransactions);
    await markTransactionsAsProcessed(pendingTransactions);
  }
}, 60 * 60 * 1000); // Every hour
Best Practices: For detailed guidance on transaction processing strategies, cost optimization, and implementation patterns, see our Developer Best Practices documentation.

Step 5: Test Your Integration

Before going live, thoroughly test your integration to ensure everything works correctly.
1

Test Click Key Capture

Verify that click keys are being captured correctly from affiliate tracking links
2

Test Customer Creation

Ensure customer records are being sent to Affelios with proper attribution
3

Test Transaction Processing

Verify that transactions are being processed according to your chosen strategy
4

Test Error Handling

Confirm that your integration handles API errors gracefully

Testing Tools

Use the API Reference interactive playground to test endpoints, or import our OpenAPI specification into Postman for comprehensive testing.

Step 6: Monitor and Maintain

Once your integration is live, ongoing monitoring and maintenance are essential for success.
Track Integration Health:
  • Monitor API response times and success rates
  • Set up alerts for failed requests or high error rates
  • Track transaction processing delays
  • Monitor click key capture rates
Ensure Data Accuracy:
  • Regularly verify customer attribution is working correctly
  • Check that transactions are being processed and attributed properly
  • Monitor for missing or duplicate data
  • Validate click key tracking across different traffic sources
Optimize API Usage:
  • Review transaction volume and adjust aggregation strategy if needed
  • Monitor API costs and usage patterns
  • Consider batching strategies for high-volume periods
  • Regular cost-benefit analysis of real-time vs. batch processing

Troubleshooting

Common Issues

Problem: Affiliate tracking links not generating click keysSolutions:
  • Verify affiliate tracking links are properly formatted
  • Check that your click key capture code is running on all pages
  • Ensure tracking parameters match your capture logic
  • Test with different affiliate tracking link formats
Problem: Customers not being attributed to correct affiliatesSolutions:
  • Verify click key is being passed to customer creation API
  • Check that click key hasn’t expired (30-day window)
  • Ensure customer creation happens within attribution window
  • Validate click key format and encoding
Problem: Transactions not being processed or attributed correctlySolutions:
  • Check transaction API endpoint and authentication
  • Verify customer ID mapping between systems
  • Ensure transaction data includes required fields
  • Review batch processing logic if using aggregation

Getting Help

1

Check Documentation

Review the API Reference and Developer Best Practices for detailed guidance
2

Review Logs

Check your application logs for specific error messages and request details
3

Test with API Tools

Use Postman or the API playground to test requests independently
4

Contact Support

Reach out to our support team with specific error details and request IDs

Best Practices Summary

Integration Checklist

  • ✅ Click key capture implemented and tested
  • ✅ Customer creation API integrated with proper attribution
  • ✅ Transaction processing strategy chosen and implemented
  • ✅ Error handling and retry logic in place
  • ✅ GDPR compliance ensured (no PII sent to Affelios)
  • ✅ Testing completed across all integration points
  • ✅ Monitoring and alerting configured
  • ✅ Documentation updated for your team

Next Steps

Your Integration is Complete!

Congratulations! Your bespoke API integration with Affelios is now set up and ready to track affiliate performance and process commissions.

What Happens Next

1

Go Live

Deploy your integration to production and start tracking affiliate performance
2

Monitor Performance

Use the Affelios dashboard to monitor clicks, conversions, and commission payouts
3

Optimize Strategy

Review performance data and adjust your transaction processing strategy as needed
4

Scale Success

Expand your affiliate program based on performance insights and data

Additional Resources

Need additional help? Our support team is available to assist with any questions or issues you might have with your bespoke API integration. Contact us via email at support@affelios.com.
I