Skip to content

Diagnostic Shipping and tax at renewal

WooCommerce subscriptions keep free shipping after it no longer qualifies

Free shipping is decided once, at checkout. You raise the minimum from 100 to 150, or turn free shipping off for a zone, and every subscription that qualified on the old rule keeps renewing with free shipping, because the renewal copies the subscription's free shipping line. Here is why, and a small read-only check that applies today's free-shipping rule to each subscription's stored order.

Python and Node.js Read only Tested on WooCommerce Subscriptions 9.4
Banknotes on yellow and white textile
Photo by Christopher Bill on Unsplash
The short answer

A renewal copies the subscription's shipping line, and for these subscriptions that line is free shipping. Nothing re-checks the rule. Run a small Python or Node.js check that, for every subscription on free shipping, reads today's settings for that free-shipping method and re-applies them to the subscription's stored line totals and coupons. It lists each subscription that would not qualify today, and each whose method was disabled or deleted. It changes nothing.

The problem in plain words

A customer subscribes to two boxes at 50.00 each. Your free-shipping minimum is 100.00, so they qualify, and the subscription stores a free shipping line. Later you raise the minimum to 150.00. A new customer with the same two boxes pays for shipping. The existing subscriber does not, on every renewal.

The same happens when you disable free shipping for a zone, or delete it: nothing goes back and checks the subscriptions that were sold with it.

Sold at 100.00minimum 100: freeMinimum raisednow 150.00Renewal createdcopies free shippingShipping absorbedevery cycle
The renewal copies the free shipping line; the rule is never applied again.

Why it happens

Free shipping is a checkout decision: WooCommerce's free shipping method checks its requirement (a minimum amount, a coupon, either or both) against the cart. A subscription keeps the resulting shipping line, and its renewals copy it. Re-applying the rule means reading the same settings and the same amounts the rule reads.

The key insight

The stored lines are the order the customer is renewing. Re-apply today's rule to those, not to the products' current prices, and the answer matches what checkout would do for the same order today.

The fix, as a flow

For each subscription on free shipping, the check finds that free-shipping instance, reads its requirement, minimum and ignore-discounts setting, and applies them to the subscription's line totals (or subtotals) and coupon lines, adding tax when your cart displays prices including tax.

Free-shipping subsREST APIToday's rulemin, coupon, discountsRe-applyto stored linesReportno longer qualifies
Read only: it reports subscriptions that would not qualify today, and free-shipping methods that are gone or disabled.

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

Re-apply the rule in one pure function

The decision takes the subscription, the shipping methods and whether the cart displays prices including tax, and returns why it no longer qualifies, or nothing.

check_free_shipping_renewals.py
def decide(sub, methods, display_incl):
    lines = [l for l in sub.get("shipping_lines") or [] if l.get("method_id") == "free_shipping"]
    if not lines:
        return None
    method = methods.get(str(lines[0].get("instance_id")))
    if not method or not method.get("enabled"):
        return "its free-shipping method is gone or disabled"
    ok = qualifies(sub, method, display_incl)
    if ok is None:
        return "the free-shipping rule could not be read"
    return None if ok else "today's rule would not give it free shipping"
check-free-shipping-renewals.mjs
export function decide(sub, methods, displayIncl) {
  const line = (sub.shipping_lines || []).find((l) => l.method_id === "free_shipping");
  if (!line) return null;
  const method = methods[String(line.instance_id)];
  if (!method || !method.enabled) return "its free-shipping method is gone or disabled";
  const ok = qualifies(sub, method, displayIncl);
  if (ok === null) return "the free-shipping rule could not be read";
  return ok ? null : "today's rule would not give it free shipping";
}
3

Run it after every free-shipping change

It exits with status 1 when it finds any.

run it
python3 check_free_shipping_renewals.py

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

