> For the complete documentation index, see [llms.txt](https://docs.concurrence.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.concurrence.com/developer-guide/reference-guides/channel-manager-voice-receiver.md).

# Connect a Channel Manager Voice Receiver

Connect a standalone voice runtime to Channel Manager using signed call events, a compatible audio WebSocket, durable event handling, and call-state reconciliation.

A standalone voice application needs an HTTPS receiver for call events and a `wss://` endpoint for audio. Events tell your application which call or participant changed. The audio connection carries speech between your runtime and the call. REST operations create and control the call's participants.

Complete [Channel Manager provisioning and authentication](https://docs.concurrence.com/developer-guide/reference-guides/integrate-channel-manager.md) first. Obtain a provisioned voice use case, its signing secret, and setup-scoped `voice:read voice:call` access. Use a controlled phone number and synthetic content for acceptance testing. Your application supplies its own agent, session storage, and audio processing.

<figure><img src="https://1651797362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YwM0LHtEGLt9S21OyC3%2Fuploads%2Fgit-blob-b557e95f750fe3b86d754915496208c04759158a%2Fchannel-manager-voice-flow.svg?alt=media" alt="Backend REST controls the Channel Manager call. Two-way WebSocket audio connects the voice runtime to the provisioned call, and two-way phone audio connects the recipient."><figcaption><p>Handle call events and audio as separate inputs to the same application session.</p></figcaption></figure>

## Configure and Verify the Event Receiver

Have the provisioning owner configure the voice use case's `webhook_url` to your HTTPS receiver and securely supply the returned `webhook_secret`. A client with `use-case:write` can set this through the [use-case update operation](https://docs.concurrence.com/developer-guide/platform-api/conversations/channel-manager.md#control-voice-calls), supplying the voice channel discriminator as well as the URL.

Supplying `webhook_url` issues a new secret even when the URL text is unchanged. The response returns that secret once. Omit the URL when changing unrelated configuration. Coordinate receiver updates with the secret handoff: this update has no old-secret overlap. The separate [messaging secret-rotation operation](https://docs.concurrence.com/developer-guide/platform-api/conversations/channel-manager.md#messaging-webhook-secrets) applies to messaging use cases.

Verify `X-AMIGO-CHANNEL-MANAGER-WEBHOOK-SIGNATURE` as a lowercase hexadecimal HMAC-SHA256 over the **exact request bytes**, with the provisioned secret as the key. Compare in constant time before trusting the JSON. Handle repeated header values and comma-combined signatures. Check `use_case_id` against your trusted configuration. The request must not select an arbitrary secret or destination.

Persist the accepted event before acknowledging it, then perform agent startup and REST calls asynchronously. In particular, acknowledge `call.received` before trying to attach audio. A read immediately after a callback can race call-state visibility, so retry the read with bounded backoff before deciding the call is missing.

## Route Voice Events

Voice events are JSON objects with `event`, `call_ref`, `use_case_id`, and `occurred_at` (Unix seconds, potentially fractional). They are separate from the messaging `inbound-turn` envelope and have no messaging `idempotency_key`. The public OpenAPI describes the REST controls. It does not include this voice event envelope.

* **`call.received`** includes `direction: "inbound"`, `phone_number`, `peer_number`, and `caller_participant_ref`. Create or resume your application session for `call_ref`, then attach one agent media participant.
* **`conference.started` and `conference.ended`** track the call lifecycle. Their `participant_ref` and `role` can be null. Reconcile `started_at` and `ended_at` through a call read.
* **`participant.joined` and `participant.left`** identify a leg through `participant_ref` and `role`. Update that participant's state without treating one participant leaving as proof the whole call ended.
* **`participant.dial_completed`** carries `participant_ref`, `role`, and `dial_status`: `answered`, `no_answer`, `busy`, or `failed`. An answered dial is not proof a human answered.
* **`participant.amd_result`** carries `participant_ref`, `role`, and `answered_by` for optional answering-machine classification. Treat it separately from dial completion.

Participant roles are `caller`, `agent`, `operator`, `transfer_target`, and `callee`. When requested for a dial participant, answering-machine classification can report `human`, `fax`, `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, or `machine_end_other`. These are classifications, not identity verification or a guarantee of detection accuracy.

An inbound event has this shape, with synthetic values:

```json
{
  "event": "call.received",
  "call_ref": "11111111-1111-4111-8111-111111111111",
  "use_case_id": "22222222-2222-4222-8222-222222222222",
  "direction": "inbound",
  "phone_number": "+12025550100",
  "peer_number": "+12025550101",
  "caller_participant_ref": "33333333-3333-4333-8333-333333333333",
  "occurred_at": 1793031032.125
}
```

Use durable application state to make each lifecycle action idempotent. Key the session by the trusted use case and `call_ref`, and participant actions by their `participant_ref`. Do not create another media participant just because an event arrives again. Preserve terminal state if an older event arrives later, and use call reads to reconcile missing or ambiguous events. Callback arrival order and delivery are not guarantees.

## Run a Local Event Receiver

Save the following as `voice_receiver.py`. It verifies signatures and stores lifecycle events in a local SQLite inbox before returning `202`. It does not place calls or start an agent. Use Python 3.11 or later and synthetic events. Load `CHANNEL_USE_CASE_ID` and `CHANNEL_WEBHOOK_SECRET` from your test configuration. The secret is separate from the API bearer token.

```python
import hashlib
import hmac
import json
import os
import re
import sqlite3
from contextlib import closing
from http.server import BaseHTTPRequestHandler, HTTPServer
from uuid import UUID

USE_CASE = str(UUID(os.environ["CHANNEL_USE_CASE_ID"]))
SECRET = os.environ["CHANNEL_WEBHOOK_SECRET"].encode()
if not SECRET:
    raise ValueError("A webhook secret is required")
DATABASE = os.environ.get("CHANNEL_EVENT_DB", "voice-events.sqlite3")
EVENTS = {
    "call.received", "conference.started", "conference.ended",
    "participant.joined", "participant.left",
    "participant.dial_completed", "participant.amd_result",
}


class Receiver(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        pass  # Keep request data out of this example's logs.

    def reply(self, status):
        self.send_response(status)
        self.send_header("Content-Length", "0")
        self.end_headers()

    def do_POST(self):
        if self.path != "/voice-events":
            return self.reply(404)
        try:
            length = int(self.headers.get("Content-Length", "0"))
        except ValueError:
            return self.reply(400)
        if not 0 < length <= 65536:  # Example receiver's own body limit.
            return self.reply(413)
        raw = self.rfile.read(length)
        expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
        signatures = [
            part.strip()
            for value in self.headers.get_all(
                "X-AMIGO-CHANNEL-MANAGER-WEBHOOK-SIGNATURE", []
            )
            for part in value.split(",")
        ]
        if not any(
            re.fullmatch(r"[0-9a-f]{64}", value)
            and hmac.compare_digest(expected, value)
            for value in signatures
        ):
            return self.reply(401)
        try:
            event = json.loads(raw)
            if str(UUID(event["use_case_id"])) != USE_CASE:
                return self.reply(403)
            call = str(UUID(event["call_ref"]))
            name = event["event"]
            if name not in EVENTS:
                return self.reply(204)
            participant = event.get("participant_ref") or event.get("caller_participant_ref")
            participant = str(UUID(participant)) if participant else ""
        except (ValueError, TypeError, KeyError, AttributeError):
            return self.reply(400)
        try:
            with closing(sqlite3.connect(DATABASE)) as db, db:
                db.execute(
                    "INSERT OR IGNORE INTO events VALUES (?, ?, ?, ?, ?)",
                    (USE_CASE, call, name, participant, raw),
                )
        except sqlite3.Error:
            return self.reply(503)
        self.reply(202)


if __name__ == "__main__":
    with closing(sqlite3.connect(DATABASE)) as db, db:
        db.execute(
            "CREATE TABLE IF NOT EXISTS events ("
            "use_case TEXT, call_ref TEXT, event TEXT, participant TEXT, body BLOB, "
            "PRIMARY KEY (use_case, call_ref, event, participant))"
        )
    HTTPServer(("127.0.0.1", 8085), Receiver).serve_forever()
```

Run `python3 voice_receiver.py`. Save the synthetic JSON above as `voice-event.json`, replacing its use-case ID with your configured test use case. In another shell with the same test secret, run:

```python
import hashlib
import hmac
import http.client
import os
from pathlib import Path

raw = Path("voice-event.json").read_bytes()
signature = hmac.new(
    os.environ["CHANNEL_WEBHOOK_SECRET"].encode(), raw, hashlib.sha256
).hexdigest()

for body, expected_status in [(raw, 202), (raw, 202), (raw + b" ", 401)]:
    connection = http.client.HTTPConnection("127.0.0.1", 8085, timeout=5)
    connection.request("POST", "/voice-events", body, {
        "Content-Type": "application/json",
        "X-AMIGO-CHANNEL-MANAGER-WEBHOOK-SIGNATURE": signature,
    })
    response = connection.getresponse()
    assert response.status == expected_status, response.status
    response.read()
    connection.close()
print("Valid event and replay accepted; modified bytes rejected.")
```

The inbox contains one row for that lifecycle event after both accepted requests. Check it with `SELECT COUNT(*) FROM events` in your SQLite client. Also test a validly signed event for another use case and verify `403`.

In production, use your application's HTTPS server, approved durable store, request limits, secret management, and asynchronous worker. The worker consumes the inbox and records completed actions. Persisting a receipt alone does not make an external action exactly once. Keep lifecycle state through restarts and reconcile the call before retrying a participant creation. Apply your retention and access policy to callback content.

## Implement the Audio Connection

Adding a `media` participant connects the provisioned audio stream to your `wss://` endpoint. The connection uses JSON events with base64-encoded G.711 mu-law audio at 8 kHz. Your agent adapter must decode and encode that format. A generic model WebSocket or a binary PCM socket is not a compatible endpoint.

1. Accept the connection and process `connected`, then `start`. Retain `streamSid` and read `start.customParameters`.
2. Put your call reference and application connection metadata in the participant's `stream_context`. These string values arrive as custom parameters. Do not rely on URL query parameters. Channel Manager forwards the values you supply rather than inventing your application's session identity.
3. Authenticate the stream before processing audio. For example, your application can issue a short-lived, single-use token bound to the call, include it in `stream_context`, and validate it against its own pending connection record. This is your application's access control. A caller-supplied call reference alone is not authentication.
4. Decode incoming `media.payload` values and send generated audio as `{"event":"media","streamSid":"<received stream ID>","media":{"payload":"<base64 mu-law audio>"}}`. Send raw encoded audio without a WAV header.
5. To interrupt buffered speech, send `{"event":"clear","streamSid":"<received stream ID>"}`. A named `mark` can track playback progress. Account for marks associated with cleared audio rather than treating every mark as proof of audibility.
6. On `stop` or disconnect, release the local audio session and reconcile the call through REST. Closing a socket is not evidence that every participant has left.

The [one-way participant audio fork](https://docs.concurrence.com/developer-guide/platform-api/conversations/channel-manager.md#fork-incoming-audio) is a separate listening connection. It does not replace the agent's two-way media participant. Give each fork its own context and connection authorization.

## Accept and Clean Up

Follow the [controlled voice walkthrough](https://docs.concurrence.com/developer-guide/reference-guides/integrate-channel-manager.md#connect-voice) to create a call, attach your media participant, and dial a test recipient. Verify event signatures, session correlation, two-way speech, interruptions, reconnect handling, no-answer behavior, and explicit teardown. For inbound calls, verify that `call.received` triggers one asynchronous attachment and that duplicate events do not start another agent.

End the test call and read `ended_at`. Stop the local receiver with Ctrl-C, revoke temporary credentials, and remove the synthetic inbox according to your test-data policy. A local receiver test validates receipt handling, and the controlled call validates the provisioned audio path.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.concurrence.com/developer-guide/reference-guides/channel-manager-voice-receiver.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
