Skip to main content
Version: Latest
Technical ManualLooking for step-by-step instructions? In the User Manual: Webhooks

Commerce Webhooks

FeatureCrestApps.OrchardCore.Commerce.Webhooks (Commerce Webhooks)
ContractsCrestApps.OrchardCore.Webhooks.Abstractions (publisher, events); event names in CrestApps.OrchardCore.Abstractions, namespace CrestApps.OrchardCore.Commerce.Webhooks
CategoryCommerce
Depends onCommerce, Webhooks

The Commerce Webhooks feature posts commerce events (an order paid, a shipment shipped, stock sold out) as signed JSON to the URLs merchants subscribe. Each event is queued in the same unit of work as the change that raised it, sent once that work is saved, and retried with backoff until the receiver answers with a 2xx status. Every delivery is logged.

The subscriptions, the signing, the delivery outbox and the admin (Configuration > Webhooks) belong to the generic Webhooks building block, which this feature turns on. Commerce Webhooks is the switch the commerce modules gate their events on: Orders, Customers, Inventory and Shipping declare and publish their events in startups behind [RequireFeatures(CommerceConstants.Features.Webhooks)].

Model​

This video shows adding a webhook in the admin:

Both documents live in the Webhooks YesSql collection and are defined in CrestApps.OrchardCore.Webhooks.Core.Models. They keep the YesSql type names Commerce Webhooks first stored them under, so existing subscriptions and deliveries stay readable.

  • WebhookSubscription (WebhookSubscriptionIndex): Name, Url, ProtectedSecret, Events (event names, or * for every event, those added later included), IsEnabled, CreatedUtc and ModifiedUtc. Takes(eventName) says whether an enabled subscription wants an event.
  • WebhookDelivery (WebhookDeliveryIndex): one event for one subscription. EventId (the same for every subscription the event went to), EventName, Payload (the JSON posted, the same on every attempt), Status (Pending, Delivered or Failed), Attempts, NextAttemptUtc, LastStatusCode, LastError (cut to 500 characters), CreatedUtc, LastAttemptUtc and DeliveredUtc.

The secret is made by WebhookDispatcher.NewProtectedSecret(): whsec_ and 24 random bytes in URL-safe base 64, protected with ASP.NET Core Data Protection under the purpose CrestApps.OrchardCore.Commerce.Webhooks.Secret (WebhookStorage.SecretProtectionPurpose; it keeps that value so stored secrets stay readable). The tenant's Data Protection keys must survive restarts and be shared by every node, or the secrets can't be read back.

Publishing an event​

public interface IWebhookPublisher
{
Task PublishAsync(string eventName, object payload, CancellationToken cancellationToken = default);

Task PublishAsync(string eventName, object payload, string eventId, CancellationToken cancellationToken = default);
}

WebhookPublisher sends only events an enabled feature declares, then reads the enabled subscriptions once per scope, and for each one that takes the event creates a pending WebhookDelivery in the current session, with the payload:

{ "id": "evt_...", "event": "order.paid", "createdUtc": "2026-10-19T14:03:22.512Z", "data": { } }

data is serialized with JsonSerializerOptions.Web (camelCase). The event id is evt_ and a new id, unless the caller passes one to PublishAsync(eventName, data, eventId): an event that may be raised twice for the same thing passes a stable id, so receivers drop the repeat. A new delivery's NextAttemptUtc is a minute away (Backoff[0]), so the background task leaves it to the first send. It then adds a ShellScope deferred task that, after the request's work is committed, sends those deliveries in a scope of its own, so a slow receiver never holds up the request. An error while queuing is logged and swallowed: a webhook must never fail the order that raised it.

A module offers an event to the admin's event picker with AddWebhookEvent(name, displayName, group) (or an IWebhookEventProvider) and publishes it from a handler that takes IWebhookPublisher in its constructor. Both are registered in a startup behind [RequireFeatures(CommerceConstants.Features.Webhooks)], so nothing is published, and no publisher is needed, while the feature is off:

[RequireFeatures(CommerceConstants.Features.Webhooks)]
public sealed class WebhooksStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ISubscriptionLifecycleHandler, SubscriptionWebhookHandler>();
services.AddWebhookEvent("subscription.renewed", "Subscription renewed", "Subscriptions");
}
}

