Receive Webhooks

An endpoint that checks each webhook delivery came from Astrada, records it once, queues it and answers straight away, with a worker that does the work after.

For: developers

Astrada sends each event to your webhook's URL, signed with that webhook's secret. This recipe is the endpoint that takes those deliveries. It checks each one came from Astrada, records it once by its event id, puts it on your queue and answers 204 straight away. A worker takes the events off the queue and does the work after the answer.

Before you start

  • A webhook for each subaccount, with its secret saved: One webhook per subaccount (recipe 2). Each webhook's URL ends in its subaccount id (/astrada/webhooks/<subaccountId>), so the path tells the receiver which secret to check with.
  • No scope: receiving a delivery makes no API call.
  • Sandbox or production. A delivery does not say which environment sent it; the secret it was signed with does, so use the secrets of the environment you registered in.

The code

What the receiver needs from your app

The receiver keeps no state of its own. It asks your app for the secret of a subaccount's webhook, a way to record an event id once and to forget it again, your queue, and a place to keep deliveries it could not read. Recording an id must be one atomic step, such as a unique key in a table or Redis SET NX.

/** One verified event, as it waits on your queue. */
export interface WebhookJob {
  subaccountId: string;
  event: AstradaWebhookEvent;
}

/** A delivery signed by Astrada that the SDK could not read. Kept for a person to look at. */
export interface KeptDelivery {
  subaccountId: string;
  body: string;
  headers: IncomingHttpHeaders;
  reason: string;
}
@dataclass
class WebhookJob:
    """One verified event, as it waits on your queue."""

    subaccount_id: str
    event: "astrada.WebhookEvent[Any]"


@dataclass
class KeptDelivery:
    """A delivery signed by Astrada that the SDK could not read. Kept for a person to look at."""

    subaccount_id: str
    body: bytes
    headers: Dict[str, str]
    reason: str
/** One verified event, as it waits on your queue. */
public static final class WebhookJob {
    public final String subaccountId;
    public final WebhookEvent event;

    public WebhookJob(String subaccountId, WebhookEvent event) {
        this.subaccountId = subaccountId;
        this.event = event;
    }
}

/** A delivery signed by Astrada that the SDK could not read. Kept for a person to look at. */
public static final class KeptDelivery {
    public final String subaccountId;
    public final byte[] body;
    public final Map<String, String> headers;
    public final String reason;

    public KeptDelivery(String subaccountId, byte[] body, Map<String, String> headers, String reason) {
        this.subaccountId = subaccountId;
        this.body = body;
        this.headers = headers;
        this.reason = reason;
    }
}

The receiver reads and writes through this interface, which your app implements:

/** What the receiver needs from your app. Replace each with your database, cache or queue. */
export interface ReceiverStores {
  /** The secret of the webhook you registered for this subaccount (recipe 2 saves it). */
  secretFor(subaccountId: string): Promise<string | undefined>;
  /** Whether this delivery id was recorded before (by `remember`). */
  seen(deliveryId: string): Promise<boolean>;
  /**
   * Records a delivery id, after its event is on your queue. Keep ids for 2 days: Astrada stops
   * retrying a delivery a little over a day after the first attempt.
   */
  remember(deliveryId: string): Promise<void>;
  /** Puts a verified event on your queue. */
  enqueue(job: WebhookJob): Promise<void>;
  /** Keeps a signed delivery the SDK could not read. */
  keep(kept: KeptDelivery): Promise<void>;
}
class ReceiverStores(Protocol):
    """What the receiver needs from your app. Replace each with your database, cache or queue."""

    def secret_for(self, subaccount_id: str) -> Optional[str]:
        """The secret of the webhook you registered for this subaccount (recipe 2 saves it)."""

    def seen(self, delivery_id: str) -> bool:
        """Whether this delivery id was recorded before (by remember)."""

    def remember(self, delivery_id: str) -> None:
        """Records a delivery id, after its event is on your queue. Keep ids for 2 days: Astrada
        stops retrying a delivery a little over a day after the first attempt."""

    def enqueue(self, job: WebhookJob) -> None:
        """Puts a verified event on your queue."""

    def keep(self, kept: KeptDelivery) -> None:
        """Keeps a signed delivery the SDK could not read."""
/** What the receiver needs from your app. Replace each with your database, cache or queue. */
public interface ReceiverStores {
    /** The secret of the webhook you registered for this subaccount (recipe 2 saves it), or null. */
    String secretFor(String subaccountId);

