Twofold v2.7

Search pages, sections and endpoints.

    Open the console

    Webhooks

    The events Twofold sends, and how to open a sealed payload in your own stack.

    Environment

    Webhooks tell you that something happened to a linked provider's note. They carry identifiers only — never note text, never patient data. You receive an event, then fetch what you need over the API with that provider's token.

    Treat them as fetch triggers, not as the source of truth. If your endpoint is down for an hour, nothing is lost: the notes list endpoint has date-range filters, and reconciling from it is the supported recovery path.

    Configure the receiving URL on the Webhooks page of the partner console. Each environment has its own URL — a staging event never reaches a production endpoint.

    Events

    EventFires
    note.startedA recording starts. Also fires for text-to-note and uploaded recordings — anything that creates a note.
    note.recording_pausedRecording stopped without the note being ended. Carries pauseReason — see below.
    note.recording_resumedRecording started again on a note that was paused. Only ever follows a note.recording_paused.
    note.recording_endedThe provider ended the session. The note's status becomes processing at this moment — see below.
    note.generated_successfullyThe note is generated. First success only; later regenerations arrive as note.edited.
    note.editedSaved note content changed after generation — a manual edit by the provider or an LLM regeneration. Debounced 10s per note.
    note.failedProcessing failed terminally. No note text will arrive for it.
    note.deletedThe provider deleted the note.
    link.revokedA link ended, from any of the three directions. Your API access to that provider is already gone when this arrives.

    Note events fire for every note a linked provider records — including notes for their own patients that have nothing to do with your system, and notes recorded before they linked.

    One consequence worth handling: events cover every note, but the notes endpoints serve only notes made with current templates (see Concepts & identifiers). A note made with one of Twofold's retired static templates would therefore announce itself and then answer 404 / note_not_found when you fetch it. It should not happen for a provider working in your product — but treat a note_not_found on a noteId you got from a webhook as "skip this one", not as an outage.

    The payload, once opened:

    json
    {
      "id": "evt_ab12Cd34Ef56",
      "type": "note.generated_successfully",
      "occurredAt": "2026-08-05T12:34:56.789Z",
      "data": {
        "externalUserId": "provider-1042",
        "noteId": "note-id-as-returned-by-the-api",
        "noteExternalId": "appointment-9",
        "patientExternalId": "client-2048"
      }
    }
    json
    {
      "id": "evt_ab12Cd34Ef56",
      "type": "note.generated_successfully",
      "occurredAt": "2026-08-05T12:34:56.789Z",
      "data": {
        "externalUserId": "provider-1042",
        "noteId": "note-id-as-returned-by-the-api",
        "noteExternalId": "appointment-9",
        "patientExternalId": "client-2048"
      }
    }

    noteExternalId and patientExternalId are null when the note has none — a recording started from inside Twofold rather than from your launch URL, or one with no patient selected. note.recording_paused adds one field to that same data: "pauseReason", either user or platform. link.revoked carries a different data: { "externalUserId": "provider-1042", "revocationReason": "user" }.

    Pauses

    A provider recording a session can stop and start again several times before the note is ended, and the two recording events let you show that rather than a session that appears to have stalled.

    pauseReasonWhat happened
    userThe provider chose to stop — they paused, switched microphone, or moved to recording a different session.
    platformThe microphone was taken away — the device interrupted the recording, or the input stream ended.

    Three things to build against:

    • A pause is not an ending. Neither event changes the note or its content, and a paused note still produces note.generated_successfully once the provider ends it. Nothing needs to be re-fetched when one arrives.
    • A resume always follows a pause, but a pause does not always get a resume. The provider may end the note from the paused state, or leave it and come back another day. Treat an unmatched note.recording_paused as "not recording right now", not as an error state to clean up.
    • Do not count pauses to measure anything. A microphone switch is one pause and one resume; so is a phone call arriving mid-session. What they mark is that recording stopped and started, not how long the session was or how many segments it has.

    The end of a recording

    note.recording_ended fills the gap between note.started and note.generated_successfully. Before it, the provider is still in the session; after it, they have finished and Twofold is transcribing and generating. Without it there was no way to tell those two apart, and a session that had ended half an hour ago still looked like it was recording.

    It is the same moment the note's status becomes processing, so an interface that shows recording state can move on this event alone and fetch when the note is generated.

    What it does and does not promise:

    • At most one per note, never two. A provider who pauses several times and then ends still gets a single note.recording_ended — ending from a paused state is an ending like any other. As with every event on this page, treat a missing one as a gap to reconcile from the notes list rather than something that cannot happen.
    • A note can be generated without one. A note typed rather than recorded has no session to end, so it goes note.started → note.generated_successfully. Do not wait for a recording to end before expecting a note.
    • An uploaded recording announces when the upload is accepted, not when the file was chosen. The event marks Twofold taking the recording, and for an upload that is the end of the transfer. recordingDurationSeconds can still be null on an uploaded note fetched the instant the event lands; it is populated a moment later.
    • It is not a promise of a note. Generation can still fail, and that arrives as note.failed.

    Sealed payloads

    The request body is not JSON. It is a JWE compact string (alg: dir, enc: A256GCM) sent with Content-Type: application/jose, which yields the JSON payload only after you decrypt it with a key fetched from Twofold. Verification cannot be skipped by accident: an unopened body is unreadable, and AES-GCM is authenticated encryption — a body that opens cleanly was produced by Twofold.

    Each delivery carries:

    Header
    Twofold-Key-IdWhich key sealed this body. Also present as kid in the JWE protected header.
    Twofold-Event-IdThe event's id, so you can dedupe without opening the body.

    The keys endpoint

    bash
    curl https://partner-api.trytwofold.com/v2/partner/webhook-keys \
      -H "Authorization: Bearer twofold_key_prod_xxxxxxxxxxxx" \
      -H "Twofold-Client-Id: prtn_ab12Cd34Ef56"
    bash
    curl https://partner-api.staging.trytwofold.com/v2/partner/webhook-keys \
      -H "Authorization: Bearer twofold_key_staging_xxxxxxxxxxxx" \
      -H "Twofold-Client-Id: prtn_ab12Cd34Ef56"
    json
    {
      "keys": {
        "latest": {
          "keyId": "019860ab-1c2d-7e3f-8a9b-0c1d2e3f4a5b",
          "key": "9c0Yy1t9y2c1V0kFQ0m0dQ4b6a1nJm2Cq8Ib2Xy7cQ0"
        },
        "previous": {
          "keyId": "019860a1-8b7c-7d6e-9f01-2a3b4c5d6e7f",
          "key": "Xk3pQ7r2Tv8Nw1Zy4Bc6Df9Gh0Jk2Lm5Np8Qr1St4U"
        }
      }
    }
    json
    {
      "keys": {
        "latest": {
          "keyId": "019860ab-1c2d-7e3f-8a9b-0c1d2e3f4a5b",
          "key": "9c0Yy1t9y2c1V0kFQ0m0dQ4b6a1nJm2Cq8Ib2Xy7cQ0"
        },
        "previous": {
          "keyId": "019860a1-8b7c-7d6e-9f01-2a3b4c5d6e7f",
          "key": "Xk3pQ7r2Tv8Nw1Zy4Bc6Df9Gh0Jk2Lm5Np8Qr1St4U"
        }
      }
    }

    Two named slots, not a lookup map: latest is what Twofold is sealing with right now, previous is the one from before the last rotation. Match the delivery's Twofold-Key-Id against each slot's keyId and decrypt with that slot's key. Both can be null — latest only before your first key has ever been minted, previous until the first rotation — so treat "no slot matches" as "re-fetch", never as "reject silently".

    ⚠️ Keys rotate every 10 minutes. The endpoint always serves the current and the previous key, which gives any single key an acceptance window of roughly 20 minutes. Cache the response for a few minutes, and refetch whenever a delivery arrives with a Twofold-Key-Id you do not hold. Never pin a key in configuration, and never write one to a log.

    Keys are per partner and per environment: your keys open only your events.

    Note what that authenticity actually rests on: the sealing key is symmetric and is fetched with your API key, so "this body opened cleanly" means "produced by someone holding your API key" — Twofold, or anyone who has your key. Guard the API key accordingly, and treat a webhook as a trigger to fetch rather than as data you trust unverified.

    Opening a payload

    Read Twofold-Key-Id, look up that key, decrypt the raw request body — make sure your framework hands you the body as text and does not try to JSON-parse it first. The sample below follows the language picked in the sidebar.

    ts
    import { compactDecrypt } from "jose";
    
    // Cache the pair for a couple of minutes; refetch when a delivery names a key you don't hold
    let cachedKeys: { latest: TwofoldKey | null; previous: TwofoldKey | null } | null = null;
    
    function findKey(keys: typeof cachedKeys, keyId: string): Buffer | null {
      const match = [keys?.latest, keys?.previous].find((slot) => slot?.keyId === keyId);
      return match ? Buffer.from(match.key, "base64url") : null;
    }
    
    async function keyFor(keyId: string): Promise<Buffer> {
      const cached = findKey(cachedKeys, keyId);
      if (cached) {
        return cached;
      }
    
      // An unknown key id is the only thing that should cost a request
      cachedKeys = await fetchTwofoldWebhookKeys();
    
      const refetched = findKey(cachedKeys, keyId);
      if (refetched) {
        return refetched;
      }
    
      throw new Error(`Twofold webhook key ${keyId} is not being served`);
    }
    
    // The body must be the raw string, not a parsed object
    export async function handleTwofoldWebhook(rawBody: string, headers: Record<string, string>) {
      const { plaintext } = await compactDecrypt(rawBody, await keyFor(headers["twofold-key-id"]));
      const event = JSON.parse(new TextDecoder().decode(plaintext));
    
      // Respond 2xx first, do the work afterwards
      await enqueue(event);
    }
    ts
    import { compactDecrypt } from "jose";
    
    // Cache the pair for a couple of minutes; refetch when a delivery names a key you don't hold
    let cachedKeys: { latest: TwofoldKey | null; previous: TwofoldKey | null } | null = null;
    
    function findKey(keys: typeof cachedKeys, keyId: string): Buffer | null {
      const match = [keys?.latest, keys?.previous].find((slot) => slot?.keyId === keyId);
      return match ? Buffer.from(match.key, "base64url") : null;
    }
    
    async function keyFor(keyId: string): Promise<Buffer> {
      const cached = findKey(cachedKeys, keyId);
      if (cached) {
        return cached;
      }
    
      // An unknown key id is the only thing that should cost a request
      cachedKeys = await fetchTwofoldWebhookKeys();
    
      const refetched = findKey(cachedKeys, keyId);
      if (refetched) {
        return refetched;
      }
    
      throw new Error(`Twofold webhook key ${keyId} is not being served`);
    }
    
    // The body must be the raw string, not a parsed object
    export async function handleTwofoldWebhook(rawBody: string, headers: Record<string, string>) {
      const { plaintext } = await compactDecrypt(rawBody, await keyFor(headers["twofold-key-id"]));
      const event = JSON.parse(new TextDecoder().decode(plaintext));
    
      // Respond 2xx first, do the work afterwards
      await enqueue(event);
    }
    python
    import json
    from jwcrypto import jwe, jwk
    
    def handle_twofold_webhook(raw_body: str, headers: dict) -> dict:
        key_id = headers["twofold-key-id"]
    
        # {"keys": {"latest": {...} | None, "previous": {...} | None}} — match on keyId.
        # Fetched per delivery to keep the sample short; cache the pair and refetch on a miss, as the TypeScript sample does.
        slots = fetch_twofold_webhook_keys()["keys"]
        match = next((s for s in (slots["latest"], slots["previous"]) if s and s["keyId"] == key_id), None)
        if match is None:
            raise ValueError(f"Twofold webhook key {key_id} is not being served")
    
        # The key is already base64url — exactly the encoding a JWK "oct" key uses
        key = jwk.JWK(kty="oct", k=match["key"])
    
        token = jwe.JWE()
        token.deserialize(raw_body, key=key)
    
        return json.loads(token.payload)
    python
    import json
    from jwcrypto import jwe, jwk
    
    def handle_twofold_webhook(raw_body: str, headers: dict) -> dict:
        key_id = headers["twofold-key-id"]
    
        # {"keys": {"latest": {...} | None, "previous": {...} | None}} — match on keyId.
        # Fetched per delivery to keep the sample short; cache the pair and refetch on a miss, as the TypeScript sample does.
        slots = fetch_twofold_webhook_keys()["keys"]
        match = next((s for s in (slots["latest"], slots["previous"]) if s and s["keyId"] == key_id), None)
        if match is None:
            raise ValueError(f"Twofold webhook key {key_id} is not being served")
    
        # The key is already base64url — exactly the encoding a JWK "oct" key uses
        key = jwk.JWK(kty="oct", k=match["key"])
    
        token = jwe.JWE()
        token.deserialize(raw_body, key=key)
    
        return json.loads(token.payload)
    go
    import (
        "encoding/base64"
        "encoding/json"
    
        "github.com/go-jose/go-jose/v4"
    )
    
    func HandleTwofoldWebhook(rawBody string, keyID string) (map[string]any, error) {
        // Returns the key whose KeyId equals keyID, from the latest/previous pair — refetching on a miss
        keyB64, err := TwofoldWebhookKeyFor(keyID)
        if err != nil {
            return nil, err
        }
    
        key, err := base64.RawURLEncoding.DecodeString(keyB64)
        if err != nil {
            return nil, err
        }
    
        object, err := jose.ParseEncrypted(
            rawBody,
            []jose.KeyAlgorithm{jose.DIRECT},
            []jose.ContentEncryption{jose.A256GCM},
        )
        if err != nil {
            return nil, err
        }
    
        payload, err := object.Decrypt(key)
        if err != nil {
            return nil, err
        }
    
        var event map[string]any
        return event, json.Unmarshal(payload, &event)
    }
    go
    import (
        "encoding/base64"
        "encoding/json"
    
        "github.com/go-jose/go-jose/v4"
    )
    
    func HandleTwofoldWebhook(rawBody string, keyID string) (map[string]any, error) {
        // Returns the key whose KeyId equals keyID, from the latest/previous pair — refetching on a miss
        keyB64, err := TwofoldWebhookKeyFor(keyID)
        if err != nil {
            return nil, err
        }
    
        key, err := base64.RawURLEncoding.DecodeString(keyB64)
        if err != nil {
            return nil, err
        }
    
        object, err := jose.ParseEncrypted(
            rawBody,
            []jose.KeyAlgorithm{jose.DIRECT},
            []jose.ContentEncryption{jose.A256GCM},
        )
        if err != nil {
            return nil, err
        }
    
        payload, err := object.Decrypt(key)
        if err != nil {
            return nil, err
        }
    
        var event map[string]any
        return event, json.Unmarshal(payload, &event)
    }

    Any JOSE library that supports JWE with dir + A256GCM works — jose (Node), jwcrypto, Authlib or joserfc (Python), go-jose (Go), Nimbus JOSE+JWT (Java), web-token (PHP), json-jwt (Ruby).

    A body that fails to decrypt must be rejected. That is the whole point of sealing: if it will not open with a key from your keys endpoint, it did not come from Twofold, and no part of it should be trusted or logged as an event.

    Delivery semantics

    • Respond 2xx quickly. A delivery times out after 20 seconds. Acknowledge first, process asynchronously.
    • Answer at the URL you registered — redirects are not followed. A 3xx is treated as a failed delivery, not as a hop to follow, so a receiver that redirects (http→https, a trailing-slash rewrite, a load balancer sending you elsewhere) never receives its events. Register the final URL. Your endpoint must also resolve to a public address; Twofold will not deliver to a private or loopback one, which is why local testing goes through a tunnel rather than a localhost URL. An address that is plainly unreachable is refused when you save it, but a hostname is only checked when we connect — so a name that resolves privately saves cleanly and then fails on delivery, with the reason on the deliveries page.
    • Retries run on a fixed schedule: 1 minute after the first failure, then 2, 4, 8, 16 and 32 minutes, then every 45 minutes — 21 attempts spanning about 12 hours. Anything that is not a 2xx, including a timeout or a connection failure, counts as a failed attempt and is retried. A delivery we can never make — a webhook URL at an address that is not reachable from the public internet — is not retried at all.
    • When you come back up, you wait for the next scheduled attempt, never longer than 45 minutes. There is nothing to call and nothing to replay: fix the receiver and the events arrive on their own.
    • Deduplicate on id. A retried delivery reuses the event id, so a duplicate is a duplicate — and an event may legitimately arrive more than once.
    • No ordering guarantee. note.edited can arrive before the note.generated_successfully it follows. Where order matters, fetch the note and use its state, which is always the current one.
    • Every attempt is re-sealed with whatever key is current at that moment, so a retry never fails because a key expired.
    • Every delivery appears on the Webhook deliveries page of the console — event id and type, the status, how many attempts have failed, when the last attempt was, the HTTP status your endpoint answered and the error we recorded. One row per delivery, not per attempt: attempts are counted rather than listed individually. A delivery we are still retrying reads Retrying, with the reason the last attempt failed; Failed means the retries are spent and we will not try again. It is the first place to look when an event you expected never arrived, and it will usually tell you whether the problem is on our side or yours without anyone opening a ticket. The page shows the last 3 days and is per environment, so a staging receiver is debugged against staging. Older deliveries are not lost, only unlisted — ask your Twofold contact for those.

    Testing your endpoint

    bash
    curl -X POST https://partner-api.trytwofold.com/v2/partner/webhooks/test \
      -H "Authorization: Bearer twofold_key_prod_xxxxxxxxxxxx" \
      -H "Twofold-Client-Id: prtn_ab12Cd34Ef56" \
      -H "Content-Type: application/json" \
      -d '{"type": "note.generated_successfully"}'
    bash
    curl -X POST https://partner-api.staging.trytwofold.com/v2/partner/webhooks/test \
      -H "Authorization: Bearer twofold_key_staging_xxxxxxxxxxxx" \
      -H "Twofold-Client-Id: prtn_ab12Cd34Ef56" \
      -H "Content-Type: application/json" \
      -d '{"type": "note.generated_successfully"}'

    This fires a synthetic, fully sealed event of that type at your configured URL, so you can exercise the whole receiver — including the key fetch and the decrypt — before a real recording exists. The identifiers in a test event are synthetic; do not try to fetch the note it names.

    A test fire is a single attempt and is never retried — unlike a real event — which is what lets the response tell you straight away whether your endpoint accepted it and with what status. It is still recorded on the deliveries page like any other delivery.

    Two checks worth running against your receiver before you go live, because they are what a sealed payload is for:

    1. Send it a body sealed with a key you have thrown away (or any random string) — it must reject, not accept.
    2. Send it a plain JSON body shaped like a real event — it must reject that too. Anything that accepts unsealed JSON has skipped verification entirely.