Skip to content

Diagnostic Shipping and tax at renewal

WooCommerce subscription renewals still charge the old shipping rate

You raised your flat rate weeks ago. New customers pay it at checkout. But every subscription sold before the change renews at the old shipping cost, every month, for as long as it runs, and the difference comes out of your margin. Nothing in the order list looks wrong. Here is why renewals keep the sign-up shipping, and a small read-only check that lists every subscription still paying it, with the money per renewal and per year.

Python and Node.js Read only Tested on WooCommerce Subscriptions 9.4
An orange wrapped gift box with a bow
Photo by Ilie Barna on Unsplash
The short answer

An automatic renewal order is built by copying the subscription's own lines, and the subscription's shipping line is the one from the day it was sold. Nothing recalculates it. Run a small Python or Node.js check that reads each active subscription's shipping line, looks up the same flat-rate instance's cost today, and lists every subscription where the two differ, with the difference per renewal and per year. It changes nothing.

The problem in plain words

A customer subscribes in March, when your flat rate is 10.00. WooCommerce Subscriptions saves a shipping line of 10.00 on the subscription. In June your courier puts its prices up and you change the flat rate to 17.00. A new customer checking out pays 17.00. The March subscriber's next renewal is created from their subscription, so it copies the 10.00 line, and Stripe charges the old total.

That repeats every renewal. Nothing fails, nothing is flagged, and the subscription screen shows exactly the amount the customer agreed to. The gap only shows up in your margin, a few dollars per subscriber per month.

Sold in Marchflat rate 10.00You change the rateflat rate 17.00Renewal createdcopies the 10.00 lineCard chargedold shipping
The flat rate changed, but the renewal is built from the subscription, which still holds March's shipping line.

Why it happens

WooCommerce's renewal documentation says that, for automatic renewals, "the same shipping method is used for all renewal payments". In the WooCommerce Subscriptions 9.4.1 source, the renewal order is created by copying the subscription's line items, shipping lines included, with their stored totals; no shipping calculation runs. So the method is the same and so is its price.

The key insight

The subscription is the record of what was sold, and it is right to keep it. The thing to compare is the renewal against today's rate, not the subscription against its own past.

The fix, as a flow

The check reads every active subscription, finds its one shipping line, looks up the same shipping method instance in your zones, and compares the stored cost with the instance's cost today. It prices only what it can price exactly: a flat rate whose cost is a plain number with no shipping-class costs. Anything else is reported as not compared, never as unchanged.

Active subscriptionsREST APIIts flat-rateinstancetoday's costComparestored vs todayReportper renewal, per year
Read only: a formula, shipping-class costs, a deleted method or two shipping lines are reported as not compared.

Build it step by step

1

Give the script read access

Create a WooCommerce REST API key with Read permission (WooCommerce, Settings, Advanced, REST API), or use an application password for an administrator. The script only ever sends GET requests.

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

Decide with one pure function

Everything that decides lives in one function that takes a subscription and the store's shipping methods and returns drift, same or not compared. It works in minor units, cents, so rounding never produces a false drift.

check_renewal_shipping.py
def decide(sub, methods):
    """One subscription -> (status, detail). status: drift, same, not_compared."""
    lines = sub.get("shipping_lines") or []
    if len(lines) != 1:
        return "not_compared", f"{len(lines)} shipping lines"
    line = lines[0]
    if line.get("method_id") != "flat_rate":
        return "not_compared", f"method {line.get('method_id')}"
    method = methods.get(str(line.get("instance_id")))
    if not method or not method.get("enabled"):
        return "not_compared", "its flat-rate instance is gone or disabled"
    today = todays_flat_cost(method)
    if today is None:
        return "not_compared", "formula or shipping-class costs"
    stored = minor(line.get("total"))
    if today == stored:
        return "same", ""
    return "drift", {"stored": stored, "today": today, "delta": today - stored}
