---
title: Extending WooCommerce Subscriptions with Custom Gateways
description: Integrate custom payment gateways with WooCommerce Subscriptions using HPOS-safe APIs, renewal tokens, idempotency and webhook reconciliation.
url: https://moxseo.com/blogs/woocommerce-subscriptions-custom-payment-gateways
date_modified: 2026-10-28
author: Aditya Bhimrajka
language: en_US
---

### Executive Summary & Key Technical Takeaways

- **WooCommerce Subscriptions Object Lifecycle:** A `WC_Subscription` extends `WC_Order`, representing a distinct contract entity with its own status machine (`active`, `on-hold`, `pending-cancel`, `cancelled`, `expired`) and scheduled payment dates.
- **High-Performance Order Storage (HPOS) Alignment:** Subscriptions in modern WooCommerce utilize custom database tables (`wp_wc_orders` with `type = 'shop_subscription'`), requiring direct SQL queries to target indexed columns rather than legacy `wp_posts` and `wp_postmeta`.
- **Tokenized Gateway Renewal Triggers:** Automated recurring renewals require payment gateways to implement `WC_Payment_Gateway_CC` and support `payment_tokens`. When Action Scheduler triggers `woocommerce_scheduled_subscription_payment_{gateway_id}`, the gateway must process the charge off-session.
- **Custom Smart Dunning Mechanics:** Implementing custom retry rules intercepting `wcs_default_retry_rules` allows enterprise merchants to customize backoff intervals, dynamic card re-attempts, and customer email alerts to reduce involuntary churn.
- **Proration and Upgrade/Downgrade Calculations:** Changing billing intervals or subscription tiers mid-cycle demands precise mathematical proration that accounts for consumed days, credit balances, and immediate vs next-cycle renewal adjustments.
- **Webhook Synchronization & Idempotency:** Gateway webhooks (e.g., Stripe invoice payments or chargebacks) must be processed idempotently using database transactions to prevent duplicate renewal order creations and race conditions.
- **Custom Billing Engineering:** MoxSEO’s web development team builds and audits custom WooCommerce subscription gateways and recurring-billing integrations; see our [WooCommerce development services](/services/web-development/e-commerce/).

Recurring revenue is the lifeblood of modern eCommerce, yet building bespoke recurring billing logic atop WooCommerce Subscriptions is one of the most complex engineering challenges in the WordPress ecosystem. A subscription is not merely a scheduled post or a standard order; it is a long-lived, multi-state financial contract that demands asynchronous off-session payment orchestration, sophisticated dunning and retry mechanics, payment token management, churn mitigation, and webhook event reconciliation. In this comprehensive technical guide, we will architect, engineer, and deploy an enterprise-grade WooCommerce Subscriptions extension from scratch using modern PHP 8.3 OOP patterns, HPOS-native database queries, custom payment gateway renewal hooks, WP-CLI automation, and smart dunning algorithms.

## 1. The Underbelly of WooCommerce Subscriptions: Object Architecture & HPOS

In modern WooCommerce (with High-Performance Order Storage enabled), a subscription is represented by the `WC_Subscription` class. Because `WC_Subscription` inherits directly from `WC_Order`, it shares core eCommerce functionality (line items, billing addresses, coupons, and totals) while introducing an intricate state machine and scheduled date properties.

#### Core Anatomical Lifecycle of a Subscription:

1. **Initial Purchase (Parent Order):** Customer completes checkout. WooCommerce creates a standard `shop_order` (the parent order) and spawns an associated `shop_subscription` record linked via `post_parent` or `parent_order_id` in HPOS.
2. **Payment Method Tokenization:** The payment gateway captures customer credentials and saves a secure payment token (`WC_Payment_Token_CC`) assigned to the customer and the subscription object.
3. **Action Scheduler Date Hooking:** WooCommerce Subscriptions schedules future background actions in the `wp_actionscheduler_actions` table matching the next payment date (`woocommerce_scheduled_subscription_payment`).
4. **Renewal Order Generation:** When the scheduled timestamp arrives, Action Scheduler executes the renewal hook, generates an unpaid child `shop_order` (renewal order), and triggers the gateway’s recurring payment method.
5. **Settlement or Dunning:** If payment succeeds, the renewal order transitions to `completed` or `processing`, and the subscription’s next payment date recalculates. If payment fails, the subscription enters the Dunning Retry state.

### Database Storage in HPOS vs Legacy Post Types

Prior to HPOS, subscriptions lived inside `wp_posts` (`post_type = 'shop_subscription'`) with dates and customer tokens scattered across dozens of rows in `wp_postmeta`. In modern HPOS:

