Skip to content

Diagnostic Shipping and tax at renewal

Before recalculating WooCommerce renewals: which subscriptions to leave alone

Once you know renewals charge old shipping and tax, the obvious next step is to recalculate them. That changes what customers are charged, so it is worth knowing first which subscriptions it would be unsafe to touch, and why the safe answer for each is to leave it exactly as stored. Here is the list, and a small read-only check that sorts your subscriptions into safe and leave-alone.

Python and Node.js Read only Tested on WooCommerce Subscriptions 9.4
A calendar with red push buttons pinned to it
Photo by Towfiqu barbhuiya on Unsplash
The short answer

Recalculate only where the new number can be proved. Leave a subscription as stored when it renews manually, when the payment provider holds the amount, when prices include tax, when it has more than one shipping line, when it is in another currency, when a product on it was deleted, or when the provider bills it on its own schedule. A small Python or Node.js check sorts every active subscription and gives the reason for each one it would leave alone. It changes nothing.

The problem in plain words

A recalculation that is wrong is worse than none. A renewal left at its stored amount costs you the difference; a renewal recalculated wrongly overcharges a customer, triggers a refund, a complaint or a chargeback, or puts a renewal on hold because the provider expected a different amount.

So the question before recalculating anything is not "what would it cost today" but "can I be sure of that number, and will the charge go through as I expect".

Upcoming renewalstored amountCan it be proved?method, gateway, taxNot sureleave as storedChargedas it would have been
Refusing costs the difference; guessing can overcharge, or put the renewal on hold.

Why it happens

Each case below is one where the new number cannot be proved from the subscription, or the charge would not follow the order total:

The key insight

"Could not check" must never read as "no change". Count the subscriptions you leave alone, and say why for each, so a quiet report means "all checked" rather than "nothing looked".

The fix, as a flow

The check reads your store currency and tax setting once, then gives every active subscription either a pass or the reasons to leave it alone.

Store settingscurrency, taxActive subscriptionsREST APIReasonsper subscriptionReportsafe vs leave alone
Read only: a count of safe subscriptions and a reason for every one to leave alone.

Build it step by step

1

Give the script read access

A WooCommerce REST API key with Read permission, or an administrator's application password. Only GET requests are sent.

setup (shell)
pip install requests

export WOO_STORE_URL="https://yourstore.com"
export WOO_CONSUMER_KEY="ck_..."     # or an admin username
export WOO_CONSUMER_SECRET="cs_..."  # or its application password
setup (shell)
# Node 18 or later: fetch is built in, nothing to install.

export WOO_STORE_URL="https://yourstore.com"
export WOO_CONSUMER_KEY="ck_..."     # or an admin username
export WOO_CONSUMER_SECRET="cs_..."  # or its application password
2

Keep the reasons in one pure function

It takes a subscription and the store's settings and returns a list of reasons; an empty list means safe to recalculate. Add your own gateways to the fixed-amount list.

check_recalc_safety.py
def reasons(sub, store):
    out = []
    if sub.get("requires_manual_renewal"):
        out.append("manual renewal (repriced at checkout anyway)")
    if sub.get("payment_method") in FIXED_AMOUNT_GATEWAYS:
        out.append(f"{sub.get('payment_method')} holds the amount")
    if store["prices_include_tax"]:
        out.append("prices include tax: a tax change moves the price")
    if len(sub.get("shipping_lines") or []) > 1:
        out.append("more than one shipping line")
    if sub.get("currency") != store["currency"]:
        out.append(f"{sub.get('currency')} is not the store currency")
    if any(not i.get("product_id") for i in sub.get("line_items") or []):
        out.append("a product on it was deleted")
    if any(m.get("key") in ("_wcpay_subscription_id", "ppcp_subscription") for m in sub.get("meta_data") or []):
        out.append("billed by the payment provider's own subscription")
    return out
