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

# CRM Integration

> End-to-end guide for integrating Oktivo with your CRM

# CRM Integration Guide

This guide walks you through connecting Oktivo to your CRM so you can trigger AI voice calls from your sales pipeline and receive structured results back.

## Architecture Overview

```
┌─────────────┐       API Token        ┌──────────────────┐
│   Your CRM  │ ─────────────────────▶ │  Oktivo CRM API  │
│             │                         │                  │
│             │ ◀───── Webhook ──────── │  Voice Agents    │
└─────────────┘                         └──────────────────┘
```

1. Your CRM triggers a call via the API when a lead enters a specific pipeline stage
2. Oktivo's AI agent makes the call and extracts structured data
3. Oktivo sends results back to your CRM via webhook

## Step 1: Generate an API Token

Create a token from the Oktivo dashboard or via API:

```bash cURL theme={null}
curl -X POST https://client-backend.oktivo.com/api/v1/crm/tokens \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "salesforce-prod",
    "expiresInDays": 90
  }'
```

```javascript Node.js theme={null}
const response = await fetch('https://client-backend.oktivo.com/api/v1/crm/tokens', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_JWT_TOKEN',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'salesforce-prod',
    expiresInDays: 90,
  }),
});

const { data } = await response.json();
// Save data.plainToken securely it won't be shown again
```

```python Python theme={null}
import requests

response = requests.post(
    "https://client-backend.oktivo.com/api/v1/crm/tokens",
    headers={
        "Authorization": "Bearer YOUR_JWT_TOKEN",
        "Content-Type": "application/json",
    },
    json={
        "name": "salesforce-prod",
        "expiresInDays": 90,
    },
)

data = response.json()["data"]
# Save data["plainToken"] securely it won't be shown again
```

> [!WARNING]
>
> Store the `plainToken` value in your CRM's secure credential store. It cannot be retrieved after this response.

## Step 2: Configure Your CRM

Add the API token to your CRM's HTTP integration settings:

* **Base URL:** `https://client-backend.oktivo.com`
* **Header:** `Authorization: Bearer okt_your_token_here`
* **Content-Type:** `application/json`

## Step 3: Trigger Calls from Your Pipeline

When a lead enters the appropriate stage, trigger a call:

```bash cURL theme={null}
curl -X POST https://client-backend.oktivo.com/api/v1/crm/calls \
  -H "Authorization: Bearer okt_your_token_here" \
  -H "Content-Type: application/json" \
  -d '{
    "phone": "+14155551234",
    "name": "Jane Smith",
    "agentId": "agent_qualification_v2",
    "dynamicVariables": {
      "company": "Acme Corp",
      "deal_value": "$50,000",
      "last_contact": "2025-01-10"
    },
    "retryConfig": {
      "retryCount": 2,
      "retryDelays": [5, 15]
    }
  }'
```

```javascript Node.js theme={null}
async function triggerOktivoCall(lead) {
  const response = await fetch('https://client-backend.oktivo.com/api/v1/crm/calls', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.OKTIVO_API_TOKEN}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      phone: lead.phone,
      name: lead.fullName,
      agentId: 'agent_qualification_v2',
      dynamicVariables: {
        company: lead.company,
        deal_value: lead.dealValue,
        last_contact: lead.lastContactDate,
      },
      retryConfig: {
        retryCount: 2,
        retryDelays: [5, 15],
      },
    }),
  });

  const result = await response.json();

  if (!result.success) {
    console.error('Call trigger failed:', result.message);
    return null;
  }

  return result.data.contactUID;
}
```

```python Python theme={null}
import requests
import os

def trigger_oktivo_call(lead):
    response = requests.post(
        "https://client-backend.oktivo.com/api/v1/crm/calls",
        headers={
            "Authorization": f"Bearer {os.environ['OKTIVO_API_TOKEN']}",
            "Content-Type": "application/json",
        },
        json={
            "phone": lead["phone"],
            "name": lead["full_name"],
            "agentId": "agent_qualification_v2",
            "dynamicVariables": {
                "company": lead["company"],
                "deal_value": lead["deal_value"],
                "last_contact": lead["last_contact_date"],
            },
            "retryConfig": {
                "retryCount": 2,
                "retryDelays": [5, 15],
            },
        },
    )

    result = response.json()

    if not result["success"]:
        print(f"Call trigger failed: {result['message']}")
        return None

    return result["data"]["contactUID"]
```

