Card Attack Emergency Kit

Are you under attack?

If dozens of failed orders appeared in minutes, each with a different card and a “card was declined” note, a bot is testing stolen cards on your checkout. It is not a broken gateway, and these are not lost sales.

Typical signs:

  • A sudden spike in Failed orders, often overnight
  • Small totals (often your cheapest product), random names and email addresses
  • A flood of “failed order” emails to you and bounced emails to fake customers
  • New disputes or processor fees for charges you never shipped

The real damage is quieter than the noise: each attempt that reaches your gateway can cost a fee, a few cards will go through and turn into chargebacks, and a high decline rate can get your merchant account reviewed or shut down. Work through the next section now.

The first 15 minutes

The goal is to stop new attempts reaching your payment gateway, then clean up. Do these in order.

Cloudflare rules (copy and paste)

If your domain runs through Cloudflare, these rules stop most bots before they touch WordPress. Add them under Security > WAF. Bots hit three different checkout addresses, so every rule covers all three: ?wc-ajax=checkout (classic checkout), /wp-json/wc/store/.../checkout (block checkout) and ?rest_route=/wc/store/... (the same API, used to dodge path-only rules).

Rule 1: Block checkout from countries you don’t ship to

Custom rule, action Block. Replace "US" "CA" with the countries you sell to.

(http.request.method eq "POST"
 and (http.request.uri.query contains "wc-ajax=checkout"
   or http.request.uri.path contains "/wc/store/"
   or http.request.uri.query contains "rest_route=/wc/store")
 and not ip.src.country in {"US" "CA"})

Rule 2: Block checkout posts with no shopping session

Custom rule, action Block. A real shopper always has a WooCommerce session cookie by the time they pay; many card-testing scripts post straight to checkout without one. Place a test order after adding this rule. Skip it if you run a headless or app-based storefront.

(http.request.method eq "POST"
 and (http.request.uri.query contains "wc-ajax=checkout"
   or http.request.uri.path contains "/wc/store/v1/checkout"
   or http.request.uri.query contains "rest_route=/wc/store")
 and not http.cookie contains "wp_woocommerce_session_")

Rule 3: Rate-limit the checkout

Rate limiting rule, counted by IP, action Block.

  • Free plan (one rule, path field only, 10-second window): match http.request.uri.path contains "/wc/store/v1/checkout", 3 requests per 10 seconds, block for 10 seconds. The plugin below covers the classic checkout, which Free plans can’t match here.
  • Pro plan and up: use the full expression below, 3 requests per 60 seconds, block for 1 hour.
(http.request.uri.query contains "wc-ajax=checkout"
 or http.request.uri.path contains "/wc/store/v1/checkout"
 or http.request.uri.query contains "rest_route=/wc/store")

If you use Cloudflare, check the plugin’s log (WooCommerce > Status > Logs, “card-attack-shield”) after its first block. Real visitor IPs there mean your host already handles Cloudflare, so change nothing. Only if the log shows Cloudflare’s own IPs, and your server accepts traffic from Cloudflare alone, set define( 'CAS_TRUST_CLOUDFLARE', true ); in wp-config.php. If your server can be reached directly, a bot could fake the Cloudflare header and get past the limit.

WooCommerce’s built-in limiter (no plugin)

WooCommerce can rate-limit the Store API, which powers the block checkout, but it is off by default. If you only want this one fix, paste the snippet into a code-snippets plugin or your child theme’s functions.php. The Card Attack Shield plugin below already includes it.

add_filter( 'woocommerce_store_api_rate_limit_options', function () {
    return array(
        'enabled'       => true,  // off by default in WooCommerce
        'proxy_support' => false, // true only behind Cloudflare or another proxy
        'limit'         => 25,    // requests allowed...
        'seconds'       => 10,    // ...per this many seconds
    );
} );

Its limit applies to all Store API requests from one visitor, so keep it generous (the default 25 per 10 seconds). A low number here breaks normal cart updates. The plugin below adds a much tighter limit on checkout attempts alone.

What this does not cover: the classic shortcode checkout (?wc-ajax=checkout) and gateway endpoints like PayPal’s card fields. Most stores still on the classic checkout get no protection from this setting.

Card Attack Shield: the drop-in plugin

This single-file plugin limits every checkout path, including the ones security plugins can’t see. Save it as wp-content/plugins/card-attack-shield/card-attack-shield.php (or upload the zip under Plugins > Add New), activate it, then place a test order.