check-recalc-safety.mjs
export function reasons(sub, store) {
  const out = [];
  if (sub.requires_manual_renewal) out.push("manual renewal (repriced at checkout anyway)");
  if (FIXED_AMOUNT_GATEWAYS.has(sub.payment_method)) out.push(`${sub.payment_method} holds the amount`);
  if (store.prices_include_tax) out.push("prices include tax: a tax change moves the price");
  if ((sub.shipping_lines || []).length > 1) out.push("more than one shipping line");
  if (sub.currency !== store.currency) out.push(`${sub.currency} is not the store currency`);
  if ((sub.line_items || []).some((i) => !i.product_id)) out.push("a product on it was deleted");
  if ((sub.meta_data || []).some((m) => ["_wcpay_subscription_id", "ppcp_subscription"].includes(m.key)))
    out.push("billed by the payment provider's own subscription");
  return out;
}
3

Run it before any bulk change

The count of subscriptions to leave alone is the number to read before deciding anything.

run it
python3 check_recalc_safety.py

# weekly, Monday 07:00
0 7 * * 1  cd /opt/checks && python3 check_recalc_safety.py || echo "see the list above"
run it
node check-recalc-safety.mjs

# weekly, Monday 07:00
0 7 * * 1  cd /opt/checks && node check-recalc-safety.mjs || echo "see the list above"
Read only, on purpose

The check never writes: no order notes, no edits, no status changes. Changing what a customer is charged is a decision to make after reading the list, not something a script should do on its own.

The full code

The complete check in one file for each language. It reads its settings from the environment and pages through every active subscription, 100 at a time.

Get this script on GitHub Follow @allanninal Python and Node.js, with tests. Read only. One of 148 WooCommerce fixes, free and open source.
check_recalc_safety.py
"""Before recalculating renewals, list the subscriptions it would be unsafe to touch.

Recalculating a renewal changes what a customer is charged, so the safe
answer for anything uncertain is to leave it as stored. This sorts active
subscriptions into "safe to recalculate" and "leave alone, because...".
Read only: it changes nothing.

Guide: https://www.allanninal.dev/woocommerce/why-renewal-recalculation-should-refuse/
"""
from requests.auth import HTTPBasicAuth
import os
import requests
import sys

WOO_URL = os.environ["WOO_STORE_URL"].rstrip("/")
AUTH = HTTPBasicAuth(os.environ["WOO_CONSUMER_KEY"], os.environ["WOO_CONSUMER_SECRET"])


def woo(path, **params):
    r = requests.get(f"{WOO_URL}/wp-json/wc/v3/{path}", auth=AUTH, params=params, timeout=30)
    r.raise_for_status()
    return r.json()


def every(path, **params):
    page = 1
    while True:
        batch = woo(path, per_page=100, page=page, **params)
        yield from batch
        if len(batch) < 100:
            return
        page += 1


def minor(amount):
    """'10.00' -> 1000. Two-decimal currencies; zero-decimal ones need their own factor."""
    return round(float(amount or 0) * 100)


def renewals_per_year(sub):
    per = {"day": 365, "week": 52, "month": 12, "year": 1}.get(sub.get("billing_period"), 0)
    return per / max(1, int(sub.get("billing_interval") or 1))


def methods_by_instance():
    """Every shipping method instance in every zone, keyed by instance id."""
    out = {}
    for zone in woo("shipping/zones"):
        for m in woo(f"shipping/zones/{zone['id']}/methods"):
            out[str(m["instance_id"])] = {**m, "zone_id": zone["id"], "zone_name": zone["name"]}
    return out


# Gateways where the provider, not WooCommerce, holds the amount: a changed
# renewal total is ignored or puts the renewal on hold.
FIXED_AMOUNT_GATEWAYS = {"paypal"}


def reasons(sub, store):
    out = []
    if sub.get("requires_manual_renewal"):
        out.append("manual renewal (repriced at checkout anyway)")
    if sub.get("payment_method") in FIXED_AMOUNT_GATEWAYS:
        out.append(f"{sub.get('payment_method')} holds the amount")
    if store["prices_include_tax"]:
        out.append("prices include tax: a tax change moves the price")
    if len(sub.get("shipping_lines") or []) > 1:
        out.append("more than one shipping line")
    if sub.get("currency") != store["currency"]:
        out.append(f"{sub.get('currency')} is not the store currency")
    if any(not i.get("product_id") for i in sub.get("line_items") or []):
        out.append("a product on it was deleted")
    if any(m.get("key") in ("_wcpay_subscription_id", "ppcp_subscription") for m in sub.get("meta_data") or []):
        out.append("billed by the payment provider's own subscription")
    return out