- The core subscription record is stored in `wp_wc_orders` where `type = 'shop_subscription'`.
- Operational addresses are indexed in `wp_wc_order_addresses`.
- Operational totals and status flags live in dedicated indexed columns rather than unstructured post meta.

| Subscription Status | Customer Access State | Scheduled Actions Active? | Permitted State Transitions |
| --- | --- | --- | --- |
| **Active** | Full entitlement access | Yes (Next payment scheduled) | On-Hold, Pending-Cancel, Cancelled, Expired |
| **On-Hold** | Suspended (Grace period optional) | Yes (Dunning retry actions active) | Active (on payment), Cancelled, Expired |
| **Pending-Cancel** | Active until end of prepaid term | Only End-Date action active | Active (Reactivation), Cancelled |
| **Cancelled** | Revoked immediately | No (All actions purged) | Terminal State (or manual Admin reactivation) |
| **Expired** | Revoked (Term limit reached) | No (All actions completed) | Terminal State |

## 2. Implementing Custom Payment Gateway Recurring Triggers

To support automated recurring charges in a custom payment gateway, your gateway class must declare support for `'subscriptions'`, `'subscription_cancellation'`, `'subscription_suspension'`, `'subscription_reactivation'`, and `'subscription_amount_changes'`.

When Action Scheduler fires the scheduled renewal hook, it executes `woocommerce_scheduled_subscription_payment_{gateway_id}`. The gateway must process the charge off-session using the stored payment token.

```
<?php
declare(strict_types=1);

namespace WPStack\Subscriptions\Gateways;

use WC_Payment_Gateway_CC;
use WC_Subscription;
use WC_Order;
use WC_Payment_Tokens;
use WC_Payment_Token_CC;
use Throwable;

final class CustomEnterprisePaymentGateway extends WC_Payment_Gateway_CC
{
    public function __construct()
    {
        $this->id = 'wpstack_enterprise_gateway';
        $this->method_title = __('WPStack Enterprise Gateway', 'wpstack-subscriptions');
        $this->method_description = __('High-performance recurring gateway with off-session token renewals.', 'wpstack-subscriptions');
        $this->has_fields = true;

        // Declare WooCommerce Subscriptions Support
        $this->supports = [
            'products',
            'subscriptions',
            'subscription_cancellation',
            'subscription_suspension',
            'subscription_reactivation',
            'subscription_amount_changes',
            'subscription_date_changes',
            'multiple_subscriptions',
            'tokenization',
        ];

        $this->init_form_fields();
        $this->init_settings();

        // Hook into scheduled subscription renewal execution
        add_action('woocommerce_scheduled_subscription_payment_' . $this->id, [$this, 'processScheduledRenewalPayment'], 10, 2);
    }

    /**
     * Executes off-session recurring renewal charges triggered by Action Scheduler.
     *
     * @param float $amountToCharge
     * @param WC_Order $renewalOrder Child renewal order created by WCS
     */
    public function processScheduledRenewalPayment(float $amountToCharge, WC_Order $renewalOrder): void
    {
        $customerId = $renewalOrder->get_customer_id();
        $tokens = WC_Payment_Tokens::get_customer_tokens($customerId, $this->id);

        if (empty($tokens)) {
            $renewalOrder->update_status('failed', __('No stored payment token found for off-session renewal charge.', 'wpstack-subscriptions'));
            return;
        }

        /** @var WC_Payment_Token_CC $defaultToken */
        $defaultToken = reset($tokens);
        $gatewayTokenId = $defaultToken->get_token();

        try {
            // Dispatch off-session API call to payment processor
            $chargeResult = $this->executeOffSessionCharge(
                tokenId: $gatewayTokenId,
                amount: $amountToCharge,
                currency: $renewalOrder->get_currency(),
                orderId: $renewalOrder->get_id()
            );

            if ($chargeResult['status'] === 'succeeded') {
                // Record transaction ID and complete payment
                $renewalOrder->payment_complete($chargeResult['transaction_id']);
                $renewalOrder->add_order_note(
                    sprintf(__('Off-session recurring renewal payment of %s completed via Token (%s).', 'wpstack-subscriptions'),
                        wc_price($amountToCharge),
                        $defaultToken->get_last4()
                    )
                );
            } else {
                $renewalOrder->update_status('failed', sprintf(__('Processor rejected charge: %s', 'wpstack-subscriptions'), $chargeResult['error_message']));
            }
        } catch (Throwable $e) {
            $renewalOrder->update_status('failed', sprintf(__('Gateway exception during recurring charge: %s', 'wpstack-subscriptions'), $e->getMessage()));
        }
    }

    private function executeOffSessionCharge(string $tokenId, float $amount, string $currency, int $orderId): array
    {
        // Mocking remote HTTPS request to payment processor API
        $payload = [
            'token'       => $tokenId,
            'amount_cents'=> (int) round($amount * 100),
            'currency'    => strtolower($currency),
            'order_id'    => $orderId,
            'off_session' => true,
        ];

        // Replace with actual cURL / wp_remote_post API dispatch
        return [
            'status'         => 'succeeded',
            'transaction_id' => 'txn_' . bin2hex(random_bytes(10)),
            'error_message'  => null,
        ];
    }
}

```

