Sync calls with your CRM
In this guide, each completed call reaches your server by webhook, without polling. The receiver:
- checks the signature;
- ignores retries;
- answers right away;
- in a queue, reads the call's detail and creates or updates the contact and the activity in your CRM.
A daily reconciliation catches anything that was missed.
Before you start
- An API key with the Webhooks — gestão (
webhooks:manage) and Chamadas e transcrições (calls:read) scopes. - A server reachable from the internet over
https://. - Python 3.11 or later with
flaskandrequests, or Node.js 18 or later.
1. Write the receiver
import hashlib
import hmac
import json
import os
import queue
import threading
import time
import requests
from flask import Flask, request
API = "https://api.diska.ai/v1"
API_KEY = os.environ["DISKA_API_KEY"]
SECRET = os.environ["DISKA_WEBHOOK_SECRET"]
app = Flask(__name__)
jobs: queue.Queue = queue.Queue()
seen: set[str] = set() # in production: a table with X-Diska-Delivery as a unique key
def is_valid(timestamp: str, body: bytes, signature: str) -> bool:
if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300:
return False
expected = hmac.new(SECRET.encode(), f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
return hmac.compare_digest(f"sha256={expected}", signature)
@app.post("/hooks/diska")
def receive():
body = request.get_data() # the raw body, before parsing the JSON
timestamp = request.headers.get("X-Diska-Timestamp", "")
if not is_valid(timestamp, body, request.headers.get("X-Diska-Signature", "")):
return "", 401
delivery = request.headers.get("X-Diska-Delivery", "")
if delivery in seen:
return "", 200 # a retry of a delivery you already received
seen.add(delivery)
event = json.loads(body)
if event.get("event") == "call.completed":
jobs.put(event) # process outside the request: answer within 10 seconds
return "", 200
def crm_upsert(phone: str | None, name: str | None, activity: dict) -> None:
# Replace with your CRM's API call: look the contact up by phone,
# create it if it does not exist and add the activity with the call id.
print("CRM", phone, name, activity)
def sync_call(event: dict) -> None:
response = requests.get(
f"{API}/calls/{event['call_id']}",
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=30,
)
response.raise_for_status()
call = response.json()
crm_upsert(
phone=event.get("caller_contact"),
name=call.get("caller_name"),
activity={
"diska_call_id": call["id"],
"started_at": call["started_at"],
"duration_seconds": call["duration_seconds"],
"agent": call["agent_name"],
"summary": call["summary"],
"sentiment": event.get("sentiment"),
"data": event.get("extracted_data", {}),
},
)
def worker() -> None:
while True:
event = jobs.get()
try:
sync_call(event)
except Exception as exc: # the daily reconciliation catches what fails here
print("sync failed", event["call_id"], exc)
finally:
jobs.task_done()
threading.Thread(target=worker, daemon=True).start()
// Node.js 18 or later, in a .mjs file
import crypto from 'node:crypto'
import http from 'node:http'
const API = 'https://api.diska.ai/v1'
const { DISKA_API_KEY, DISKA_WEBHOOK_SECRET } = process.env
const seen = new Set() // in production: a table with X-Diska-Delivery as a unique key
function isValid(timestamp, rawBody, signature) {
if (!/^\d+$/.test(timestamp || '') || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false
const expected = 'sha256=' + crypto.createHmac('sha256', DISKA_WEBHOOK_SECRET)
.update(`${timestamp}.`).update(rawBody).digest('hex')
const a = Buffer.from(expected)
const b = Buffer.from(signature || '')
return a.length === b.length && crypto.timingSafeEqual(a, b)
}
async function crmUpsert(phone, name, activity) {
// Replace with your CRM's API call: look the contact up by phone,
// create it if it does not exist and add the activity with the call id.
console.log('CRM', phone, name, activity)
}
async function syncCall(event) {
const response = await fetch(`${API}/calls/${event.call_id}`, {
headers: { Authorization: `Bearer ${DISKA_API_KEY}` }
})
if (!response.ok) throw new Error(`HTTP ${response.status}`)
const call = await response.json()
await crmUpsert(event.caller_contact, call.caller_name, {
diska_call_id: call.id,
started_at: call.started_at,
duration_seconds: call.duration_seconds,
agent: call.agent_name,
summary: call.summary,
sentiment: event.sentiment,
data: event.extracted_data ?? {}
})
}
http.createServer((req, res) => {
if (req.method !== 'POST' || req.url !== '/hooks/diska') return res.writeHead(404).end()
const chunks = []
req.on('data', chunk => chunks.push(chunk))
req.on('end', () => {
const rawBody = Buffer.concat(chunks) // the raw body, before parsing the JSON
if (!isValid(req.headers['x-diska-timestamp'], rawBody, req.headers['x-diska-signature'])) return res.writeHead(401).end()
res.writeHead(200).end() // answer now; process afterwards
const delivery = req.headers['x-diska-delivery']
if (seen.has(delivery)) return // a retry of a delivery you already received
seen.add(delivery)
const event = JSON.parse(rawBody)
if (event.event === 'call.completed') {
syncCall(event).catch(err => console.error('sync failed', event.call_id, err)) // the reconciliation catches what fails
}
})
}).listen(Number(process.env.PORT || 3000))
What the receiver does, in order:
- Checks the signature over the raw body, with the endpoint's secret. A request without a valid signature gets
401. See Verify the signature. - Ignores retries. A repeated delivery carries the same
X-Diska-Delivery. - Answers right away with
200, and processes afterwards: Diska waits at most 10 seconds. - Reads the call's detail at
GET /v1/calls/{call_id}, for the summary, the duration and the caller's name. The event already carries the sentiment and the extracted data. - Calls your CRM in
crm_upsert/crmUpsert. Replace theprintwith your CRM's API, and usediska_call_idas the activity's unique key so it is never created twice.
The test event (ping) also gets 200, so step 3 works.
To run the receiver, with the DISKA_API_KEY and DISKA_WEBHOOK_SECRET variables set:
pip install flask requests
flask --app receiver run --port 3000 # Python
node receiver.mjs # Node.js (port 3000)
In production, put it behind your web server or proxy, with HTTPS.
2. Register the endpoint
curl -X POST https://api.diska.ai/v1/webhook-endpoints \
-H "Authorization: Bearer $DISKA_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://your-system.com/hooks/diska", "description": "CRM", "events": ["call.completed"]}'
The response carries the secret (dskw_…) only this once. Save it in DISKA_WEBHOOK_SECRET and restart the receiver. Keep the endpoint.id too.
3. Test
curl -X POST https://api.diska.ai/v1/webhook-endpoints/<endpoint_id>/test \
-H "Authorization: Bearer $DISKA_API_KEY"
The response should carry "status": "delivered". If it says failed, the error field says why: unreachable URL, invalid certificate, or the receiver answered 401 because the secret is wrong.
Then call the agent's number and end the call normally. When post-call processing finishes, the receiver gets call.completed and the contact shows up in your CRM.
4. Reconcile once a day
Deliveries are best effort: if your server is down during the retries, the event is lost. The source of truth is GET /v1/calls. This script walks the completed calls of the last few days:
import os
import time
from datetime import datetime, timedelta, timezone
import requests
API = "https://api.diska.ai/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['DISKA_API_KEY']}"
def get(path: str, params: dict | None = None) -> dict:
while True:
response = session.get(f"{API}{path}", params=params, timeout=60)
if response.status_code == 429: # rate limit: wait as long as the API says
time.sleep(int(response.headers.get("Retry-After", "5")))
continue
response.raise_for_status()
return response.json()
def calls_since(since: datetime):
"""Completed calls since `since`, most recent first."""
params = {"cursor": "start", "limit": 200, "status": "completed"}
while True:
page = get("/calls", params)
for call in page["items"]:
if call["started_at"] and datetime.fromisoformat(call["started_at"]) < since:
return # the list is newest first: you can stop here
yield call
if not page["next_cursor"]:
return
params["cursor"] = page["next_cursor"]
since = datetime.now(timezone.utc) - timedelta(days=2) # a little more than the time between runs
for call in calls_since(since):
print("check in the CRM:", call["id"], call["started_at"]) # create the activity if it does not exist yet
Run it once a day, for example with cron, and create the activity in your CRM for any call that is not there. Because the list is newest first, the script stops at the first call older than the cut-off date.
For production
- Keep the processed
X-Diska-Deliveryvalues in a table, not in memory: the receiver can restart. - Use a persistent queue (for example Redis or SQS) instead of the in-memory one.
- Log sync failures: the reconciliation recovers them, but you want to know they happened.
- Watch the endpoint:
GET /v1/webhook-endpointsshowsfailure_countandactive. After 20 consecutive failures the endpoint is disabled; once fixed, re-enable it with{"active": true}.

