Skip to content

Diagnostic Bank transfers and statement matching

Why a same-amount bank transfer must never match an order automatically

Two customers each owe 25.00. A payment of 25.00 arrives with no order number in it. A program that matches by amount has two equally good answers and a one in two chance of crediting the wrong customer, who gets a parcel they did not pay for while the other keeps waiting. The safe rule is that a person decides. Here is why, and a small read-only check that lists which of your unpaid orders share an amount, so you know which payments will need that person.

Python and Node.js Read only Tested on WooCommerce 11.3
A lot of 100 us dollar banknotes
Photo by Mackenzie Marco on Unsplash
The short answer

When two or more unpaid bank-transfer orders have the same total and the payment names none of them, nothing in the payment tells them apart, so matching it automatically is a guess. Automatic confirmation should need an identifier, a reference that names exactly one order, plus the exact amount. A small Python or Node.js check groups your On hold bank-transfer orders by currency and exact amount and lists the groups of two or more. It changes nothing.

The problem in plain words

Order 1103 is for 25.00 from one customer and order 1104 is for 25.00 from another. Both chose bank transfer and both are On hold. A line arrives on your statement: 25.00, from a name that matches neither billing name, with the text "Danke".

Pick 1103 and you are right half the time. When you are wrong, 1104's customer is still waiting, 1103's customer has a shipped order they have not paid for, and both will write to you. The amount is the least specific evidence a payment carries.

Two ordersboth 25.00One payment25.00, no referencePick onea coin tossWrong customershipped unpaid
Guessing between them is a coin toss with someone else's money.

Why it happens

A match is only as strong as the evidence that separates one candidate from the others:

The key insight

Confidence is about how many other orders the evidence would also fit. For an amount alone that number can be counted in advance, from your own unpaid orders, which is exactly what the check does.

The fix, as a flow

The check reads every On hold order, keeps the bank-transfer ones, converts each total to whole cents and groups them by currency and exact amount. Every group of two or more is a set of orders that a payment with no reference cannot tell apart.

On hold ordersREST APIBank transfer onlypayment method bacsGroupcurrency and centsReportamounts shared by 2+
Read only: the list is the set of payments that will need a person.

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

Group in one pure function

The function takes the orders and returns the groups of two or more with the same currency and exact amount. It compares whole cents, so 25 and 25.00 are one amount, and it ignores zero totals.

check_same_amount_orders.py
def shared_amounts(orders):
    """Orders -> [{currency, total_minor, orders: [numbers]}] for amounts two or more share."""
    groups = {}
    for o in orders:
        if o.get("status") != "on-hold" or o.get("payment_method") != "bacs":
            continue
        cents = minor(o.get("total"))
        if cents <= 0:
            continue
        groups.setdefault((o.get("currency", ""), cents), []).append(str(o.get("number") or o["id"]))
    return [
        {"currency": cur, "total_minor": cents, "orders": numbers}
        for (cur, cents), numbers in sorted(groups.items())
        if len(numbers) > 1
    ]
check-same-amount-orders.mjs
export function sharedAmounts(orders) {
  const groups = new Map();
  for (const o of orders) {
    if (o.status !== "on-hold" || o.payment_method !== "bacs") continue;
    const cents = minor(o.total);
    if (cents <= 0) continue;
    const key = `${o.currency || ""}\t${cents}`;
    if (!groups.has(key)) groups.set(key, { currency: o.currency || "", total_minor: cents, orders: [] });
    groups.get(key).orders.push(String(o.number || o.id));
  }
  return [...groups.values()]
    .filter((g) => g.orders.length > 1)
    .sort((a, b) => a.currency.localeCompare(b.currency) || a.total_minor - b.total_minor);
}
3

Run it when you reconcile

It exits with status 1 when it finds any shared amount. A payment for one of those amounts that names no order is yours to decide.

run it
python3 check_same_amount_orders.py

# every morning, 07:00
0 7 * * *  cd /opt/checks && python3 check_same_amount_orders.py || echo "see the list above"
run it
node check-same-amount-orders.mjs

# every morning, 07:00
0 7 * * *  cd /opt/checks && node check-same-amount-orders.mjs || echo "see the list above"
Read only, on purpose