check-renewal-shipping.mjs
export function decide(sub, methods) {
  const lines = sub.shipping_lines || [];
  if (lines.length !== 1) return ["not_compared", `${lines.length} shipping lines`];
  const line = lines[0];
  if (line.method_id !== "flat_rate") return ["not_compared", `method ${line.method_id}`];
  const method = methods[String(line.instance_id)];
  if (!method || !method.enabled) return ["not_compared", "its flat-rate instance is gone or disabled"];
  const today = todaysFlatCost(method);
  if (today === null) return ["not_compared", "formula or shipping-class costs"];
  const stored = minor(line.total);
  if (today === stored) return ["same", ""];
  return ["drift", { stored, today, delta: today - stored }];
}
3

Run it on a schedule

It exits with status 1 when it finds anything, so a weekly cron job can alert you. Expect a list after every rate change; that list is money you are not collecting.

run it
python3 check_renewal_shipping.py

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

# weekly, Monday 07:00
0 7 * * 1  cd /opt/checks && node check-renewal-shipping.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_renewal_shipping.py
"""List active subscriptions whose renewals still charge the shipping they were sold with.

WooCommerce Subscriptions copies a subscription's shipping line onto every
renewal. Change your flat rate and existing subscribers keep paying the old
one. This compares each subscription's stored shipping with what its own
flat-rate instance charges today. Read only: it changes nothing.

It prices only what it can price exactly: a flat rate with a plain number for
its cost and no shipping-class costs. Anything else (a [qty] or [cost]
formula, class costs, another method) is listed as "not compared", never as
"no change".

Guide: https://www.allanninal.dev/woocommerce/renewals-charge-sign-up-shipping/
"""
from requests.auth import HTTPBasicAuth
import os
import re
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


def todays_flat_cost(method):
    """The instance's cost in minor units, or None when a script cannot price it exactly."""
    s = {k: (v or {}).get("value") for k, v in (method.get("settings") or {}).items()}
    cost = (s.get("cost") or "").strip()
    if not re.fullmatch(r"\d+(\.\d+)?", cost):
        return None  # a formula, or empty
    if any((s.get(k) or "").strip() for k in s if k.startswith("class_cost") or k == "no_class_cost"):
        return None  # shipping-class costs depend on the products
    return minor(cost)


def decide(sub, methods):
    """One subscription -> (status, detail). status: drift, same, not_compared."""
    lines = sub.get("shipping_lines") or []
    if len(lines) != 1:
        return "not_compared", f"{len(lines)} shipping lines"
    line = lines[0]
    if line.get("method_id") != "flat_rate":
        return "not_compared", f"method {line.get('method_id')}"
    method = methods.get(str(line.get("instance_id")))
    if not method or not method.get("enabled"):
        return "not_compared", "its flat-rate instance is gone or disabled"
    today = todays_flat_cost(method)
    if today is None:
        return "not_compared", "formula or shipping-class costs"
    stored = minor(line.get("total"))
    if today == stored:
        return "same", ""
    return "drift", {"stored": stored, "today": today, "delta": today - stored}


def main():
    methods = methods_by_instance()
    found = 0
    for sub in every("subscriptions", status="active"):
        if sub.get("requires_manual_renewal"):
            continue  # a manual renewal goes through checkout and is repriced there
        status, detail = decide(sub, methods)
        if status == "drift":
            found += 1
            year = detail["delta"] * renewals_per_year(sub) / 100
            print(f"#{sub['id']}: shipping {detail['stored'] / 100:.2f} stored, {detail['today'] / 100:.2f} today "
                  f"({detail['delta'] / 100:+.2f} a renewal, {year:+.2f} a year, before tax)")
        elif status == "not_compared":
            print(f"#{sub['id']}: not compared ({detail})")
    print(f"{found} subscription(s) renew at an old shipping cost.")
    return 1 if found else 0


if __name__ == "__main__":
    sys.exit(main())