## 3. Engineering Custom Smart Dunning Rules & Retry Mechanics

Default WooCommerce Subscriptions retry rules follow a rigid schedule (e.g., retry after 12 hours, 24 hours, 48 hours, up to 5 attempts). For enterprise SaaS and B2B stores, intelligent dunning strategies significantly reduce involuntary churn by tailoring retry intervals around weekend credit card clearing cycles and payroll dates (1st and 15th of the month).

```
<?php
declare(strict_types=1);

namespace WPStack\Subscriptions\Dunning;

use WC_Subscription;
use WC_Order;

final class SmartDunningManager
{
    public function registerHooks(): void
    {
        add_filter('wcs_default_retry_rules', [$this, 'customizeDunningSchedule']);
        add_action('woocommerce_subscriptions_after_apply_retry_rule', [$this, 'sendProactiveDunningAlert'], 10, 2);
    }

    /**
     * Customizes automated retry intervals and status triggers.
     *
     * @param array<int, array<string, mixed>> $defaultRules
     * @return array<int, array<string, mixed>>
     */
    public function customizeDunningSchedule(array $defaultRules): array
    {
        return [
            // Attempt 1: 4 hours after initial failure (catches temporary bank fraud holds)
            [
                'retry_after_interval' => 4 * HOUR_IN_SECONDS,
                'email_template'       => 'WC_Email_Customer_Retry',
                'status_to_apply'      => 'on-hold',
            ],
            // Attempt 2: 24 hours later
            [
                'retry_after_interval' => DAY_IN_SECONDS,
                'email_template'       => 'WC_Email_Customer_Retry',
                'status_to_apply'      => 'on-hold',
            ],
            // Attempt 3: 72 hours later (after customer receives email)
            [
                'retry_after_interval' => 3 * DAY_IN_SECONDS,
                'email_template'       => 'WC_Email_Customer_Retry',
                'status_to_apply'      => 'on-hold',
            ],
            // Attempt 4: 7 days later (aligns with weekly payroll cycle)
            [
                'retry_after_interval' => 7 * DAY_IN_SECONDS,
                'email_template'       => 'WC_Email_Customer_Retry',
                'status_to_apply'      => 'on-hold',
            ],
            // Final Attempt: 14 days later before hard cancellation
            [
                'retry_after_interval' => 14 * DAY_IN_SECONDS,
                'email_template'       => 'WC_Email_Customer_Renewal_Invoice',
                'status_to_apply'      => 'cancelled',
            ],
        ];
    }

    public function sendProactiveDunningAlert(WC_Order $renewalOrder, int $retryCount): void
    {
        $subscriptionId = $renewalOrder->get_meta('_subscription_renewal');
        if (empty($subscriptionId)) {
            return;
        }

        $subscription = wcs_get_subscription((int)$subscriptionId);
        if (!$subscription instanceof WC_Subscription) {
            return;
        }

        $customerEmail = $renewalOrder->get_billing_email();
        $updateCardUrl = $subscription->get_change_payment_method_url();

        // Dispatch custom SMS / Slack / Email webhook notification
        do_action('wpstack_dunning_notification_dispatched', [
            'subscription_id' => $subscription->get_id(),
            'email'           => $customerEmail,
            'retry_attempt'   => $retryCount,
            'update_card_url' => $updateCardUrl,
        ]);
    }
}

```

### Proactive Pre-Dunning: Card Expiration Interceptors

The most effective dunning strategy is preventing card failure before the renewal date arrives. In WooCommerce, credit card expiration months and years are stored inside `wp_woocommerce_payment_tokenmeta`. We implement a scheduled daily cron worker that queries tokens expiring at the end of the current month and dispatches automated reminder emails with secure one-click update links.