The check never writes: no order notes, no edits, no status changes. Matching a payment to an order 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 On hold order, 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_same_amount_orders.py
"""List unpaid bank-transfer orders that share an exact amount.

A payment for 25.00 that quotes no order number cannot be given to either of two
unpaid orders for 25.00 by a program: it would be a coin toss with someone's money.
This groups the On hold bank-transfer (BACS) orders by currency and exact amount and
lists the groups with two or more orders, so you know which payments will need a
person. Read only: it sends GET requests and changes nothing.

Guide: https://www.allanninal.dev/woocommerce/same-amount-bank-transfers-never-auto-match/
"""
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):
    """'25.00' -> 2500. Two-decimal currencies; zero-decimal ones need their own factor."""
    return round(float(amount or 0) * 100)


def shared_amounts(orders):
    """Orders -> [{currency, total_minor, orders: [numbers]}] for amounts two or more share."""
    groups = {}
    for o in orders:
        if o.get("status") != "on-hold" or o.get("payment_method") != "bacs":
            continue
        cents = minor(o.get("total"))
        if cents <= 0:
            continue
        groups.setdefault((o.get("currency", ""), cents), []).append(str(o.get("number") or o["id"]))
    return [
        {"currency": cur, "total_minor": cents, "orders": numbers}
        for (cur, cents), numbers in sorted(groups.items())
        if len(numbers) > 1
    ]


def main():
    groups = shared_amounts(every("orders", status="on-hold"))
    for g in groups:
        listed = ", ".join("#" + n for n in g["orders"])
        print(f"{g['total_minor'] / 100:.2f} {g['currency']}: {listed}")
    orders = sum(len(g["orders"]) for g in groups)
    print(f"{len(groups)} amount(s) shared by {orders} unpaid bank-transfer order(s): a payment for one of them that names no order needs a person.")
    return 1 if groups else 0


if __name__ == "__main__":
    sys.exit(main())
check-same-amount-orders.mjs
/**
 * List unpaid bank-transfer orders that share an exact amount.
 *
 * A payment for 25.00 that quotes no order number cannot be given to either of two unpaid
 * orders for 25.00 by a program: it would be a coin toss with someone's money. This groups
 * the On hold bank-transfer (BACS) orders by currency and exact amount and lists the groups
 * with two or more orders, so you know which payments will need a person. Read only.
 *
 * Guide: https://www.allanninal.dev/woocommerce/same-amount-bank-transfers-never-auto-match/
 */
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;
  }
}

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

export function sharedAmounts(orders) {
  const groups = new Map();
  for (const o of orders) {
    if (o.status !== "on-hold" || o.payment_method !== "bacs") continue;
    const cents = minor(o.total);
    if (cents <= 0) continue;
    const key = `${o.currency || ""}\t${cents}`;
    if (!groups.has(key)) groups.set(key, { currency: o.currency || "", total_minor: cents, orders: [] });
    groups.get(key).orders.push(String(o.number || o.id));
  }
  return [...groups.values()]
    .filter((g) => g.orders.length > 1)
    .sort((a, b) => a.currency.localeCompare(b.currency) || a.total_minor - b.total_minor);
}

