One Webhook per Subaccount

Register a webhook for each subaccount as soon as you create it, save its secret, and keep exactly one webhook at your URL however often the code runs.

For: developers

Give each subaccount its own webhook, at a URL with the subaccount id in its path, so your receiver (recipe 1) knows which secret to check a delivery with. Run this right after you create a subaccount (recipe 3) and before any card is enrolled on it: an event that happens while a subaccount has no webhook is not delivered later.

Astrada returns a webhook's secret only once, in the answer to the create, so the code saves it straight away.

Before you start

  • Scopes: webhooks:read and webhooks:write.
  • Your receiver's public https address, such as https://hooks.northwind.example.
  • A place to keep each subaccount's webhook id and secret, such as a table next to your subaccounts. The secret is a credential: never log it.
  • Sandbox or production.

The code

Running it again is safe. Each run:

  • keeps the webhook whose secret you hold, and updates its event types if your list changed;
  • makes a new webhook when you hold no secret, for example when a crash came between the create and the save;
  • deletes any other webhook at the same URL, because it signs with a secret you do not hold and your receiver would answer its deliveries with 400;
  • leaves the subaccount's webhooks at other URLs alone.

Add the event types you handle to the list at the top. The worker in recipe 1 logs the ones it has no step for.

/** The events this app wants. Add the ones you handle; the worker in recipe 1 logs the rest. */
export const EVENT_TYPES: WebhookEventTypes = [
  'cardsubscription.created',
  'cardsubscription.updated',
  'transaction.created',
  'transaction.updated',
];

/** Where you keep each subaccount's webhook id and secret (a table in your database). */
export interface WebhookRegistrations {
  get(subaccountId: string): Promise<{ webhookId: string; secret: string } | undefined>;
  save(subaccountId: string, registration: { webhookId: string; secret: string }): Promise<void>;
}

/** The URL of a subaccount's webhook: recipe 1 reads the subaccount id back from the path. */
export function webhookUrlFor(receiverBaseUrl: string, subaccountId: string): string {
  return `${receiverBaseUrl.replace(/\/+$/, '')}/astrada/webhooks/${encodeURIComponent(subaccountId)}`;
}

function sameEventTypes(a: readonly string[], b: readonly string[]): boolean {
  return a.length === b.length && [...a].sort().join() === [...b].sort().join();
}

/** What ensureWebhook did. */
export interface EnsureWebhookResult {
  webhookId: string;
  created: boolean;
  updated: boolean;
  deleted: string[];
}
EVENT_TYPES: List[str] = [
    "cardsubscription.created",
    "cardsubscription.updated",
    "transaction.created",
    "transaction.updated",
]
"""The events this app wants. Add the ones you handle; the worker in recipe 1 logs the rest."""


@dataclass
class Registration:
    webhook_id: str
    secret: str


class WebhookRegistrations(Protocol):
    """Where you keep each subaccount's webhook id and secret (a table in your database)."""

    def get(self, subaccount_id: str) -> Optional[Registration]: ...

    def save(self, subaccount_id: str, registration: Registration) -> None: ...


def webhook_url_for(receiver_base_url: str, subaccount_id: str) -> str:
    """The URL of a subaccount's webhook: recipe 1 reads the subaccount id back from the path."""
    return "%s/astrada/webhooks/%s" % (receiver_base_url.rstrip("/"), quote(subaccount_id, safe=""))


@dataclass
class EnsureWebhookResult:
    """What ensure_webhook did."""

    webhook_id: str = ""
    created: bool = False
    updated: bool = False
    deleted: List[str] = field(default_factory=list)
/** The events this app wants. Add the ones you handle; the worker in recipe 1 logs the rest. */
public static final List<String> EVENT_TYPES = Collections.unmodifiableList(Arrays.asList(
        "cardsubscription.created",
        "cardsubscription.updated",
        "transaction.created",
        "transaction.updated"));

/** A subaccount's webhook id and secret. */
public static final class Registration {
    public final UUID webhookId;
    public final String secret;