```
<?php
declare(strict_types=1);

namespace WPStack\Subscriptions\Dunning;

use wpdb;
use WC_Payment_Tokens;

final class CardExpirationMonitor
{
    private wpdb $db;

    public function __construct(wpdb $db)
    {
        $this->db = $db;
    }

    public function checkExpiringTokens(): void
    {
        $currentYear = (int)gmdate('Y');
        $currentMonth = (int)gmdate('m');

        // Query payment tokens expiring this month for active subscribers
        $sql = "
            SELECT DISTINCT t.user_id, t.token_id, m_exp_month.meta_value AS exp_month, m_exp_year.meta_value AS exp_year
            FROM {$this->db->prefix}woocommerce_payment_tokens t
            JOIN {$this->db->prefix}woocommerce_payment_tokenmeta m_exp_month ON t.token_id = m_exp_month.payment_token_id AND m_exp_month.meta_key = 'expiry_month'
            JOIN {$this->db->prefix}woocommerce_payment_tokenmeta m_exp_year ON t.token_id = m_exp_year.payment_token_id AND m_exp_year.meta_key = 'expiry_year'
            WHERE m_exp_year.meta_value = %s AND m_exp_month.meta_value = %s
        ";

        $expiringTokens = $this->db->get_results($this->db->prepare($sql, (string)$currentYear, sprintf('%02d', $currentMonth)), ARRAY_A);

        foreach ($expiringTokens as $item) {
            $user = get_userdata((int)$item['user_id']);
            if ($user && !empty($user->user_email)) {
                wp_mail(
                    $user->user_email,
                    'Action Required: Your Payment Card is Expiring Soon',
                    "Your credit card on file expires this month. Please update your payment details in My Account to prevent any interruption in your subscription services."
                );
            }
        }
    }
}

```

## 4. Mathematical Proration Engine for Mid-Cycle Upgrades & Downgrades

When a customer switches from a $50/month tier to a $150/month tier 10 days into a 30-day billing cycle, charging the full $150 immediately results in double-billing. The `SubscriptionProrationEngine` calculates exact per-second credits and debits.

```
<?php
declare(strict_types=1);

namespace WPStack\Subscriptions\Proration;

use WC_Subscription;
use InvalidArgumentException;

final class SubscriptionProrationEngine
{
    /**
     * Calculates the exact financial delta for an immediate mid-cycle tier switch.
     *
     * @param WC_Subscription $subscription
     * @param float $newTierMonthlyCost
     * @return array{
     *     credit_unused_current_tier: float,
     *     cost_remaining_new_tier: float,
     *     net_charge_amount: float,
     *     days_remaining_in_period: float
     * }
     */
    public function calculateProratedTierSwitch(WC_Subscription $subscription, float $newTierMonthlyCost): array
    {
        $startTime = $subscription->get_time('date_created');
        $lastPaymentTime = $subscription->get_time('last_order_date_created') ?: $startTime;
        $nextPaymentTime = $subscription->get_time('next_payment');
        $currentTime = time();

        if ($nextPaymentTime <= $currentTime || $nextPaymentTime <= $lastPaymentTime) {
            throw new InvalidArgumentException('Subscription has no active remaining period to prorate.');
        }

        $totalPeriodSeconds = $nextPaymentTime - $lastPaymentTime;
        $remainingSeconds = $nextPaymentTime - $currentTime;
        $fractionRemaining = $remainingSeconds / $totalPeriodSeconds;

        $currentTierCost = (float)$subscription->get_total();

        // Calculate unused value of current tier
        $unusedCredit = round($currentTierCost * $fractionRemaining, 2);

        // Calculate cost of new tier for remaining duration
        $newTierProratedCost = round($newTierMonthlyCost * $fractionRemaining, 2);

        // Net charge to process immediately
        $netCharge = max(0.0, round($newTierProratedCost - $unusedCredit, 2));

        return [
            'credit_unused_current_tier' => $unusedCredit,
            'cost_remaining_new_tier'    => $newTierProratedCost,
            'net_charge_amount'          => $netCharge,
            'days_remaining_in_period'   => round($remainingSeconds / 86400, 2),
        ];
    }
}

```

## 5. Anti-Churn Workflows: Subscription Pause & Cancellation Interceptors

Allowing customers to pause their subscription for 30 or 60 days rather than cancelling outright can retain some at-risk subscribers who would otherwise cancel. We construct a custom cancellation interceptor that hooks into the “Cancel Subscription” action in WooCommerce My Account.

