Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 39 ยท Payments and Shipping

Webhooks, Signatures and Payment Security

Handle payment webhooks in a WooCommerce gateway: wc-api callbacks, HMAC signature checks, idempotent events, PCI scope, safe logging and return-URL races.

A redirect gateway cannot trust the browser. The shopper may close the tab after paying, a bank may confirm minutes later, and anyone can type your return URL by hand. The reliable signal is a webhook: the provider calls a URL on your server and tells you what happened. That URL is public, so everything about it must assume hostile callers, duplicate deliveries and events that arrive in the wrong order.

This lesson shows how to receive a callback in WooCommerce, how to verify its signature, how to process each event exactly once, and how to keep your gateway out of the heaviest PCI duties. The WooCommerce code is read-only because it needs WordPress. Two runnable stand-ins implement the signature check and the replay guard in plain PHP. The generic theory is in Webhooks and Signature Verification and PCI and 3-D Secure; here we apply it to a gateway. The previous lesson built the gateway itself: Building a Payment Gateway.

Where a callback lands in WooCommerce

WooCommerce has a small router for gateway callbacks. WC()->api_request_url( 'Acme_Gateway' ) returns a URL such as https://shop.example/wc-api/Acme_Gateway/. A request to that URL fires the action woocommerce_api_acme_gateway, where the name is the class name in lowercase. You register the handler in the gateway constructor:

PHP
<?php
// In Acme_Gateway::__construct()
add_action( 'woocommerce_api_acme_gateway', [ $this, 'handle_webhook' ] );

// Give this URL to the provider in its dashboard.
$webhook_url = WC()->api_request_url( 'Acme_Gateway' );

The handler runs on a normal front-end request: no nonce, no logged-in user, no cookie. That is correct, because the caller is a server. The only proof that the request is genuine is the signature. For events that belong to your own plugin and are not tied to a gateway, you can also register a REST route; see Custom REST Endpoints and Outgoing Webhooks.

sequenceDiagram
    participant P as Provider
    participant H as handle_webhook
    participant D as Event log
    participant O as WC_Order
    P->>H: POST event + signature header
    H->>H: Read raw body, verify HMAC
    H->>D: Seen this event id before?
    D-->>H: no
    H->>O: payment_complete() once
    H->>D: Store event id
    H-->>P: 200 OK

Verify first, de-duplicate second, change the order third, and answer quickly.

Verifying the signature

Providers sign the payload with a secret that only you and they know. The common scheme is an HMAC-SHA256 over the raw request body, often combined with a timestamp. The rules for a correct check are short:

  1. Read the body exactly as received with file_get_contents( 'php://input' ). Do not decode and re-encode JSON first; one changed space breaks the hash.
  2. Recompute the HMAC with your secret and compare with hash_equals(), which takes the same time for every input, so an attacker cannot learn the signature byte by byte.
  3. Reject old timestamps (a few minutes of tolerance) so a captured request cannot be replayed next week.
  4. Return 401 or 400 for a bad signature and do nothing else. Do not reveal why.
PHP
<?php
public function handle_webhook(): void {
    $payload   = file_get_contents( 'php://input' );
    $signature = $_SERVER['HTTP_ACME_SIGNATURE'] ?? '';
    $secret    = $this->get_option( 'webhook_secret' );

    if ( ! Acme_Signature::is_valid( $payload, $signature, $secret ) ) {
        status_header( 400 );
        exit;
    }

    $event = json_decode( $payload, true );
    // ... de-duplicate, then act on $event['type'] ...

    status_header( 200 );
    exit;
}

The header name and the exact signing format are defined by your provider, so always follow its documentation; the stand-in below uses a simple, invented t=...,v1=... format to show the mechanics.

PHP Signature verifier with timestamp tolerance

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.

This is a stand-in: the real scheme differs per provider, but the shape (raw body, HMAC, constant-time compare, time window) is the same everywhere.

Handle each event once

