Dev Pattern Labs logo
Dev Pattern Labs Blog
WooCommerce 13 min readOct 16, 2026

Integrating Stripe with WooCommerce: REST API + Webhooks

Connect Stripe payments to WooCommerce via the REST API and webhooks. Learn payment intents, webhook handlers, 3DS authentication, and refund processing.

Dev Pattern Labs Author

Dev Pattern Labs

Peer-reviewed technical tutorial · Production tested

Stripe and WooCommerce payment integration on e-commerce platform
Executive Summary & Key Insight

Connect Stripe payments to WooCommerce via the REST API and webhooks. Learn payment intents, webhook handlers, 3DS authentication, and refund processing. This practical guide covers step-by-step setup, real-world code snippets, security hardening, and common production edge cases.

Accepting payments reliably is the single most critical function of any e-commerce store. WooCommerce powers over 28% of all online stores worldwide, and Stripe is widely regarded as the most developer-friendly payment processor available today. Combining the two gives you a battle-tested checkout flow backed by Stripe's global card network support, fraud detection, and real-time webhooks — all without leaving the WordPress ecosystem.

Out of the box, the official WooCommerce Stripe plugin handles the basics well. But any store with non-standard checkout flows, subscriptions, marketplace payouts, or custom order processing quickly hits the limits of the plugin's UI. That's where the REST API and Stripe's webhook infrastructure come in. By wiring these together, you can build fully automated payment pipelines: create payment intents server-side, listen for asynchronous payment confirmation events, trigger refunds programmatically, and enforce 3D Secure authentication — all without a single manual step in the dashboard.

This guide takes a deep-dive technical approach. We'll walk through plugin configuration, dissect the payment intent lifecycle, map out every relevant webhook event, and write real TypeScript (for a Node.js webhook receiver) and PHP (for WooCommerce hooks) code that you can drop directly into your project.


Prerequisites

Before starting, ensure you have the following in place:

  • WordPress 6.x with WooCommerce 8.x installed and activated
  • PHP 8.1+ with the curl and openssl extensions enabled
  • A Stripe account with API keys (Publishable + Secret) from the Stripe Dashboard
  • Node.js 18+ for the TypeScript webhook handler examples
  • The Stripe CLI installed locally for local webhook forwarding: stripe listen --forward-to localhost:3000/webhooks
  • Basic familiarity with WooCommerce hooks (add_action, add_filter) and the WooCommerce REST API

1. Installing and Configuring the WooCommerce Stripe Plugin

Install the official plugin from the WordPress plugin directory or via WP-CLI:

wp plugin install woocommerce-gateway-stripe --activate

Once activated, navigate to WooCommerce → Settings → Payments → Stripe and enter your API keys. For programmatic configuration — useful in CI/CD pipelines or multi-environment setups — you can set the keys via wp-config.php constants or directly via the WordPress options API:

<?php
// functions.php or a site-specific plugin

add_action( 'init', function () {
    if ( ! class_exists( 'WC_Stripe' ) ) {
        return;
    }

    // Programmatically set Stripe keys (e.g., from environment variables)
    $stripe_settings = get_option( 'woocommerce_stripe_settings', [] );

    $stripe_settings['enabled']        = 'yes';
    $stripe_settings['testmode']       = getenv( 'STRIPE_TEST_MODE' ) ? 'yes' : 'no';
    $stripe_settings['publishable_key'] = getenv( 'STRIPE_PUBLISHABLE_KEY' );
    $stripe_settings['secret_key']      = getenv( 'STRIPE_SECRET_KEY' );
    $stripe_settings['test_publishable_key'] = getenv( 'STRIPE_TEST_PUBLISHABLE_KEY' );
    $stripe_settings['test_secret_key']      = getenv( 'STRIPE_TEST_SECRET_KEY' );
    $stripe_settings['webhook_secret']  = getenv( 'STRIPE_WEBHOOK_SECRET' );

    update_option( 'woocommerce_stripe_settings', $stripe_settings );
} );