```
<?php
declare(strict_types=1);

namespace WPStack\Subscriptions\Churn;

use WC_Subscription;

final class SubscriptionPauseManager
{
    public function registerHooks(): void
    {
        add_action('wp_ajax_wpstack_pause_subscription', [$this, 'handleSubscriptionPause']);
    }

    public function handleSubscriptionPause(): void
    {
        check_ajax_referer('wpstack_pause_nonce', 'security');

        $subscriptionId = (int)($_POST['subscription_id'] ?? 0);
        $pauseDays = min(90, max(14, (int)($_POST['pause_days'] ?? 30)));

        $subscription = wcs_get_subscription($subscriptionId);
        if (!$subscription instanceof WC_Subscription) {
            wp_send_json_error(['message' => 'Subscription not found.'], 404);
        }

        // Verify ownership
        if ($subscription->get_customer_id() !== get_current_user_id()) {
            wp_send_json_error(['message' => 'Unauthorized.'], 403);
        }

        // Calculate new next payment date
        $currentNextPayment = $subscription->get_time('next_payment');
        $newNextPayment = $currentNextPayment + ($pauseDays * DAY_IN_SECONDS);

        // Update scheduled date and transition to on-hold
        $subscription->update_dates([
            'next_payment' => gmdate('Y-m-d H:i:s', $newNextPayment),
        ]);

        $subscription->update_status('on-hold', sprintf(__('Customer paused subscription for %d days via My Account.', 'wpstack-subscriptions'), $pauseDays));

        wp_send_json_success([
            'message' => sprintf(__('Your subscription is paused. Next billing date: %s', 'wpstack-subscriptions'), date('F j, Y', $newNextPayment)),
            'new_date' => date('Y-m-d', $newNextPayment),
        ]);
    }
}

```

## 6. Webhook Reconciliation & Asynchronous Idempotency

When external payment gateways process asynchronous recurring payments or dispute chargebacks, they dispatch webhooks. If the network experiences packet loss or retries, your endpoint might receive the same webhook five times within seconds. Without strict idempotency guards and MySQL row-level locking, your store will spawn duplicate renewal orders, generate multiple invoices, and double-charge customer cards.

```
<?php
declare(strict_types=1);

namespace WPStack\Subscriptions\Webhooks;

use wpdb;
use WC_Subscription;
use WP_REST_Request;
use WP_REST_Response;

final class IdempotentWebhookHandler
{
    private wpdb $db;

    public function __construct(wpdb $db)
    {
        $this->db = $db;
    }

    public function handleIncomingPaymentWebhook(WP_REST_Request $request): WP_REST_Response
    {
        $eventId = (string)$request->get_param('event_id');
        $subscriptionId = (int)$request->get_param('subscription_id');
        $transactionId = (string)$request->get_param('transaction_id');

        if (empty($eventId) || empty($subscriptionId)) {
            return new WP_REST_Response(['error' => 'Missing event metadata'], 400);
        }

        // 1. Atomic Idempotency Check using MySQL Transaction Lock
        $this->db->query('START TRANSACTION');

        $isProcessed = $this->db->get_var($this->db->prepare(
            "SELECT id FROM {$this->db->prefix}wpstack_processed_webhooks WHERE event_id = %s FOR UPDATE",
            $eventId
        ));

        if ($isProcessed !== null) {
            $this->db->query('COMMIT');
            return new WP_REST_Response(['status' => 'duplicate_ignored'], 200);
        }

        // Record event in processing table
        $this->db->insert(
            $this->db->prefix . 'wpstack_processed_webhooks',
            [
                'event_id'     => $eventId,
                'created_at'   => current_time('mysql'),
            ]
        );

        $this->db->query('COMMIT');

        // 2. Safely Process Subscription Renewal
        $subscription = wcs_get_subscription($subscriptionId);
        if ($subscription instanceof WC_Subscription) {
            $subscription->payment_complete($transactionId);
            $subscription->add_order_note(sprintf(__('Webhook %s processed: Recurring renewal confirmed.', 'wpstack-subscriptions'), $eventId));
        }

        return new WP_REST_Response(['status' => 'success'], 200);
    }
}

```

## 7. Complete Subscription Lifecycle Action Hooks & Filter Reference

To orchestrate complex business workflows (such as provisioning third-party SaaS accounts, firing marketing automation events, or generating custom PDF invoices), developers must master the key lifecycle hooks exposed by WooCommerce Subscriptions.