check-renewal-shipping.mjs
/**
 * List active subscriptions whose renewals still charge the shipping they were sold with.
 *
 * WooCommerce Subscriptions copies a subscription's shipping line onto every renewal.
 * Change your flat rate and existing subscribers keep paying the old one. This compares
 * each subscription's stored shipping with what its own flat-rate instance charges today.
 * It prices only a flat rate with a plain number for its cost and no shipping-class
 * costs; anything else is listed as "not compared", never as "no change". Read only.
 *
 * Guide: https://www.allanninal.dev/woocommerce/renewals-charge-sign-up-shipping/
 */
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]));

export function todaysFlatCost(method) {
  const s = settingsOf(method);
  const cost = String(s.cost || "").trim();
  if (!/^\d+(\.\d+)?$/.test(cost)) return null; // a formula, or empty
  const classCosts = Object.keys(s).filter((k) => k.startsWith("class_cost") || k === "no_class_cost");
  if (classCosts.some((k) => String(s[k] || "").trim())) return null; // depends on the products
  return minor(cost);
}

export function decide(sub, methods) {
  const lines = sub.shipping_lines || [];
  if (lines.length !== 1) return ["not_compared", `${lines.length} shipping lines`];
  const line = lines[0];
  if (line.method_id !== "flat_rate") return ["not_compared", `method ${line.method_id}`];
  const method = methods[String(line.instance_id)];
  if (!method || !method.enabled) return ["not_compared", "its flat-rate instance is gone or disabled"];
  const today = todaysFlatCost(method);
  if (today === null) return ["not_compared", "formula or shipping-class costs"];
  const stored = minor(line.total);
  if (today === stored) return ["same", ""];
  return ["drift", { stored, today, delta: today - stored }];
}