Never hard-code API keys in source-controlled files. Always read them from environment variables or a secrets manager.

Enable Payment Request Buttons (Apple Pay / Google Pay) and Stripe Link in the plugin settings for maximum conversion. These are automatically available once your domain is registered in the Stripe Dashboard under Stripe Elements → Payment Request.


2. Understanding the Payment Intent Flow

The modern Stripe checkout uses the Payment Intents API rather than the legacy Charges API. A PaymentIntent represents the full lifecycle of a payment — from creation through confirmation, authentication, and capture.

The typical flow in a WooCommerce context looks like this:

  1. Customer reaches the checkout page → WooCommerce calls Stripe to create a PaymentIntent with the order total.
  2. The browser loads Stripe.js with the client_secret from the PaymentIntent.
  3. The customer enters card details → Stripe.js confirms the PaymentIntent client-side.
  4. If 3DS is required, Stripe handles the redirect/modal automatically.
  5. Stripe fires a payment_intent.succeeded webhook to your server.
  6. Your webhook handler updates the WooCommerce order status to processing or completed.

Here's how to create a PaymentIntent server-side in TypeScript using the official Stripe SDK:

import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: "2024-04-10",
});

interface CreatePaymentIntentParams {
  amountInCents: number;
  currency: string;
  orderId: number;
  customerEmail: string;
}

export async function createPaymentIntent(
  params: CreatePaymentIntentParams
): Promise<Stripe.PaymentIntent> {
  const { amountInCents, currency, orderId, customerEmail } = params;

  const paymentIntent = await stripe.paymentIntents.create({
    amount: amountInCents,          // e.g. 4999 for $49.99
    currency: currency.toLowerCase(), // "usd", "gbp", "eur"
    automatic_payment_methods: { enabled: true },
    metadata: {
      woocommerce_order_id: String(orderId),
      customer_email: customerEmail,
    },
    receipt_email: customerEmail,
  });

  return paymentIntent;
}

The metadata field is crucial — it maps the Stripe PaymentIntent back to the WooCommerce order when the webhook fires later.


3. Webhook Events for WooCommerce-Stripe

Stripe communicates asynchronous payment outcomes via webhooks. The WooCommerce Stripe plugin registers a webhook endpoint automatically at:

https://yourdomain.com/?wc-api=wc_stripe

The following table lists the key Stripe events relevant to a WooCommerce integration, what triggers them, and how they affect order status:

Stripe EventTriggerWooCommerce Order Action
payment_intent.succeededPayment fully capturedSet order to processing
payment_intent.payment_failedCard declined / auth failureSet order to failed
payment_intent.requires_action3DS challenge requiredHold order, prompt customer
charge.refundedFull or partial refund issuedCreate WC refund record
charge.dispute.createdCardholder files chargebackFlag order, notify admin
charge.dispute.wonDispute resolved in merchant's favourRemove hold/flag
charge.dispute.lostDispute resolved against merchantMark order as refunded
customer.subscription.deletedSubscription cancelled (WC Subscriptions)Cancel subscription order
invoice.payment_succeededRecurring invoice paidRenew subscription order
invoice.payment_failedRecurring invoice payment failedSuspend subscription

Register only the events you need in the Stripe Dashboard under Developers → Webhooks → Add Endpoint to reduce noise and improve response time.


4. Custom Payment Flow via REST API

Sometimes you need to trigger a payment outside the standard checkout — for example, charging a saved payment method for a quote, or re-attempting a failed order via an admin panel. Here's a self-contained TypeScript Express route that creates a WooCommerce order via the WC REST API and immediately charges a saved Stripe PaymentMethod:

import express, { Request, Response } from "express";
import Stripe from "stripe";
import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";

const router = express.Router();
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { apiVersion: "2024-04-10" });

const wc = new WooCommerceRestApi({
  url: process.env.WC_STORE_URL!,
  consumerKey: process.env.WC_CONSUMER_KEY!,
  consumerSecret: process.env.WC_CONSUMER_SECRET!,
  version: "wc/v3",
});