// In SubscriptionWebhookHandler, which takes IWebhookPublisher in its constructor:
await _publisher.PublishAsync("subscription.renewed", new { subscription = ToApi(subscription) }, cancellationToken);

Send the commerce API's shapes in data where there is one, so a receiver reads one format.

Events​

CommerceWebhookEvents names the events the commerce modules publish:

EventPublished bydata
order.createdOrders, OrderWebhookEventHandler.CreatedAsync: in a deferred task, once the order is saved and isn't canceled (another handler, such as the stock hold, can still refuse it), with the id evt_order-created_ and the order's idorder (ApiOrder)
order.paidOrders, OrderWebhookEventHandler.PaidAsyncorder
order.canceledOrders, OrderWebhookEventHandler.CanceledAsync, for every OrderCancelReason but Replacedorder, reason (camelCase OrderCancelReason)
order.refundedOrders, OrderWebhookEventHandler.RefundedAsync, once per refundorder, refund (ApiOrderRefund)
customer.createdCustomers, CustomerWebhookHandler (an ICustomerHandler that CustomerStore.CreateAsync runs for every new customer: a guest's order, an account's first customer record, Add customer in the admin and the Customers recipe step), with the id evt_customer-created_ and the customer's idcustomer (ApiCustomer)
shipment.shippedShipping, ShipmentWebhookHandler.ShippedAsyncshipment (ApiShipment), orderNumber, customerEmail
shipment.deliveredShipping, ShipmentWebhookHandler.DeliveredAsyncthe same
stock.changedInventory, StockWebhookHandler.AvailableChangedAsync (an IStockLevelHandler): after the unit of work commits, one event per stock item whose total Available differs from before its first changestock (ApiStockItem), previousAvailable
stock.lowInventory, StockWebhookHandler (an IStockLevelHandler), when RanLow and not SoldOutstock, previousAvailable
stock.sold-outInventory, StockWebhookHandler, when SoldOutstock, previousAvailable
webhook.pingThe admin's Send a test event, to one subscription onlywebhookId, name

Customers made by the Customers recipe step aren't published.

Delivery​

WebhookDispatcher.SendAsync makes one attempt at a pending delivery and saves what it came to.

  • It sends through IWebhookSender, which posts Payload with Content-Type: application/json, a CrestApps-Webhooks/1.0 user agent, and the headers in WebhookHeaders: X-Webhook-Id (the event id), X-Webhook-Event, X-Webhook-Timestamp (Unix seconds, at this attempt) and X-Webhook-Signature.
  • The signature is IWebhookSigner.Sign(secret, timestamp, body) (HmacSha256WebhookSigner): v1= and the lowercase hex HMAC-SHA256 of {timestamp}.{body}, keyed with the UTF-8 bytes of the whole secret.
  • It uses the named HttpClient CrestApps.Webhooks, registered with AddEgressGuardedHttpClient, with a 15-second timeout, and doesn't follow redirects: a 3xx is an answer that isn't 2xx. The egress guard (EgressNetwork) refuses to connect when the host resolves only to loopback, private or link-local addresses, so a hostname can't reach the site's own network either; loopback is allowed while the host environment is Development. Of a refusal, only the first 500 characters are read, for at most 5 seconds.
  • A host the egress guard refuses fails the delivery at once: it would be refused again on every attempt.
  • A 2xx answer marks it Delivered. Any other answer, a timeout or a connection error schedules the next attempt from WebhookDispatcher.Backoff: 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours and 24 hours after the attempts so far. After the eighth attempt fails it's Failed.
  • A delivery fails at once, without being sent, when its subscription was deleted (The webhook was deleted.), is turned off (The webhook was turned off.), or has a secret Data Protection can't unprotect (The webhook's signing secret can't be read. Give it a new secret, then send it again.).

WebhookDeliveriesBackgroundTask runs every minute, under a 10-minute lock. It sends up to 20 pending deliveries whose NextAttemptUtc has come (IWebhookDeliveryStore.ListDueAsync, oldest first), loading each afresh and saving it as soon as it's sent, so a run that stops half way, or the next run, never sends it again. It then deletes up to 20 delivered or failed deliveries created more than 30 days ago, leaving out the events a feature keeps (AI Webhooks keeps every AI event); see Delivery log retention.