What it does:

  • Per-IP limit on checkout attempts: 5 per 10 minutes across the classic checkout, the block checkout and Store API, and PayPal’s card-field endpoint
  • Checkout token: the classic checkout form must carry a signed hidden field and be at least 3 seconds old. Scripts that post straight to ?wc-ajax=checkout fail. Apple Pay and Google Pay buttons are not affected.
  • Automatic lockdown: 10 failed orders within 15 minutes locks guest checkout for 30 minutes and emails you. Logged-in customers can still buy.
  • WooCommerce’s own Store API limiter, switched on
  • Optional minimum order total, to block the $1 test charges
  • Logs every block to WooCommerce > Status > Logs, under “card-attack-shield”

Change any setting by adding a line to wp-config.php, above “That’s all, stop editing”:

Setting Default What it controls
CAS_IP_LIMIT / CAS_IP_WINDOW 5 / 600 s Checkout attempts allowed per IP per window
CAS_FAILED_THRESHOLD / CAS_FAILED_WINDOW 10 / 900 s Failed orders that trigger lockdown
CAS_LOCKDOWN_SECONDS 1800 Lockdown length; 0 turns lockdown off
CAS_MIN_ORDER_TOTAL 0 (off) Smallest cart total allowed, e.g. 5
CAS_REQUIRE_TOKEN true Set false if your theme’s custom checkout rejects real orders
CAS_TRUST_CLOUDFLARE false Use Cloudflare’s visitor IP; only if all traffic goes through Cloudflare
CAS_EXTRA_WC_AJAX ppc-create-order Extra gateway endpoints to limit, comma-separated

Example: define( 'CAS_MIN_ORDER_TOTAL', 5 );

Before you rely on it: some page builders and checkout themes (custom WoodMart layouts, CheckoutWC and similar) don’t output the standard checkout hooks. If real orders show “Please reload the checkout page”, set CAS_REQUIRE_TOKEN to false. A PayPal purchase counts as two attempts, so a customer whose card is declined twice may hit the limit. Raise CAS_IP_LIMIT if that matters for your store.

<?php
/**
 * Plugin Name: Card Attack Shield for WooCommerce
 * Description: Rate-limits every checkout path (classic, Store API/blocks, PayPal Payments), adds a checkout token to classic checkout, and auto-locks guest checkout when failed orders spike.
 * Version:     1.0.0
 * Author:      Sage's Brain
 * Author URI:  https://www.sagesbrain.com/
 * Text Domain: card-attack-shield
 * Requires at least: 6.4
 * Requires Plugins: woocommerce
 * Requires PHP: 7.4
 * WC requires at least: 8.0
 * License:     GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

/*
 * Settings. Override any of these in wp-config.php, e.g. define( 'CAS_IP_LIMIT', 3 );
 */
defined( 'CAS_IP_LIMIT' )          || define( 'CAS_IP_LIMIT', 5 );          // checkout attempts allowed per IP...
defined( 'CAS_IP_WINDOW' )         || define( 'CAS_IP_WINDOW', 600 );       // ...per this many seconds (10 min).
defined( 'CAS_FAILED_THRESHOLD' )  || define( 'CAS_FAILED_THRESHOLD', 10 ); // failed orders in the window that trigger lockdown.
defined( 'CAS_FAILED_WINDOW' )     || define( 'CAS_FAILED_WINDOW', 900 );   // window for counting failed orders (15 min).
defined( 'CAS_LOCKDOWN_SECONDS' )  || define( 'CAS_LOCKDOWN_SECONDS', 1800 ); // lockdown length (30 min). 0 disables lockdown.
defined( 'CAS_MIN_ORDER_TOTAL' )   || define( 'CAS_MIN_ORDER_TOTAL', 0 );   // block carts below this total. 0 = off.
defined( 'CAS_REQUIRE_TOKEN' )     || define( 'CAS_REQUIRE_TOKEN', true );  // classic checkout must carry the hidden token. Set false if your theme's checkout skips woocommerce_after_order_notes.
defined( 'CAS_TOKEN_MIN_AGE' )     || define( 'CAS_TOKEN_MIN_AGE', 3 );     // classic checkout form must be at least this old (seconds).
defined( 'CAS_TRUST_CLOUDFLARE' )  || define( 'CAS_TRUST_CLOUDFLARE', false ); // true ONLY if all traffic goes through Cloudflare.
defined( 'CAS_EXTRA_WC_AJAX' )     || define( 'CAS_EXTRA_WC_AJAX', 'ppc-create-order' ); // comma-separated extra wc-ajax actions to limit.

final class Card_Attack_Shield {

    const LOG_SOURCE = 'card-attack-shield';

