VYG Docs
Messaging API

Webhooks guide

Receive signed events for customer texts, delivery results and opt-outs, verify them, and handle retries, ordering and duplicates.

VYG sends an HTTPS POST to your endpoint when a customer texts in, a message is sent, delivered or fails, or a contact opts out or back in. Each delivery is signed with Standard Webhooks, so you can check it came from VYG and was not changed.

Webhooks need the messaging API turned on for the brand and an API key with webhooks:manage. See the Messaging guide for keys and scopes, the Webhooks concept page for the endpoint rules, and the Webhooks reference for every field of every endpoint.

Set up the endpoint

A brand has one webhook endpoint, at /v1/webhooks. There is no endpoint id. The URL must be HTTPS on a public host. Create it with the event types you want:

curl -X POST "https://api.vyg.app/v1/webhooks" \
  -H "Authorization: Bearer $VYG_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "url": "https://example.com/hooks/vyg",
  "event_types": ["message.received", "message.sent", "message.delivered", "message.failed"]
}'

The answer includes secret, the signing secret. It starts with whsec_ and is shown only this once. Store it in your secret manager; if you lose it, rotate it. Creating an endpoint when the brand already has one answers 409 conflict: change the existing one, or delete it first.

export interface CreatedWebhookEndpoint {
	url: string;
	event_types: string[];
	enabled: boolean;
	include_phone: boolean;
	disabled_reason: string | null;
	created_at: string | null;
	updated_at: string | null;
	/** The signing secret. Returned only once: store it in your secret manager. */
	secret: string;
}

/**
 * Create the brand's webhook endpoint for the given event types: POST /v1/webhooks. A brand has one endpoint;
 * creating a second answers 409 conflict, so change the existing one with PATCH /v1/webhooks instead.
 */
export async function createWebhookEndpoint(options: {
	apiKey: string;
	url: string;
	eventTypes: string[];
	baseUrl?: string;
	fetch?: typeof fetch;
}): Promise<CreatedWebhookEndpoint> {
	const send = options.fetch ?? fetch;
	const response = await send(`${options.baseUrl ?? 'https://api.vyg.app'}/v1/webhooks`, {
		method: 'POST',
		headers: { Authorization: `Bearer ${options.apiKey}`, 'Content-Type': 'application/json' },
		body: JSON.stringify({ url: options.url, event_types: options.eventTypes }),
	});
	if (!response.ok) throw new Error(`Creating the webhook endpoint failed with ${response.status}`);
	return (await response.json()) as CreatedWebhookEndpoint;
}

Then send a test event to check your endpoint and signature check:

curl -X POST "https://api.vyg.app/v1/webhooks/test" -H "Authorization: Bearer $VYG_API_KEY"

The endpoint operations:

OperationWhat it does
POST /v1/webhooksCreate the endpoint and return its secret once.
GET /v1/webhooksRead the endpoint, including enabled and disabled_reason. The secret is never returned.
PATCH /v1/webhooksChange url, event_types or include_phone, or set enabled to turn it off or back on.
DELETE /v1/webhooksDelete the endpoint. Deliveries still queued for it are dropped.
POST /v1/webhooks/rotate-secretReturn a new secret. The old one keeps working for 24 hours.
POST /v1/webhooks/testSend a signed webhook.test event. Answers 202 with its event_id. The endpoint must be on.

A URL that is not HTTPS or does not resolve to a public address answers 400 invalid_webhook_url. Setting include_phone needs contacts:read-phone as well, and so does changing the URL of an endpoint that includes the phone number.

Which events the endpoint gets

The endpoint gets events for changes that happen after it was created and after its last settings change (URL, event types, phone number or enabled state). Nothing older is sent. Turning a disabled endpoint back on does not send the events it missed while it was off; read the conversations you need instead.

Events

Every event is a JSON object with these fields. A webhook.test event has only event_id, type, occurred_at, brand_id and test.

FieldMeaning
event_idThe event id (evt_...). The same value is sent in the webhook-id header.
typeThe event type.
occurred_atWhen the change happened (ISO 8601, UTC). Use it to order events.
brand_idThe brand.
conversation_idThe conversation, or null when there is none.
contact_idThe contact.
contact_channel_idThe contact's SMS channel. Use it to send by contact.
testtrue on a webhook.test event and on VYG's internal test sends; false for real customer traffic.
phoneThe contact's phone number in E.164. Only when the endpoint has include_phone.

Payloads never include email addresses or names. There are no events for a pause or a resume.

message.received

A customer texted the brand. images lists the URLs of any MMS images.