    public Registration(UUID webhookId, String secret) {
        this.webhookId = webhookId;
        this.secret = secret;
    }
}

/** Where you keep each subaccount's webhook id and secret (a table in your database). */
public interface WebhookRegistrations {
    Registration get(UUID subaccountId);

    void save(UUID subaccountId, Registration registration);
}

/** The URL of a subaccount's webhook: recipe 1 reads the subaccount id back from the path. */
public static String webhookUrlFor(String receiverBaseUrl, UUID subaccountId) {
    return receiverBaseUrl.replaceAll("/+$", "") + "/astrada/webhooks/"
            + URLEncoder.encode(subaccountId.toString(), StandardCharsets.UTF_8);
}

/** What ensureWebhook did. */
public static final class EnsureWebhookResult {
    public UUID webhookId;
    public boolean created;
    public boolean updated;
    public final List<UUID> deleted = new ArrayList<>();
}

The function that makes or fixes the subaccount's webhook, using those:

/** Makes sure the subaccount has exactly one webhook at your URL, and that you hold its secret. */
export async function ensureWebhook(
  astrada: Astrada,
  registrations: WebhookRegistrations,
  subaccountId: string,
  receiverBaseUrl: string,
  eventTypes: WebhookEventTypes = EVENT_TYPES,
): Promise<EnsureWebhookResult> {
  const url = webhookUrlFor(receiverBaseUrl, subaccountId);
  const saved = await registrations.get(subaccountId);

  // Every webhook of this subaccount at your URL, across all pages.
  const atOurUrl: Webhook[] = [];
  for await (const webhook of astrada.webhooks.listAll({ subaccountId })) {
    if (webhook.url === url) atOurUrl.push(webhook);
  }

  const result: EnsureWebhookResult = { webhookId: '', created: false, updated: false, deleted: [] };
  const kept = saved === undefined ? undefined : atOurUrl.find((webhook) => webhook.id === saved.webhookId);
  if (kept === undefined) {
    // No webhook whose secret you hold: make one, and save its secret before anything else.
    // The SDK retries this create under one Idempotency-Key, so a lost answer does not make two.
    const created = await astrada.webhooks.create({
      url,
      subaccountId,
      eventTypes,
      enabled: true,
      description: 'Northwind Travel receiver',
    });
    await registrations.save(subaccountId, { webhookId: created.id, secret: created.secret });
    result.webhookId = created.id;
    result.created = true;
  } else {
    result.webhookId = kept.id;
    if (!sameEventTypes(kept.eventTypes, eventTypes)) {
      await astrada.webhooks.update(kept.id, { eventTypes });
      result.updated = true;
    }
  }

  // Any other webhook at your URL signs with a secret you do not hold, so recipe 1 would answer
  // its deliveries with 400. Delete it, after the one you keep exists.
  for (const webhook of atOurUrl) {
    if (webhook.id !== result.webhookId) {
      await astrada.webhooks.delete(webhook.id);
      result.deleted.push(webhook.id);
    }
  }
  return result;
}
def ensure_webhook(
    client: astrada.Astrada,
    registrations: WebhookRegistrations,
    subaccount_id: str,
    receiver_base_url: str,
    event_types: Optional[List[str]] = None,
) -> EnsureWebhookResult:
    """Makes sure the subaccount has exactly one webhook at your URL, and that you hold its secret."""
    wanted = list(event_types or EVENT_TYPES)
    url = webhook_url_for(receiver_base_url, subaccount_id)
    saved = registrations.get(subaccount_id)

    # Every webhook of this subaccount at your URL, across all pages.
    at_our_url = [webhook for webhook in client.webhooks.list_all(subaccount_id=subaccount_id)
                  if webhook.url == url]

    result = EnsureWebhookResult()
    kept = next((webhook for webhook in at_our_url
                 if saved is not None and str(webhook.id) == saved.webhook_id), None)
    if kept is None:
        # No webhook whose secret you hold: make one, and save its secret before anything else.
        # The SDK retries this create under one Idempotency-Key, so a lost answer does not make two.
        created = client.webhooks.create({
            "url": url,
            "subaccountId": subaccount_id,
            "eventTypes": wanted,
            "enabled": True,
            "description": "Northwind Travel receiver",
        })
        registrations.save(subaccount_id, Registration(str(created.id), created.secret))
        result.webhook_id = str(created.id)
        result.created = True
    else:
        result.webhook_id = str(kept.id)
        if sorted(kept.event_types) != sorted(wanted):
            client.webhooks.update(kept.id, {"eventTypes": wanted})
            result.updated = True

    # Any other webhook at your URL signs with a secret you do not hold, so recipe 1 would answer
    # its deliveries with 400. Delete it, after the one you keep exists.
    for webhook in at_our_url:
        if str(webhook.id) != result.webhook_id:
            client.webhooks.delete(webhook.id)
            result.deleted.append(str(webhook.id))
    return result