router.post("/charge-saved-method", async (req: Request, res: Response) => {
  const { customerId, stripeCustomerId, paymentMethodId, lineItems } = req.body;

  try {
    // Step 1: Create WooCommerce order
    const { data: wcOrder } = await wc.post("orders", {
      customer_id: customerId,
      line_items: lineItems,
      payment_method: "stripe",
      payment_method_title: "Credit Card (Stripe)",
      set_paid: false,
    });

    const amountInCents = Math.round(parseFloat(wcOrder.total) * 100);

    // Step 2: Create and confirm PaymentIntent off-session
    const paymentIntent = await stripe.paymentIntents.create({
      amount: amountInCents,
      currency: wcOrder.currency.toLowerCase(),
      customer: stripeCustomerId,
      payment_method: paymentMethodId,
      confirm: true,
      off_session: true,
      metadata: { woocommerce_order_id: String(wcOrder.id) },
    });

    if (paymentIntent.status === "succeeded") {
      // Step 3: Mark WooCommerce order as paid
      await wc.put(`orders/${wcOrder.id}`, {
        status: "processing",
        transaction_id: paymentIntent.id,
      });

      return res.json({ success: true, orderId: wcOrder.id, paymentIntentId: paymentIntent.id });
    }

    return res.status(402).json({ success: false, status: paymentIntent.status });
  } catch (err: any) {
    // Handle card errors gracefully
    if (err.type === "StripeCardError") {
      return res.status(402).json({ error: err.message, code: err.code });
    }
    throw err;
  }
});

export default router;

5. Handling Refunds Programmatically

WooCommerce supports refunds natively, but if you process refunds via a custom admin tool or external system, you need to both refund in Stripe and create a matching WooCommerce refund record. Here's a PHP function that does both atomically:

<?php
/**
 * Issue a full or partial refund for a WooCommerce order via Stripe.
 *
 * @param int    $order_id       WooCommerce order ID.
 * @param float  $refund_amount  Amount to refund in store currency.
 * @param string $reason         Reason for the refund (shown on Stripe dashboard).
 * @return WP_Error|WC_Order_Refund
 */
function dpls_stripe_refund_order( int $order_id, float $refund_amount, string $reason = '' ) {
    $order = wc_get_order( $order_id );

    if ( ! $order ) {
        return new WP_Error( 'invalid_order', 'Order not found.' );
    }

    $transaction_id = $order->get_transaction_id();

    if ( empty( $transaction_id ) ) {
        return new WP_Error( 'no_transaction', 'No Stripe transaction ID found on this order.' );
    }

    // Retrieve Stripe secret key from plugin settings
    $settings   = get_option( 'woocommerce_stripe_settings', [] );
    $test_mode  = isset( $settings['testmode'] ) && $settings['testmode'] === 'yes';
    $secret_key = $test_mode ? $settings['test_secret_key'] : $settings['secret_key'];

    \Stripe\Stripe::setApiKey( $secret_key );

    // Determine whether to refund a Charge or PaymentIntent
    $refund_params = [
        'amount' => (int) round( $refund_amount * 100 ),
        'reason' => 'requested_by_customer',
    ];

    if ( str_starts_with( $transaction_id, 'pi_' ) ) {
        $refund_params['payment_intent'] = $transaction_id;
    } else {
        $refund_params['charge'] = $transaction_id;
    }

    $stripe_refund = \Stripe\Refund::create( $refund_params );

    if ( $stripe_refund->status !== 'succeeded' ) {
        return new WP_Error( 'stripe_refund_failed', 'Stripe refund did not succeed.' );
    }

    // Create matching WooCommerce refund record
    $wc_refund = wc_create_refund( [
        'order_id'       => $order_id,
        'amount'         => $refund_amount,
        'reason'         => $reason,
        'refund_payment' => false, // Payment already refunded via Stripe above
    ] );

    $order->add_order_note(
        sprintf( 'Refund of %s issued via Stripe. Refund ID: %s', wc_price( $refund_amount ), $stripe_refund->id )
    );

    return $wc_refund;
}