    public static function init() {
        // Classic (shortcode) checkout.
        add_action( 'woocommerce_after_order_notes', array( __CLASS__, 'render_token' ) );
        add_action( 'woocommerce_checkout_process', array( __CLASS__, 'guard_classic_checkout' ), 1 );

        // Block checkout and direct Store API calls.
        add_filter( 'rest_pre_dispatch', array( __CLASS__, 'guard_store_api' ), 10, 3 );
        add_filter( 'woocommerce_store_api_rate_limit_options', array( __CLASS__, 'store_api_rate_limits' ) );

        // Gateway endpoints that create payment attempts before checkout (e.g. PayPal Payments card fields).
        foreach ( array_filter( array_map( 'trim', explode( ',', (string) CAS_EXTRA_WC_AJAX ) ) ) as $action ) {
            add_action( 'wc_ajax_' . $action, array( __CLASS__, 'guard_gateway_ajax' ), 0 );
        }

        // Watch failed orders to trigger lockdown.
        add_action( 'woocommerce_order_status_failed', array( __CLASS__, 'on_failed_order' ) );
    }

    /* ---------- Guards ---------- */

    public static function guard_classic_checkout() {
        $error = self::check_request( 'classic' );

        // Token only for the classic form post. Express buttons (Apple Pay, Google Pay) reach
        // process_checkout through their own wc-ajax actions and never carry the form field.
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $is_form_post = isset( $_GET['wc-ajax'] ) && 'checkout' === $_GET['wc-ajax'];

        if ( ! $error && CAS_REQUIRE_TOKEN && $is_form_post ) {
            $error = self::check_token();
        }

        if ( $error ) {
            wc_add_notice( $error, 'error' );
        }
    }

    public static function guard_store_api( $result, $server, $request ) {
        if ( 'POST' !== $request->get_method() ) {
            return $result;
        }
        if ( ! preg_match( '#^/wc/store(/v\d+)?/checkout#', $request->get_route() ) ) {
            return $result;
        }

        $error = self::check_request( 'store_api' );

        return $error ? new WP_Error( 'cas_blocked', $error, array( 'status' => 429 ) ) : $result;
    }

    public static function guard_gateway_ajax() {
        $error = self::check_request( 'gateway_ajax' );

        if ( $error ) {
            wp_send_json_error( array( 'message' => $error ), 429 );
        }
    }

    /**
     * Runs every check that applies to all checkout paths. Returns an error message or ''.
     */
    private static function check_request( $path ) {
        $ip = self::client_ip();

        if ( self::in_lockdown() && ! is_user_logged_in() ) {
            self::log( "Lockdown block ($path) from $ip" );
            return __( 'Checkout is temporarily limited. Please log in to your account or try again in a little while.', 'card-attack-shield' );
        }

        if ( ! self::within_ip_limit( $ip ) ) {
            self::log( "Rate limit block ($path) from $ip" );
            return __( 'Too many checkout attempts. Please wait a few minutes and try again.', 'card-attack-shield' );
        }

        if ( CAS_MIN_ORDER_TOTAL > 0 && function_exists( 'WC' ) && WC()->cart ) {
            $total = (float) WC()->cart->get_total( 'edit' );
            if ( $total > 0 && $total < (float) CAS_MIN_ORDER_TOTAL ) {
                self::log( "Minimum total block ($path) from $ip, total $total" );
                return __( 'This order is below our minimum order amount.', 'card-attack-shield' );
            }
        }

        return '';
    }

    /* ---------- Per-IP rate limit ---------- */

    private static function within_ip_limit( $ip ) {
        $key  = 'cas_ip_' . md5( $ip );
        $hits = get_transient( $key );
        $hits = is_array( $hits ) ? $hits : array();
        $now  = time();

        // Keep only hits inside the window (sliding window).
        $hits = array_values(
            array_filter(
                $hits,
                static function ( $t ) use ( $now ) {
                    return $t > $now - CAS_IP_WINDOW;
                }
            )
        );

        if ( count( $hits ) >= CAS_IP_LIMIT ) {
            return false;
        }

        $hits[] = $now;
        set_transient( $key, $hits, CAS_IP_WINDOW );

        return true;
    }

    /* ---------- Classic checkout token ---------- */

    public static function render_token() {
        $time  = time();
        $token = $time . '.' . self::sign( (string) $time );
        echo '<input type="hidden" name="cas_token" value="' . esc_attr( $token ) . '" />';
    }

    private static function check_token() {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- WooCommerce verifies its own nonce; this is an extra bot check.
        $raw = isset( $_POST['cas_token'] ) ? sanitize_text_field( wp_unslash( $_POST['cas_token'] ) ) : '';
        $ip  = self::client_ip();

        $parts = explode( '.', $raw, 2 );
        if ( 2 !== count( $parts ) || ! hash_equals( self::sign( $parts[0] ), $parts[1] ) ) {
            self::log( "Missing/invalid checkout token from $ip" );
            return __( 'Please reload the checkout page and try again.', 'card-attack-shield' );
        }

        $age = time() - (int) $parts[0];
        if ( $age < CAS_TOKEN_MIN_AGE || $age > DAY_IN_SECONDS ) {
            self::log( "Checkout token age $age s rejected from $ip" );
            return __( 'Please reload the checkout page and try again.', 'card-attack-shield' );
        }

        return '';
    }