# weekly, Monday 07:00
0 7 * * 1  cd /opt/checks && node check-free-shipping-renewals.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_free_shipping_renewals.py
"""List subscriptions that still get free shipping they no longer qualify for.

Free shipping is decided once, at checkout. After that the renewal just
copies the free shipping line, even if you raise the minimum, switch the
method off, or the subscriber removes items. This re-applies today's rule to
each subscription's stored lines. Read only: it changes nothing.

Guide: https://www.allanninal.dev/woocommerce/free-shipping-kept-after-it-no-longer-qualifies/
"""
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 qualifies(sub, method, display_incl):
    """True, False, or None when the rule cannot be read."""
    s = {k: (v or {}).get("value") for k, v in (method.get("settings") or {}).items()}
    requires = s.get("requires") or ""
    if requires == "":
        return True
    has_coupon = any(c.get("free_shipping") for c in sub.get("coupon_lines") or [])
    if s.get("ignore_discounts") == "yes":
        subtotal = sum(minor(i.get("subtotal")) for i in sub.get("line_items") or [])
        if display_incl:
            subtotal += sum(minor(i.get("subtotal_tax")) for i in sub.get("line_items") or [])
    else:
        subtotal = sum(minor(i.get("total")) for i in sub.get("line_items") or [])
        if display_incl:
            subtotal += sum(minor(i.get("total_tax")) for i in sub.get("line_items") or [])
    met = subtotal >= minor(s.get("min_amount"))
    return {"coupon": has_coupon, "min_amount": met, "either": met or has_coupon, "both": met and has_coupon}.get(requires)


def decide(sub, methods, display_incl):
    lines = [l for l in sub.get("shipping_lines") or [] if l.get("method_id") == "free_shipping"]
    if not lines:
        return None
    method = methods.get(str(lines[0].get("instance_id")))
    if not method or not method.get("enabled"):
        return "its free-shipping method is gone or disabled"
    ok = qualifies(sub, method, display_incl)
    if ok is None:
        return "the free-shipping rule could not be read"
    return None if ok else "today's rule would not give it free shipping"


def main():
    methods = methods_by_instance()
    display_incl = woo("settings/tax/woocommerce_tax_display_cart")["value"] == "incl"
    found = 0
    for sub in every("subscriptions", status="active"):
        why = decide(sub, methods, display_incl)
        if why:
            found += 1
            print(f"#{sub['id']}: free shipping on every renewal, but {why}")
    print(f"{found} subscription(s) keep free shipping today's rules would not give them.")
    return 1 if found else 0


if __name__ == "__main__":
    sys.exit(main())
check-free-shipping-renewals.mjs
/**
 * List subscriptions that still get free shipping they no longer qualify for.
 *
 * Free shipping is decided once, at checkout; renewals copy the free line after that,
 * even if you raise the minimum or switch the method off. This re-applies today's rule
 * to each subscription's stored lines. Read only.
 *
 * Guide: https://www.allanninal.dev/woocommerce/free-shipping-kept-after-it-no-longer-qualifies/
 */
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 qualifies(sub, method, displayIncl) {
  const s = settingsOf(method);
  const requires = s.requires || "";
  if (requires === "") return true;
  const items = sub.line_items || [];
  const hasCoupon = (sub.coupon_lines || []).some((c) => c.free_shipping);
  const ignore = s.ignore_discounts === "yes";
  let subtotal = items.reduce((n, i) => n + minor(ignore ? i.subtotal : i.total), 0);
  if (displayIncl) subtotal += items.reduce((n, i) => n + minor(ignore ? i.subtotal_tax : i.total_tax), 0);
  const met = subtotal >= minor(s.min_amount);
  return { coupon: hasCoupon, min_amount: met, either: met || hasCoupon, both: met && hasCoupon }[requires] ?? null;
}

export function decide(sub, methods, displayIncl) {
  const line = (sub.shipping_lines || []).find((l) => l.method_id === "free_shipping");
  if (!line) return null;
  const method = methods[String(line.instance_id)];
  if (!method || !method.enabled) return "its free-shipping method is gone or disabled";
  const ok = qualifies(sub, method, displayIncl);
  if (ok === null) return "the free-shipping rule could not be read";
  return ok ? null : "today's rule would not give it free shipping";
}

