# Making Your Platform AIDP-Compatible

Step-by-step guide to integrating AIDP into your SaaS platform.

## Integration Overview

AIDP provides three integration methods:

1. **REST API** - Full programmatic access
2. **Webhooks** - Real-time event notifications
3. **Embedded UI** - Pre-built interface components

***

## Step 1: Authentication

### Get Partner API Key

1. Apply at [platform.aidp.dev/partners](https://platform.aidp.dev/partners)
2. Receive partner credentials
3. Generate API keys for each environment

### API Key Types

* **Partner Key**: Your platform's master key
* **Customer Keys**: Individual keys for each customer
* **Sandbox Keys**: For testing

### Authentication

```bash
curl -X GET https://api.aidp.dev/v1/partner/customers \
  -H "Authorization: Bearer YOUR_PARTNER_KEY"
```

***

## Step 2: Customer Provisioning

### Create Customer Account

```typescript
import { AIDPPartnerClient } from '@aidp/partner-sdk';

const partner = new AIDPPartnerClient({
  apiKey: process.env.AIDP_PARTNER_KEY,
});

// Create customer
const customer = await partner.customers.create({
  externalId: 'your-customer-id-123',
  businessName: 'Artisan Coffee Roasters',
  email: 'owner@artisancoffee.com',
  plan: 'professional',
  metadata: {
    posSystemId: 'pos_abc123',
    subscriptionTier: 'premium',
  },
});

console.log(`Customer created: ${customer.id}`);
console.log(`API Key: ${customer.apiKey}`);
```

### Customer Lifecycle

```typescript
// Update customer
await partner.customers.update(customer.id, {
  plan: 'enterprise',
  metadata: { upgraded: true },
});

// Suspend customer
await partner.customers.suspend(customer.id, {
  reason: 'payment_failed',
});

// Reactivate customer
await partner.customers.activate(customer.id);

// Delete customer
await partner.customers.delete(customer.id);
```

***

## Step 3: Data Synchronization

### Sync Business Profile

```typescript
// Sync business data from your platform
await partner.sync.business(customer.id, {
  name: 'Artisan Coffee Roasters',
  category: 'restaurants',
  description: 'Family-owned coffee roastery...',
  address: {
    street: '123 Main St',
    city: 'Portland',
    state: 'OR',
    zip: '97201',
  },
  contact: {
    phone: '+1-503-555-0123',
    email: 'hello@artisancoffee.com',
    website: 'https://artisancoffee.com',
  },
  hours: {
    monday: { open: '07:00', close: '18:00' },
    tuesday: { open: '07:00', close: '18:00' },
    // ...
  },
});
```

### Sync Services

```typescript
await partner.sync.services(customer.id, [
  {
    name: 'Espresso Drinks',
    description: 'Handcrafted espresso beverages',
    pricing: { min: 4.0, max: 6.5 },
  },
  {
    name: 'Pour Over Coffee',
    description: 'Single-origin pour over',
    pricing: { fixed: 5.0 },
  },
]);
```

### Sync Media

```typescript
await partner.sync.media(customer.id, [
  {
    type: 'photo',
    url: 'https://cdn.yourplatform.com/photos/123.jpg',
    caption: 'Our cozy interior',
    primary: true,
  },
]);
```

***

## Step 4: Webhook Integration

### Subscribe to Events

```typescript
await partner.webhooks.create({
  url: 'https://yourplatform.com/webhooks/aidp',
  events: ['customer.profile.updated', 'analytics.impression', 'analytics.citation'],
  secret: 'your-webhook-secret',
});
```

### Handle Webhooks

```typescript
import express from 'express';
import crypto from 'crypto';

const app = express();

app.post('/webhooks/aidp', express.json(), (req, res) => {
  // Verify signature
  const signature = req.headers['x-aidp-signature'];
  const payload = JSON.stringify(req.body);
  const expected = crypto.createHmac('sha256', 'your-webhook-secret').update(payload).digest('hex');

  if (signature !== expected) {
    return res.status(401).send('Invalid signature');
  }

  // Handle event
  const event = req.body;

  switch (event.type) {
    case 'analytics.impression':
      handleImpression(event.data);
      break;
    case 'analytics.citation':
      handleCitation(event.data);
      break;
  }

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

***

## Step 5: Embedded UI

### Embed Analytics Dashboard

```html
<iframe
  src="https://embed.aidp.dev/analytics?customerId=cust_abc123&token=embed_token"
  width="100%"
  height="600"
  frameborder="0"
></iframe>
```

### Generate Embed Token

```typescript
const embedToken = await partner.embed.createToken({
  customerId: customer.id,
  expiresIn: 3600, // 1 hour
  permissions: ['analytics:read'],
});
```

### Customize Appearance

```typescript
const embedUrl = partner.embed.buildUrl({
  customerId: customer.id,
  token: embedToken,
  theme: {
    primaryColor: '#007bff',
    fontFamily: 'Inter, sans-serif',
  },
  features: {
    upstream: true,
    journeys: true,
    benchmarking: false,
  },
});
```

***

## Step 6: Analytics Integration

### Fetch Analytics

```typescript
// Get upstream metrics
const upstream = await partner.analytics.upstream({
  customerId: customer.id,
  startDate: '2024-01-01',
  endDate: '2024-12-31',
});

// Get intent journeys
const journeys = await partner.analytics.intentJourneys({
  customerId: customer.id,
  period: 'last_30_days',
});
```

### Display in Your Dashboard

```typescript
function AnalyticsSummary({ customerId }) {
  const [metrics, setMetrics] = useState(null);

  useEffect(() => {
    async function loadMetrics() {
      const data = await partner.analytics.upstream({
        customerId,
        period: 'last_30_days'
      });
      setMetrics(data);
    }
    loadMetrics();
  }, [customerId]);

  if (!metrics) return <div>Loading...</div>;

  return (
    <div>
      <h3>AI Discovery Performance</h3>
      <div>Impressions: {metrics.totalImpressions}</div>
      <div>Citations: {metrics.totalCitations}</div>
      <div>Citation Rate: {metrics.citationRate}%</div>
    </div>
  );
}
```

***

## Best Practices

### 1. Incremental Sync

Only sync changed data:

```typescript
// Track last sync time
const lastSync = await getLastSyncTime(customerId);

// Sync only updated records
const updates = await getUpdatedRecords(customerId, lastSync);
await partner.sync.incremental(customerId, updates);

// Update sync timestamp
await setLastSyncTime(customerId, Date.now());
```

### 2. Error Handling

```typescript
try {
  await partner.sync.business(customerId, data);
} catch (error) {
  if (error.code === 'RATE_LIMIT_EXCEEDED') {
    // Wait and retry
    await sleep(error.retryAfter * 1000);
    await partner.sync.business(customerId, data);
  } else {
    // Log and alert
    console.error('Sync failed:', error);
    await notifyAdmin(error);
  }
}
```

### 3. Batch Operations

```typescript
// Batch customer creation
const customers = await partner.customers.createBatch([
  { externalId: 'cust_1', businessName: 'Business 1' },
  { externalId: 'cust_2', businessName: 'Business 2' },
  // ...
]);
```

***

## Testing

### Sandbox Environment

```typescript
const partner = new AIDPPartnerClient({
  apiKey: process.env.AIDP_SANDBOX_KEY,
  environment: 'sandbox',
});

// Test customer creation
const testCustomer = await partner.customers.create({
  externalId: 'test-123',
  businessName: 'Test Business',
});
```

***

## Support

* 📧 Email: <integration@aidp.dev>
* 📚 API Docs: [docs.aidp.dev/partner-api](https://docs.aidp.dev/partner-api)

***

**Next**: [Data Export →](https://amistan.gitbook.io/aidp-docs/for-saas-platforms/data-export)