    /** Whether this delivery id was recorded before (by {@code remember}). */
    boolean seen(String deliveryId);

    /**
     * Records a delivery id, after its event is on your queue. Keep ids for 2 days: Astrada stops
     * retrying a delivery a little over a day after the first attempt.
     */
    void remember(String deliveryId);

    /** Puts a verified event on your queue. */
    void enqueue(WebhookJob job);

    /** Keeps a signed delivery the SDK could not read. */
    void keep(KeptDelivery kept);
}

Check and answer each delivery

The signature is checked on the raw bytes of the body, before anything parses them. So mount the route where no JSON body parser runs first: in Express, express.raw({ type: 'application/json' }) on this route; in FastAPI or Starlette, await request.body(); in Spring, a byte[] request body. Pass the subaccount id from the last part of the path. What the receiver answers, and why:

The delivery, and the answerWhy
404: no secret saved for that subaccountNot a webhook you registered, or the secret is missing from your store. Astrada sends it again later, after you fix the store
204, after keeping a copy: signed by Astrada, but the SDK cannot read the bodyA retry would send the same bytes, so keep it for a person to look at
400: bad or missing signature, or a timestamp more than five minutes from your server's clockIt cannot be trusted
204: an event id you have already queuedA retried delivery keeps its event id
500: your store or queue failedAstrada sends it again
204, once it is on your queue: anything elseThe work happens after the answer
/**
 * Checks one delivery and returns the status to answer with. Rejects when the delivery should be
 * sent again (your store or queue failed): answer 500 then.
 */
export async function receiveDelivery(
  astrada: Astrada,
  stores: ReceiverStores,
  subaccountId: string,
  body: Buffer,
  headers: IncomingHttpHeaders,
): Promise<number> {
  const secret = await stores.secretFor(subaccountId);
  if (secret === undefined) {
    // Not a webhook you registered (or its secret is missing from your store). Any answer outside
    // 2xx makes Astrada send a real delivery again later, after you fix the store.
    return 404;
  }

  let event: AstradaWebhookEvent;
  try {
    // The signature is checked on the raw bytes, before anything parses them.
    event = astrada.webhooks.verify(body, headers, secret);
  } catch (error) {
    if (error instanceof WebhookEventTypeMismatchError || error instanceof WebhookPayloadError) {
      // Signed by Astrada, but its body does not fit its type, or is not JSON. A retry would send
      // the same bytes, so keep it and answer 2xx. After the 2xx Astrada will not send it again:
      // if keeping it fails, this rejects and the delivery gets a 500 instead.
      await stores.keep({ subaccountId, body: body.toString('utf8'), headers, reason: error.message });
      return 204;
    }
    if (error instanceof WebhookVerificationError) {
      // Cannot be trusted: a bad or missing signature, or a timestamp outside five minutes.
      return 400;
    }
    throw error;
  }

  // A delivery that is retried keeps its id. Skip one you have already queued.
  if (await stores.seen(event.id)) {
    return 204;
  }
  // Queue first, then record the id. A crash between the two queues the retry again: an
  // occasional duplicate job, which the worker handles (each write is safe to repeat). The other
  // order would lose the event: the retry would find the id recorded and be skipped. To have no
  // duplicates at all, record the id and the job in one database transaction (an outbox).
  // If either step throws, the delivery gets a 500 and Astrada sends it again.
  await stores.enqueue({ subaccountId, event });
  await stores.remember(event.id);
  // Answer now. The work happens in the worker, after this answer.
  return 204;
}
def receive_delivery(
    stores: ReceiverStores, subaccount_id: str, body: bytes, headers: Mapping[str, str]
) -> int:
    """Checks one delivery and returns the status to answer with. Raises when the delivery should
    be sent again (your store or queue failed): answer 500 then."""
    secret = stores.secret_for(subaccount_id)
    if secret is None:
        # Not a webhook you registered (or its secret is missing from your store). Any answer
        # outside 2xx makes Astrada send a real delivery again later, after you fix the store.
        return 404

    plain_headers = {name.lower(): value for name, value in headers.items()}
    try:
        # The signature is checked on the raw bytes, before anything parses them.
        event = astrada.verify_webhook(body, plain_headers, secret)
    except astrada.WebhookEventTypeMismatchError as mismatch:
        # Signed by Astrada, but its body does not fit its type. A retry would send the same
        # bytes, so keep it and answer 2xx. After the 2xx Astrada will not send it again: if
        # keeping it fails, this raises and the delivery gets a 500 instead.
        stores.keep(KeptDelivery(subaccount_id, body, plain_headers, str(mismatch)))
        return 204
    except astrada.WebhookNotJsonError as not_json:
        # Signed by Astrada, but the body is not JSON. Also a WebhookVerificationError, so it is
        # caught first. A retry would send the same bytes: keep it and answer 2xx, as above.
        stores.keep(KeptDelivery(subaccount_id, body, plain_headers, str(not_json)))
        return 204
    except astrada.WebhookVerificationError:
        # Cannot be trusted: a bad or missing signature, or a timestamp outside five minutes.
        return 400
    if event.unreadable:
        # Signed by Astrada, but this SDK cannot read the body (often an SDK older than the
        # event). Keep it, as above, and answer 2xx.
        reason = "unreadable at %s: %s" % (event.unreadable_field, event.unreadable_problem)
        stores.keep(KeptDelivery(subaccount_id, body, plain_headers, reason))
        return 204

    # A delivery that is retried keeps its id. Skip one you have already queued.
    if stores.seen(event.id):
        return 204
    # Queue first, then record the id. A crash between the two queues the retry again: an
    # occasional duplicate job, which the worker handles (each write is safe to repeat). The other
    # order would lose the event: the retry would find the id recorded and be skipped. To have no
    # duplicates at all, record the id and the job in one database transaction (an outbox).
    # If either step raises, the delivery gets a 500 and Astrada sends it again.
    stores.enqueue(WebhookJob(subaccount_id, event))
    stores.remember(event.id)
    # Answer now. The work happens in the worker, after this answer.
    return 204