export async function run() {
  const methods = await methodsByInstance();
  const displayIncl = (await woo("settings/tax/woocommerce_tax_display_cart")).value === "incl";
  let found = 0;
  for await (const sub of every("subscriptions", { status: "active" })) {
    const why = decide(sub, methods, displayIncl);
    if (why) { found++; console.log(`#${sub.id}: free shipping on every renewal, but ${why}`); }
  }
  console.log(`${found} subscription(s) keep free shipping today's rules would not give them.`);
  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_free_shipping_renewals.py
from check_free_shipping_renewals import decide


def method(requires="min_amount", min_amount="100", ignore_discounts="no", enabled=True):
    return {"enabled": enabled, "settings": {"requires": {"value": requires}, "min_amount": {"value": min_amount}, "ignore_discounts": {"value": ignore_discounts}}}


def sub(total="100.00", subtotal="100.00", coupon=False):
    return {
        "shipping_lines": [{"method_id": "free_shipping", "instance_id": "3"}],
        "line_items": [{"total": total, "subtotal": subtotal, "total_tax": "0", "subtotal_tax": "0"}],
        "coupon_lines": [{"free_shipping": True}] if coupon else [],
    }


def test_still_qualifies():
    assert decide(sub(), {"3": method()}, False) is None


def test_a_raised_minimum_is_reported():
    assert "would not" in decide(sub(), {"3": method(min_amount="150")}, False)


def test_a_discount_counts_unless_ignored():
    discounted = sub(total="90.00", subtotal="100.00")
    assert decide(discounted, {"3": method()}, False) is not None
    assert decide(discounted, {"3": method(ignore_discounts="yes")}, False) is None


def test_a_coupon_rule_reads_the_stored_coupon():
    assert decide(sub(coupon=True), {"3": method(requires="coupon")}, False) is None
    assert decide(sub(), {"3": method(requires="coupon")}, False) is not None


def test_a_disabled_method_is_reported():
    assert "gone or disabled" in decide(sub(), {"3": method(enabled=False)}, False)


def test_a_subscription_without_free_shipping_is_ignored():
    assert decide({"shipping_lines": [{"method_id": "flat_rate"}]}, {}, False) is None
check-free-shipping-renewals.test.mjs
import { test } from "node:test";
import assert from "node:assert/strict";
import { decide } from "./check-free-shipping-renewals.mjs";

const method = (requires = "min_amount", min_amount = "100", ignore_discounts = "no", enabled = true) => ({
  enabled, settings: { requires: { value: requires }, min_amount: { value: min_amount }, ignore_discounts: { value: ignore_discounts } },
});
const sub = (total = "100.00", subtotal = "100.00", coupon = false) => ({
  shipping_lines: [{ method_id: "free_shipping", instance_id: "3" }],
  line_items: [{ total, subtotal, total_tax: "0", subtotal_tax: "0" }],
  coupon_lines: coupon ? [{ free_shipping: true }] : [],
});

test("still qualifies", () => assert.equal(decide(sub(), { 3: method() }, false), null));
test("a raised minimum is reported", () => assert.match(decide(sub(), { 3: method("min_amount", "150") }, false), /would not/));
test("a discount counts unless ignored", () => {
  assert.notEqual(decide(sub("90.00", "100.00"), { 3: method() }, false), null);
  assert.equal(decide(sub("90.00", "100.00"), { 3: method("min_amount", "100", "yes") }, false), null);
});
test("a coupon rule reads the stored coupon", () => {
  assert.equal(decide(sub("100.00", "100.00", true), { 3: method("coupon") }, false), null);
  assert.notEqual(decide(sub(), { 3: method("coupon") }, false), null);
});
test("a disabled method is reported", () => assert.match(decide(sub(), { 3: method("min_amount", "100", "no", false) }, false), /gone or disabled/));

Worked example

From the test store

What it found

On a test store with WooCommerce Subscriptions 9.4.1, a subscription to two 50.00 boxes was sold with free shipping at a 100.00 minimum. The check reported nothing. With the minimum raised to 150.00 it listed the subscription as no longer qualifying; with the method disabled, as gone or disabled.

Deciding what that customer should pay instead (which paid method, at what price) is yours: the check does not pick one.

FAQ

Why do subscriptions keep free shipping after I raised the minimum?

Free shipping is decided at checkout and stored as the subscription's shipping line. Renewals copy that line, so a changed minimum never reaches subscriptions that already have it.

Should the subscription just be moved to my paid flat rate?

Maybe, but that is a decision about one customer, and possibly a change to what they agreed to. The check lists them so you can decide; it does not choose a method for them.

Does an expired free-shipping coupon count?

The check reads the coupon recorded on the subscription. Re-validating the coupon's expiry or usage limit today would remove free shipping from customers who were promised it, which is rarely what anyone wants.

Related field notes

Citations

  1. WooCommerce docs: free shipping and its minimum-amount and coupon requirements. woocommerce.com/document/free-shipping
  2. WooCommerce docs: the renewal process, including how taxes and the shipping method carry to automatic renewals. woocommerce.com/document/subscriptions/renewal-process
  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
Every renewal checked against today's free-shipping rule

Recalcproof runs this rule for every renewal in its daily check and shows the ones that no longer qualify. It deliberately does not move a subscription to a paid method on its own: which one, and at what price, stays your decision.

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