6. 3D Secure (3DS) Authentication

3DS2 is mandatory for many card issuers in the EU (under PSD2 SCA rules) and increasingly common globally. Stripe handles the 3DS flow automatically when automatic_payment_methods is enabled, but you can also explicitly request it for high-risk transactions:

// Force 3DS for orders over $500
export async function createHighValuePaymentIntent(
  amountInCents: number,
  currency: string,
  orderId: number
): Promise<{ clientSecret: string; requiresAction: boolean }> {
  const paymentIntent = await stripe.paymentIntents.create({
    amount: amountInCents,
    currency,
    payment_method_options: {
      card: {
        request_three_d_secure: amountInCents >= 50000 ? "any" : "automatic",
      },
    },
    metadata: { woocommerce_order_id: String(orderId) },
  });

  return {
    clientSecret: paymentIntent.client_secret!,
    requiresAction: paymentIntent.status === "requires_action",
  };
}

On the client side, Stripe.js handles the 3DS modal automatically when you call stripe.confirmCardPayment(clientSecret). If the customer fails authentication, Stripe fires payment_intent.payment_failed with last_payment_error.code === "authentication_required". Your webhook handler should set the order status to pending (not failed) so the customer can re-attempt checkout.


7. Testing in Sandbox Mode

Stripe provides a robust test environment. Enable Test Mode in the WooCommerce Stripe plugin settings, then use the following test card numbers:

ScenarioCard NumberCVCExpiry
Successful payment4242 4242 4242 4242Any 3 digitsAny future date
3DS required (pass)4000 0027 6000 3184Any 3 digitsAny future date
3DS required (fail)4000 0084 0000 1629Any 3 digitsAny future date
Insufficient funds4000 0000 0000 9995Any 3 digitsAny future date
Card declined4000 0000 0000 0002Any 3 digitsAny future date
Dispute (chargeback)4000 0000 0000 2685Any 3 digitsAny future date

Use the Stripe CLI to forward webhooks to your local environment during development:

# Install Stripe CLI, then:
stripe login
stripe listen --forward-to http://localhost:8888/?wc-api=wc_stripe

# In a separate terminal, trigger a specific event manually:
stripe trigger payment_intent.succeeded

The CLI outputs a webhook signing secret (whsec_...) that you should copy into the WooCommerce Stripe plugin's Webhook Secret field during local testing.


8. Common Integration Issues and Solutions

Here's a TypeScript webhook handler that validates the Stripe signature (a critical security step), parses the event, and dispatches it to a handler map:

import express from "express";
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { apiVersion: "2024-04-10" });
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;

const app = express();

// IMPORTANT: Use raw body parser for Stripe webhook signature verification
app.post(
  "/stripe/webhook",
  express.raw({ type: "application/json" }),
  async (req, res) => {
    const sig = req.headers["stripe-signature"] as string;

    let event: Stripe.Event;

    try {
      // constructEvent throws if the signature is invalid
      event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
    } catch (err: any) {
      console.error(`Webhook signature verification failed: ${err.message}`);
      return res.status(400).send(`Webhook Error: ${err.message}`);
    }

    // Dispatch to typed handlers
    const handlers: Partial<Record<Stripe.Event["type"], (e: Stripe.Event) => Promise<void>>> = {
      "payment_intent.succeeded": handlePaymentSucceeded,
      "payment_intent.payment_failed": handlePaymentFailed,
      "charge.refunded": handleChargeRefunded,
      "charge.dispute.created": handleDisputeCreated,
    };

    const handler = handlers[event.type];

    if (handler) {
      await handler(event);
    }

    res.json({ received: true });
  }
);