/**
 * Checks one delivery and returns the status to answer with. Throws when the delivery should be
 * sent again (your store or queue failed): answer 500 then.
 */
public static int receiveDelivery(ReceiverStores stores, String subaccountId, byte[] body, Map<String, String> headers) {
    String secret = stores.secretFor(subaccountId);
    if (secret == null) {
        // Not a webhook you registered (or its secret is missing from your store). Any answer
        // outside 2xx makes Astrada send a real delivery again later, after you fix the store.
        return 404;
    }

    WebhookEvent event;
    try {
        // The signature is checked on the raw bytes, before anything parses them.
        event = new WebhookVerifier(secret).verifyAndParse(body, headers);
        // Read the body now, so one this SDK cannot read is kept here, not lost in the worker.
        event.getData();
        event.getTransaction();
    } catch (WebhookVerifier.WebhookEventTypeMismatchException | WebhookEvent.WebhookPayloadException e) {
        // Signed by Astrada, but its body does not fit its type, or is not JSON. A retry would send
        // the same bytes, so keep it and answer 2xx. After the 2xx Astrada will not send it again:
        // if keeping it fails, this throws and the delivery gets a 500 instead.
        stores.keep(new KeptDelivery(subaccountId, body, headers, e.getMessage()));
        return 204;
    } catch (WebhookVerifier.WebhookVerificationException e) {
        // Cannot be trusted: a bad or missing signature, or a timestamp outside five minutes.
        return 400;
    }

    // A delivery that is retried keeps its id. Skip one you have already queued.
    if (stores.seen(event.getId())) {
        return 204;
    }
    // Queue first, then record the id. A crash between the two queues the retry again: an
    // occasional duplicate job, which the worker handles (each write is safe to repeat). The other
    // order would lose the event: the retry would find the id recorded and be skipped. To have no
    // duplicates at all, record the id and the job in one database transaction (an outbox).
    // If either step throws, the delivery gets a 500 and Astrada sends it again.
    stores.enqueue(new WebhookJob(subaccountId, event));
    stores.remember(event.getId());
    // Answer now. The work happens in the worker, after this answer.
    return 204;
}

Do the work after the answer

Events can arrive in any order, and an event can be queued again after a crash, so each write in the worker is safe to repeat. For transactions the worker keeps the newest copy by updatedAt, so an older update that arrives late does not overwrite a newer one. Event types newer than your SDK still arrive; the worker logs them.

/** The newest copy of each transaction your app has seen, by transaction id. */
export type TransactionTable = Map<string, { status: string; amount: number; currency: string; updatedAt: string }>;
TransactionTable = Dict[str, Dict[str, Any]]
"""The newest copy of each transaction your app has seen, by transaction id."""
/** The newest copy of one transaction your app has seen. */
public static final class TransactionRow {
    public final String status;
    public final BigDecimal amount;
    public final String currency;
    public final OffsetDateTime updatedAt;