export async function run() {
  const orders = [];
  for await (const o of every("orders", { status: "on-hold" })) orders.push(o);
  const groups = sharedAmounts(orders);
  for (const g of groups) {
    console.log(`${(g.total_minor / 100).toFixed(2)} ${g.currency}: ${g.orders.map((n) => "#" + n).join(", ")}`);
  }
  const n = groups.reduce((s, g) => s + g.orders.length, 0);
  console.log(`${groups.length} amount(s) shared by ${n} unpaid bank-transfer order(s): a payment for one of them that names no order needs a person.`);
  return groups.length ? 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_same_amount_orders.py
from check_same_amount_orders import shared_amounts


def order(id, total, **over):
    return {"id": id, "number": str(id), "status": "on-hold", "payment_method": "bacs", "total": total, "currency": "EUR", **over}


def test_two_orders_for_the_same_amount_are_grouped():
    out = shared_amounts([order(1, "25.00"), order(2, "25.00"), order(3, "49.90")])
    assert out == [{"currency": "EUR", "total_minor": 2500, "orders": ["1", "2"]}]


def test_an_amount_held_by_one_order_is_not_listed():
    assert shared_amounts([order(1, "25.00"), order(2, "25.01")]) == []


def test_the_same_amount_in_two_currencies_is_not_shared():
    assert shared_amounts([order(1, "25.00"), order(2, "25.00", currency="CHF")]) == []


def test_only_unpaid_bank_transfers_count():
    assert shared_amounts([order(1, "25.00"), order(2, "25.00", status="processing"), order(3, "25.00", payment_method="stripe")]) == []


def test_amounts_compare_in_cents_so_25_and_25_00_are_one_amount():
    assert shared_amounts([order(1, "25"), order(2, "25.00")])[0]["orders"] == ["1", "2"]


def test_zero_totals_are_ignored():
    assert shared_amounts([order(1, "0.00"), order(2, "0.00")]) == []
check-same-amount-orders.test.mjs
import { test } from "node:test";
import assert from "node:assert/strict";
import { sharedAmounts } from "./check-same-amount-orders.mjs";

const order = (id, total, over = {}) => ({ id, number: String(id), status: "on-hold", payment_method: "bacs", total, currency: "EUR", ...over });

test("two orders for the same amount are grouped", () =>
  assert.deepEqual(sharedAmounts([order(1, "25.00"), order(2, "25.00"), order(3, "49.90")]), [{ currency: "EUR", total_minor: 2500, orders: ["1", "2"] }]));
test("an amount held by one order is not listed", () => assert.deepEqual(sharedAmounts([order(1, "25.00"), order(2, "25.01")]), []));
test("the same amount in two currencies is not shared", () => assert.deepEqual(sharedAmounts([order(1, "25.00"), order(2, "25.00", { currency: "CHF" })]), []));
test("only unpaid bank transfers count", () =>
  assert.deepEqual(sharedAmounts([order(1, "25.00"), order(2, "25.00", { status: "processing" }), order(3, "25.00", { payment_method: "stripe" })]), []));
test("amounts compare in cents so 25 and 25.00 are one amount", () => assert.deepEqual(sharedAmounts([order(1, "25"), order(2, "25.00")])[0].orders, ["1", "2"]));
test("zero totals are ignored", () => assert.deepEqual(sharedAmounts([order(1, "0.00"), order(2, "0.00")]), []));

Worked example

From the test store

What it found

On the same store, two of the unpaid bank-transfer orders were for 25.00 (#12 and #14). The check listed that one shared amount and nothing else. A 25.00 order paid by cash on delivery and a 25.00 bank-transfer order already Processing were left out, correctly: a payment can only be for an unpaid bank-transfer order.

output (Python)
25.00 EUR: #14, #12
1 amount(s) shared by 2 unpaid bank-transfer order(s): a payment for one of them that names no order needs a person.
(exit status 1)
output (Node.js)
25.00 EUR: #14, #12
1 amount(s) shared by 2 unpaid bank-transfer order(s): a payment for one of them that names no order needs a person.
(exit status 1)

That pair is the case to settle by hand. A payment of 25.00 that names neither order cannot be given to one of them by a program; if it quotes one order's reference, it names one order and the question goes away.

FAQ

Is it safe to auto-match when only one order has that amount?

It is much safer, but it is still a guess about a stranger's money: the payer may have meant an order that has since been cancelled, or may be paying for someone else. A cautious matcher treats an amount-only match as a suggestion for a person to confirm.

What if the payer's name matches the billing name?

That is supporting evidence, not an identifier. Names are written many ways (MUELLER, ERIKA, or Erika Müller) and two customers can share one. It can rank the suggestions; it should not confirm one.

Why group by currency?

25.00 EUR and 25.00 CHF are different amounts of money, and a payment in one currency does not pay an order in the other.

Related field notes

Citations

  1. WooCommerce docs: Direct bank transfer (BACS). New orders are set On hold and you confirm the deposit yourself. woocommerce.com/document/bacs
  2. WooCommerce REST API: listing orders, their status, payment method, totals and dates. woocommerce.github.io/woocommerce-rest-api-docs
A person decides, with the candidates listed

In Transferproof, two open orders for the same amount and no identifier are always a choice for a person, never automatic. Automatic confirmation needs an identifier, the exact amount due, the same currency and exactly one order named, and it is off until you turn it on.

Did this save you a morning with the bank statement?

If it did, 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