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

# E-commerce Integration

> Learn how to integrate UseDropTrail with your e-commerce platform

# E-commerce Integration Guide

This guide demonstrates how to integrate UseDropTrail's delivery system with your e-commerce platform. You'll learn how to automatically create delivery requests when orders are placed and track deliveries in real-time.

## Overview

When integrating UseDropTrail with your e-commerce platform, you'll typically want to:

1. Create delivery requests automatically when orders are placed
2. Track delivery status and update order status accordingly
3. Provide real-time tracking information to customers
4. Handle delivery notifications

## Prerequisites

* UseDropTrail API key
* Organization account
* E-commerce platform with webhook support

## Implementation Steps

### 1. Initialize the SDK

```javascript theme={null}
const UseDropTrail = require('usedroptrail');
const usedroptrail = new UseDropTrail({
  apiKey: 'YOUR_API_KEY'
});
```

### 2. Create a Delivery Request

```javascript theme={null}
const deliveryRequest = await usedroptrail.deliveryRequests.create({
  orderId: '123456',
  pickupAddress: '123 Main St, Anytown, USA',
  deliveryAddress: '456 Elm St, Anytown, USA',
  pickupTime: '2024-01-01T10:00:00Z',
  deliveryTime: '2024-01-01T12:00:00Z'
});
```

### 3. Track Delivery Status

```javascript theme={null}
const deliveryStatus = await usedroptrail.deliveryRequests.get(deliveryRequest.id);
console.log(deliveryStatus);
```

### 4. Handle Delivery Notifications

```javascript theme={null}
const deliveryNotification = await usedroptrail.deliveryRequests.update(deliveryRequest.id, {
  status: 'delivered'
});
console.log(deliveryNotification);
```

### 4. Handle Webhooks

```javascript theme={null}
app.post('/webhooks/usedroptrail', async (req, res) => {
  const event = req.body;

  switch (event.type) {
    case 'delivery.accepted':
      await handleDeliveryAccepted(event.data);
      break;
    case 'delivery.in_transit':
      await handleDeliveryInTransit(event.data);
      break;
    case 'delivery.completed':
      await handleDeliveryCompleted(event.data);
      break;
    case 'delivery.cancelled':
      await handleDeliveryCancelled(event.data);
      break;
  }

  res.status(200).send('Webhook received');
});
```

This example demonstrates how to create a delivery request, track its status, and handle delivery notifications. You can customize this implementation based on your specific requirements and e-commerce platform.

## Best Practices

1. **Error Handling**
   * Always implement proper error handling
   * Have fallback delivery options
   * Store delivery request IDs for reference

2. **Customer Communication**
   * Send tracking information immediately after delivery request creation
   * Provide real-time status updates
   * Set up automated notifications for important status changes

3. **Order Management**
   * Keep order and delivery status synchronized
   * Store all tracking information
   * Implement retry logic for failed delivery requests

4. **Testing**
   * Use sandbox environment for testing
   * Test with various order scenarios
   * Simulate different delivery statuses

## Common Issues and Solutions

### Issue: Delivery Request Creation Fails

```javascript theme={null}
try {
  const deliveryRequest = await createDeliveryFromOrder(order);
} catch (error) {
  if (error.code === 'INVALID_ADDRESS') {
    // Validate and clean up address
    const correctedAddress = await validateAddress(order.shipping_address);
    // Retry with corrected address
    return createDeliveryFromOrder({ ...order, shipping_address: correctedAddress });
  }
  // Handle other errors
}
```

### Issue: Tracking Updates Not Received

```javascript theme={null}
function setupDeliveryTrackingWithRetry(deliveryRequestId, maxRetries = 3) {
  let retries = 0;
  
  function connect() {
    const ws = droptrail.tracking.connect(deliveryRequestId);
    
    ws.on('error', (error) => {
      console.error('Tracking connection error:', error);
      if (retries < maxRetries) {
        retries++;
        setTimeout(connect, 5000 * retries);
      }
    });
    
    return ws;
  }
  
  return connect();
}
```

## Conclusion

By following these steps, you can integrate UseDropTrail's delivery system with your e-commerce platform. This integration allows you to automatically create delivery requests, track delivery status, and provide real-time tracking information to customers.

For more detailed information, you can refer to the [API Reference](/api-reference).