{
	"event_id": "evt_01JD0000000000000000000001",
	"type": "message.received",
	"occurred_at": "2026-11-10T15:04:05.000Z",
	"brand_id": "0a000000-0000-4000-8000-000000000001",
	"conversation_id": "0c000000-0000-4000-8000-000000000001",
	"contact_id": "0d000000-0000-4000-8000-000000000001",
	"contact_channel_id": "0e000000-0000-4000-8000-000000000001",
	"test": false,
	"message_id": "0f000000-0000-4000-8000-000000000001",
	"direction": "inbound",
	"text": "Hi, where is my order?",
	"images": [],
	"status": "received"
}

message.sent

An outbound message was accepted for sending. origin says where it came from: api (this API), agent (the brand's agents), flow (a campaign) or app (other automated sends). Every reply you send through the API has origin api, including a held reply when it goes out later.

{
	"event_id": "evt_01JD0000000000000000000002",
	"type": "message.sent",
	"occurred_at": "2026-11-10T15:06:00.000Z",
	"brand_id": "0a000000-0000-4000-8000-000000000001",
	"conversation_id": "0c000000-0000-4000-8000-000000000001",
	"contact_id": "0d000000-0000-4000-8000-000000000001",
	"contact_channel_id": "0e000000-0000-4000-8000-000000000001",
	"test": false,
	"message_id": "0f000000-0000-4000-8000-000000000002",
	"direction": "outbound",
	"text": "Your order ships tomorrow.",
	"images": [],
	"status": "sent",
	"origin": "api"
}

message.delivered

The carrier confirmed delivery to the handset. A carrier that reports the same result twice does not produce a second event.

{
	"event_id": "evt_01JD0000000000000000000003",
	"type": "message.delivered",
	"occurred_at": "2026-11-10T15:06:04.000Z",
	"brand_id": "0a000000-0000-4000-8000-000000000001",
	"conversation_id": "0c000000-0000-4000-8000-000000000001",
	"contact_id": "0d000000-0000-4000-8000-000000000001",
	"contact_channel_id": "0e000000-0000-4000-8000-000000000001",
	"test": false,
	"message_id": "0f000000-0000-4000-8000-000000000002",
	"direction": "outbound",
	"text": "Your order ships tomorrow.",
	"images": [],
	"status": "delivered"
}

message.failed

Sending or delivery failed. reason says why, for example the carrier's reason, or null when none was given. A send that answered 503 with "nothing went out" fires no event (see When a send fails).

{
	"event_id": "evt_01JD0000000000000000000004",
	"type": "message.failed",
	"occurred_at": "2026-11-10T15:06:04.000Z",
	"brand_id": "0a000000-0000-4000-8000-000000000001",
	"conversation_id": "0c000000-0000-4000-8000-000000000001",
	"contact_id": "0d000000-0000-4000-8000-000000000001",
	"contact_channel_id": "0e000000-0000-4000-8000-000000000001",
	"test": false,
	"message_id": "0f000000-0000-4000-8000-000000000003",
	"direction": "outbound",
	"text": "Your order ships tomorrow.",
	"images": [],
	"status": "failed",
	"reason": "undelivered"
}

contact.opted_out

The contact opted out, for example by texting STOP. Replies to them are refused until they opt back in.

{
	"event_id": "evt_01JD0000000000000000000005",
	"type": "contact.opted_out",
	"occurred_at": "2026-11-10T15:10:00.000Z",
	"brand_id": "0a000000-0000-4000-8000-000000000001",
	"conversation_id": "0c000000-0000-4000-8000-000000000001",
	"contact_id": "0d000000-0000-4000-8000-000000000001",
	"contact_channel_id": "0e000000-0000-4000-8000-000000000001",
	"test": false
}

contact.opted_in

The contact opted back in, for example by texting START.

{
	"event_id": "evt_01JD0000000000000000000006",
	"type": "contact.opted_in",
	"occurred_at": "2026-11-10T15:12:00.000Z",
	"brand_id": "0a000000-0000-4000-8000-000000000001",
	"conversation_id": "0c000000-0000-4000-8000-000000000001",
	"contact_id": "0d000000-0000-4000-8000-000000000001",
	"contact_channel_id": "0e000000-0000-4000-8000-000000000001",
	"test": false
}

webhook.test

Sent only when you call POST /v1/webhooks/test. You cannot subscribe to it. It carries no customer data:

{
	"event_id": "evt_01JD0000000000000000000007",
	"type": "webhook.test",
	"occurred_at": "2026-11-10T15:00:00.000Z",
	"brand_id": "0a000000-0000-4000-8000-000000000001",
	"test": true,
	"message": "This is a test webhook event from VYG."
}

Verify the signature

Each delivery carries three headers:

HeaderValue
webhook-idThe event id. It stays the same when a delivery is retried.
webhook-timestampUnix seconds when this attempt was sent.
webhook-signatureOne or more space-separated v1,<signature> tokens.

Each signature is the base64 HMAC-SHA256 of {webhook-id}.{webhook-timestamp}.{body}, keyed with your secret after the whsec_ prefix is removed and the rest base64-decoded. To verify a delivery:

  1. Read the raw request body as text. Do not parse and re-serialize it first; the signature covers the exact bytes.
  2. Reject the delivery if webhook-timestamp is more than five minutes from your clock, so an old delivery cannot be replayed against you.
  3. Compute the signature and compare it in constant time with each v1 token. Accept if any token matches.
  4. Answer 401 if the check fails.

While a rotated secret overlaps the new one, the header carries one token for each secret, so a receiver holding either secret verifies.

This TypeScript (Node.js 18 or later) has no dependencies. CI runs it on every change: a delivery signed the way VYG signs it verifies, and the same delivery with a changed body does not.

import { createHmac, timingSafeEqual } from 'node:crypto';

/** Reject a delivery whose timestamp is more than five minutes from your clock. */
const TOLERANCE_SECONDS = 5 * 60;

type HeaderSource = Headers | Record<string, string | string[] | undefined>;

function header(headers: HeaderSource, name: string): string | null {
	if (headers instanceof Headers) return headers.get(name);
	const value = headers[name];
	return (Array.isArray(value) ? value[0] : value) ?? null;
}

/**
 * Verify a VYG webhook delivery (Standard Webhooks, v1 signatures).
 *
 * `secret` is the endpoint's signing secret, as returned when you created the endpoint or rotated its secret.
 * `rawBody` must be the exact request body you received, read as text before any JSON parsing. Returns true when
 * the timestamp is recent and any `v1` signature in the `webhook-signature` header matches.
 */
export function verifyWebhook(
	secret: string,
	headers: HeaderSource,
	rawBody: string,
	nowMs: number = Date.now()
): boolean {
	const id = header(headers, 'webhook-id');
	const timestamp = header(headers, 'webhook-timestamp');
	const signatures = header(headers, 'webhook-signature');
	if (!id || !timestamp || !signatures) return false;

	const seconds = Number(timestamp);
	if (!Number.isInteger(seconds) || Math.abs(nowMs / 1000 - seconds) > TOLERANCE_SECONDS) return false;

	// The secret is a prefix, an underscore, then the base64 key. Sign `${id}.${timestamp}.${body}` with HMAC-SHA256.
	const key = Buffer.from(secret.slice(secret.indexOf('_') + 1), 'base64');
	const expected = createHmac('sha256', key).update(`${id}.${timestamp}.${rawBody}`).digest();

	// The header holds one or more space-separated `v1,<base64>` tokens (two while a rotated secret overlaps).
	return signatures.split(' ').some((token) => {
		const [version, signature] = token.split(',');
		if (version !== 'v1' || !signature) return false;
		const received = Buffer.from(signature, 'base64');
		return received.length === expected.length && timingSafeEqual(received, expected);
	});
}

Any Standard Webhooks library also verifies these headers. Pass it the full secret, including the whsec_ prefix.

Respond, retries and failures

Answer with any 2xx status within 15 seconds. Do the slow work after you answer, for example from a queue. Redirects are not followed.

If your endpoint times out, cannot be reached or answers anything else, VYG retries the same event with the same webhook-id. An event gets up to 10 attempts over about 3 hours. The waits before attempts 2 to 10 are 30 seconds, 2 minutes, 5 minutes, 10 minutes, 15 minutes, 20 minutes, 30 minutes, 45 minutes and 50 minutes.

  • After the last attempt the event is dropped. If your endpoint accepted no delivery at all during that window, it is turned off with disabled_reason sustained_delivery_failure.
  • If your endpoint answers 410 Gone, the event is not retried and the endpoint is turned off at once with disabled_reason endpoint_returned_410.

A turned-off endpoint gets no deliveries. Fix it, then turn it back on with PATCH /v1/webhooks and {"enabled": true}.

Event payloads are kept for 4 days, then deleted. Delivery history is not stored, so there is no delivery log and no replay. To fill a gap, read the conversations you need.

Ordering is not guaranteed

Events can arrive in a different order from the order they happened. Retries make this more likely: a message.delivered can arrive before its message.sent. Do not depend on arrival order:

  • Use occurred_at to order events for the same message or conversation.
  • Treat each event as a fact about one moment, and keep the latest state you have seen. For example, do not let a late message.sent overwrite a delivered status.
  • When in doubt, read the current state with GET /v1/conversations/{id}/messages.

Duplicates

Delivery is at least once, so the same event can arrive more than once. webhook-id (equal to event_id in the body) is the duplicate key: it is the same on every delivery of one event. Two deliveries of one event can arrive at the same time, so a check followed by a separate write is not enough: both can pass the check. Claim the webhook-id in one atomic step before any side effect, for example an INSERT ... ON CONFLICT (webhook_id) into a table with a unique key, and handle the event only when your delivery got the claim. Mark the claim done when you finish (ideally in the same transaction as your own writes). Answer 2xx for an event that is already done, or it will be retried. If handling fails, delete the claim and answer an error, so the retry is handled. While another delivery is still handling the event, answer an error such as 409 so it is retried later. Give the claim a lease (for example five minutes) so that if your receiver stops before finishing, a later retry takes the claim over instead of dropping the event. The receiver sample below shows the SQL.

This receiver works with any framework that gives you a standard Request. CI runs it too.

import { verifyWebhook } from './verify-webhook';

/**
 * Where you record the webhook-id of each event you handle. Claiming must be atomic, so that two copies of one event
 * arriving at the same time cannot both pass, and a claim must expire if your receiver stops before finishing, so a
 * crash mid-handling never drops the event. With a database: a table keyed on webhook_id with a state
 * ('processing' | 'done') and a claimed_at time.
 */
export interface ProcessedEvents {
	/**
	 * Claims the webhook-id. Returns 'claimed' when this delivery should handle the event (new, or a 'processing' claim
	 * older than the lease, left by a receiver that stopped), 'done' when it was already handled, or 'busy' when another
	 * delivery is handling it right now. In SQL:
	 *   INSERT INTO processed_webhooks (webhook_id, state, claimed_at) VALUES ($1, 'processing', now())
	 *   ON CONFLICT (webhook_id) DO UPDATE SET claimed_at = now()
	 *     WHERE processed_webhooks.state = 'processing'
	 *       AND processed_webhooks.claimed_at < now() - interval '5 minutes'
	 *   RETURNING webhook_id
	 * A returned row means 'claimed'; otherwise read the row's state: 'done', or 'busy' while it is 'processing'.
	 */
	claim(webhookId: string): Promise<'claimed' | 'done' | 'busy'>;
	/**
	 * Marks the event handled. In SQL: UPDATE processed_webhooks SET state = 'done' WHERE webhook_id = $1. Ideally in
	 * the same transaction as your own writes for the event.
	 */
	complete(webhookId: string): Promise<void>;
	/** Removes a claim after handling failed, so the retry of the event is handled. In SQL: DELETE ... WHERE webhook_id = $1. */
	release(webhookId: string): Promise<void>;
}

/** The fields every event payload carries. Each event type adds its own fields. */
export interface VygEvent {
	event_id: string;
	type: string;
	occurred_at: string;
	brand_id: string;
	test: boolean;
	[field: string]: unknown;
}

/**
 * A webhook receiver for any framework that gives you a standard Request. Verify first, then claim the webhook-id
 * before any side effect: a retry reuses the same webhook-id, and only the delivery that claims it handles the
 * event. Mark it done when handled. If handling fails, release the claim and answer 500, so the retry is handled.
 * While another delivery is still handling it, answer 409 so VYG retries later; if that delivery stopped without
 * finishing, its claim expires and a later retry handles the event.
 */
export async function handleWebhook(
	request: Request,
	secret: string,
	processed: ProcessedEvents,
	onEvent: (event: VygEvent) => Promise<void>
): Promise<Response> {
	const rawBody = await request.text();
	if (!verifyWebhook(secret, request.headers, rawBody)) {
		return new Response('invalid signature', { status: 401 });
	}

	const webhookId = request.headers.get('webhook-id')!;
	const claim = await processed.claim(webhookId);
	if (claim === 'done') return new Response(null, { status: 204 });
	if (claim === 'busy') return new Response('already being handled', { status: 409 });

	try {
		await onEvent(JSON.parse(rawBody) as VygEvent);
		await processed.complete(webhookId);
	} catch (error) {
		await processed.release(webhookId);
		console.error('webhook handling failed', webhookId, error);
		return new Response('handling failed', { status: 500 });
	}
	return new Response(null, { status: 204 });
}

Errors

StatuscodeWhen
400bad_requestThe body is invalid, for example the URL is missing or an event type is unknown.
400invalid_webhook_urlThe URL is not HTTPS, has credentials, or does not resolve to a public address.
403insufficient_scopeThe key lacks webhooks:manage, or include_phone was set (or a phone-bearing endpoint's URL changed) without contacts:read-phone.
403feature_not_enabledThe messaging API is not turned on for the brand.
404not_foundThe brand has no webhook endpoint.
409conflictThe brand already has an endpoint (create), or the endpoint is turned off (send a test).
429rate_limitedToo many requests. Wait Retry-After seconds.

On this page