Providers retry. If your server answered slowly, or answered 500, the same event arrives again, possibly several times and possibly in parallel. If each delivery calls payment_complete(), you risk double stock reduction, double emails and double fulfilment. Two defenses work together:

  • Store event ids. Keep a table (or order meta) of processed ids with a unique index. Insert before acting; if the insert fails, you have seen the event. The idea is the same as an idempotency key; see Idempotency.
  • Check the order state. Before completing, ask whether the order is already paid. $order->is_paid() is true for the paid statuses, and payment_complete() is meant to be called on an order that is not paid yet. Guard it yourself so a late duplicate does nothing.

Also design for out-of-order events. A refund event can arrive before the success event it refers to. Handlers should either look up the current state at the provider or park the event and retry later. Do not assume a polite sequence. A background queue is the usual tool; see Background Processing With Action Scheduler.

PHP Replay guard and idempotent order update

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.

In production the "claim" must be atomic across PHP workers, so use a database unique key (INSERT that fails on duplicates) rather than an in-memory array. Both guards matter: the event store stops retries, the state check stops two different events from doing the same job.

The return URL race

Two things tell you a payment finished: the shopper returning to your site and the webhook. They race. Sometimes the shopper lands on the thank-you page before the webhook arrives; sometimes the webhook wins and the shopper arrives to a paid order. Rules that keep this safe:

  • The return page may display a message, but it must not be the only thing that marks an order paid unless it re-verifies the payment with the provider server to server.
  • Treat the webhook as the source of truth, and make the return handler idempotent with the same state check shown above.
  • If the order is still pending when the shopper returns, show "We are confirming your payment" instead of a failure. The webhook will finish the job.

PCI scope, secrets and logs

You are responsible for protecting card data only if it touches your server. Design the gateway so it never does:

  • Hosted pages and hosted fields. Redirect gateways and provider-hosted iframes send the card number straight to the provider. Your server only sees a token or a payment id. This keeps you in the simplest self-assessment category. Posting raw card numbers to your own PHP code puts the whole store in a much heavier scope.
  • Never log secrets or card data. WC_Logger writes to files that admins, hosts and backup tools can read. Log event ids, order ids and status codes, not payloads containing tokens, API keys or personal data. If you must log a request for debugging, redact it first.
  • Keep keys out of the code. Store them in settings or, better, constants in wp-config.php, and never print them back into the settings page (show a placeholder instead).
  • Separate test and live. Keep two sets of keys and two webhook secrets, and make the mode visible in admin so a live key is never pasted into a test field by accident.
  • Verify amounts yourself. When a success event arrives, compare the paid amount and currency with the order total before completing. A webhook for a small payment must not unlock a large order.
PHP
<?php
$paid_cents = (int) $event['data']['amount'];
$expected   = (int) round( $order->get_total() * 100 );

if ( $paid_cents !== $expected || $event['data']['currency'] !== strtolower( $order->get_currency() ) ) {
    $order->update_status( 'on-hold', 'Amount mismatch, manual review needed.' );
    return;
}

For wider guidance on hardening your extensions see Security for WooCommerce Extensions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must a webhook signature be computed over the raw request body?

    The HMAC covers the exact bytes the provider sent. Parsing and re-serializing can alter whitespace or key order and break verification.
  2. 2. Why compare signatures with hash_equals() instead of ===?

    A normal comparison can stop at the first differing byte, which leaks timing information. hash_equals() takes the same time regardless of where the strings differ.
  3. 3. A provider retries the same event three times. What prevents three stock reductions?

    De-duplicating by event id plus a paid-state check makes the handler idempotent, so repeated deliveries change nothing.
  4. 4. What is the safest way to keep card numbers out of your PCI scope?

    If the card number never reaches your server, you cannot leak it. Hosted fields and redirects are designed for exactly this.

Summary

  • Register a callback with WC()->api_request_url( 'Class_Name' ) and the action woocommerce_api_class_name; the caller is a server, so there is no nonce or login.
  • Verify an HMAC over the raw body, compare with hash_equals(), and reject stale timestamps.
  • Make handling idempotent: claim event ids atomically and check the order state before payment_complete().
  • Expect duplicates, retries and out-of-order events, and treat the webhook, not the return URL, as the source of truth.
  • Use hosted fields or redirects, never log secrets or card data, and compare the paid amount with the order total.

Next: Custom Shipping Methods