# Send your first message

> Connect a test number, send a WhatsApp message and receive its events at your webhook endpoint.

In this quickstart you connect two test numbers, register a webhook endpoint,
send a message from one Number to the other and confirm the events reach your
server. It takes about 15 minutes. Test numbers are simulated, so nothing
reaches a real WhatsApp account. To use a real phone instead, see
[Use a real number](#use-a-real-number).

> **Note**
>
> Test numbers require access. If **Create a testing number for free** is not
> available in your project, a team owner or admin can join the test numbers beta
> in [Opt-in features](https://docs.polymorfa.com/teams/opt-in-features). See [Testing](https://docs.polymorfa.com/testing).

## Before you begin

- A Polymorfa team and project. New teams start on Free, which includes one
  project. See [Teams and projects](https://docs.polymorfa.com/teams#create-a-project).
- The project ID. Open the project in the Console and select
  **Copy project ID** in the project header.
- A public HTTPS URL that can receive `POST` requests, for the webhook.
- For the TypeScript samples, Node.js 20 or later.

## Set up

### Create a project token

A project token works only inside one project, so it is the safest credential
for this quickstart.

1. Open the project in the Console.
2. Open **Settings → API Keys** and select **Create project key**.
3. Choose **Service account**, enter a label and choose an expiry.
4. Choose **Restricted**, then set **Numbers** to **Read**, **Messages** to
   **Write**, **QuickLinks** to **Write** and **Webhooks** to **Write**.
5. Create the key, then select **Copy**. The Console shows the full token only
   once.

Store the token and project ID in environment variables. Keep the token on
your server; never put it in browser or mobile code.

```bash
export POLYMORFA_KEY="pmfa_pt_..."
export POLYMORFA_PROJECT_ID="00000000-0000-4000-8000-000000000001"
```

See [API keys](https://docs.polymorfa.com/development/api-keys) for team keys, ownership and revocation.

### Install the SDK

Skip this step if you use cURL.

```bash
npm install --save-exact @polymorfa/sdk@dev
```

The SDK is published as a development prerelease under the `dev` tag. See
[Install the TypeScript SDK](https://docs.polymorfa.com/get-started/development-environment#install-the-typescript-sdk).

Create the two clients you use below. `Client` calls the Platform API and
`MessagingClient` calls the Messaging API:

```typescript
import { Client, MessagingClient } from "@polymorfa/sdk";

const key = process.env.POLYMORFA_KEY!;
const projectId = process.env.POLYMORFA_PROJECT_ID!;

const platform = new Client({
  credential: { type: "projectToken", value: key },
  projectId,
  apiVersion: "2026-09-22",
});

const messaging = new MessagingClient({
  credential: { type: "projectToken", value: key },
  apiVersion: "2026-09-22",
});
```

## Write the integration

### Connect two test numbers

A test number can message only other active test numbers in the same project,
so create two: a sender and a recipient. Repeat this step for each one.

**Console:**

1. Open **Numbers** in the project and, under **Test numbers**, select
   **Add test number**.
2. Enter a display name and select **Create setup link**.
3. Select **Open test setup**. On the setup page, select **Create simulated
   account**, then **Finish setup**.

The Number appears in the **Numbers** list once it connects. To read each
Number's ID and phone number, list the project's Numbers:

```bash
curl "https://api.polymorfa.com/platform/sessions?projectId=$POLYMORFA_PROJECT_ID" \
  -H "Authorization: Bearer $POLYMORFA_KEY"
```

Test numbers have `testMode: true`. Use `sessionId` as the Number ID and
`phone` as its phone number.

**API:**

Create a QuickLink with `configuration.testing`. The response returns the
setup page URL and the `session` ID of the new Number.

```bash cURL
curl -X POST "https://api.polymorfa.com/messaging/quicklinks" \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Polymorfa-Version: 2026-09-22" \
  -H "Content-Type: application/json" \
  -d '{
    "projectId": "'"$POLYMORFA_PROJECT_ID"'",
    "configuration": { "testing": { "country": "US" } }
  }'
```

```typescript TypeScript
const created = await messaging.quickLinks.create({
  projectId,
  configuration: { testing: { country: "US" } },
});

const { id, url, session } = created.data.data;
console.log(id, session);
// Your application opens or hands over the URL privately; this is not an SDK method. Do not log it.
await openSetupPage(url);
```

```json
{
  "success": true,
  "data": {
    "id": "ql_0c1d8f2a3b4c5d6e7f80",
    "url": "https://www.polymorfa.com/connect/...",
    "session": "739182640518203",
    "expiresAt": null
  }
}
```

Open `url` in a browser. Select **Create simulated account**, then
**Finish setup**. Treat the URL as a secret: anyone who has it can complete
the setup, so don't log it.

Then read the QuickLink until `status` is `connected`. The response includes
the Number's `phone` in E.164 format:

```bash cURL
curl "https://api.polymorfa.com/messaging/quicklinks/ql_0c1d8f2a3b4c5d6e7f80" \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Polymorfa-Version: 2026-09-22"
```

```typescript TypeScript
const link = await messaging.quickLinks.retrieve(id);
console.log(link.data.data.status, link.data.data.phone);
```

Save the values for both Numbers:

```bash
export SENDER_ID="739182640518203"
export RECIPIENT_PHONE="+15550100002"
```

Each project has a limit on active test numbers. See
[Test numbers](https://docs.polymorfa.com/testing/test-numbers) for the limit and for removing a Number.

### Register a webhook endpoint

Polymorfa sends events, such as an incoming message or a delivery receipt, to
your HTTPS endpoint. Register the endpoint for this project and choose its
event types. Webhook changes require an `Idempotency-Key` header: a unique
value per change, so a retried request can't create a second endpoint.

**Console:**

1. Open **Settings → Webhooks** in the project and add an endpoint.
2. Enter your URL and select `message.received`, `message.ack` and
   `session.status`.
3. Save, then copy the signing secret from the confirmation dialog. The Console
   never shows it again.

**API:**

```bash cURL
curl -X POST "https://api.polymorfa.com/platform/projects/$POLYMORFA_PROJECT_ID/webhooks" \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Idempotency-Key: quickstart-webhook-1" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/polymorfa/webhook",
    "eventTypes": ["message.received", "message.ack", "session.status"],
    "format": "native"
  }'
```

```typescript TypeScript
const endpoint = await platform.webhooks.create(
  {
    url: "https://example.com/polymorfa/webhook",
    eventTypes: ["message.received", "message.ack", "session.status"],
    format: "native",
  },
  { idempotencyKey: "quickstart-webhook-1" },
);

console.log(endpoint.data.webhook.id);
// Keep the one-time signing secret in your application's secret store, which is not an SDK API. Do not log it.
await secretStore.put("polymorfa-webhook-signing-secret", endpoint.data.secret);
```

The response contains the endpoint and its signing `secret`. Store the secret
now. Read responses and a repeated request with the same idempotency key return
`secret: null`.

Store the signing secret where your server can read it:

```bash
export WEBHOOK_SECRET="replace-with-the-signing-secret"
```

### Verify each delivery

Each delivery carries an `X-Webhook-Signature` header: a hex HMAC-SHA256 of the
raw request body, keyed with the signing secret. Check it before you parse the
body, and answer with a `2xx` status once you have stored the event. This
handler uses the SDK's `webhooks.verify`:

```typescript
import { WebhookSignatureError, webhooks } from "@polymorfa/sdk";

const secret = process.env.WEBHOOK_SECRET;
if (!secret) throw new Error("Set WEBHOOK_SECRET to the endpoint signing secret.");

const MAX_WEBHOOK_BYTES = 2 * 1024 * 1024;

// Read the raw body, or return null as soon as it passes the limit.
async function readRawBody(request: Request): Promise<Uint8Array | null> {
  if (Number(request.headers.get("content-length")) > MAX_WEBHOOK_BYTES) return null;
  const reader = request.body?.getReader();
  if (!reader) return new Uint8Array();
  const chunks: Uint8Array[] = [];
  let total = 0;
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    total += value.byteLength;
    if (total > MAX_WEBHOOK_BYTES) {
      await reader.cancel();
      return null;
    }
    chunks.push(value);
  }
  const body = new Uint8Array(total);
  let offset = 0;
  for (const chunk of chunks) {
    body.set(chunk, offset);
    offset += chunk.byteLength;
  }
  return body;
}

export async function handleWebhook(request: Request): Promise<Response> {
  const body = await readRawBody(request);
  if (!body) return new Response(null, { status: 413 });
  try {
    const event = await webhooks.verify({
      body,
      signature: request.headers.get("x-webhook-signature") ?? "",
      secret,
    });
    console.log(event.id, event.event);
    return new Response(null, { status: 204 });
  } catch (error) {
    if (error instanceof WebhookSignatureError) return new Response(null, { status: 400 });
    throw error;
  }
}
```

Read the body as bytes. Parsing and re-serializing the JSON changes the bytes
and the signature no longer matches. Cap the size before you verify: the sample
answers `413` above `MAX_WEBHOOK_BYTES` (2 MiB), a sample default you can raise. Deliveries are retried, so skip an event
`id` you have already processed. See [Webhooks](https://docs.polymorfa.com/development/webhooks) for
other languages, retries and every event type.

### Send a message

Send a text message from the sender to the recipient's phone number. Put
exactly one message kind inside `content`. The `Idempotency-Key` is optional
here; send one so you can retry the request safely.

```bash cURL
curl -X POST "https://api.polymorfa.com/messaging/$SENDER_ID/messages/send" \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Polymorfa-Version: 2026-09-22" \
  -H "Idempotency-Key: quickstart-message-1" \
  -H "Content-Type: application/json" \
  -d '{
    "conversation": { "phoneNumber": "'"$RECIPIENT_PHONE"'" },
    "content": { "text": "Hello from Polymorfa" }
  }'
```

```typescript TypeScript
const sent = await messaging.messages.send(
  process.env.SENDER_ID!,
  {
    conversation: { phoneNumber: process.env.RECIPIENT_PHONE! },
    content: { text: "Hello from Polymorfa" },
  },
  { idempotencyKey: "quickstart-message-1" },
);

console.log(sent.data.data.id, sent.data.data.status);
```

Already have code written for Meta's Cloud API? The
[Graph API](https://docs.polymorfa.com/api/graph) accepts Meta's request shape at
`/graph/whatsapp/v26.0` and answers in Meta's shape.

A `200` response returns the message with its Polymorfa `id`. Keep the ID as a
string; use it for later actions on the message. Delivery and read receipts
arrive later as `message.ack` events. See
[Send a message](https://docs.polymorfa.com/api/messages/send-message) for every message kind
and field.

## Try it out

1. Send a test delivery to confirm your endpoint and signature check work:
   `POST /platform/projects/{projectId}/webhooks/{webhookId}/tests` with an
   `Idempotency-Key` header and an empty body, or
   `platform.webhooks.test(webhookId, {}, { idempotencyKey })` in the SDK. Your
   handler receives a `polymorfa.test` event.
2. Send the message above. Your handler receives the events you subscribed to
   for both Numbers.
3. Open the recipient Number in the Console, or in
   [Inspector](https://docs.polymorfa.com/testing/inspector/install), to see the message arrive.

If the send returns `404`, the recipient is not an active, connected test
number in the same project. If it returns `401` or `403`, check the token and
its permissions. Every error response includes a `docs` link to its entry in
[Errors](https://docs.polymorfa.com/api/errors).

You've sent a WhatsApp message through Polymorfa and received its events at a
verified endpoint.

## Use a real number

A real number connects a WhatsApp account on a phone and can message any
WhatsApp user.

- **Free team:** open **Numbers**, select **New number** and choose **Link a real
  number now**. The Console shows a QR code or pairing code for the phone with
  you. One real number is included at no charge.
- **Pay-As-You-Go team:** create a QuickLink without `configuration.testing`
  and send its `url` to the person holding the phone. See
  [QuickLink](https://docs.polymorfa.com/numbers/quicklink).

Free teams can't create QuickLinks for real numbers; the API returns `409`
with the code `payg_required`. See
[Free and Pay-As-You-Go teams](https://docs.polymorfa.com/teams#free-and-pay-as-you-go-teams).

Then send to any WhatsApp number in E.164 format, including `+`. Before you
send at volume, read about [Safety](https://docs.polymorfa.com/safety) and the
[warm-up plan](https://docs.polymorfa.com/safety/warm-up-plan).

## Next steps

- **[Messaging](https://docs.polymorfa.com/messaging)**
Send media, interactive messages and replies, and read conversations.

- **[Connect Numbers with QuickLink](https://docs.polymorfa.com/numbers/quicklink)**
Send hosted setup links and follow each connection to the end.

- **[Webhooks](https://docs.polymorfa.com/development/webhooks)**
Choose event types, configure retries and inspect deliveries.

- **[Integration checklist](https://docs.polymorfa.com/get-started/checklist)**
Check versioning, errors, retries, credentials and safety before you send real traffic.