export async function run() {
  const methods = await methodsByInstance();
  let found = 0;
  for await (const sub of every("subscriptions", { status: "active" })) {
    if (sub.requires_manual_renewal) continue; // repriced at checkout
    const [status, detail] = decide(sub, methods);
    if (status === "drift") {
      found++;
      const year = (detail.delta * renewalsPerYear(sub)) / 100;
      const sign = (n) => (n >= 0 ? "+" : "") + n.toFixed(2);
      console.log(`#${sub.id}: shipping ${(detail.stored / 100).toFixed(2)} stored, ${(detail.today / 100).toFixed(2)} today (${sign(detail.delta / 100)} a renewal, ${sign(year)} a year, before tax)`);
    } else if (status === "not_compared") {
      console.log(`#${sub.id}: not compared (${detail})`);
    }
  }
  console.log(`${found} subscription(s) renew at an old shipping cost.`);
  return found ? 1 : 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_renewal_shipping.py
from check_renewal_shipping import decide, todays_flat_cost


def method(cost="17", enabled=True, **settings):
    s = {"cost": {"value": cost}, **{k: {"value": v} for k, v in settings.items()}}
    return {"enabled": enabled, "settings": s}


def sub(total="10.00", method_id="flat_rate", instance="4", lines=1):
    return {"shipping_lines": [{"method_id": method_id, "instance_id": instance, "total": total}] * lines}


def test_a_rate_rise_is_drift_in_minor_units():
    assert decide(sub("10.00"), {"4": method("17")}) == ("drift", {"stored": 1000, "today": 1700, "delta": 700})


def test_a_rate_fall_is_drift_too():
    assert decide(sub("20.00"), {"4": method("17")})[1]["delta"] == -300


def test_unchanged_is_same():
    assert decide(sub("17.00"), {"4": method("17")}) == ("same", "")


def test_a_formula_or_class_cost_is_not_compared_never_same():
    assert todays_flat_cost(method("10 + [qty] * 2")) is None
    assert todays_flat_cost(method("17", class_cost_18="5")) is None
    assert decide(sub("10.00"), {"4": method("[cost] * 0.1")})[0] == "not_compared"


def test_a_deleted_instance_or_two_lines_is_not_compared():
    assert decide(sub(), {})[0] == "not_compared"
    assert decide(sub(lines=2), {"4": method()})[0] == "not_compared"
check-renewal-shipping.test.mjs
import { test } from "node:test";
import assert from "node:assert/strict";
import { decide, todaysFlatCost } from "./check-renewal-shipping.mjs";

const method = (cost = "17", extra = {}, enabled = true) => ({
  enabled,
  settings: { cost: { value: cost }, ...Object.fromEntries(Object.entries(extra).map(([k, v]) => [k, { value: v }])) },
});
const sub = (total = "10.00", lines = 1) => ({ shipping_lines: Array(lines).fill({ method_id: "flat_rate", instance_id: "4", total }) });

test("a rate rise is drift, in minor units", () => {
  assert.deepEqual(decide(sub("10.00"), { 4: method("17") }), ["drift", { stored: 1000, today: 1700, delta: 700 }]);
});
test("a rate fall is drift too", () => assert.equal(decide(sub("20.00"), { 4: method("17") })[1].delta, -300));
test("unchanged is same", () => assert.deepEqual(decide(sub("17.00"), { 4: method("17") }), ["same", ""]));
test("a formula or class cost is not compared, never same", () => {
  assert.equal(todaysFlatCost(method("10 + [qty] * 2")), null);
  assert.equal(todaysFlatCost(method("17", { class_cost_18: "5" })), null);
  assert.equal(decide(sub(), { 4: method("[cost] * 0.1") })[0], "not_compared");
});
test("a deleted instance or two lines is not compared", () => {
  assert.equal(decide(sub(), {})[0], "not_compared");
  assert.equal(decide(sub("10.00", 2), { 4: method() })[0], "not_compared");
});

Worked example

From the test store

What it found

On a test store with WooCommerce Subscriptions 9.4.1, the flat rate was raised from 10.00 to 17.00 after five subscriptions were sold. The check listed the three still on 10.00 (+7.00 a renewal, +84.00 a year each, before tax), the one on 20.00 that would now be charged less (−3.00), and the one whose shipping method had since been deleted as "not compared". The subscription already at 17.00 and a manual-renewal subscription were left out, as they should be.

Before tax: GST at 10% adds 0.70 to each 7.00, so the real renewal moved from 66.00 to 73.70.

FAQ

Why do WooCommerce subscription renewals not use my new shipping rate?

A renewal order is copied from the subscription, and the subscription stores the shipping line from the day it was sold. WooCommerce Subscriptions does not recalculate shipping for automatic renewals, so a changed rate only reaches new checkouts.

Should I edit every subscription's shipping line by hand?

You can, but it changes what the subscription says the customer agreed to, it has to be repeated at every rate change, and it is easy to get one wrong. Listing the affected subscriptions first tells you how much is at stake before you decide.

Why does the check skip subscriptions with shipping-class costs or formulas?

Those costs depend on the products and quantities, so a script that only reads the subscription cannot price them exactly. Reporting them as not compared is safer than guessing a number and calling it the answer.

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 docs: flat rate shipping, its cost formulas and shipping-class costs. woocommerce.com/document/flat-rate-shipping
  3. WooCommerce Subscriptions REST API: listing subscriptions and their shipping and tax lines. woocommerce.github.io/subscriptions-rest-api-docs
  4. WooCommerce REST API: shipping zones, zone methods, zone locations, taxes and settings. woocommerce.github.io/woocommerce-rest-api-docs
Recalculating every renewal, not just listing them

The check lists the subscriptions; it does not change what they are charged. Recalcproof recalculates each automatic renewal at today's shipping and tax just before the card is charged, by asking WooCommerce itself, so formulas and shipping-class costs are priced exactly. It previews first, leaves the subscription untouched, and logs every 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