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

# Use Cases

> Discover real-world integration scenarios for the Chariow API

The Chariow API enables a wide range of integration scenarios for selling digital products. Here are five common use cases to help you get started.

## 1. Custom Storefront Integration

Build a fully branded shopping experience on your own website while leveraging Chariow for payment processing and product delivery.

### Scenario

You have an existing website or web application and want to sell digital products without redirecting customers to an external store.

### Implementation

<Steps>
  <Step title="Display Products">
    Fetch your product catalog using the [List Products](/api-reference/products/list-products) endpoint and display them on your website.
  </Step>

  <Step title="Collect Customer Information">
    Create a custom checkout form to collect customer details (name, email, phone).
  </Step>

  <Step title="Initiate Checkout">
    Call the [Checkout API](/api-reference/checkout/init-checkout) with customer data and redirect to the payment URL.
  </Step>

  <Step title="Handle Completion">
    Use a custom `redirect_url` to bring customers back to your thank-you page, and set up [Pulses](/en/guides/pulses) for reliable sale notifications.
  </Step>
</Steps>

### Code Example

```javascript theme={null}
// Fetch products for display
const products = await fetch('https://api.chariow.com/v1/products', {
  headers: { 'Authorization': 'Bearer sk_live_your_api_key' }
}).then(res => res.json());

// When customer submits checkout form
async function handleCheckout(productId, customerData) {
  const response = await fetch('https://api.chariow.com/v1/checkout', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sk_live_your_api_key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      product_id: productId,
      email: customerData.email,
      first_name: customerData.firstName,
      last_name: customerData.lastName,
      phone: {
        number: customerData.phone,
        country_code: customerData.countryCode
      },
      redirect_url: 'https://yoursite.com/thank-you?sale={sale_id}'
    })
  });

  const result = await response.json();

  if (result.data.step === 'payment') {
    window.location.href = result.data.payment.checkout_url;
  }
}
```

***

## 2. Software License Management

Sell software with automated license key generation, validation, and activation management.

### Scenario

You develop desktop or mobile software and need to protect it with license keys, control the number of installations, and manage activations.

### Implementation

<Steps>
  <Step title="Sell License Products">
    Create license-type products in Chariow with activation limits configured.
  </Step>

  <Step title="Validate on Launch">
    When your software starts, call the [Get License](/api-reference/licenses/get-license) endpoint to check if the license is valid (verify `is_active`, `is_expired`, and `can_activate` fields).
  </Step>

  <Step title="Activate on Install">
    On first run, call [Activate License](/api-reference/licenses/activate-license) with a unique machine identifier.
  </Step>

  <Step title="Manage Activations">
    Allow users to revoke licenses when switching devices using [Revoke License](/api-reference/licenses/revoke-license).
  </Step>
</Steps>

### Code Example

```python theme={null}
import requests
import hashlib
import platform

def get_machine_id():
    """Generate a unique machine identifier"""
    machine_info = f"{platform.node()}-{platform.machine()}-{platform.processor()}"
    return hashlib.sha256(machine_info.encode()).hexdigest()[:32]

def validate_license(license_key):
    """Check if license is valid via Get License endpoint"""
    response = requests.get(
        f'https://api.chariow.com/v1/licenses/{license_key}',
        headers={'Authorization': 'Bearer sk_live_your_api_key'}
    )
    data = response.json()
    return data['data']['is_active'] and not data['data']['is_expired']

def activate_license(license_key):
    """Activate license for this machine"""
    response = requests.post(
        'https://api.chariow.com/v1/licenses/activate',
        headers={'Authorization': 'Bearer sk_live_your_api_key'},
        json={
            'license_key': license_key,
            'identifier': get_machine_id(),
            'label': f"{platform.node()} - {platform.system()}"
        }
    )
    return response.json()

# On application startup
license_key = load_stored_license()
if not validate_license(license_key):
    show_license_expired_dialog()
```

***

## 3. E-commerce Platform Plugin

Create a plugin or integration for e-commerce platforms (WordPress, Shopify, etc.) to sell Chariow products.

### Scenario

You want to extend an existing e-commerce platform to sell digital products managed in Chariow, synchronizing products and processing orders.

### Implementation

<Steps>
  <Step title="Sync Product Catalog">
    Periodically fetch products from Chariow and sync them to your platform's database.
  </Step>

  <Step title="Handle Add to Cart">
    Store Chariow product IDs alongside platform cart items.
  </Step>

  <Step title="Process Checkout">
    On checkout, create Chariow checkout sessions for each digital product.
  </Step>

  <Step title="Fulfill Orders">
    Listen to Chariow [Pulses](/en/guides/pulses) to mark orders as fulfilled in your platform.
  </Step>
</Steps>

### Code Example

```php theme={null}
<?php
// WordPress/WooCommerce example

// Sync products from Chariow
function sync_chariow_products() {
    $response = wp_remote_get('https://api.chariow.com/v1/products', [
        'headers' => [
            'Authorization' => 'Bearer ' . get_option('chariow_api_key')
        ]
    ]);

    $products = json_decode(wp_remote_retrieve_body($response), true);

    foreach ($products['data'] as $product) {
        update_or_create_wc_product($product);
    }
}

// Process checkout for Chariow product
function process_chariow_checkout($order_id) {
    $order = wc_get_order($order_id);

    foreach ($order->get_items() as $item) {
        $chariow_product_id = get_post_meta($item->get_product_id(), '_chariow_product_id', true);

        if ($chariow_product_id) {
            $response = wp_remote_post('https://api.chariow.com/v1/checkout', [
                'headers' => [
                    'Authorization' => 'Bearer ' . get_option('chariow_api_key'),
                    'Content-Type' => 'application/json'
                ],
                'body' => json_encode([
                    'product_id' => $chariow_product_id,
                    'email' => $order->get_billing_email(),
                    'first_name' => $order->get_billing_first_name(),
                    'last_name' => $order->get_billing_last_name(),
                    'phone' => [
                        'number' => preg_replace('/[^0-9]/', '', $order->get_billing_phone()),
                        'country_code' => $order->get_billing_country()
                    ]
                ])
            ]);

            $result = json_decode(wp_remote_retrieve_body($response), true);
            update_post_meta($order_id, '_chariow_sale_id', $result['data']['purchase']['id']);
        }
    }
}
```