    TransactionRow(String status, BigDecimal amount, String currency, OffsetDateTime updatedAt) {
        this.status = status;
        this.amount = amount;
        this.currency = currency;
        this.updatedAt = updatedAt;
    }
}

The worker step reads each job and writes it to that table:

/**
 * The worker: does the work for one event, after the delivery was answered. Events can arrive in
 * any order, and an event can be queued again after a crash, so each write here is safe to repeat.
 */
export async function work(job: WebhookJob, transactions: TransactionTable): Promise<void> {
  const { event } = job;
  if (event.type === 'transaction.created' || event.type === 'transaction.updated') {
    // `type` does not narrow `data` here (the list of types stays open for newer ones), so name it.
    const transaction = event.data as TransactionWebhookData;
    const known = transactions.get(transaction.id);
    // Keep the newest copy: an older update that arrives late must not overwrite a newer one.
    if (known && Date.parse(known.updatedAt) >= Date.parse(transaction.updatedAt)) return;
    transactions.set(transaction.id, {
      status: transaction.status,
      amount: transaction.transactionHoldAmount,
      currency: transaction.transactionCurrency,
      updatedAt: transaction.updatedAt,
    });
    return;
  }
  if (event.type === 'cardsubscription.created') {
    console.log('card enrolled on subaccount', job.subaccountId, event.data);
    return;
  }
  // Every other type, including types newer than this SDK: log it, or route it to its own worker.
  console.log('event', event.type, event.id);
}
def work(job: WebhookJob, transactions: TransactionTable) -> None:
    """The worker: does the work for one event, after the delivery was answered. Events can
    arrive in any order, and an event can be queued again after a crash, so each write here is
    safe to repeat."""
    event = job.event
    transaction = event.data
    if event.type in ("transaction.created", "transaction.updated") and isinstance(
            transaction, astrada.Transaction):
        known = transactions.get(str(transaction.id))
        # Keep the newest copy: an older update that arrives late must not overwrite a newer one.
        updated_at: datetime = transaction.updated_at
        if known is not None and known["updated_at"] >= updated_at:
            return
        transactions[str(transaction.id)] = {
            "status": transaction.status,
            "amount": transaction.transaction_hold_amount,
            "currency": transaction.transaction_currency,
            "updated_at": updated_at,
        }
        return
    if event.type == "cardsubscription.created":
        print("card enrolled on subaccount", job.subaccount_id, event.data)
        return
    # Every other type, including types newer than this SDK: log it, or route it to its own worker.
    print("event", event.type, event.id)
/**
 * The worker: does the work for one event, after the delivery was answered. Events can arrive
 * in any order, and an event can be queued again after a crash, so each write here is safe to
 * repeat.
 */
public static void work(WebhookJob job, Map<String, TransactionRow> transactions) {
    WebhookEvent event = job.event;
    String type = event.getType();
    if ("transaction.created".equals(type) || "transaction.updated".equals(type)) {
        Transaction transaction = event.getTransaction();
        String id = transaction.getId().toString();
        TransactionRow known = transactions.get(id);
        // Keep the newest copy: an older update that arrives late must not overwrite a newer one.
        if (known != null && !transaction.getUpdatedAt().isAfter(known.updatedAt)) {
            return;
        }
        transactions.put(id, new TransactionRow(transaction.getStatusRawValue(), transaction.getTransactionHoldAmount(),
                transaction.getTransactionCurrency(), transaction.getUpdatedAt()));
        return;
    }
    if ("cardsubscription.created".equals(type)) {
        System.out.println("card enrolled on subaccount " + job.subaccountId + ": " + event.getCardSubscription().getCardId());
        return;
    }
    // Every other type, including types newer than this SDK: log it, or route it to its own worker.
    System.out.println("event " + type + " " + event.getId());
}

Whole example files: TypeScript, Python, Java.

What to expect

  • Each delivery your webhook receives gets one answer, and an event Astrada sends again is normally not queued again. A crash between queuing a job and recording its id, or two copies arriving at the same moment, can queue one twice, which is why each write in the worker is safe to repeat.
  • Keep event ids for two days. Astrada keeps sending a delivery that gets no 2xx for hours (the retry schedule): in sandbox it came again about 5 seconds, 5 minutes, half an hour and two hours after the attempt before.
  • The demo in the example file runs the receiver with in-memory stores and reads secrets from the file recipe 2's demo writes. In your app, each store is your database or queue.

Read more


Did this page help you?