Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 39 ยท REST API and Integrations

Custom REST Endpoints and Outgoing Webhooks

Build your own WooCommerce REST endpoints with permission callbacks and schemas, and learn how outgoing webhooks are signed, delivered, retried and disabled.

Sooner or later an integration needs something the built-in endpoints do not offer: a "refund summary for this customer" route, a bulk status change with business rules, a hook for your warehouse. WooCommerce lets you add your own REST routes with the same machinery it uses itself. The other direction matters just as much: when something happens in the store (an order is paid) you often want to tell another system, and that is what webhooks are for.

This lesson covers both. You will write a controller with permission callbacks and a schema, learn how WooCommerce delivers and signs its own webhooks, and build the receiving side correctly. The real code needs WordPress, so it is read-only here. The runnable examples are plain PHP simulations of signing, verification and retries. If you have not yet seen the general WordPress route API, read Custom REST Endpoints first; for the theory of webhooks, see Webhooks and Signatures.

When to add your own endpoint

Ask three questions before you write a route:

  1. Can the existing wc/v3 endpoints do it, perhaps with a filter or a batch call? Prefer them: clients already know them.
  2. Is it for the shopper's browser? Then it belongs in the Store API (The REST API and the Store API) as an extension or update callback, not as a new public route.
  3. Is it a back-office action with its own rules? Then a custom route is right.

Use your own namespace (acme/v1) rather than adding to wc/v3. A namespace you own cannot clash with a future WooCommerce route, and you control its versioning.

A controller with permissions and a schema

WooCommerce has base controller classes (WC_REST_Controller is the long-standing one that extends WordPress's WP_REST_Controller). For a small extension, extending the WordPress class gives you the same structure with fewer assumptions. The shape is always: register the route, check permission, validate input, return data that matches a schema.

PHP
<?php
class Acme_Refund_Summary_Controller extends WP_REST_Controller {

    protected $namespace = 'acme/v1';
    protected $rest_base = 'customers';

    public function register_routes(): void {
        register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)/refund-summary', array(
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_item' ),
                'permission_callback' => array( $this, 'get_item_permissions_check' ),
                'args'                => array(
                    'id'    => array( 'type' => 'integer', 'required' => true, 'minimum' => 1 ),
                    'since' => array( 'type' => 'string', 'format' => 'date-time' ),
                ),
            ),
            'schema' => array( $this, 'get_public_item_schema' ),
        ) );
    }

    public function get_item_permissions_check( $request ) {
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            return new WP_Error(
                'acme_forbidden',
                __( 'You cannot view refund summaries.', 'acme' ),
                array( 'status' => rest_authorization_required_code() )
            );
        }
        return true;
    }

    public function get_item( $request ) {
        $customer_id = (int) $request['id'];
        $orders      = wc_get_orders( array( 'customer_id' => $customer_id, 'limit' => -1, 'return' => 'objects' ) );

        $refunded = 0.0;
        foreach ( $orders as $order ) {
            $refunded += (float) $order->get_total_refunded();
        }

        return rest_ensure_response( array(
            'customer_id'    => $customer_id,
            'orders'         => count( $orders ),
            'total_refunded' => wc_format_decimal( $refunded, wc_get_price_decimals() ),
        ) );
    }

    public function get_item_schema() {
        return array(
            '$schema'    => 'http://json-schema.org/draft-04/schema#',
            'title'      => 'acme_refund_summary',
            'type'       => 'object',
            'properties' => array(
                'customer_id'    => array( 'type' => 'integer', 'readonly' => true ),
                'orders'         => array( 'type' => 'integer', 'readonly' => true ),
                'total_refunded' => array( 'type' => 'string',  'readonly' => true ),
            ),
        );
    }
}

add_action( 'rest_api_init', function () {
    ( new Acme_Refund_Summary_Controller() )->register_routes();
} );

Points worth underlining:

  • permission_callback is mandatory in practice. A route without one triggers a notice and is treated as public in older WordPress versions. Write '__return_true' only when a route is meant to be public, and say so in a comment.
  • Capabilities, not roles. manage_woocommerce is the capability store managers hold. WooCommerce also offers helpers such as wc_rest_check_manager_permissions() for its own resource names; a plain current_user_can() check is clearer for your own routes.
  • Validation lives in args. Types, minimum, enum, format and sanitize_callback run before your callback. Your callback should trust $request['id'] as an integer because the framework enforced it.
  • Return WP_Error with a status for failures, so clients can tell a 400 from a 404 from a 403.
  • The schema is documentation and contract. Clients and OPTIONS requests read it.
  • Avoid unbounded work. The example uses limit => -1 for brevity; in real code page through orders or aggregate in a query, as discussed in Performance and Scaling Large Stores.

Authentication for your route

You do not write authentication code. A request is authenticated by WordPress or WooCommerce before your permission callback runs: a logged-in admin with a REST nonce (from the admin screens) or a wc/v3 consumer key that WooCommerce resolves to a user. Your callback then asks what that user may do. This is why current_user_can() is the single source of truth.

Outgoing webhooks