    private static function sign( $value ) {
        return hash_hmac( 'sha256', $value, wp_salt( 'nonce' ) );
    }

    /* ---------- Failed-order lockdown ---------- */

    public static function on_failed_order() {
        if ( CAS_LOCKDOWN_SECONDS <= 0 || self::in_lockdown() ) {
            return;
        }

        $failed = wc_get_orders(
            array(
                'status'       => 'failed',
                'date_created' => '>' . ( time() - CAS_FAILED_WINDOW ),
                'limit'        => CAS_FAILED_THRESHOLD,
                'return'       => 'ids',
            )
        );

        if ( count( $failed ) >= CAS_FAILED_THRESHOLD ) {
            set_transient( 'cas_lockdown', time(), CAS_LOCKDOWN_SECONDS );
            self::log( 'Lockdown started: ' . count( $failed ) . ' failed orders in ' . CAS_FAILED_WINDOW . ' s' );

            wp_mail(
                get_option( 'admin_email' ),
                '[' . wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) . '] Possible card-testing attack: guest checkout locked',
                sprintf(
                    "%d failed orders in the last %d minutes. Guest checkout is locked for %d minutes; logged-in customers can still buy.\n\nCheck WooCommerce > Status > Logs (card-attack-shield) and your payment processor dashboard.",
                    count( $failed ),
                    CAS_FAILED_WINDOW / 60,
                    CAS_LOCKDOWN_SECONDS / 60
                )
            );
        }
    }

    private static function in_lockdown() {
        return CAS_LOCKDOWN_SECONDS > 0 && false !== get_transient( 'cas_lockdown' );
    }

    /* ---------- Store API native limiter ---------- */

    public static function store_api_rate_limits( $options ) {
        $options['enabled']       = true;
        $options['proxy_support'] = (bool) CAS_TRUST_CLOUDFLARE;
        $options['limit']         = 25;
        $options['seconds']       = 10;
        return $options;
    }

    /* ---------- Helpers ---------- */

    private static function client_ip() {
        if ( CAS_TRUST_CLOUDFLARE && ! empty( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ) {
            $ip = sanitize_text_field( wp_unslash( $_SERVER['HTTP_CF_CONNECTING_IP'] ) );
        } else {
            $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
        }
        return filter_var( $ip, FILTER_VALIDATE_IP ) ? $ip : '0.0.0.0';
    }

    private static function log( $message ) {
        if ( function_exists( 'wc_get_logger' ) ) {
            wc_get_logger()->warning( $message, array( 'source' => self::LOG_SOURCE ) );
        }
    }
}

add_action( 'plugins_loaded', array( 'Card_Attack_Shield', 'init' ) );

Clean up after the attack

Once new failed orders stop, clear out the junk and recover what you can. Back up your database first.

Without WP-CLI: go to WooCommerce > Orders, filter by Failed, select all, choose Move to Trash, then empty the trash. Repeat per page.

With WP-CLI (faster for thousands of orders). Count first:

wp eval '
$ids = wc_get_orders( array( "status" => "failed", "date_created" => ">" . strtotime( "-3 days" ), "limit" => -1, "return" => "ids" ) );
echo count( $ids ) . " failed orders in the last 3 days\n";
'

Then permanently delete the failed guest orders from that window. Failed orders from registered customers are kept for you to review.

wp eval '
$ids = wc_get_orders( array( "status" => "failed", "date_created" => ">" . strtotime( "-3 days" ), "limit" => -1, "return" => "ids" ) );
$n = 0;
foreach ( $ids as $id ) {
    $order = wc_get_order( $id );
    if ( $order && ! $order->get_customer_id() ) { $order->delete( true ); $n++; }
}
echo "Deleted $n failed guest orders\n";
'

This works with both the old and the new (HPOS) order storage. Change -3 days to match when the attack started.

With your payment processor:

  • Refund every charge that succeeded during the attack, if you haven’t already. A refund now beats a chargeback later.
  • Ask your processor to refund the per-attempt fees. Many will for a documented attack; send them the time window and the number of attempts from your log.
  • If they warn you about your decline rate, reply with what you’ve changed. It shows the attack is handled.

Keep it from happening again

Attackers often come back to stores that were easy targets. Leave these in place after the attack ends.