| Action / Filter Hook | Execution Timing | Passed Parameters | Common Use Cases |
| --- | --- | --- | --- |
| `woocommerce_scheduled_subscription_payment` | Fires when renewal timestamp is reached | `$subscription_id` | Initiating custom off-session payments |
| `wcs_renewal_order_created` | Immediately after child renewal order is inserted | `$renewal_order, $subscription` | Copying custom meta from subscription to order |
| `woocommerce_subscription_status_updated` | Upon any status transition | `$subscription, $new_status, $old_status` | Revoking or provisioning SaaS access credentials |
| `woocommerce_subscriptions_switch_order_created` | When customer switches/upgrades plan | `$switch_order, $subscription` | Recording upgrade telemetry and MRR deltas |
| `wcs_get_subscription_date` | Filter applied when evaluating date types | `$date_string, $date_type, $subscription` | Customizing trial lengths or grace periods dynamically |

```
<?php
declare(strict_types=1);

namespace WPStack\Subscriptions\Listeners;

use WC_Subscription;
use WC_Order;

final class SubscriptionLifecycleListener
{
    public function register(): void
    {
        add_action('woocommerce_subscription_status_updated', [$this, 'handleStatusTransition'], 10, 3);
        add_action('wcs_renewal_order_created', [$this, 'syncCustomMetadataToRenewal'], 10, 2);
    }

    public function handleStatusTransition(WC_Subscription $subscription, string $newStatus, string $oldStatus): void
    {
        $customerId = $subscription->get_customer_id();

        if ($newStatus === 'cancelled' || $newStatus === 'expired') {
            // Revoke SaaS license key or external account API access
            do_action('wpstack_saas_revoke_account', $customerId, $subscription->get_id());
        }

        if ($newStatus === 'active' && ($oldStatus === 'on-hold' || $oldStatus === 'pending')) {
            // Reactivate SaaS license key
            do_action('wpstack_saas_activate_account', $customerId, $subscription->get_id());
        }
    }

    public function syncCustomMetadataToRenewal(WC_Order $renewalOrder, WC_Subscription $subscription): void
    {
        // Propagate enterprise customer tax ID and VAT numbers to renewal invoice
        $vatNumber = $subscription->get_meta('_wpstack_vat_number');
        if (!empty($vatNumber)) {
            $renewalOrder->update_meta_data('_wpstack_vat_number', $vatNumber);
            $renewalOrder->save();
        }
    }
}

```

## 8. Dynamic Coupon Invalidation & Recurring Discount Logic

A frequent business requirement in subscription businesses is granting a temporary discount for the first N recurring cycles (e.g., 50% off for the first 3 months) before automatically reverting to standard full pricing.

```
<?php
declare(strict_types=1);

namespace WPStack\Subscriptions\Coupons;

use WC_Subscription;
use WC_Order;

final class RecurringCouponLifecycleManager
{
    public function registerHooks(): void
    {
        add_action('woocommerce_subscription_payment_complete', [$this, 'evaluateRecurringCoupons'], 10, 1);
    }

    /**
     * Inspects payment cycles and strips intro discounts after expiration.
     */
    public function evaluateRecurringCoupons(WC_Subscription $subscription): void
    {
        $coupons = $subscription->get_items('coupon');
        if (empty($coupons)) {
            return;
        }

        $completedRenewals = count($subscription->get_related_orders('all', 'renewal'));

        foreach ($coupons as $couponItem) {
            $couponCode = $couponItem->get_name();
            $maxCycles = (int) get_post_meta(wc_get_coupon_id_by_code($couponCode), '_wpstack_max_discount_cycles', true);

            if ($maxCycles > 0 && $completedRenewals >= $maxCycles) {
                // Remove expired coupon from future renewals
                $subscription->remove_coupon($couponCode);
                $subscription->calculate_totals();
                $subscription->save();

                $subscription->add_order_note(
                    sprintf(__('Introductory discount "%s" reached max duration (%d cycles) and was removed.', 'wpstack-subscriptions'), $couponCode, $maxCycles)
                );
            }
        }
    }
}

```

## 9. Database Index Optimization for High-Volume HPOS Subscriptions

On stores managing upwards of 100,000 active subscriptions, query latency during daily renewal sweeps can degrade store checkout performance unless composite indexes are added to the HPOS tables.

```
-- Optimize HPOS Orders table for High-Frequency Subscription Queries
ALTER TABLE `wp_wc_orders`
ADD INDEX `idx_sub_type_status_date` (`type`, `status`, `date_created_gmt`),
ADD INDEX `idx_sub_customer_type` (`customer_id`, `type`, `status`);

-- Optimize Action Scheduler queries for pending renewals
ALTER TABLE `wp_actionscheduler_actions`
ADD INDEX `idx_claim_hook_status` (`hook`, `status`, `scheduled_date_gmt`);

```