def main():
    store = {
        "currency": woo("settings/general/woocommerce_currency")["value"],
        "prices_include_tax": woo("settings/tax/woocommerce_prices_include_tax")["value"] == "yes",
    }
    safe = held = 0
    for sub in every("subscriptions", status="active"):
        why = reasons(sub, store)
        if why:
            held += 1
            print(f"#{sub['id']}: leave alone: " + "; ".join(why))
        else:
            safe += 1
    print(f"{safe} safe to recalculate, {held} to leave as stored.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
check-recalc-safety.mjs
/**
 * Before recalculating renewals, list the subscriptions it would be unsafe to touch.
 *
 * Recalculating a renewal changes what a customer is charged, so the safe answer for
 * anything uncertain is to leave it as stored. This sorts active subscriptions into
 * "safe to recalculate" and "leave alone, because...". Read only.
 *
 * Guide: https://www.allanninal.dev/woocommerce/why-renewal-recalculation-should-refuse/
 */
import { pathToFileURL } from "node:url";

const WOO_URL = (process.env.WOO_STORE_URL || "https://example.com").replace(/\/$/, "");
const AUTH = "Basic " + Buffer.from(
  `${process.env.WOO_CONSUMER_KEY || "ck_dummy"}:${process.env.WOO_CONSUMER_SECRET || "cs_dummy"}`
).toString("base64");

async function woo(path, params = {}) {
  const url = new URL(`${WOO_URL}/wp-json/wc/v3/${path}`);
  for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
  const res = await fetch(url, { headers: { Authorization: AUTH } });
  if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
  return res.json();
}

async function* every(path, params = {}) {
  for (let page = 1; ; page++) {
    const batch = await woo(path, { per_page: 100, page, ...params });
    yield* batch;
    if (batch.length < 100) return;
  }
}

/** "10.00" -> 1000. Two-decimal currencies; zero-decimal ones need their own factor. */
const minor = (amount) => Math.round(Number(amount || 0) * 100);

function renewalsPerYear(sub) {
  const per = { day: 365, week: 52, month: 12, year: 1 }[sub.billing_period] || 0;
  return per / Math.max(1, Number(sub.billing_interval || 1));
}

/** Every shipping method instance in every zone, keyed by instance id. */
async function methodsByInstance() {
  const out = {};
  for (const zone of await woo("shipping/zones")) {
    for (const m of await woo(`shipping/zones/${zone.id}/methods`)) {
      out[String(m.instance_id)] = { ...m, zone_id: zone.id, zone_name: zone.name };
    }
  }
  return out;
}

const settingsOf = (method) =>
  Object.fromEntries(Object.entries(method.settings || {}).map(([k, v]) => [k, (v || {}).value]));

// Gateways where the provider, not WooCommerce, holds the amount.
const FIXED_AMOUNT_GATEWAYS = new Set(["paypal"]);

export function reasons(sub, store) {
  const out = [];
  if (sub.requires_manual_renewal) out.push("manual renewal (repriced at checkout anyway)");
  if (FIXED_AMOUNT_GATEWAYS.has(sub.payment_method)) out.push(`${sub.payment_method} holds the amount`);
  if (store.prices_include_tax) out.push("prices include tax: a tax change moves the price");
  if ((sub.shipping_lines || []).length > 1) out.push("more than one shipping line");
  if (sub.currency !== store.currency) out.push(`${sub.currency} is not the store currency`);
  if ((sub.line_items || []).some((i) => !i.product_id)) out.push("a product on it was deleted");
  if ((sub.meta_data || []).some((m) => ["_wcpay_subscription_id", "ppcp_subscription"].includes(m.key)))
    out.push("billed by the payment provider's own subscription");
  return out;
}

export async function run() {
  const store = {
    currency: (await woo("settings/general/woocommerce_currency")).value,
    prices_include_tax: (await woo("settings/tax/woocommerce_prices_include_tax")).value === "yes",
  };
  let safe = 0, held = 0;
  for await (const sub of every("subscriptions", { status: "active" })) {
    const why = reasons(sub, store);
    if (why.length) { held++; console.log(`#${sub.id}: leave alone: ${why.join("; ")}`); } else safe++;
  }
  console.log(`${safe} safe to recalculate, ${held} to leave as stored.`);
  return 0;
}

if (import.meta.url === pathToFileURL(process.argv[1]).href) {
  run().then((code) => process.exit(code)).catch((err) => { console.error(err); process.exit(2); });
}

Add a test

The decision is the part most worth testing, and because it is a pure function the tests need no store and no network: they feed in plain objects and check the answer.

test_recalc_safety.py
from check_recalc_safety import reasons

STORE = {"currency": "AUD", "prices_include_tax": False}


def sub(**over):
    return {"payment_method": "stripe", "currency": "AUD", "shipping_lines": [{}], "line_items": [{"product_id": 10}], "meta_data": [], **over}


def test_a_plain_stripe_subscription_is_safe():
    assert reasons(sub(), STORE) == []


def test_each_reason_to_leave_alone():
    assert reasons(sub(requires_manual_renewal=True), STORE)
    assert reasons(sub(payment_method="paypal"), STORE)
    assert reasons(sub(shipping_lines=[{}, {}]), STORE)
    assert reasons(sub(currency="USD"), STORE)
    assert reasons(sub(line_items=[{"product_id": 0}]), STORE)
    assert reasons(sub(meta_data=[{"key": "_wcpay_subscription_id", "value": "sub_1"}]), STORE)
    assert reasons(sub(), {**STORE, "prices_include_tax": True})
check-recalc-safety.test.mjs
import { test } from "node:test";
import assert from "node:assert/strict";
import { reasons } from "./check-recalc-safety.mjs";

const STORE = { currency: "AUD", prices_include_tax: false };
const sub = (over = {}) => ({ payment_method: "stripe", currency: "AUD", shipping_lines: [{}], line_items: [{ product_id: 10 }], meta_data: [], ...over });

test("a plain Stripe subscription is safe", () => assert.deepEqual(reasons(sub(), STORE), []));
test("each reason to leave alone", () => {
  for (const over of [{ requires_manual_renewal: true }, { payment_method: "paypal" }, { shipping_lines: [{}, {}] }, { currency: "USD" }, { line_items: [{ product_id: 0 }] }, { meta_data: [{ key: "_wcpay_subscription_id" }] }]) {
    assert.ok(reasons(sub(over), STORE).length, JSON.stringify(over));
  }
  assert.ok(reasons(sub(), { ...STORE, prices_include_tax: true }).length);
});

Worked example

From the test store

What it found

On a test store with WooCommerce Subscriptions 9.4.1 and seven active subscriptions, the check passed six and listed one to leave alone: a manual renewal, repriced at checkout anyway.

The list is a starting point: a store with other gateways or a multi-currency plugin will add its own reasons.

FAQ

Is it safe to recalculate every WooCommerce subscription renewal?

No. Manual renewals, gateways that hold the amount, provider-billed subscriptions, tax-inclusive prices, more than one shipping line, other currencies and deleted products are all cases where the new number cannot be proved or the charge would not follow it. Leave those as stored.

Why not recalculate and just cap the increase?

A cap limits how wrong a guess can be; it does not make it right. For the cases above, the stored amount is the only number you can be sure of.

What does refusing cost?

The difference between the stored amount and today's, for that subscription, until it is handled. Listing every refusal with its reason keeps that cost visible instead of silent.

Related field notes

Citations

  1. WooCommerce docs: the renewal process, including how taxes and the shipping method carry to automatic renewals. woocommerce.com/document/subscriptions/renewal-process
  2. WooCommerce Subscriptions REST API: listing subscriptions and their shipping and tax lines. woocommerce.github.io/subscriptions-rest-api-docs
  3. WooCommerce REST API: shipping zones, zone methods, zone locations, taxes and settings. woocommerce.github.io/woocommerce-rest-api-docs
Built on refusing

Recalcproof refuses each of these cases, and a few more, by default, and lists every renewal it could not price with the reason, so "could not check" never shows as "no change".

Did this find money you were not collecting?

If this check turned up renewals charging old rates, you can buy me a coffee. It is the best way to keep these field notes free and growing.

Buy me a coffee on Ko-fi

Back to all WooCommerce and Stripe field notes