/** Makes sure the subaccount has exactly one webhook at your URL, and that you hold its secret. */
public static EnsureWebhookResult ensureWebhook(ApiClient client, WebhookRegistrations registrations, UUID subaccountId,
        String receiverBaseUrl, List<String> eventTypes) {
    String url = webhookUrlFor(receiverBaseUrl, subaccountId);
    Registration saved = registrations.get(subaccountId);

    // Every webhook of this subaccount at your URL, across all pages.
    List<Webhook> atOurUrl = new ArrayList<>();
    for (Webhook webhook : client.webhooks().listAll(ListWebhooksRequest.builder().subaccountId(subaccountId).build())) {
        if (url.equals(String.valueOf(webhook.getUrl()))) {
            atOurUrl.add(webhook);
        }
    }

    EnsureWebhookResult result = new EnsureWebhookResult();
    Webhook kept = null;
    for (Webhook webhook : atOurUrl) {
        if (saved != null && webhook.getId().equals(saved.webhookId)) {
            kept = webhook;
        }
    }
    if (kept == null) {
        // No webhook whose secret you hold: make one, and save its secret before anything else.
        // The SDK retries this create under one Idempotency-Key, so a lost answer does not make two.
        WebhookCreateResult created = client.webhooks().create(new WebhookCreateParams()
                .url(URI.create(url))
                .subaccountId(subaccountId)
                .eventTypes(eventTypes.stream().map(WebhookCreateParams.EventTypesEnum::fromValue).collect(Collectors.toList()))
                .enabled(true)
                .description("Northwind Travel receiver"));
        registrations.save(subaccountId, new Registration(created.getId(), created.getSecret()));
        result.webhookId = created.getId();
        result.created = true;
    } else {
        result.webhookId = kept.getId();
        // The raw values keep event types newer than this SDK as sent, so they compare too.
        List<String> raw = kept.getEventTypesRawValues();
        List<String> current = (raw == null ? List.<String>of() : raw).stream().sorted().collect(Collectors.toList());
        if (!current.equals(eventTypes.stream().sorted().collect(Collectors.toList()))) {
            client.webhooks().update(kept.getId(), new WebhookUpdateParams()
                    .eventTypes(eventTypes.stream().map(WebhookUpdateParams.EventTypesEnum::fromValue).collect(Collectors.toList())));
            result.updated = true;
        }
    }

    // Any other webhook at your URL signs with a secret you do not hold, so recipe 1 would answer
    // its deliveries with 400. Delete it, after the one you keep exists.
    for (Webhook webhook : atOurUrl) {
        if (!webhook.getId().equals(result.webhookId)) {
            client.webhooks().delete(webhook.getId());
            result.deleted.add(webhook.getId());
        }
    }
    return result;
}

Whole example files: TypeScript, Python, Java.

What to expect

  • The first run creates one webhook and saves its id and secret. A second run with the same event types changes nothing.
  • The SDK retries the create under one Idempotency-Key, so an answer lost on the way back does not make a second webhook.
  • The list call reads every webhook of the subaccount, across all pages.

Read more


Did this page help you?