Adding the `idx_sub_type_status_date` composite index turns scheduled renewal lookups from a full table scan into an indexed range seek, preventing database lock contention when Action Scheduler processes batches of hundreds of recurring renewals concurrently.

## 10. High-Concurrency Webhook Load Testing with k6

To verify that our idempotency database lock prevents double-charging under heavy webhook retry storms, we execute a load test script using k6.

```
// k6 script: webhook_idempotency_storm.js
import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
  scenarios: {
    webhook_burst: {
      executor: 'per-vu-iterations',
      vus: 20, // 20 concurrent workers firing same event ID
      iterations: 1,
      maxDuration: '10s',
    },
  },
};

export default function () {
  const url = 'https://example.com/wp-json/wpstack/v1/subscription-webhook';
  const payload = JSON.stringify({
    event_id: 'evt_burst_test_8892',
    subscription_id: 1042,
    transaction_id: 'txn_mock_9921',
  });

  const params = {
    headers: { 'Content-Type': 'application/json' },
  };

  const res = http.post(url, payload, params);

  check(res, {
    'status is 200': (r) => r.status === 200,
    'handled correctly': (r) => r.json().status === 'success' || r.json().status === 'duplicate_ignored',
  });
}

```

## 9. WP-CLI Automation: Subscription Health & Metric Telemetry

Managing thousands of active subscriptions requires automated command-line tools to audit stalled queues, force retry dunning on stuck orders, and calculate Monthly Recurring Revenue (MRR).

```
<?php
declare(strict_types=1);

namespace WPStack\Subscriptions\Cli;

use WP_CLI;
use WP_CLI_Command;

if (!defined('WP_CLI') || !WP_CLI) {
    return;
}

final class SubscriptionCliCommand extends WP_CLI_Command
{
    /**
     * Calculates real-time Monthly Recurring Revenue (MRR) from active HPOS subscriptions.
     *
     * ## EXAMPLES
     *
     *     wp wpstack sub mrr
     */
    public function mrr(array $args, array $assocArgs): void
    {
        global $wpdb;

        $ordersTable = $wpdb->prefix . 'wc_orders';
        $metaTable = $wpdb->prefix . 'wc_orders_meta';

        $sql = "
            SELECT 
                o.total_amount,
                m_interval.meta_value AS billing_interval,
                m_period.meta_value AS billing_period
            FROM {$ordersTable} o
            JOIN {$metaTable} m_interval ON o.id = m_interval.order_id AND m_interval.meta_key = '_billing_interval'
            JOIN {$metaTable} m_period ON o.id = m_period.order_id AND m_period.meta_key = '_billing_period'
            WHERE o.type = 'shop_subscription' AND o.status = 'wc-active'
        ";

        $rows = $wpdb->get_results($sql, ARRAY_A);
        $totalMrr = 0.0;

        foreach ($rows as $row) {
            $amount = (float)$row['total_amount'];
            $interval = max(1, (int)$row['billing_interval']);
            $period = (string)$row['billing_period'];

            $monthlyValue = match ($period) {
                'day'   => ($amount / $interval) * 30.416,
                'week'  => ($amount / $interval) * 4.345,
                'month' => ($amount / $interval),
                'year'  => ($amount / $interval) / 12,
                default => 0.0,
            };

            $totalMrr += $monthlyValue;
        }

        WP_CLI::success(sprintf('Active Subscribers: %d | Total MRR: $%s USD', count($rows), number_format($totalMrr, 2)));
    }
}

WP_CLI::add_command('wpstack sub', SubscriptionCliCommand::class);

```

## 10. Automated PHPUnit Integration Test Suite for Subscriptions

To ensure custom subscription triggers, smart dunning schedules, and proration math remain stable during continuous integration, we write comprehensive PHPUnit integration tests.