Send again in the admin (WebhookDispatcher.ResendAsync) resets a delivery to pending with no attempts and sends it at once.

The same outbox also sends direct deliveries to receivers that aren't subscriptions, such as the order updates Agentic Commerce sends AI agent platforms. They are signed by their protocol's formatter instead of with X-Webhook-Signature, and retried on the same schedule.

Receiving​

A receiver should check the signature against the raw body, refuse an old timestamp, answer 2xx quickly and do its work afterwards, and drop an X-Webhook-Id it has already handled, since a delivery can arrive more than once. A retried message can arrive after a later one, so it reads the status and times in data, or gets the latest from the commerce API, rather than relying on the order events arrive in.

The payload​

Each event is a POST with a JSON body. Names are camelCase, and money is an amount with its currency, as in the commerce API:

{
"id": "evt_4k2x9m7qz1c8",
"event": "order.paid",
"createdUtc": "2026-10-19T14:03:22.512Z",
"data": {
"order": {
"id": "4d1k8s0p2w",
"number": "1042",
"status": "paid",
"customerEmail": "avery@example.com",
"totals": { "total": { "amount": 29.7, "currency": "USD" } }
}
}
}

The example leaves out most of the order. X-Webhook-Id carries the same id on every attempt.

Send a test event posts a webhook.ping, signed like any other:

{
"id": "evt_7q3m1x8k2c9n",
"event": "webhook.ping",
"createdUtc": "2026-10-19T14:10:05.031Z",
"data": { "webhookId": "4p9w2k7x1m3q", "name": "Warehouse" }
}

Checking the signature​

The signature is v1= and the lowercase hex HMAC-SHA256 of X-Webhook-Timestamp, a dot and the raw body, keyed with the whole signing secret (whsec_ included). Compute it over the body exactly as it arrived, before parsing the JSON, compare it in constant time, and refuse a timestamp more than a few minutes old: an old message may be a recording someone sends again. Each attempt is signed again when it's sent, so a retry has a fresh timestamp.

In C#:

using System.Security.Cryptography;
using System.Text;

static bool IsFromStore(string secret, string timestamp, string body, string signature)
{
// A message signed more than 5 minutes ago may be replayed.
if (!long.TryParse(timestamp, out var seconds) ||
Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - seconds) > 300)
{
return false;
}

var hash = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), Encoding.UTF8.GetBytes(timestamp + "." + body));
var expected = "v1=" + Convert.ToHexString(hash).ToLowerInvariant();

return CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(signature ?? ""));
}

In Node.js, with Express:

const crypto = require('crypto');
const express = require('express');
const app = express();

// Read the body as it arrived: the signature is over its exact bytes.
app.post('/store', express.raw({ type: 'application/json' }), (req, res) => {
const timestamp = req.get('X-Webhook-Timestamp') || '';
const signature = req.get('X-Webhook-Signature') || '';
const body = req.body.toString('utf8');

const expected = 'v1=' + crypto
.createHmac('sha256', process.env.STORE_WEBHOOK_SECRET)
.update(timestamp + '.' + body)
.digest('hex');

const fresh = Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300;
const valid = expected.length === signature.length &&
crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));

if (!fresh || !valid) {
return res.sendStatus(401);
}

const message = JSON.parse(body);
// Skip message.id if it was handled before; otherwise queue the work.
res.sendStatus(200);
});

Keep the signing secret in the receiver's settings or secret store, never in a web page or an app.

Admin​

  • Commerce > Webhooks (commerce/webhooks, WebhooksAdminController) lists the subscriptions through the AdminList shape, with Add webhook.
  • A subscription's editor sets its name, URL, whether it's on, and its events, grouped by each event's group. IsAllowedUrl takes an absolute https URL without user info, and refuses a loopback, private or link-local IP address; plain http only to a loopback host when the host environment is Development. Deleting a subscription deletes its deliveries. Saved, it shows the Signing secret, with New secret (RotateSecret).
  • Deliveries (commerce/webhooks/Deliveries/{itemId}) lists a subscription's deliveries, newest first, with a status filter, Send again per delivery, and Send a test event (Ping), which sends webhook.ping to that subscription in the request.

Permissions​

PermissionAllows
Manage commerce webhooks (ManageCommerceWebhooks)Everything under Commerce > Webhooks, including reading the signing secrets.

Administrators have it by default.