## Step 4: Set Up a Webhook for Results

Create an endpoint to receive call analysis back into your CRM. You can do the same in the dashboard under **Connecter > Webhooks**. Webhook requests use the login token (JWT) of a dashboard user, not the `okt_` API token.

```bash theme={null}
curl -X POST https://client-backend.oktivo.com/webhooks/endpoints \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-crm.com/webhooks/oktivo-results",
    "eventTypes": ["call.analysis_ready", "call.completed"],
    "agentIds": ["agent_qualification_v2"]
  }'
```

## Step 5: Process Webhook Payloads

Handle incoming webhook events to update your CRM records:

```javascript Node.js (Express) theme={null}
const crypto = require('crypto');

// Keep the raw body: the signature covers the exact bytes received
app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } }));

app.post('/webhooks/oktivo-results', (req, res) => {
  // Verify signature: HMAC-SHA256 of "<timestamp>.<raw body>"
  const signature = req.headers['x-oktivo-signature'] || '';
  const timestamp = req.headers['x-oktivo-timestamp'];
  const expected = crypto
    .createHmac('sha256', process.env.OKTIVO_WEBHOOK_SECRET)
    .update(`${timestamp}.`)
    .update(req.rawBody)
    .digest('hex');

  const a = Buffer.from(signature);
  const b = Buffer.from(expected);
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
    return res.status(401).send('Invalid signature');
  }

  // Process the event
  const { type: event, data } = req.body;

  if (event === 'call.analysis_ready') {
    // Update CRM with analysis results
    updateLeadInCRM(data.contactUID, {
      interested: data.analysis.interested,
      notes: data.analysis.reason,
      callbackTime: data.analysis.callback_time,
    });
  }

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

```python Python (Flask) theme={null}
import hmac
import hashlib
import json
import os
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/webhooks/oktivo-results', methods=['POST'])
def handle_oktivo_webhook():
    # Verify signature
    signature = request.headers.get('x-oktivo-signature', '')
    timestamp = request.headers.get('x-oktivo-timestamp', '')
    raw_body = request.get_data()  # exact bytes received
    expected = hmac.new(
        os.environ['OKTIVO_WEBHOOK_SECRET'].encode(),
        timestamp.encode() + b"." + raw_body,
        hashlib.sha256,
    ).hexdigest()

    if not hmac.compare_digest(signature, expected):
        return jsonify({"error": "Invalid signature"}), 401

    # Process the event
    payload = json.loads(raw_body)
    event = payload["type"]
    data = payload["data"]

    if event == "call.analysis_ready":
        update_lead_in_crm(data["contactUID"], {
            "interested": data["analysis"]["interested"],
            "notes": data["analysis"]["reason"],
            "callback_time": data["analysis"]["callback_time"],
        })

    return "OK", 200
```

## Error Handling

| HTTP Code | Meaning | Action |
| - | - | - |
| 400 | Validation error | Fix the request body |
| 402 | Insufficient credits | Top up your balance |
| 404 | Agent not found | Verify the `agentId` |
| 403 | Contact is on the Do Not Disturb list, or calling is not allowed at this time | Do not retry straight away |
| 429 | Concurrent-call limit reached, or more than 60 requests in a minute | Wait, then retry with growing delays (use the `Retry-After` header when present) |
| 503 | Service unavailable | Retry with exponential backoff, and respect the `Retry-After` header when present |

## Using Panzo, n8n or Zapier

* **Panzo:** follow the dedicated [Panzo guide](https://stage-docs.oktivo.com/connectors/panzo.md). It uses the **Panzo CRM** delivery format.
* **n8n, Zapier and similar tools:** use the same steps as above. Place calls with an HTTP request to /api/v1/crm/calls, and receive results with the tool's webhook trigger. Keep the **Standard (default)** delivery format. If the tool cannot check signatures, restrict access in another way, such as a secret path in the URL.

## Next Steps

* [Retry Logic Guide](https://stage-docs.oktivo.com/guides/retry-logic.md) configure automatic retries
* [Webhook Filtering](https://stage-docs.oktivo.com/guides/webhook-filtering.md) route events per agent
* [API Reference](https://stage-docs.oktivo.com/api-reference/overview.md) full endpoint documentation


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.