***

## 4. Course Platform with Access Control

Build an online learning platform where course access is controlled by Chariow purchases.

### Scenario

You run an educational platform and want to sell courses, controlling access based on purchase status and managing enrollments.

### Implementation

<Steps>
  <Step title="Create Course Products">
    Set up course-type products in Chariow with your curriculum content.
  </Step>

  <Step title="Verify Access">
    When users try to access course content, verify their purchase using the [Get Sale](/api-reference/sales/get-sale) endpoint.
  </Step>

  <Step title="Handle Enrollments">
    Use [Pulses](/en/guides/pulses) to automatically enroll users when purchases complete.
  </Step>

  <Step title="Track Progress">
    Store course progress in your database, linked to the Chariow customer ID.
  </Step>
</Steps>

### Code Example

```javascript theme={null}
// Express.js middleware for course access control

async function verifyCourseAccess(req, res, next) {
  const { courseSlug } = req.params;
  const userEmail = req.user.email;

  // Find the sale for this user and course
  const salesResponse = await fetch(
    `https://api.chariow.com/v1/sales?product_slug=${courseSlug}&customer_email=${userEmail}`,
    {
      headers: { 'Authorization': 'Bearer sk_live_your_api_key' }
    }
  );

  const sales = await salesResponse.json();
  const validSale = sales.data.find(sale => sale.status === 'completed');

  if (!validSale) {
    return res.status(403).json({
      error: 'Access denied',
      message: 'Please purchase this course to access the content',
      purchase_url: `/checkout/${courseSlug}`
    });
  }

  req.sale = validSale;
  next();
}

// Pulse webhook handler for auto-enrollment
app.post('/webhooks/chariow', async (req, res) => {
  const { event, data } = req.body;

  if (event === 'sale.completed') {
    const { customer, product } = data;

    // Auto-enroll user in course
    await db.enrollments.create({
      user_email: customer.email,
      course_id: product.id,
      enrolled_at: new Date(),
      sale_id: data.id
    });

    // Send welcome email
    await sendCourseWelcomeEmail(customer.email, product.name);
  }

  res.status(200).send('OK');
});
```

***

## 5. Affiliate and Campaign Tracking

Track sales attribution across marketing campaigns and affiliate partners.

### Scenario

You run marketing campaigns or have affiliate partners and need to track which sales come from which sources to calculate commissions or measure ROI.

### Implementation

<Steps>
  <Step title="Create Campaign IDs">
    Generate unique campaign identifiers for each marketing channel or affiliate.
  </Step>

  <Step title="Pass Campaign on Checkout">
    Include the `campaign_id` parameter when initiating checkouts.
  </Step>

  <Step title="Track in Pulses">
    Capture campaign data from sale Pulses to attribute conversions.
  </Step>

  <Step title="Generate Reports">
    Use the [List Sales](/api-reference/sales/list-sales) endpoint with campaign filters to generate attribution reports.
  </Step>
</Steps>

### Code Example

```javascript theme={null}
// Track campaign from URL parameters
function getCheckoutDataWithCampaign(productId, customerData) {
  const urlParams = new URLSearchParams(window.location.search);
  const campaignId = urlParams.get('ref') || urlParams.get('utm_campaign') || urlParams.get('affiliate');

  const checkoutData = {
    product_id: productId,
    email: customerData.email,
    first_name: customerData.firstName,
    last_name: customerData.lastName,
    phone: {
      number: customerData.phone,
      country_code: customerData.countryCode
    }
  };

  if (campaignId) {
    checkoutData.campaign_id = campaignId;
  }

  return checkoutData;
}

// Backend: Generate affiliate report
async function generateAffiliateReport(affiliateId, startDate, endDate) {
  const response = await fetch(
    `https://api.chariow.com/v1/sales?campaign_id=${affiliateId}&from=${startDate}&to=${endDate}`,
    {
      headers: { 'Authorization': 'Bearer sk_live_your_api_key' }
    }
  );

  const sales = await response.json();

  const report = {
    affiliate_id: affiliateId,
    period: { start: startDate, end: endDate },
    total_sales: sales.data.length,
    total_revenue: sales.data.reduce((sum, sale) => sum + sale.amount.value, 0),
    commission: 0
  };

  // Calculate 20% commission
  report.commission = report.total_revenue * 0.20;

  return report;
}
```

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Best Practices" icon="shield-check" href="/en/guides/best-practices">
    Learn checkout API best practices for production
  </Card>

  <Card title="Checkout Guide" icon="cart-shopping" href="/en/guides/checkout">
    Deep dive into the checkout flow
  </Card>

  <Card title="Pulses" icon="webhook" href="/en/guides/pulses">
    Set up webhooks for real-time notifications
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore the complete API documentation
  </Card>
</CardGroup>
