---
title: "How to connect your own phone gateway to SayHi"
description: "Add a Phone Gateway configuration in SayHi, create a device token and a line, then connect your gateway over WebSockets with the reference client."
url: https://sapps.co/explore/sayhi/articles/connect-phone-gateway-websocket
app: "SayHi"
app_url: https://sapps.co/explore/sayhi
published: 2026-12-02T07:33:26.768Z
updated: 2026-12-02T09:42:21.054Z
tags: ["phone gateway","telephony","websocket","how-to"]
lang: "en"
---

# How to connect your own phone gateway to SayHi

To connect your own phone gateway to SayHi, add a **Phone Gateway (WebSocket)** configuration under **Telephony**, then create a device and a line. Your gateway connects to the control URL with the device token in the `X-Gateway-Token` header.

A phone gateway is anything that owns phone lines and can carry their calls over secure WebSockets: a phone app, a small computer with a modem, or a bridge in front of a gateway appliance. The gateway needs no SIP, UDP or extra telephony server.

This provider is not for SIP or UDP trunks. It speaks only Phone Gateway protocol 1 over WebSockets. Browser softphones are also out of scope: browsers cannot set the `X-Gateway-Token` header on a WebSocket, and protocol 1 accepts the token nowhere else.

## Before you start

You need:

- SayHi running, with its telephony URL shown in the control panel (see [Get started with SayHi](https://sapps.co/explore/sayhi/articles/get-started-sayhi-voice-agent-server)).
- At least one agent in SayHi, if the lines should answer inbound calls.
- A gateway you can configure, or Python 3 to run the reference client for a first test.

## Add a Phone Gateway configuration

A configuration holds the devices and lines of one set of gateways.

1. In SayHi, open **Telephony**.
2. Click **Add configuration**.
3. In **Name**, type a name, for example `Front office lines`.
4. In **Provider**, choose **Phone Gateway (WebSocket)**.
5. Optional: in **Preferred audio format**, choose **PCM 16-bit (320 bytes per frame)** or **G.711 mu-law (160 bytes per frame)**. SayHi uses it when the gateway offers that format, otherwise the gateway's other format.
6. Optional: turn on **Set as default for outbound calls** so test calls and campaigns use this configuration when no other one is selected.
7. Click **Create**.
8. Click the new configuration in the list to open it.

The configuration page shows a **Phone Gateway** card with the **Control URL**, **Devices** and **Lines**.

## Add a device and save its token

A device is one running gateway app. Each device gets its own token.

1. On the **Phone Gateway** card, click **Add device**.
2. In **Name**, type the device name, for example `Front office gateway`.
3. In **Simultaneous calls on this device**, choose how many calls it carries at once (1 to 8, default 1). The gateway does not send this value: it is set only here.
4. Click **Add device**.
5. In the **Token for Front office gateway** dialog, click **Copy** next to the token.
6. Paste the token into your gateway's settings.
7. Click **I saved the token**.

The token looks like `pgw1.<configuration>.<device>.<secret>`. SayHi stores only its SHA-256 hash, so the dialog is the only time you see it. If you lose it, click **Regenerate** on the device, then **Regenerate** again to confirm: the old token stops working at once and a connected gateway is disconnected. **Revoke** cuts a device off without issuing a new token.

## Add a line

A line is one phone line on one device. SayHi's list decides which announced lines it accepts.

1. On the **Phone Gateway** card, click **Add line**. The button stays disabled until a device that isn't revoked exists.
2. In **Line ID**, type the ID your gateway will announce, for example `sim1`. Use letters, digits and `. _ : -`, starting with a letter or digit, up to 64 characters.
3. In **Label**, type a name such as `Main line`.
4. Optional: in **Phone number (optional)**, type the line's number. Outbound calls from this number go out on this line.
5. In **Device**, choose the device that carries the line.
6. In **Inbound agent**, choose the agent that answers calls. With **(none: reject inbound calls)**, SayHi rejects incoming calls on the line.
7. In **Simultaneous calls on this line**, choose a limit (default 1).
8. Click **Add line**.

You can't change a line ID later.

## Connect the control socket

Every gateway keeps one control socket open to SayHi, and every call gets its own media socket.

The **Control URL** on the card follows this pattern:

```
wss://<telephony host>/api/v1/telephony/ws/gateway/control
```

The telephony host is your SayHi telephony endpoint. It is named `<name>-tel` after your SayHi URL name, as long as that name is at most 36 characters; longer names get a platform address. Changing the URL name changes the control URL, so update your gateways afterwards. Click **Copy** next to the URL instead of typing it.

Your gateway must follow these rules on the control socket:

- Send the token in the `X-Gateway-Token` header. Don't use `Authorization` (the platform router refuses it), and never put the token in the URL or in a message.
- No `Origin` header is needed.
- Send `hello` as the first message, within 10 s.
- Send `{"type":"ping"}` every 15 s and answer the server's `ping` with `{"type":"pong"}`. WebSocket ping frames are not used. After 45 s with nothing received, the device is offline.

A gateway that announces two SIM lines, only one of which exists in SayHi, sends:

```json
{"type":"hello","protocol":1,"features":[],
 "client":{"name":"my-gateway","version":"1.0.0","platform":"android"},
 "lines":[{"line_id":"sim1","number":"+15551234567"},{"line_id":"sim2"}],
 "audio":{"formats":["pcm16","ulaw"],"sample_rates":[8000]},
 "active_calls":[]}
```

SayHi answers with `welcome` and says per line whether it was accepted:

```json
{"type":"welcome","protocol":1,"features":[],"config_id":"7","device_id":"dev_3f9a1c27b04e",
 "server_time":"2026-12-01T12:00:00Z",
 "lines":[{"line_id":"sim1","accepted":true},
          {"line_id":"sim2","accepted":false,"reason":"unknown_line"}]}
```

`unknown_line` means no line with that ID exists in SayHi. `other_device` means the line is assigned to a different device. Once connected, the device shows **Online** on the card with its client name and version, and its accepted lines show **Online** too.

## Test with the reference client

SayHi ships a small Python client, `port/tools/phone-gateway-client.py`, that implements the whole protocol. It is in the SayHi source archive, behind the **Source code** link in the SayHi sidebar. It needs the `websockets` package, version 13.0 or later, because it uses the asyncio client [added in websockets 13.0 on 20 August 2024](https://websockets.readthedocs.io/en/stable/project/changelog.html).

The client reads the token from the `PHONE_GATEWAY_TOKEN` environment variable, never from the command line. `read -rs` lets you paste the token without it showing or reaching your shell history:

```
tar xzf source.tar.gz port/tools/phone-gateway-client.py
pip install "websockets>=13"
read -rs PHONE_GATEWAY_TOKEN && export PHONE_GATEWAY_TOKEN
python3 port/tools/phone-gateway-client.py \
  --url 'wss://<telephony host>/api/v1/telephony/ws/gateway/control' \
  --line sim1=+15551234567
```

It prints `welcome`, answers every `dial` and streams audio on each call. Its flags:

| Flag | What it does |
| --- | --- |
| `--url` | The control URL from SayHi (required) |
| `--line line_id[=number]` | A line to announce; repeat for more lines |
| `--format pcm16` or `ulaw` | An audio format to offer; repeat for both (default: both) |
| `--name` | Client name in `hello` (default `my-gateway`) |
| `--incoming line_id:caller` | Offer one inbound call after connecting, for example `sim1:+15557654321` |
| `--play file` | Raw 8 kHz 16-bit mono audio to send on each call (default: 2 s of silence) |
| `--listen` | Seconds to keep each media socket open (default 30) |

With `--incoming`, the client prints the `media_url` or `reject_incoming` reply, then a `media <run>: … frames in` line with the frame sizes it received once the call ends. It stops for good on close codes `4401` (token rejected), `4406` (protocol not supported) and `4409` (replaced by a newer connection with the same token). After any other failure it reconnects with backoff.

## Handle inbound calls

An inbound call starts on the gateway while the phone is still ringing:

1. The gateway sends `{"type":"incoming_call","call_id":"c-123","line_id":"sim1","from":"+15550001111"}`. SayHi routes by `line_id`, never by the dialled number.
2. SayHi checks that the line belongs to this device and was accepted, reserves it, and starts a run with the line's inbound agent.
3. SayHi replies with `media_url`, or with `reject_incoming` and a reason (`no_workflow`, `busy`, `quota` or `unknown_line`).
4. If no reply arrives within 8 s, the gateway rejects the phone call and sends `call_state` `failed` with `reason` `timeout`.
5. After `media_url`, the gateway answers the phone call, waits until audio is ready and opens the media socket.

If the caller hangs up while it is still ringing, the gateway sends `{"type":"call_state","call_id":"c-123","state":"ended"}`.

## Handle outbound calls

For an outbound call, SayHi picks the line whose number matches the campaign's caller number, or any free accepted line:

1. SayHi sends `{"type":"dial","run_id":"456","line_id":"sim1","number":"+15550002222"}`.
2. The gateway must reply with `dial_ack` (with its own `call_id`) within 5 s, or with `dial_reject` (`busy`, `no_line`, `not_ready` or `unsupported`). A timeout or a reject fails the run and frees the line. A `dial_ack` that arrives too late gets a `hangup`, and the gateway hangs up the phone call.
3. The gateway sends `call_state` `ringing`, then `answered`.
4. On `answered`, SayHi sends `media_url` and the gateway opens the media socket.

`busy`, `no_answer` and `failed` end the run with SayHi's normal statuses, so campaign retries work.

## Stream audio on the media socket

Each call uses the `url` from `media_url`. Audio is 8 kHz mono in 20 ms binary frames, in the format named in `media_url`:

| Format | Encoding | Bytes per 20 ms frame |
| --- | --- | --- |
| `pcm16` | 16-bit little-endian | 320 |
| `ulaw` | G.711 mu-law | 160 |

SayHi also sends two text events: `{"event":"clear"}` when the caller interrupts (flush your playback buffer) and `{"event":"hangup"}`. Keep a playback buffer of 60 to 100 ms. Keep the media URL private: it carries a token signed for that run.

There is no resume. When the media socket closes for any reason, the gateway hangs up the phone call and sends `call_state` `ended`.

If the gateway connects but drops, or calls fail, [Fix Phone Gateway errors in SayHi](https://sapps.co/explore/sayhi/articles/fix-phone-gateway-connection-errors) explains each close code and timeout.

The full protocol, with your control URL filled in, opens from the **Protocol** button on the **Phone Gateway** card.

No SayHi server for your gateway to connect to yet? [Get SayHi from the Sapps Store](https://sapps.co/explore/sayhi) and announce your first line.
