> ## Documentation Index
> Fetch the complete documentation index at: https://docs.affelios.com/llms.txt
> Use this file to discover all available pages before exploring further.

# REST API Integration Guide

> Complete guide to integrating with Affelios using the REST API, including authentication, endpoints, and best practices.

## 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.

<Card title="Developer Resources" icon="code">
  Visit the [Developers tab](/developers/overview) 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
</Card>

<Card title="API Reference" icon="book">
  For complete endpoint documentation, visit the [API Reference](/api-reference) section where you can find all available endpoints, request/response schemas, and interactive examples for every API operation.
</Card>

<Info>
  The [Developers tab](/developers/overview) provides everything you need to understand how to authenticate, make requests, and handle responses when integrating with the Affelios API. The [API Reference](/api-reference) contains detailed documentation for all available endpoints.
</Info>

## Setting Up Custom Integration

### Step 1: Configure Brand Integration Settings

<Steps>
  <Step title="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"**.
  </Step>

  <Step title="Select Custom Integration">
    Choose **"Custom"** from the available integration methods for REST API integration.
  </Step>

  <Step title="Configure API Settings">
    Set up your API configuration as needed.
  </Step>
</Steps>

<Info>
  The "Custom" integration option enables you to use the full REST API capabilities for programmatic access to all platform features.
</Info>

### Step 2: Capture Click Keys from Tracking Links

Once your custom integration is set up, you'll need to capture click keys from affiliate tracking links to properly attribute conversions.

<Card title="Understanding Click Keys" icon="link">
  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.
</Card>

<Steps>
  <Step title="Understand Click Key Generation">
    Learn how click keys are generated in our [Attribution documentation](/knowledge-base/operators/attribution) to understand the technical details of the attribution process.
  </Step>

  <Step title="Learn About Tracking Links">
    Review our [Tracking Links guide](/knowledge-base/affiliates/tracking-links) to understand how affiliate tracking links work and how click keys are passed through the system.
  </Step>

  <Step title="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.
  </Step>
</Steps>

<Warning>
  **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.
</Warning>

#### Click Key Capture Example

Here's a practical example of how to capture click keys from affiliate tracking links:

<CodeGroup>
  ```javascript JavaScript Example theme={null}
  // 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();
  }
  ```

  ```php PHP Example theme={null}
  // Capture click key from URL parameters
  function captureClickKey() {
      $clickKey = $_GET['btag'] ?? 
                  $_GET['clickId'] ?? 
                  $_GET['clickkey'] ?? 
                  $_GET['affiliate_id'] ?? 
                  null;
      
      if ($clickKey) {
          // Store in session for 30 days
          $_SESSION['affiliate_click_key'] = $clickKey;
          setcookie('affiliate_click_key', $clickKey, time() + (30 * 24 * 60 * 60), '/');
      }
  }

  // Call on page load
  captureClickKey();

  // Function to retrieve stored click key
  function getStoredClickKey() {
      return $_SESSION['affiliate_click_key'] ?? 
             $_COOKIE['affiliate_click_key'] ?? 
             null;
  }

  // Use during registration/purchase
  function submitRegistration($userData) {
      $clickKey = getStoredClickKey();
      
      $registrationData = array_merge($userData, [
          'affiliate_click_key' => $clickKey
      ]);
      
      // Store in database alongside user/transaction data
      $sql = "INSERT INTO users (name, email, affiliate_click_key) VALUES (?, ?, ?)";
      // Execute database query...
  }
  ```

  ```python Python Example theme={null}
  from flask import Flask, request, session, make_response
  import urllib.parse

  app = Flask(__name__)

  # Capture click key from URL parameters
  def capture_click_key():
      click_key = (request.args.get('btag') or 
                   request.args.get('clickId') or 
                   request.args.get('clickkey') or 
                   request.args.get('affiliate_id'))
      
      if click_key:
          # Store in session and cookie
          session['affiliate_click_key'] = click_key
          response = make_response('Click key captured')
          response.set_cookie('affiliate_click_key', click_key, max_age=30*24*60*60)
          return response
      
      return 'No click key found'

  # Function to retrieve stored click key
  def get_stored_click_key():
      return (session.get('affiliate_click_key') or 
              request.cookies.get('affiliate_click_key'))

  # Use during registration/purchase
  @app.route('/register', methods=['POST'])
  def submit_registration():
      user_data = request.json
      click_key = get_stored_click_key()
      
      registration_data = {
          **user_data,
          'affiliate_click_key': click_key
      }
      
      # Store in database alongside user/transaction data
      # database.insert_user(registration_data)
      
      return {'status': 'success', 'click_key': click_key}
  ```
</CodeGroup>

<Info>
  **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
</Info>

### 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](https://docs.affelios.com/api-reference/customer/creates-a-new-customer-item).