```
<?php
declare(strict_types=1);

namespace WPStack\Subscriptions\Tests;

use WP_UnitTestCase;
use WPStack\Subscriptions\Proration\SubscriptionProrationEngine;
use WC_Subscription;

final class SubscriptionProrationTest extends WP_UnitTestCase
{
    public function testProrationCalculatesAccurateNetCharge(): void
    {
        $engine = new SubscriptionProrationEngine();

        // Create mock subscription object
        $subscription = $this->createMock(WC_Subscription::class);

        $now = time();
        $periodStart = $now - (10 * 86400); // 10 days ago
        $periodEnd = $now + (20 * 86400);   // 20 days remaining (total 30-day cycle)

        $subscription->method('get_time')->willReturnMap([
            ['date_created', $periodStart],
            ['last_order_date_created', $periodStart],
            ['next_payment', $periodEnd],
        ]);

        $subscription->method('get_total')->willReturn('30.00'); // $30/month ($1/day)

        // Upgrade to $90/month ($3/day)
        $result = $engine->calculateProratedTierSwitch($subscription, 90.00);

        // Unused credit of current tier: $30 * (20/30) = $20.00
        $this->assertEquals(20.00, $result['credit_unused_current_tier']);

        // Cost of new tier for remaining 20 days: $90 * (20/30) = $60.00
        $this->assertEquals(60.00, $result['cost_remaining_new_tier']);

        // Net charge to pay immediately: $60 - $20 = $40.00
        $this->assertEquals(40.00, $result['net_charge_amount']);
    }
}

```

## 11. Troubleshooting Runbook: Resolving Stuck Subscriptions in Production

### Operational Subscriptions Triage Matrix

1. **Subscription Stalled in “Pending Cancellation”:**

- *Root Cause:* Action Scheduler end-date action (`woocommerce_scheduled_subscription_end_of_prepaid_term`) failed to spawn or was purged.
- *Remedy:* Run `wp action-scheduler run --hooks=woocommerce_scheduled_subscription_end_of_prepaid_term` via WP-CLI.
2. **Duplicate Renewal Orders Generated:**

- *Root Cause:* Action Scheduler timeout triggered a worker retry while the payment gateway request was still pending.
- *Remedy:* Implement atomic database idempotency locks on `woocommerce_scheduled_subscription_payment`.
3. **Payment Method Token Expired:**

- *Root Cause:* Gateway token invalidated on processor side without firing customer notification.
- *Remedy:* Automatically transition subscription to `on-hold` and dispatch the `WC_Email_Customer_Payment_Retry` email.

## Frequently Asked Questions (FAQ)

### 1. How does WooCommerce Subscriptions handle scheduled renewal payments?

WooCommerce Subscriptions uses the Action Scheduler background engine. When a subscription is activated, an action is scheduled in `wp_actionscheduler_actions` for the exact timestamp of the next renewal. When triggered, it creates a child renewal order and dispatches an off-session charge to the customer’s tokenized payment gateway.

### 2. What is the difference between a Parent Order and a Renewal Order?

The Parent Order is the initial checkout order placed by the customer that establishes the subscription contract and captures initial payment tokens. A Renewal Order is a new child `shop_order` generated automatically at each billing cycle representing the recurring transaction and invoice.

### 3. How do smart dunning retry rules reduce involuntary churn?

Smart dunning rules replace immediate subscription cancellations with an intelligent series of delayed payment retries (e.g., after 4 hours, 24 hours, 3 days, and 7 days). This catches transient card declines caused by temporary bank fraud filters, daily spending limits, and payroll replenishment cycles.

### 4. How are subscriptions stored in WooCommerce High-Performance Order Storage (HPOS)?

Under HPOS, subscriptions are stored as first-class order records in the dedicated `wp_wc_orders` table with `type = 'shop_subscription'`. Operational metadata, customer addresses, and order operational flags are indexed in dedicated relational tables, eliminating the need for slow `wp_postmeta` joins.

### 5. How does payment tokenization work for recurring WooCommerce charges?

Payment tokenization replaces raw credit card details with a secure cryptographic string (token) provided by the payment processor (e.g., Stripe, Braintree). The token is saved in `wp_woocommerce_payment_tokens` and associated with the customer ID, allowing the server to initiate off-session charges without storing sensitive PCI data.

### 6. What happens when a customer upgrades their subscription mid-cycle?

When a customer upgrades mid-cycle, a proration engine calculates the monetary value of the unused days on their current plan and credits it against the prorated cost of the new higher tier for the remainder of the billing period, charging only the net financial difference.

### 7. Why is webhook idempotency essential for subscription renewal webhooks?

Payment gateways frequently resend webhooks if they do not receive an immediate HTTP 200 response within 2–5 seconds. Without idempotency tables and database row-level locking, duplicate webhooks will trigger multiple renewal order creations and duplicate charges for the same billing cycle.

### 8. Can I manually trigger a scheduled subscription payment via WP-CLI?

Yes. You can trigger pending subscription renewals immediately using WP-CLI by running `wp action-scheduler run --group=woocommerce-subscriptions` or targeting individual subscription actions by ID with `wp action-scheduler run --action-id=<id>`.
