> 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/integrate-channel-manager.md).

# Integrate Channel Manager Through the API

Use Channel Manager from your own backend. Start from an approved sender or provision one, then send and receive SMS, run voice calls, receive webhooks, and measure an SMS campaign.

Use Channel Manager to connect your own agent or backend to communication channels for patient outreach, scheduling, intake, and follow up. Your application chooses the recipients and content and records workflow results. Channel Manager provides provisioned senders, channel APIs, and the delivery evidence each channel makes available. No Concurrence workspace, agent, service, or Developer Console is required.

## Choose Your Starting Point

* **Your sender is approved and a number is assigned.** Follow [Launch an SMS Outreach Campaign](https://docs.concurrence.com/developer-guide/reference-guides/launch-sms-outreach-campaign.md). It covers the first controlled message, delivery, replies, opt-out, and go-live acceptance without the provisioning steps. On this page you need only steps 1, 6, 8, 9, and 10.
* **You are setting up a sender.** Work through this page in order. Steps 2 to 5 are one-time provisioning, and each one waits on a review.

## What You Can Do

1. [Get access](#id-1.-verify-scoped-access) with a scoped token.
2. [Create a setup](#2.-create-a-setup), the access boundary for your channel resources.
3. [Get a business profile and A2P registration approved](#3.-get-a-business-profile-and-a2p-registration-approved).
4. [Get a phone number](#4.-get-a-phone-number).
5. [Create a use case](#5.-create-a-use-case) and assign the number.
6. [Send and receive SMS](#id-4.-send-one-controlled-message-and-read-the-result), plus email, iMessage, and WhatsApp.
7. [Run voice calls](#connect-voice): forwarding, hold music, and participants.
8. [Receive webhooks](#id-3.-connect-your-inbound-receiver) for inbound messages and call events.
9. [Measure an SMS outreach campaign](#measure-an-sms-outreach-campaign).

Start with one channel and a recipient your team controls. The [reference](https://docs.concurrence.com/developer-guide/platform-api/conversations/channel-manager.md) holds the operation contracts. Companion guides:

* [Reconcile a Channel Manager Attempt](https://docs.concurrence.com/developer-guide/reference-guides/reconcile-channel-manager.md) when a response is lost.
* [Send Email With a Channel Manager Template](https://docs.concurrence.com/developer-guide/reference-guides/channel-manager-email-templates.md) for reusable email content.
* [Connect a Channel Manager Voice Receiver](https://docs.concurrence.com/developer-guide/reference-guides/channel-manager-voice-receiver.md) for signed call events and the audio protocol.

Your application owns the workflow. Save your workflow ID next to every returned message or call ID. A delivered message is not a completed request, and a call and an email reply do not become one conversation unless your application links them. Check permission again before switching channels.

## Before You Start

Access is a client ID and secret that you exchange for a one-hour token. Each client carries a list of granted scopes and a list of setups it can reach. Your Concurrence implementation contact issues the client through a secure channel. Your application cannot create clients or change a grant.

**To send and receive with an approved sender**, you need:

* Your assigned API host.
* The setup ID and use case ID.
* The sender approval status, which is a verified campaign for a US long code or an approved toll-free verification.
* A runtime client ID and secret with its granted scopes.
* The webhook signing secret for the use case.
* An HTTPS receiver URL that your team owns.
* A test recipient your team controls, with approved content that holds no personal data.
* Your support contacts.

Keep the client secret, access tokens, and the webhook signing secret in your secret store and out of tickets, chat, and source control. Treat message content and recipient details as sensitive. Setup, use case, and message IDs are not credentials, and you can quote the relevant ones in an approved support channel. Your support contacts are not secrets.

**To provision a sender**, you also need a separate client that carries the setup-create grant, your legal business details, and an authorized representative. Submitting a registration is not an approval. Each step reports a status that you read before moving on.

## 1. Get Access <a href="#id-1.-verify-scoped-access" id="id-1.-verify-scoped-access"></a>

Use the host assigned to your deployment, currently `https://channels.api-us.concurrence.com`. Keep it in configuration. Request only the scopes for the tasks you run:

| Task                                   | Scopes                                                                  |
| -------------------------------------- | ----------------------------------------------------------------------- |
| Create a setup                         | `twilio-setup:create`                                                   |
| Read or fix a setup                    | `twilio-setup:read twilio-setup:write`                                  |
| Business profile and A2P registration  | `compliance:sms:read compliance:sms:write`                              |
| Numbers                                | `twilio-phone-number:read twilio-phone-number:write`                    |
| Use cases, forwarding list, hold music | `use-case:read use-case:write`                                          |
| SMS                                    | `sms:read sms:send`                                                     |
| SMS opt-in and opt-out                 | `sms:consent:read sms:consent:write`                                    |
| Email, iMessage, WhatsApp              | `email:read email:send`, `imessage:read imessage:send`, `whatsapp:send` |
| Voice runtime                          | `voice:read voice:call`                                                 |

Keep provisioning and runtime on separate clients. Load `CHANNEL_CLIENT_ID` and `CHANNEL_CLIENT_SECRET` from your secret store. The examples use Bash, cURL, and `jq`. The request below keeps the secret and the token out of the terminal output and prints only the grant details.

```bash
export CHANNEL_API_BASE=https://channels.api-us.concurrence.com
CHANNEL_SCOPES='use-case:read sms:read sms:send'

token_json=$(curl --fail-with-body --silent --show-error --config - \
  --request POST "$CHANNEL_API_BASE/v1/oauth/token" \
  --data-urlencode 'grant_type=client_credentials' \
  --data-urlencode "scope=$CHANNEL_SCOPES" <<EOF
user = "$CHANNEL_CLIENT_ID:$CHANNEL_CLIENT_SECRET"
EOF
)
CHANNEL_ACCESS_TOKEN=$(jq -er '.access_token' <<<"$token_json")
export CHANNEL_ACCESS_TOKEN
jq '{token_type, expires_in, scope}' <<<"$token_json"
unset token_json

# Helper used by the examples below.
cm() { curl --fail-with-body --silent --show-error \
  --config <(printf 'header = "Authorization: Bearer %s"\n' "$CHANNEL_ACCESS_TOKEN") "$@"; }
```

Expected output: `{"token_type": "bearer", "expires_in": 3600, "scope": "..."}`. Compare `scope` with what you requested. Ungranted scopes are omitted. Tokens last one hour and there is no refresh token, so repeat the request when a call returns `401`.

On the token request, a `401` means the client credentials are missing, a `403` means they are invalid, and a `422` means a malformed request. Send both `grant_type=client_credentials` and `scope`. A scope missing from the response needs a corrected grant from the credential owner.

## 2. Create a Setup <a href="#id-2.-create-a-setup" id="id-2.-create-a-setup"></a>

A setup holds your business profile, numbers, and use cases. A customer can have several. The request below submits the business for review.

```bash
cm --request POST "$CHANNEL_API_BASE/v1/twilio-setup" \
  --header 'Content-Type: application/json' --data @- <<'JSON'
{
  "friendly_name": "Example outreach",
  "business_name": "Example Health Co",
  "business_type": "Corporation",
  "business_industry": "HEALTHCARE",
  "business_registration_identifier": "EIN",
  "business_registration_number": "000000000",
  "business_regions_of_operation": "USA_AND_CANADA",
  "website_url": "https://www.example.com",
  "business_address": {"street": "1 Main St", "city": "Springfield", "region": "IL", "postal_code": "62701", "iso_country": "US"},
  "authorized_representative": {"first_name": "Alex", "last_name": "Rivera", "email": "alex@example.com", "phone_number": "+15555550100", "business_title": "Chief Technology Officer", "job_position": "CEO"}
}
JSON
```

Expected `201`: `{"id": "<setup_id>", "friendly_name": "...", "customer_profile": {"status": "pending-review", "last_failure": null}, ...}`. Save `id` as `CHANNEL_SETUP_ID`. Read `GET /v1/twilio-setup/$CHANNEL_SETUP_ID` until `customer_profile.status` is `twilio-approved` or `provisionally-approved`.

Next: if the status is `twilio-rejected`, read `last_failure`, then correct the business details with `PUT /v1/twilio-setup/$CHANNEL_SETUP_ID` using the same body without `friendly_name`. It resubmits for review.

| Outcome         | Meaning and next step                                                                                   |
| --------------- | ------------------------------------------------------------------------------------------------------- |
| `403`           | Token lacks `twilio-setup:create`, or the setup.                                                        |
| `409` on update | The profile is not rejected, so it cannot be edited.                                                    |
| `422`           | The pre-submission check found the business details noncompliant. Read `last_failure` and correct them. |

## 3. Get a Business Profile and A2P Registration Approved <a href="#id-3.-get-a-business-profile-and-a2p-registration-approved" id="id-3.-get-a-business-profile-and-a2p-registration-approved"></a>

US long-code SMS needs an approved profile, a messaging profile, a brand registration, and later a campaign (step 5). US and Canada toll-free numbers use a toll-free verification instead (step 4). Complete each request after the previous one reports an approved or verified state.

1. Submit the messaging profile:

   ```bash
   cm --request POST "$CHANNEL_API_BASE/v1/twilio-setup/$CHANNEL_SETUP_ID/bundle/a2p-messaging-profile" \
     --header 'Content-Type: application/json' \
     --data '{"company_type": "private", "brand_contact_email": "brand@example.com"}'
   ```

   `company_type` is `private`, `public`, `non-profit`, or `government`. A `public` company also sends `stock_exchange` and `stock_ticker`. The response is a bundle with `status` and `last_failure`. Read it again with `GET .../bundle`.
2. Once the bundle is approved, submit the brand registration. Non-profit and government brands must use `standard`:

   ```bash
   cm --request POST "$CHANNEL_API_BASE/v1/twilio-setup/$CHANNEL_SETUP_ID/bundle/a2p-brand-registration" \
     --header 'Content-Type: application/json' --data '{"brand_type": "standard"}'
   ```

   Expected `200`: `{"brand_type": "standard", "primary_vetting_status": "pending", "secondary_vetting_status": "pending", "resubmit_count": 0, "allowed_campaign_usecases": null, ...}`.
3. Poll `GET .../bundle/a2p-brand-registration` until `primary_vetting_status` is `verified`. The response then lists `allowed_campaign_usecases`, the codes you can use in step 5. If it is `unverified`, read `primary_vetting_errors`, fix the cause, and submit again.

| Outcome             | Meaning and next step                                                                                                                           |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `409`               | The profile is not approved, the messaging profile is missing, or the bundle is in review or approved and locked. Wait or fix the earlier step. |
| `422`               | The brand tier does not fit the company type, the brand type changed on resubmit, or the limit of 3 resubmissions is reached.                   |
| `404` on brand read | No brand registration exists yet.                                                                                                               |

Other countries or number types can need a regulatory bundle: `GET .../regulation?iso_country=...&number_type=...` returns the requirements (`404` means none), and `GET .../bundle` lists every bundle and status.

## 4. Get a Phone Number <a href="#id-4.-get-a-phone-number" id="id-4.-get-a-phone-number"></a>

Search, then buy. Both need an approved profile.

```bash
cm --get "$CHANNEL_API_BASE/v1/twilio-setup/$CHANNEL_SETUP_ID/phone-number/available" \
  --data-urlencode 'country=US' --data-urlencode 'number_type=local' \
  --data-urlencode 'area_code=212' --data-urlencode 'capabilities=sms' --data-urlencode 'limit=5'

cm --request POST "$CHANNEL_API_BASE/v1/twilio-setup/$CHANNEL_SETUP_ID/phone-number" \
  --header 'Content-Type: application/json' \
  --data '{"phone_number": "+12125550123", "country": "US", "number_type": "local"}'
```

The search returns `{"items": [{"phone_number": "+1212...", "locality": "...", ...}]}`. `limit` is at most 20 and `area_code` applies only to `local`. The purchase returns `201` with `id`, `phone_number`, `capabilities`, and an empty `use_case_ids`. Save `id` as `CHANNEL_PHONE_NUMBER_ID`. List owned numbers with `GET .../phone-number`. Add `use_case_id=unassigned` to show free ones.

For a US or Canada toll-free number, submit `POST .../phone-number/$CHANNEL_PHONE_NUMBER_ID/tollfree-verification` as multipart form data with the business, use-case, sample message, opt-in method and confirmation text, volume, policy URLs, and JPEG or PNG opt-in proof images of at most 5 MiB each. Read it with `GET` on the same path until `status` is `twilio-approved`. A rejected one can be resubmitted.

| Outcome       | Meaning and next step                                                                            |
| ------------- | ------------------------------------------------------------------------------------------------ |
| `409`         | The number is already owned, or the profile or a required bundle is not approved.                |
| `422`         | The country or type does not match the setup, or the number's address requirements do not match. |
| `413` / `415` | A toll-free proof image is over 5 MiB or not JPEG or PNG.                                        |

## 5. Create a Use Case <a href="#id-5.-create-a-use-case" id="id-5.-create-a-use-case"></a>

A use case is the purpose, channel, and routing for one program. Create one per channel. `name` and `entity_name` use letters, hyphens, and spaces, 31 characters at most, and are unique together. `environment` and `region` cannot be changed later.

```bash
cm --request POST "$CHANNEL_API_BASE/v1/use-case" \
  --header 'Content-Type: application/json' --data @- <<JSON
{
  "channel": "sms", "twilio_setup_id": "$CHANNEL_SETUP_ID",
  "entity_name": "Example Health", "name": "member outreach",
  "environment": "production", "region": "us-east-1",
  "webhook_url": "https://app.example.com/channel/sms"
}
JSON
```

Expected `201`: the use case with `id` and `webhook_secret`. The secret is returned once. Store it now, because it verifies [inbound webhooks](#id-3.-connect-your-inbound-receiver). Save `id` as `CHANNEL_USE_CASE_ID`.

Other channels use the same request with these fields:

| Channel          | Extra required fields                                                                                                         |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `outbound_voice` | `twilio_setup_id`, `allowed_forwarding_numbers`, optional `webhook_url`                                                       |
| `inbound_voice`  | `twilio_setup_id`, `inbound_voice_url`, `allowed_forwarding_numbers`, optional `fallback_forwarding_number` and `webhook_url` |
| `email`          | `ses_setup_id`, `sender_email_address`, `sender_email_alias`, `email_type`, `unsubscribable`, `inbound_mode`, `webhook_url`   |
| `imessage`       | `sendblue_setup_id`, `webhook_url`                                                                                            |
| `whatsapp`       | `whatsapp_setup_id`, `phone_number_id`, `phone_number_pin`, `webhook_url`                                                     |

For `inbound_voice`, `fallback_forwarding_number` is an E.164 number that calls forward to when `inbound_voice_url` errors or times out. Update it with `PUT /v1/use-case/{id}`, where `null` removes it. `allowed_forwarding_numbers` holds at most 150 E.164 numbers. An empty list denies all forwarding.

**Create the SMS campaign.** For a US long-code SMS use case, submit the campaign. Use a code from the brand's `allowed_campaign_usecases`:

```bash
cm --request POST "$CHANNEL_API_BASE/v1/use-case/$CHANNEL_USE_CASE_ID/a2p-campaign" \
  --header 'Content-Type: application/json' --data @- <<'JSON'
{
  "us_app_to_person_usecase": "CUSTOMER_CARE",
  "description": "Appointment reminders and follow-up questions for enrolled members.",
  "message_samples": ["Example Health: your visit is tomorrow at 9am. Reply C to confirm.", "Example Health: how did your visit go?"],
  "message_flow": "Members opt in on the enrollment form and receive a confirmation text.",
  "has_embedded_links": false, "has_embedded_phone": false, "age_gated": false, "direct_lending": false,
  "opt_in_message": "Example Health: you are subscribed to visit texts. Reply STOP to end, HELP for help.",
  "opt_in_keywords": ["START"],
  "opt_out_message": "Example Health: you are unsubscribed and will get no more texts.",
  "opt_out_keywords": ["STOP", "STOPALL", "UNSUBSCRIBE", "CANCEL", "END", "QUIT"],
  "help_message": "Example Health: for help call 555-0100 or reply STOP to unsubscribe.",
  "help_keywords": ["HELP"],
  "privacy_policy_url": "https://www.example.com/privacy",
  "terms_and_conditions_url": "https://www.example.com/terms"
}
JSON
```

Expected `201` with `status: IN_PROGRESS`. Read `GET .../a2p-campaign` until `VERIFIED`. A `FAILED` campaign lists `errors`, and `PUT` updates it.

**Assign the number.** Once the campaign is `VERIFIED` (or the toll-free verification is approved), assign:

```bash
cm --request PUT "$CHANNEL_API_BASE/v1/twilio-setup/$CHANNEL_SETUP_ID/phone-number/$CHANNEL_PHONE_NUMBER_ID/use-case/$CHANNEL_USE_CASE_ID"
```

Expected `204`. Read the use case with `GET /v1/use-case/$CHANNEL_USE_CASE_ID` and confirm the number is in `phone_numbers` (the list response leaves it empty), and for voice also `allowed_forwarding_numbers` and `hold_music_enabled`.

| Outcome                  | Meaning and next step                                                                         |
| ------------------------ | --------------------------------------------------------------------------------------------- |
| `409` on create          | The profile is not approved, or the name or sender is already used.                           |
| `409` on campaign        | The messaging profile or brand is not verified, or a campaign already exists.                 |
| `422` on campaign        | The use-case code is not allowed for the brand, or the STOP and HELP keywords are incomplete. |
| `409` on assign          | The number already serves another use case on this channel, or a bundle is missing.           |
| `422` on forwarding list | More than 150 numbers, or a number is not E.164.                                              |

## 6. Send and Receive SMS <a href="#id-4.-send-one-controlled-message-and-read-the-result" id="id-4.-send-one-controlled-message-and-read-the-result"></a>

Check the recipient, permission, and content immediately before sending. Your team holds the consent evidence and the approved content. The send has no client-supplied idempotency key. After a timeout, [reconcile before retrying](https://docs.concurrence.com/developer-guide/reference-guides/reconcile-channel-manager.md). For the shortest path with an approved sender, use [Launch an SMS Outreach Campaign](https://docs.concurrence.com/developer-guide/reference-guides/launch-sms-outreach-campaign.md).

1. On a supported US long-code or US and Canada toll-free route, send the registered opt-in message first. This needs `sms:consent:write` and your own consent evidence:

   ```bash
   cm --request POST "$CHANNEL_API_BASE/v1/sms/opt-in" \
     --header 'Content-Type: application/json' \
     --data "{\"use_case_id\": \"$CHANNEL_USE_CASE_ID\", \"to_phone_number\": \"$CHANNEL_TEST_RECIPIENT\"}"
   ```

   Expected `201` with no message ID. When an opt-in-message record already exists for this recipient on the use case, a repeated call returns success and sends nothing. A `409` means the recipient has an active setup-wide opt-out, which this call cannot reverse.
2. Send a message. Add `--form 'media_attachments=@/path/to/test-image.png'` for MMS:

   ```bash
   cm --request POST "$CHANNEL_API_BASE/v1/sms/" \
     --form-string "use_case_id=$CHANNEL_USE_CASE_ID" \
     --form-string "to_phone_number=$CHANNEL_TEST_RECIPIENT" \
     --form-string "message=$CHANNEL_TEST_MESSAGE"
   ```

   Expected `201`: a message with `id` and `status`. Save the `id`. Success means the message was accepted. It does not show delivery or sender approval.
3. Read it for delivery: `cm "$CHANNEL_API_BASE/v1/sms/$CHANNEL_MESSAGE_ID"`. `status` is `pending`, `sent`, `delivered`, `failed`, or `undelivered`. `errored_at` and `error_message` report failures. Delivery status is not posted to your webhook, so read it here.
4. Have the recipient reply. The reply arrives at your [webhook receiver](#id-3.-connect-your-inbound-receiver) and appears in `GET /v1/sms?setup_id=...&use_case_id=...&direction=inbound`. A reply is not a delivery receipt.

| Outcome         | Meaning and next step                                                                                                                                                                                                                                                                    |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `403`           | The token lacks `sms:send`, or the setup.                                                                                                                                                                                                                                                |
| `404`           | The SMS use case was not found.                                                                                                                                                                                                                                                          |
| `409` on opt-in | A setup-wide opt-out is active.                                                                                                                                                                                                                                                          |
| `422` on send   | The recipient opted out, the opt-in message was not sent, no number or verified registration backs the use case, the content does not match the registered use case, or the number is invalid. The response `detail` names the cause.                                                    |
| Opt-out read    | `GET /v1/sms/opt-out?setup_id=...` lists active opt-outs. A client with `sms:consent:write` can clear one with `POST /v1/sms/remove-setup-opt-out` and a recorded `reason`. A `409` there means a toll-free line still has an opt-out, so the recipient texts `START` or `UNSTOP` first. |

See [SMS recipient opt-in and opt-out](https://docs.concurrence.com/developer-guide/platform-api/conversations/channel-manager.md#sms-recipient-opt-in-and-opt-out) for the contract.

### Other Messaging Channels

Each send is one `POST` with `use_case_id` and the `cm` helper. Save the returned ID.

| Channel  | Request and rules                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Email    | `POST /v1/email/` with `to_address`, `mode=raw_html`, `subject`, `body_html`. An unsubscribable use case needs `{{ unsubscribe_link }}` and `{{ unsubscribe_from_all_link }}` in the HTML. Read with `GET /v1/email/{id}` and `GET /v1/email/event?setup_id=...&email_id=...`. Sending needs verified DKIM, MAIL FROM, and DMARC records (`409` otherwise). To reply, pass `reply_to_inbound_email_id`. [Email contract](https://docs.concurrence.com/developer-guide/platform-api/conversations/channel-manager.md#send-and-reconcile-email) |
| iMessage | `POST /v1/imessage/` with `to_number` and `content`. Before the contact replies: 300 characters at most, no link, phone number, email address, or media, six messages at most (`422` otherwise). Read `service` and `was_downgraded` with `GET /v1/imessage/{id}`. Delivery can fall back to SMS. [iMessage contract](https://docs.concurrence.com/developer-guide/platform-api/conversations/channel-manager.md#send-and-reconcile-imessage)                                                                                                 |
| WhatsApp | `POST /v1/whatsapp/` form-encoded with `to_bsuid` (the inbound `caller_ref`), `message_type=text`, and `message`, within 23 hours of the recipient's message. Free-form replies only, and no read operation. [WhatsApp contract](https://docs.concurrence.com/developer-guide/platform-api/conversations/channel-manager.md#reply-through-whatsapp)                                                                                                                                                                                           |

## 7. Run Voice Calls <a href="#connect-voice" id="connect-voice"></a>

Voice needs an event receiver and a compatible audio endpoint before the first call. Implement the [signed voice events and media protocol](https://docs.concurrence.com/developer-guide/reference-guides/channel-manager-voice-receiver.md) first. REST controls the call, and audio uses a separate WebSocket to your runtime.

<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>A successful control request does not prove that audio reached the recipient.</p></figcaption></figure>

Use a token with `voice:read voice:call` and an `outbound_voice` use case with an assigned number.

1. Create the call. This reserves a `call_ref` and a sender number but dials nobody. Add `idempotency_key` to make a retry return the same call:

   ```bash
   cm --request POST "$CHANNEL_API_BASE/v1/voice-call/" \
     --header 'Content-Type: application/json' \
     --data "{\"use_case_id\": \"$CHANNEL_USE_CASE_ID\", \"idempotency_key\": \"$WORKFLOW_ID\"}"
   ```

   Expected: `{"call_ref": "<uuid>", "phone_number": "+1..."}`. `404` means the use case is not `outbound_voice` or has no assigned numbers.
2. Attach your runtime's audio:

   ```bash
   cm --request POST "$CHANNEL_API_BASE/v1/voice-call/$CHANNEL_CALL_REF/participant" \
     --header 'Content-Type: application/json' \
     --data "{\"kind\": \"media\", \"stream_url\": \"$CHANNEL_VOICE_STREAM_URL\", \"stream_context\": {\"call_ref\": \"$CHANNEL_CALL_REF\"}}"
   ```
3. **This request dials the number.** Add the callee:

   ```bash
   cm --request POST "$CHANNEL_API_BASE/v1/voice-call/$CHANNEL_CALL_REF/participant" \
     --header 'Content-Type: application/json' \
     --data "{\"kind\": \"dial\", \"role\": \"callee\", \"to_phone_number\": \"$CHANNEL_TEST_RECIPIENT\", \"detect_answering_machine\": false}"
   ```

   Each participant request returns `participant_ref` and `role`. Save the `participant_ref`. It returns before the person answers.
4. Read the call with `GET /v1/voice-call/$CHANNEL_CALL_REF`. Check the participant's `dial_status`, `answered_by`, `joined_at`, and `left_at`, and the call's `ended_at`.
5. End the call with `DELETE /v1/voice-call/$CHANNEL_CALL_REF`, then read it again for `ended_at`.

### Forward and Transfer

Operator and `transfer_target` participants, and `dial` redirects, can only reach numbers in the use case's `allowed_forwarding_numbers` (at most 150). Replace the whole list with the use case update, which needs `use-case:write`:

```bash
cm --request PUT "$CHANNEL_API_BASE/v1/use-case/$CHANNEL_USE_CASE_ID" \
  --header 'Content-Type: application/json' \
  --data '{"channel": "outbound_voice", "allowed_forwarding_numbers": ["+15555550111", "+15555550112"]}'
```

Use `"channel": "inbound_voice"` for an inbound use case, which also accepts `fallback_forwarding_number`. Omit `allowed_forwarding_numbers` to leave the list unchanged. Move a connected participant with `POST .../participant/{participant_ref}/redirect` and `{"kind": "dial", "to": "+15555550111"}`, or end it with `{"kind": "farewell", "message": "Goodbye."}` (1 to 1000 characters).

### Hold and Resume

```bash
cm --request PUT "$CHANNEL_API_BASE/v1/voice-call/$CHANNEL_CALL_REF/participant/$CHANNEL_PARTICIPANT_REF" \
  --header 'Content-Type: application/json' --data '{"hold": true}'
```

Send `{"hold": false}` to resume. `muted` and `ends_call_on_exit` use the same request, and omitted fields keep their values. A participant that has not joined or has left returns `409`.

### Configure Hold Music <a href="#configure-and-test-hold-music" id="configure-and-test-hold-music"></a>

A use case plays its uploaded track when configured and default hold music otherwise. Upload an MP3 (`audio/mpeg`) or WAV (`audio/wav`, `audio/wave`, `audio/x-wav`) of 10 KiB to 5 MiB with `use-case:write`. An upload replaces the existing track:

```bash
cm --request PUT "$CHANNEL_API_BASE/v1/use-case/$CHANNEL_USE_CASE_ID/hold-music" \
  --form "hold_music=@${CHANNEL_HOLD_MUSIC_FILE};type=audio/mpeg"
```

Read the use case and confirm `hold_music_enabled` is `true`, then hold a controlled participant and confirm the track is audible. `DELETE` on the same path clears it. Neither operation holds or resumes anyone.

| Outcome                          | Meaning and next step                                                                       |
| -------------------------------- | ------------------------------------------------------------------------------------------- |
| `409` on participant             | The call ended, or the participant is not in the conference. Read the call.                 |
| `422` on participant or redirect | The destination is not in `allowed_forwarding_numbers`, or the carrier rejected the number. |
| `404` on call create             | The use case is not outbound voice or has no number.                                        |
| Timeout                          | Read the call before repeating. Do not assume the person is held, joined, or dialed.        |

## 8. Receive Webhooks <a href="#id-3.-connect-your-inbound-receiver" id="id-3.-connect-your-inbound-receiver"></a>

Messaging use cases post inbound events to their `webhook_url`. Voice use cases with a `webhook_url` post call events under a separate contract, described in the [voice receiver guide](https://docs.concurrence.com/developer-guide/reference-guides/channel-manager-voice-receiver.md). Both sign requests with the secret returned when the URL was set.

<figure><img src="https://1651797362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YwM0LHtEGLt9S21OyC3%2Fuploads%2Fgit-blob-5dcab75af91bb8b0f261035ec4bcfd7fda04857a%2Fchannel-manager-message-flow.svg?alt=media" alt="An application sends through a provisioned channel, retains the message ID, verifies and stores signed reply callbacks before acknowledging them, and reads supported delivery state separately."><figcaption><p>Message acceptance, a reply, and confirmed delivery are different evidence.</p></figcaption></figure>

In your receiver:

1. Read the raw bytes. Verify `X-AMIGO-CHANNEL-MANAGER-WEBHOOK-SIGNATURE` as a lowercase hexadecimal HMAC-SHA256 with the use case's secret as the key, in constant time, before parsing the JSON.
2. Check `use_case_id` against your configuration and select the secret from it, never from the request. During rotation, handle repeated or comma-combined signature values.
3. Deduplicate on `(use_case_id, idempotency_key)`. Store the event durably before returning success, then process it asynchronously.
4. Match the event to your workflow with the table below.

The [schema](https://channels.api-us.concurrence.com/openapi.json) describes the `inbound-turn` envelope. Its `authenticated` flag concerns channel-origin verification, not the person's identity or consent.

| Channel          | How to correlate the reply                                                                                                         |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| SMS and iMessage | `parent_outbound_ref` is empty. Use the use case, `caller_ref`, and your own routing rules.                                        |
| Email            | Read `/v1/email/{email_id}` using `inbound_message_ref`. `in_reply_to_email_id` matches the CM email `id` you saved, or is `null`. |
| WhatsApp         | `caller_ref` is the recipient's business-scoped address. A recognized reply can carry your CM `message_id` as its parent.          |

Opt-out and help keywords that Channel Manager handles for a registered SMS sender are not posted. A US or Canada toll-free sender handles the exact words `STOP`, `START`, and `UNSTOP`, and other text, including `HELP`, is posted as a normal message. Outbound delivery status is not posted either, so read it with the message `GET`. If your receiver does not return a `2xx` response, the event can be sent again.

An absent parent is normal. Do not assume a reply answers the latest message when several workflows could match. Content URLs are absolute and issued per use case. Fetch them as given with the agreed authentication, and never send a bearer token to an arbitrary URL.

**Rotate or change the secret.** For a messaging use case, `POST /v1/use-case/{id}/webhook-secret` returns a new `webhook_secret` once and `old_secret_lasts_until`. Until then requests carry both signatures. Changing `webhook_url` with `PUT /v1/use-case/{id}` returns a new secret once, without that overlap. Rotation returns `400` for a voice use case.

Return `4xx` for a bad signature and store nothing. Acknowledge a replayed `idempotency_key` without a second action. If the secret is lost, rotate it (messaging) or set the URL again (voice), then update the receiver.

## 9. Measure an SMS Outreach Campaign <a href="#measure-an-sms-outreach-campaign" id="measure-an-sms-outreach-campaign"></a>

Channel Manager provides the message and opt-out records. These three metrics need no extra endpoint. Use a token with `sms:read` and `sms:consent:read`. Measures that depend on your own operational records are covered in [Measure Business Outcomes](#measure-business-outcomes).

**Messaged recipients** is the denominator for both rates. It counts distinct `to_number` values with at least one outbound message record in the cohort. By default the cohort is every outbound message on the use case created in the send window, where `start <= created_at < end`. That includes sends that later failed or were undelivered, and any other outreach on the use case in the window, such as test messages. An accepted send is not a deliverable one. The unit is a recipient phone number, not a message.

To limit the cohort to one campaign, save each message `id` returned by your campaign sends and pass those IDs as `message_ids`. The opt-in call returns no message ID, so the registered opt-in message is not a record you can select.

The example counts phone numbers. For reporting by person or account, join message IDs to the corresponding records in your application and count each person or account once. One person can use several numbers, and numbers can be shared. Report unmatched or ambiguous mappings separately.

**Response rate** is messaged recipients with a qualifying reply, divided by messaged recipients. A qualifying reply is an inbound message from that number, on the same use case, created after that recipient's earliest outbound message in the send window and before `reply_end`. Messages that recorded an opt-out are excluded.

**Time to first response** is the earliest qualifying reply minus the earliest outbound message in the send window, per recipient who replied. Report the median with the number of repliers.

**Opt-out rate** is messaged recipients with an opt-out record created at or after their earliest outbound message and before `reply_end`, divided by messaged recipients.

### Choose the Windows

Fix three timestamps before you read anything: `start` and `end` bound the sends, and `reply_end` closes the observation period. Set `reply_end` later than `end` so the last recipients have time to answer. A reply or opt-out at or after `reply_end` is not counted. Run the report after `reply_end` has passed. A closed window reduces the records that can be added while you read. The lists are not a transactional snapshot. A message status can still update, a record can be erased, and an opt-out can be cleared between two runs, so a second run can return different numbers. To reproduce a report, save the records you fetched and the time you fetched them.

### Read Every Record

Read messages with `GET /v1/sms` and `setup_id`, `use_case_id`, `direction`, `created_after`, and `created_before`. The recipient of an outbound message is `to_number`, and the sender of an inbound message is `from_number`. Read opt-outs with `GET /v1/sms/opt-out`, `setup_id`, and `include_deleted=true`, which keeps opt-outs that were cleared later. That list has no time filter.

* **Pages.** Each list returns `items`, `has_more`, and `continuation_token`. Send `limit=200`, the maximum, and pass the token back unchanged with the same filters until `has_more` is `false`.
* **Order.** Send `sort_by=+created_at` so records arrive oldest first. A closed window makes a record added between two page reads less likely. The example skips an `id` it has already seen.
* **Boundaries.** `created_before` excludes its own timestamp. To keep a message created exactly at a lower bound, the example asks for records from one second earlier and applies `start <= created_at < end` itself.

The example uses only the Python standard library and reads the same environment variables as the steps above.

```python
import json
import os
import statistics
import urllib.parse
import urllib.request
from datetime import datetime, timedelta


def ts(value):
    return datetime.fromisoformat(value.replace("Z", "+00:00"))


def fetch(path, params):
    url = f"{os.environ['CHANNEL_API_BASE']}{path}?{urllib.parse.urlencode(params)}"
    request = urllib.request.Request(
        url, headers={"Authorization": f"Bearer {os.environ['CHANNEL_ACCESS_TOKEN']}"})
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.load(response)


def pages(fetch, path, **params):
    params = {**params, "limit": 200, "sort_by": "+created_at"}
    seen = set()
    while True:
        body = fetch(path, params)
        for item in body["items"]:
            if item["id"] not in seen:
                seen.add(item["id"])
                yield item
        if not body["has_more"]:
            return
        params["continuation_token"] = body["continuation_token"]


def messages(fetch, setup_id, use_case_id, direction, lower, upper):
    query = dict(setup_id=setup_id, use_case_id=use_case_id, direction=direction,
                 created_after=(lower - timedelta(seconds=1)).isoformat(),
                 created_before=upper.isoformat())
    for message in pages(fetch, "/v1/sms", **query):
        if lower <= ts(message["created_at"]) < upper:
            yield message


def campaign_metrics(fetch, setup_id, use_case_id, start, end, reply_end, message_ids=None):
    first_out, delivered = {}, set()
    for m in messages(fetch, setup_id, use_case_id, "outbound", start, end):
        if message_ids is not None and m["id"] not in message_ids:
            continue  # outside the campaign cohort
        first_out.setdefault(m["to_number"], ts(m["created_at"]))
        if m["status"] == "delivered":
            delivered.add(m["to_number"])

    opted_out, opt_out_messages = set(), set()
    for o in pages(fetch, "/v1/sms/opt-out", setup_id=setup_id, include_deleted="true"):
        sent = first_out.get(o["phone_number"])
        if sent and sent <= ts(o["created_at"]) < reply_end:
            opted_out.add(o["phone_number"])
            opt_out_messages.add(o["opted_out_message_id"])

    first_reply = {}
    for m in messages(fetch, setup_id, use_case_id, "inbound", start, reply_end):
        sent = first_out.get(m["from_number"])
        if sent and ts(m["created_at"]) > sent and m["id"] not in opt_out_messages:
            first_reply.setdefault(m["from_number"], ts(m["created_at"]))

    messaged = len(first_out)
    seconds = [(first_reply[n] - first_out[n]).total_seconds() for n in first_reply]
    return {
        "messaged_recipients": messaged,
        "delivered_recipients": len(delivered),
        "replied_recipients": len(first_reply),
        "replied_delivered_recipients": len(delivered & set(first_reply)),
        "opted_out_recipients": len(opted_out),
        "response_rate": len(first_reply) / messaged if messaged else None,
        "opt_out_rate": len(opted_out) / messaged if messaged else None,
        "median_seconds_to_first_response": statistics.median(seconds) if seconds else None,
    }


if __name__ == "__main__":
    print(json.dumps(campaign_metrics(
        fetch, os.environ["CHANNEL_SETUP_ID"], os.environ["CHANNEL_USE_CASE_ID"],
        start=ts("2026-10-01T00:00:00Z"), end=ts("2026-10-15T00:00:00Z"),
        reply_end=ts("2026-10-22T00:00:00Z")), indent=2))
```

With no messaged recipients the rates are `null`, and with no replies the median is `null`. `delivered_recipients` counts cohort recipients with at least one message whose `status` is `delivered` when you read it. `replied_delivered_recipients` counts the repliers within that same set. To report against confirmed delivery, divide `replied_delivered_recipients` by `delivered_recipients` so that the numerator and the denominator cover the same recipients. Dividing `replied_recipients` by `delivered_recipients` can exceed 100%, because a recipient can reply without a recorded delivery. Delivery confirmation depends on the carrier and can be absent, so this set can be smaller than the recipients who received a message. State the cohort and the denominator with every rate.

### Know the Limits

* **Attribution is by phone number and time.** An SMS reply carries no link to the message it answers. When two campaigns or workflows message the same person through one use case in overlapping windows, the records cannot assign the reply to one of them. Give each campaign its own use case, or decide with your own workflow records. Passing `message_ids` selects the outbound cohort only. It does not attribute a reply to a campaign.
* **Earlier conversations count.** A reply to a message sent before `start` qualifies when it arrives after that recipient's first message in the window.
* **Keyword messages.** A help keyword counts as a reply, whether Channel Manager answers it or posts it to your receiver. Filter on `body` to exclude it.
* **Opt-outs are setup-wide.** A record can come from another use case on the same setup. A recipient with an active opt-out from before `start` cannot be messaged, so they appear in neither the numerator nor the denominator. A repeated `STOP` during an active opt-out adds no record.
* **History is limited to these records.** The list holds active and cleared opt-outs, not a snapshot of who was opted out at a past moment. When the inbound message behind an opt-out has been erased, its `opted_out_message_id` is `null`, and that message can count as a reply.
* **Workflow evidence.** A delivery receipt does not establish that a person read the message or completed its task. Join messages to confirmed results in your own systems using your workflow ID. See [Measure Business Outcomes](#measure-business-outcomes).

### Measure Business Outcomes <a href="#measure-business-outcomes" id="measure-business-outcomes"></a>

Calculate these measures in your reporting process by joining Channel Manager API records to your operational records. The examples below define general workflow measures.

Fix the eligible cohort, the unit you count, and the send and observation windows before you read results. Each numerator is a subset of its denominator.

* **Engagement rate** is recipients with a recorded request for follow up, divided by messaged recipients.
* **Completion rate** is recipients who reach the campaign's defined outcome inside the observation window, divided by messaged recipients. Confirm the outcome in the operational system, such as a booking or intake record. These counts do not establish that messaging caused the outcome.
* **Cancellation rate** is recipients with a cancellation recorded after their confirmation and inside the observation window, divided by recipients with a confirmed appointment.

A reply or a delivery receipt is not a recorded completion.

Retain your campaign or workflow ID, each Channel Manager message `id` and send time, the recipient mapping, and the dated operational records. An authorized client can read the current Channel Manager records with the example in [Read Every Record](#read-every-record).

Report recipients with no mapping, missing data, or a pending result as separate counts. Do not count an unknown as a negative or drop it silently.

## 10. Accept the Integration and Hand It Over

Before launch, run these checks on the actual deployment and record each result. The record is your team's acceptance decision. The API does not enforce it.

* Missing or expired credentials fail, and your client cannot reach another setup.
* A reply or call reaches the intended session.
* Invalid signatures fail, and a replay causes one action.
* Voice has two-way audio, audible hold music, approved transfer destinations, and confirmed teardown.
* Opt-out rules block later sends.
* A timeout starts an investigation, not a duplicate send.
* A support owner can find the records.

For supported toll-free SMS, `START` or `UNSTOP` clears the line-specific opt-out only. After reviewing renewed consent, a client with `sms:consent:write` can clear the setup-wide opt-out with a recorded reason. An opt-in-message send record is not proof of consent. See [SMS consent controls](https://docs.concurrence.com/channels/sms).

Unset `CHANNEL_ACCESS_TOKEN` and `CHANNEL_CLIENT_SECRET` after testing. Keep test and suppression records for the agreed retention period, and use [Troubleshooting](https://docs.concurrence.com/developer-guide/guides/troubleshooting.md) to raise an issue with the relevant IDs and errors, leaving out credentials and unnecessary message content.


---

# 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/integrate-channel-manager.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.