<Card title="Customer API Endpoint" icon="user-plus">
  **POST** `/api/v1/customer` - Creates a new customer item in Affelios with tracking information for proper attribution.
</Card>

#### Required Fields

Based on the [API reference](https://docs.affelios.com/api-reference/customer/creates-a-new-customer-item), 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:

<CodeGroup>
  ```javascript JavaScript Example theme={null}
  // 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;
  }
  ```

  ```php PHP Example theme={null}
  // Send customer to Affelios when they register
  function createAffeliosCustomer($customerData, $clickKey) {
      $affeliosCustomer = [
          'externalId' => $customerData['id'], // Your internal customer ID
          'brandId' => $_ENV['AFFELIOS_BRAND_ID'], // Your Affelios brand ID
          'clickKey' => $clickKey, // Captured from tracking link
          'username' => $customerData['username'],
          'registrationDate' => date('c'), // ISO 8601 format
          'country_code' => $customerData['countryCode']
      ];

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, 'https://platform.affelios.com/api/v1/customer');
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, [
          'X-Api-Key: ' . $_ENV['AFFELIOS_API_KEY'],
          'Content-Type: application/json'
      ]);
      curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($affeliosCustomer));
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

      $response = curl_exec($ch);
      $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      curl_close($ch);

      if ($httpCode !== 200) {
          throw new Exception('Affelios API error: HTTP ' . $httpCode);
      }

      $result = json_decode($response, true);
      error_log('Customer created in Affelios: ' . $result['id']);
      return $result;
  }

  // Integration with your registration process
  function handleUserRegistration($userData) {
      // 1. Create user in your system
      $newUser = createUserInYourSystem($userData);
      
      // 2. Get stored click key
      $clickKey = getStoredClickKey();
      
      // 3. Send to Affelios if click key exists
      if ($clickKey) {
          try {
              createAffeliosCustomer($newUser, $clickKey);
          } catch (Exception $e) {
              // Log error but don't fail registration
              error_log('Affelios integration failed: ' . $e->getMessage());
          }
      }
      
      return $newUser;
  }
  ```

  ```python Python Example theme={null}
  import requests
  import os
  from datetime import datetime

  # Send customer to Affelios when they register
  def create_affelios_customer(customer_data, click_key):
      affelios_customer = {
          'externalId': customer_data['id'],  # Your internal customer ID
          'brandId': os.getenv('AFFELIOS_BRAND_ID'),  # Your Affelios brand ID
          'clickKey': click_key,  # Captured from tracking link
          'username': customer_data.get('username'),
          'registrationDate': datetime.now().isoformat(),
          'country_code': customer_data.get('countryCode')
      }

      try:
          response = requests.post(
              'https://platform.affelios.com/api/v1/customer',
              headers={
                  'X-Api-Key': os.getenv('AFFELIOS_API_KEY'),
                  'Content-Type': 'application/json'
              },
              json=affelios_customer
          )
          
          response.raise_for_status()
          result = response.json()
          print(f'Customer created in Affelios: {result["id"]}')
          return result
          
      except requests.RequestException as e:
          print(f'Failed to create customer in Affelios: {e}')
          raise

  # Integration with your registration process
  def handle_user_registration(user_data):
      # 1. Create user in your system
      new_user = create_user_in_your_system(user_data)
      
      # 2. Get stored click key
      click_key = get_stored_click_key()
      
      # 3. Send to Affelios if click key exists
      if click_key:
          try:
              create_affelios_customer(new_user, click_key)
          except Exception as e:
              # Log error but don't fail registration
              print(f'Affelios integration failed: {e}')
      
      return new_user
  ```
</CodeGroup>

<Warning>
  **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.
</Warning>

<Info>
  **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
</Info>

### 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.

<Card title="Transaction Cost Consideration" icon="dollar-sign">
  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](/knowledge-base/getting-started/understanding-billing) and see detailed pricing information at [Affelios Pricing](https://affelios.com/pricing).

  <Warning>
    **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
  </Warning>
</Card>

#### Aggregation Strategies

<AccordionGroup>
  <Accordion title="Real-time Processing">
    **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
  </Accordion>

  <Accordion title="Batch Processing">
    **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
  </Accordion>

  <Accordion title="Hybrid Approach">
    **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
  </Accordion>
</AccordionGroup>

#### Implementation Examples

<CodeGroup>
  ```javascript JavaScript Example theme={null}
  // 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
  ```

  ```php PHP Example theme={null}
  // Real-time transaction processing
  function processTransactionRealtime($transactionData, $customerId) {
      $affeliosTransaction = [
          'externalId' => $transactionData['id'],
          'externalCustomerId' => $customerId,
          'externalBrandId' => $_ENV['AFFELIOS_BRAND_ID'],
          'type' => 'deposit',
          'grossRevenue' => $transactionData['amount'],
          'transactionDate' => date('c')
      ];

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

  // Batch transaction processing
  function processTransactionsBatch($transactions) {
      // Group transactions by customer
      $groupedTransactions = [];
      foreach ($transactions as $transaction) {
          $customerId = $transaction['customerId'];
          if (!isset($groupedTransactions[$customerId])) {
              $groupedTransactions[$customerId] = [];
          }
          $groupedTransactions[$customerId][] = $transaction;
      }

      foreach ($groupedTransactions as $customerId => $customerTransactions) {
          // Aggregate transaction data
          $aggregatedData = [
              'externalCustomerId' => $customerId,
              'externalBrandId' => $_ENV['AFFELIOS_BRAND_ID'],
              'grossRevenue' => array_sum(array_column($customerTransactions, 'amount')),
              'transactionCount' => count($customerTransactions),
              'transactionDate' => date('c')
          ];

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

  // Cron job for batch processing (run every hour)
  // Add to crontab: 0 * * * * php /path/to/process_transactions.php
  ```
</CodeGroup>

<Info>
  **Best Practices**: For detailed guidance on transaction processing strategies, cost optimization, and implementation patterns, see our [Developer Best Practices](/developers/best-practices) documentation.
</Info>

### Step 5: Test Your Integration

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

<Steps>
  <Step title="Test Click Key Capture">
    Verify that click keys are being captured correctly from affiliate tracking links
  </Step>

  <Step title="Test Customer Creation">
    Ensure customer records are being sent to Affelios with proper attribution
  </Step>

  <Step title="Test Transaction Processing">
    Verify that transactions are being processed according to your chosen strategy
  </Step>

  <Step title="Test Error Handling">
    Confirm that your integration handles API errors gracefully
  </Step>
</Steps>

<Card title="Testing Tools" icon="flask">
  Use the [API Reference](/api-reference) interactive playground to test endpoints, or import our [OpenAPI specification](https://platform.affelios.com/swagger/v1/swagger.json) into Postman for comprehensive testing.
</Card>

### Step 6: Monitor and Maintain

Once your integration is live, ongoing monitoring and maintenance are essential for success.

<AccordionGroup>
  <Accordion title="Performance Monitoring">
    **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
  </Accordion>

  <Accordion title="Data Quality">
    **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
  </Accordion>

  <Accordion title="Cost Optimization">
    **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
  </Accordion>
</AccordionGroup>

## Troubleshooting

### Common Issues

<AccordionGroup>
  <Accordion title="Click Key Not Captured">
    **Problem**: Affiliate tracking links not generating click keys

    **Solutions**:

    * 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
  </Accordion>

  <Accordion title="Customer Attribution Failing">
    **Problem**: Customers not being attributed to correct affiliates

    **Solutions**:

    * 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
  </Accordion>

  <Accordion title="Transaction Processing Issues">
    **Problem**: Transactions not being processed or attributed correctly

    **Solutions**:

    * 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
  </Accordion>
</AccordionGroup>

### Getting Help

<Steps>
  <Step title="Check Documentation">
    Review the [API Reference](/api-reference) and [Developer Best Practices](/developers/best-practices) for detailed guidance
  </Step>

  <Step title="Review Logs">
    Check your application logs for specific error messages and request details
  </Step>

  <Step title="Test with API Tools">
    Use Postman or the API playground to test requests independently
  </Step>

  <Step title="Contact Support">
    Reach out to our support team with specific error details and request IDs
  </Step>
</Steps>

## Best Practices Summary

<Card title="Integration Checklist" icon="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
</Card>

***

## Next Steps

<Card title="Your Integration is Complete!" icon="circle-check">
  Congratulations! Your bespoke API integration with Affelios is now set up and ready to track affiliate performance and process commissions.
</Card>

### What Happens Next

<Steps>
  <Step title="Go Live">
    Deploy your integration to production and start tracking affiliate performance
  </Step>

  <Step title="Monitor Performance">
    Use the Affelios dashboard to monitor clicks, conversions, and commission payouts
  </Step>

  <Step title="Optimize Strategy">
    Review performance data and adjust your transaction processing strategy as needed
  </Step>

  <Step title="Scale Success">
    Expand your affiliate program based on performance insights and data
  </Step>
</Steps>

### Additional Resources

<CardGroup cols={2}>
  <Card title="API Reference" icon="book" href="/api-reference">
    Complete API documentation with interactive examples
  </Card>

  <Card title="Developer Best Practices" icon="star" href="/developers/best-practices">
    Guidelines for secure, efficient, and maintainable integrations
  </Card>

  <Card title="Understanding Billing" icon="dollar-sign" href="/knowledge-base/getting-started/understanding-billing">
    Learn how Affelios charges work and optimize your costs
  </Card>

  <Card title="Support" icon="life-ring" href="mailto:support@affelios.com">
    Get help with your integration from our support team
  </Card>
</CardGroup>

<Info>
  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](mailto:support@affelios.com).
</Info>
