Diagnostic Shipping and tax at renewal
WooCommerce subscriptions renewing on a shipping method you removed
You tidy up your shipping: delete an old flat rate, disable a method, or take a country out of a zone. Checkout stops offering them at once. Subscriptions sold on them keep renewing on them, at the old price, because a subscription remembers the exact method instance it was sold with and nothing checks it is still on offer. Here is how to find them.
A subscription's shipping line records the method id and the instance id it was sold with, and renewals copy it. Deleting or disabling the instance, or moving the address out of its zone, changes nothing on the subscription. Run a small Python or Node.js check that looks up each subscription's instance in your zones and reports every one that is deleted, disabled, or in a zone that no longer covers the customer's country. It changes nothing.
The problem in plain words
A subscriber in Australia was sold "Old flat", instance 5 in your Australia zone. You replace it with a new flat rate and delete instance 5. A customer checking out today never sees it. The subscriber's renewals still carry "Old flat" at its old price, because the renewal copies the subscription's line, instance number and all.
The same happens when you disable the instance, or edit the zone so it no longer includes the customer's country.
Why it happens
A shipping method instance is a method added to a zone; its instance id is what a subscription's shipping line points at. The zone's locations decide who is offered it at checkout. None of that is consulted when a renewal is created: the renewal copies the line.
- A deleted instance: the line points at an id that no longer exists.
- A disabled instance: it exists but nobody can choose it.
- A zone that no longer covers the customer's country or state.
- Postcode-based zones are not decided by this check; it says so rather than guessing.
Match the subscription's method by its instance id, not its method id. Two flat rates in two zones share the id flat_rate; only the instance tells you which price the customer was actually sold.
The fix, as a flow
The check loads every zone's methods once, then for each subscription finds its instance and checks that it exists, is enabled, and that its zone still covers the shipping address (country and state; postcode zones are skipped). The catch-all zone covers everyone else.
Build it step by step
Give the script read access
A WooCommerce REST API key with Read permission, or an administrator's application password. Only GET requests are sent.
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
# 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
Decide in one function
The decision takes the subscription, the methods by instance id and a way to read a zone's locations, and returns why the method is not on offer, or nothing.
def decide(sub, methods, locations_of):
"""One subscription -> a reason string, or None when its method is still on offer."""
for line in sub.get("shipping_lines") or []:
if line.get("method_id") in ("", None):
continue
method = methods.get(str(line.get("instance_id")))
if not method:
return f"{line.get('method_title')} ({line.get('method_id')}:{line.get('instance_id')}) was deleted"
if not method.get("enabled"):
return f"{line.get('method_title')} is disabled in {method['zone_name']}"
if method["zone_id"] == 0:
continue # "Locations not covered by your other zones" covers everyone else
address = sub.get("shipping") or {}
if not address.get("country"):
address = sub.get("billing") or {}
hit = covers(locations_of(method["zone_id"]), address.get("country", ""), address.get("state", ""))
if hit is False:
return f"{line.get('method_title')} is in {method['zone_name']}, which no longer covers {address.get('country')}"
return None
export async function decide(sub, methods, locationsOf) {
for (const line of sub.shipping_lines || []) {
if (!line.method_id) continue;
const method = methods[String(line.instance_id)];
if (!method) return `${line.method_title} (${line.method_id}:${line.instance_id}) was deleted`;
if (!method.enabled) return `${line.method_title} is disabled in ${method.zone_name}`;
if (method.zone_id === 0) continue; // covers every address no other zone does
const a = sub.shipping && sub.shipping.country ? sub.shipping : sub.billing || {};
const hit = covers(await locationsOf(method.zone_id), a.country || "", a.state || "");
if (hit === false) return `${line.method_title} is in ${method.zone_name}, which no longer covers ${a.country}`;
}
return null;
}
Run it after every shipping change
It exits with status 1 when it finds any.
python3 check_shipping_method_gone.py
# weekly, Monday 07:00
0 7 * * 1 cd /opt/checks && python3 check_shipping_method_gone.py || echo "see the list above"
node check-shipping-method-gone.mjs
# weekly, Monday 07:00
0 7 * * 1 cd /opt/checks && node check-shipping-method-gone.mjs || echo "see the list above"
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.
"""List subscriptions whose shipping method is no longer offered to them.
A subscription remembers the exact shipping method instance it was sold with.
Delete or disable that instance, or move the customer's country out of its
zone, and renewals keep charging it anyway: nothing re-checks it. Read only.
Guide: https://www.allanninal.dev/woocommerce/subscription-shipping-method-no-longer-offered/
"""
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
def covers(locations, country, state):
"""Does a zone's location list include this address? None when only postcodes decide."""
if not locations:
return None
hit = False
for loc in locations:
kind, code = loc.get("type"), loc.get("code") or ""
if kind == "country" and code == country:
hit = True
elif kind == "state" and code == f"{country}:{state}":
hit = True
elif kind == "postcode":
return None
return hit
def decide(sub, methods, locations_of):
"""One subscription -> a reason string, or None when its method is still on offer."""
for line in sub.get("shipping_lines") or []:
if line.get("method_id") in ("", None):
continue
method = methods.get(str(line.get("instance_id")))
if not method:
return f"{line.get('method_title')} ({line.get('method_id')}:{line.get('instance_id')}) was deleted"
if not method.get("enabled"):
return f"{line.get('method_title')} is disabled in {method['zone_name']}"
if method["zone_id"] == 0:
continue # "Locations not covered by your other zones" covers everyone else
address = sub.get("shipping") or {}
if not address.get("country"):
address = sub.get("billing") or {}
hit = covers(locations_of(method["zone_id"]), address.get("country", ""), address.get("state", ""))
if hit is False:
return f"{line.get('method_title')} is in {method['zone_name']}, which no longer covers {address.get('country')}"
return None
def main():
methods = methods_by_instance()
cache = {}
locations_of = lambda z: cache.setdefault(z, woo(f"shipping/zones/{z}/locations"))
found = 0
for sub in every("subscriptions", status="active"):
why = decide(sub, methods, locations_of)
if why:
found += 1
print(f"#{sub['id']}: {why}")
print(f"{found} subscription(s) renew on a shipping method nobody can choose today.")
return 1 if found else 0
if __name__ == "__main__":
sys.exit(main())
/**
* List subscriptions whose shipping method is no longer offered to them.
*
* A subscription remembers the exact shipping method instance it was sold with. Delete
* or disable it, or move the customer's country out of its zone, and renewals keep
* charging it anyway: nothing re-checks it. Read only.
*
* Guide: https://www.allanninal.dev/woocommerce/subscription-shipping-method-no-longer-offered/
*/
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 covers(locations, country, state) {
if (!locations.length) return null;
let hit = false;
for (const loc of locations) {
if (loc.type === "postcode") return null;
if (loc.type === "country" && loc.code === country) hit = true;
if (loc.type === "state" && loc.code === `${country}:${state}`) hit = true;
}
return hit;
}
export async function decide(sub, methods, locationsOf) {
for (const line of sub.shipping_lines || []) {
if (!line.method_id) continue;
const method = methods[String(line.instance_id)];
if (!method) return `${line.method_title} (${line.method_id}:${line.instance_id}) was deleted`;
if (!method.enabled) return `${line.method_title} is disabled in ${method.zone_name}`;
if (method.zone_id === 0) continue; // covers every address no other zone does
const a = sub.shipping && sub.shipping.country ? sub.shipping : sub.billing || {};
const hit = covers(await locationsOf(method.zone_id), a.country || "", a.state || "");
if (hit === false) return `${line.method_title} is in ${method.zone_name}, which no longer covers ${a.country}`;
}
return null;
}
export async function run() {
const methods = await methodsByInstance();
const cache = new Map();
const locationsOf = async (z) => {
if (!cache.has(z)) cache.set(z, await woo(`shipping/zones/${z}/locations`));
return cache.get(z);
};
let found = 0;
for await (const sub of every("subscriptions", { status: "active" })) {
const why = await decide(sub, methods, locationsOf);
if (why) { found++; console.log(`#${sub.id}: ${why}`); }
}
console.log(`${found} subscription(s) renew on a shipping method nobody can choose today.`);
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.
from check_shipping_method_gone import covers, decide
def sub(country="AU", instance="4"):
return {"shipping_lines": [{"method_id": "flat_rate", "method_title": "Flat AU", "instance_id": instance}], "shipping": {"country": country, "state": ""}}
METHODS = {"4": {"enabled": True, "zone_id": 1, "zone_name": "Australia"}}
AU = lambda z: [{"type": "country", "code": "AU"}]
def test_still_offered():
assert decide(sub(), METHODS, AU) is None
def test_a_deleted_instance():
assert "was deleted" in decide(sub(instance="9"), METHODS, AU)
def test_a_disabled_instance():
assert "disabled" in decide(sub(), {"4": {**METHODS["4"], "enabled": False}}, AU)
def test_an_address_outside_the_zone():
assert "no longer covers US" in decide(sub(country="US"), METHODS, AU)
def test_a_postcode_zone_is_not_decided_here():
assert covers([{"type": "postcode", "code": "2000"}], "AU", "") is None
import { test } from "node:test";
import assert from "node:assert/strict";
import { covers, decide } from "./check-shipping-method-gone.mjs";
const sub = (country = "AU", instance = "4") => ({ shipping_lines: [{ method_id: "flat_rate", method_title: "Flat AU", instance_id: instance }], shipping: { country, state: "" } });
const METHODS = { 4: { enabled: true, zone_id: 1, zone_name: "Australia" } };
const AU = async () => [{ type: "country", code: "AU" }];
test("still offered", async () => assert.equal(await decide(sub(), METHODS, AU), null));
test("a deleted instance", async () => assert.match(await decide(sub("AU", "9"), METHODS, AU), /was deleted/));
test("a disabled instance", async () => assert.match(await decide(sub(), { 4: { ...METHODS[4], enabled: false } }, AU), /disabled/));
test("an address outside the zone", async () => assert.match(await decide(sub("US"), METHODS, AU), /no longer covers US/));
test("a postcode zone is not decided here", () => assert.equal(covers([{ type: "postcode", code: "2000" }], "AU", ""), null));
Worked example
What it found
On a test store with WooCommerce Subscriptions 9.4.1, a subscription was sold on a flat-rate instance that was deleted afterwards. The check reported "Old flat (flat_rate:5) was deleted". The six subscriptions on methods still offered were not listed.
Choosing the method these customers move to is yours: matching by method id alone could silently pick another zone's price.
FAQ
Why do renewals still use a shipping method I deleted?
A subscription's shipping line stores the method instance it was sold with, and renewals copy the line. Deleting the instance removes it from checkout but leaves every existing line untouched.
Can I just match the old method to my new one by name or method id?
Not safely. Several instances share a method id such as flat_rate, one per zone, at different prices. Matching by method id can silently move a customer to another zone's rate.
Why does the check skip postcode zones?
Postcode zones can use ranges and wildcards, and deciding whether an address falls inside one is WooCommerce's job at checkout. The check reports what it can decide exactly and leaves the rest.
Related field notes
Citations
- WooCommerce docs: setting up shipping zones and their methods. woocommerce.com/document/setting-up-shipping-zones
- WooCommerce docs: the renewal process, including how taxes and the shipping method carry to automatic renewals. woocommerce.com/document/subscriptions/renewal-process
- WooCommerce Subscriptions REST API: listing subscriptions and their shipping and tax lines. woocommerce.github.io/subscriptions-rest-api-docs
- WooCommerce REST API: shipping zones, zone methods, zone locations, taxes and settings. woocommerce.github.io/woocommerce-rest-api-docs
Recalcproof matches a renewal's shipping by method and instance, exactly. A renewal whose method is gone is left at its stored amount and listed with the reason; it never substitutes another method.
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