A webhook is the store calling your URL when an event happens. In WooCommerce > Settings > Advanced > Webhooks you create one by choosing:

  • a topic: order.created, order.updated, order.deleted, order.restored, the same for product, customer and coupon, or action.<hook_name> to fire on any WordPress action;
  • a delivery URL and a secret;
  • a status (Active, Paused, Disabled).

When the event fires, WooCommerce queues a delivery with Action Scheduler (see Background Processing With Action Scheduler), so the shopper's checkout is not slowed down by your server. The delivery is an HTTP POST with a JSON body (the same representation the REST API returns) and these notable headers:

Header Meaning
X-WC-Webhook-Topic For example order.created
X-WC-Webhook-Resource / X-WC-Webhook-Event order and created
X-WC-Webhook-Source The store URL
X-WC-Webhook-ID The webhook's ID in the store
X-WC-Webhook-Delivery-ID A unique ID for this delivery
X-WC-Webhook-Signature Base64 of the HMAC-SHA256 of the raw body using your secret

Verifying the signature

The receiver must recompute the HMAC over the exact bytes it received and compare in constant time. Verifying a re-encoded or "pretty" version of the JSON fails, because any whitespace change alters the hash.

PHP
<?php
// Receiver side (read-only snippet, plain PHP).
$raw       = file_get_contents( 'php://input' );
$sent      = $_SERVER['HTTP_X_WC_WEBHOOK_SIGNATURE'] ?? '';
$expected  = base64_encode( hash_hmac( 'sha256', $raw, getenv( 'WC_WEBHOOK_SECRET' ), true ) );

if ( ! hash_equals( $expected, $sent ) ) {
    http_response_code( 401 );
    exit;
}

// Acknowledge fast; do the heavy work in a queue.
http_response_code( 200 );

Failures and retries

Be careful about what you assume. A delivery counts as successful for a 2xx response and as failed for anything else or for a network error. WooCommerce keeps a count of consecutive failures per webhook, and when it passes a limit (5 by default, adjustable with the woocommerce_max_webhook_delivery_failures filter) it switches the webhook to Disabled and stops sending. A successful delivery resets the count. WooCommerce does not promise a retry schedule with growing delays for each individual event, so a receiver that was down loses those events unless you reconcile them later (for example by listing orders with modified_after).

That has two consequences for your design:

  1. Respond with 2xx quickly and process asynchronously. A slow handler looks like a failure.
  2. Treat webhooks as a hint that something changed, and make the receiver idempotent (Idempotency): the same delivery ID may arrive twice.

When you build your own sender for a custom integration, you decide the retry policy. The usual one is exponential backoff with a cap and a dead-letter state after the final attempt, which is exactly what the next stand-in shows.

sequenceDiagram
    participant S as Store
    participant R as Receiver
    S->>R: POST body + X-WC-Webhook-Signature
    R-->>S: 500 (down)
    Note over S: failure count 1
    S->>R: next delivery
    R-->>S: 200 OK
    Note over S: failure count reset to 0

A webhook is disabled only after consecutive failures reach the limit; one success resets the counter.

Runnable stand-ins

These are simulations in plain PHP: they implement the signing scheme and a generic retry policy, not WooCommerce's own scheduler. The first signs and verifies a body, including what happens if it is tampered with or re-encoded. The second delivers to a flaky receiver with backoff on a simulated clock, so the output is deterministic.

PHP Sign, verify and tamper-check a webhook body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The pretty-printed case is rejected although the data is identical. That is why receivers must hash the raw request body before any JSON decoding.

PHP Delivery with exponential backoff and a dead-letter state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Real WooCommerce counts consecutive failures and disables the webhook instead of retrying forever. A sender you write yourself, such as an outbound integration to a courier, should do what this stand-in does: back off, cap the delay and keep failed events somewhere a human can replay them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a custom route register in its own namespace such as acme/v1?

    Your namespace is yours to evolve. Adding routes to wc/v3 risks collisions with future core routes and blurs ownership.
  2. 2. What does a permission_callback that returns a WP_Error with status 403 do?

    The framework calls the permission callback before the main callback. A WP_Error (or false) stops the request with the status you provide.
  3. 3. What must a webhook receiver hash to verify X-WC-Webhook-Signature?

    The signature is an HMAC of the raw body bytes. Re-encoding changes whitespace or key order and breaks the comparison.
  4. 4. After repeated failed deliveries, what does WooCommerce do with a webhook?

    Consecutive failures are counted (5 by default, filterable) and the webhook is disabled when the limit is passed. Receivers should therefore answer 2xx quickly and reconcile missed events.

Summary

  • Add custom endpoints in your own namespace, with a permission_callback that checks a capability such as manage_woocommerce, validation in args, and a schema.
  • Authentication happens before your callback; your job is authorization with current_user_can().
  • Outgoing webhooks are queued deliveries signed with a base64 HMAC-SHA256 of the raw body; verify with hash_equals on the unmodified bytes.
  • A failed delivery is anything that is not 2xx; consecutive failures disable the webhook, so acknowledge fast, process asynchronously and reconcile missed events.
  • Make receivers idempotent, and give your own senders backoff plus a dead-letter state.

Next: Background Processing With Action Scheduler