async function handlePaymentSucceeded(event: Stripe.Event): Promise<void> {
  const intent = event.data.object as Stripe.PaymentIntent;
  const wcOrderId = intent.metadata?.woocommerce_order_id;

  if (!wcOrderId) {
    console.warn("PaymentIntent has no WooCommerce order ID in metadata.");
    return;
  }

  // Call WooCommerce REST API to update order status
  const response = await fetch(
    `${process.env.WC_STORE_URL}/wp-json/wc/v3/orders/${wcOrderId}`,
    {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Basic ${Buffer.from(
          `${process.env.WC_CONSUMER_KEY}:${process.env.WC_CONSUMER_SECRET}`
        ).toString("base64")}`,
      },
      body: JSON.stringify({
        status: "processing",
        transaction_id: intent.id,
      }),
    }
  );

  if (!response.ok) {
    throw new Error(`Failed to update WooCommerce order ${wcOrderId}: ${response.statusText}`);
  }

  console.log(`Order ${wcOrderId} marked as processing.`);
}

async function handlePaymentFailed(event: Stripe.Event): Promise<void> {
  const intent = event.data.object as Stripe.PaymentIntent;
  const wcOrderId = intent.metadata?.woocommerce_order_id;
  const errorCode = intent.last_payment_error?.code;

  console.error(`Payment failed for order ${wcOrderId}. Reason: ${errorCode}`);
  // Update WooCommerce order to "failed" status...
}

async function handleChargeRefunded(event: Stripe.Event): Promise<void> {
  const charge = event.data.object as Stripe.Charge;
  console.log(`Charge ${charge.id} refunded. Amount: ${charge.amount_refunded}`);
  // Sync WooCommerce refund record if needed...
}

async function handleDisputeCreated(event: Stripe.Event): Promise<void> {
  const dispute = event.data.object as Stripe.Dispute;
  console.warn(`Dispute created: ${dispute.id}. Amount: ${dispute.amount}`);
  // Notify admin, flag order...
}

app.listen(3000, () => console.log("Webhook server running on port 3000"));

Common pitfalls and fixes:

  • Signature verification fails: Ensure you are using express.raw() (not express.json()) before the webhook route. express.json() parses the body and invalidates the signature.
  • Duplicate order processing: Stripe may deliver webhooks more than once. Use the event.id as an idempotency key stored in your database to prevent double-processing.
  • Webhook timeout: Stripe expects a 200 response within 30 seconds. Offload heavy processing (e.g., sending emails, generating invoices) to a job queue and respond immediately.
  • Currency mismatch: WooCommerce stores totals as strings with decimals. Always multiply by 100 and use Math.round() to convert to Stripe's integer cent format.
  • Webhook endpoint not reachable: Use the Stripe CLI during local development. On staging/production, ensure your server's IP is not behind a firewall that blocks Stripe's IP ranges.

Conclusion

Integrating Stripe with WooCommerce goes far beyond installing a plugin. A production-grade integration requires a solid understanding of the Payment Intent lifecycle, reliable webhook handling with signature verification, idempotent event processing, and language-level tooling for programmatic refunds and 3DS enforcement.

Key takeaways from this guide:

  1. Use PaymentIntents, not the legacy Charges API — it supports 3DS2, off-session payments, and multi-step payment flows.
  2. Always verify webhook signatures using stripe.webhooks.constructEvent() with the raw request body.
  3. Store the WooCommerce order ID in PaymentIntent metadata so your webhook handler can reliably map back to the correct order.
  4. Handle idempotency — Stripe can deliver the same webhook event multiple times; your handler must be safe to run twice.
  5. Test thoroughly using the Stripe CLI and dedicated test card numbers before going live.
  6. Never hard-code API keys — load them from environment variables or a secrets manager in all environments.

With the REST API patterns and webhook architecture covered in this article, you have everything you need to build a robust, automated WooCommerce payment pipeline that scales with your store.

Tags:#WooCommerce#Stripe#Payments#REST API#Webhooks
Dev Pattern Labs Engineering Team

Written by Dev Pattern LabsCore Engineering

Dev Pattern Labs is an engineering lab and digital consultancy specializing in custom Next.js web applications, WooCommerce REST API integrations, and workflow automation for growing businesses.

Recommended Companion Articles