How to add to a WHMCS cart from another website

WHMCS's cart is CSRF-protected, so another site can't fill it. How we sell from our own basket anyway, and keep personal data off the URL.

A basket on the left passing through a narrow gate into a sealed box on the right, a line of small tokens travelling between them, on the SaneChoice navy

You sell hosting, domains or email from your own website, and the billing runs in WHMCS. You want an "Add to cart" button on every page that sells something, one basket that follows the visitor around, and one checkout at the end. What you've got is two shops: your website, and WHMCS's own store on another host, with its own cart.

WHMCS does document single-product links and an exception for its domain checker, but neither can hand over a whole basket. The obvious fix, a form on your site that posts the basket into WHMCS's cart, doesn't work. WHMCS checks a CSRF token on its forms, a secret tied to the visitor's session on the WHMCS host, and its security settings describe the option as stopping "malicious visitors from forging form posts" and recommend always keeping it on unless WHMCS support says otherwise. Your website can't know that token, so WHMCS refuses the post, which is exactly what it should do.

This is how we sell from our own basket anyway, through a checkout we can't change, with that protection left on. It rests on the cart's own endpoints rather than a documented API, so most of what follows covers the checks that make that safe.

Two baskets meant some customers checked out twice#

Our website's basket is a small Flask application. Somebody reading about monitoring adds it on the monitoring page, and the basket asks nothing on the way in. Which domain a service is for, how many years a registration runs and the registry's own questions are asked once, on the basket page.

Payment has to happen in WHMCS, which holds the client records, invoices and payment gateways. Its PHP is encoded with ionCube, so its code can't be read or changed, as we found when speeding it up. The gap had a cost: until 12 October 2026, a domain transfer went to WHMCS's own cart while everything else went through ours, so somebody moving a domain and buying hosting for it checked out twice.

The documented routes either failed or billed too early#

We built the first version of the handoff on 10 September 2026, and went looking for something better four days later. Both alternatives are the first places anyone with this problem looks.

WHMCS 9's newer REST API has a real cart. Its documentation was marked beta when we read it. We tested it against our live install on 14 September 2026, and most of it was what we wanted: a cart created by one call, items added by another, and a checkout link that a fresh browser could open with the right total. Products went in. But adding a domain registration returned a server error at one, two, five and ten years, with the request checked against the published specification, and we found nothing published describing it. A cart that can't register a domain is no use to a business that sells domains.

The classic API's AddOrder is documented and stable. It also needs a client ID, and it creates an order and, by default, an invoice. That rules out a first-time customer, who has no client ID yet, and turns every abandoned basket into an abandoned order in the billing system. So we kept the approach we'd started with.

Send a description, and replay it where the token lives#

When the customer presses checkout, our basket becomes a compact string on the link to WHMCS's cart. Each item is a token: a letter, then its fields, separated by tildes. Tokens are separated by semicolons.

d~example.co.uk;d~example.com~5;n~ns1.example.net~ns2.example.net;p~123~monthly~example.co.uk;t~example.org
TokenWhat it means
d~name, d~name~yearsA domain registration, for one year or for 2 to 10
n~ns1~ns2 (up to four)Custom nameservers, for the whole order
p~pid~cycle, p~pid~cycle~domainA product and its billing term, optionally set up against a domain
s~pid~cycle~domainHosting, which needs WHMCS's two-step domain route
t~nameA domain transfer in. Its code is never on the URL

Inside our WHMCS theme, a small script we call the bridge reads that string on the cart page. The page already carries the visitor's CSRF token, because WHMCS's own cart JavaScript needs it. The bridge uses it to make the same calls that JavaScript makes, read out of the standard_cart order form or captured by watching the browser's requests.

function post(url, fields) {
  var body = new URLSearchParams();
  body.set("token", token);            // the page's own CSRF token
  for (var k in fields) body.set(k, fields[k]);
  return fetch(url, {
    method: "POST",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body.toString()
  });
}

// e.g. a registration, as the cart's own JavaScript adds one
post("/cart.php", { a: "addToCart", domain: "example.co.uk" });

This doesn't get round CSRF protection. The requests come from WHMCS's own page, in the customer's browser and session, doing what they could do by clicking.

The order matters. The bridge empties the WHMCS cart first, because anything already there is left over from an abandoned visit, and a surprise line on a bill isn't a small mistake. Domains go next, so a product can be set up against one being registered in the same basket. A basket with a domain lands on WHMCS's domain configuration page. Anything else goes straight to checkout.

A customer signed in on our website goes through WHMCS's CreateSsoToken API, a one-time sign-in link that lands in the cart. If that call fails, they go through as a guest, because a worse checkout is better than a broken one.

The side doing the work does the checking#

Our website checks every field before it writes the string. The bridge checks every field again before it adds anything: a product ID must be digits, a billing term must be one of WHMCS's own names, and a domain must look like a domain. A URL is something anybody can write, so the side that acts on it checks it, whatever the other side promised.

An unrecognised token refuses the whole basket rather than replaying the rest. A basket missing a line is worse than one that never arrived, because the customer would pay for it without noticing what was missing.

The tests try to bend the string. They submit domains containing a semicolon, a tilde, a newline or a script tag, and check that nothing reaches the handoff the basket didn't put there. They hand it a tampered session with a quantity of 99,999 and a separator smuggled inside a domain, and check that the basket is rebuilt rather than trusted.

The format also has to survive the two halves being deployed at different moments. A one-year registration is still written exactly as it was before terms existed. When hosting needed a different route, it got a new letter rather than an extra field on p~: an old bridge refuses an s~ token outright, where it would have sent a p~ down the route that drops hosting.

WHMCS ignores a quantity, so quantity becomes repetition#

WHMCS's product add endpoint ignores a quantity field: we sent three and got one line. So the string repeats a product once per unit, and the bridge groups the repeats back together, adds the product once, and posts the quantity the way the cart's own Update button does. Measured on our live cart on 28 September 2026:

Five mailboxes, measured 28 September 2026Lines in the cartHow VAT is rounded
Added five times5On each of five small lines, which came to a penny more
Added once, quantity set to 51Once, on the whole line

The penny comes from our WHMCS calculating VAT per line item, which is one of two choices under its Tax Calculation Mode setting, so our basket's estimated total now rounds per line too. If you copy this, match your own setting. Otherwise the last number somebody reads before paying is a penny out.

Count the limit in the unit that actually travels#

A link can only be so long, so both halves cap the basket. Ours allowed twelve lines; the bridge allowed twelve tokens. They aren't the same number: custom nameservers add a token, and a product repeats once per unit. Twelve domains plus custom nameservers is thirteen tokens, and so is three domains and two products at a quantity of five.

The bridge refused both, before it had marked itself busy, so its error handling and its timeout never ran. The customer landed on an empty WHMCS cart with no message and no way back.

The fix, on 28 September 2026, was to count tokens on both sides, raise the cap to 24, and make the website's count a mirror of the function that writes the string:

def tokens_used(cart):
    """How many tokens this cart becomes. Mirrors spec() exactly."""
    return (len(cart["domains"])
            + len(cart["transfers"])
            + (1 if cart["nameservers"] else 0)
            + sum(1 if is_hosting(item) else item["qty"]
                  for item in cart["products"]))

The website refuses the 25th token on the basket page, where there's somewhere to say so, and the bridge keeps its cap as a backstop. A test holds the two functions together:

check("tokens_used agrees with spec()",
      B.tokens_used(cart) == len([t for t in B.spec(cart).split(";") if t]))

Keep names and transfer codes off the URL entirely#

Some of what the bridge needs must never go on a link. A .co.uk registration asks for a Registrant Name, a person's name. A transfer needs the code that lets anyone holding it take the domain. URLs end up in browser history and server logs, and can leak through referrer headers.

So they stay in the customer's session with our website, and the bridge fetches them with a credentialed request:

fetch("https://www.example.co.uk/your-data-endpoint", {
  method: "GET",
  credentials: "include",       // send the website's session cookie
  cache: "no-store",
  headers: { "Accept": "application/json" }
});

Two web standards make this work without a token of its own. First, www.sanechoice.cloud and clients.sanechoice.cloud are different origins but the same site, because they share a registrable domain. Our session cookie is SameSite=Lax, which holds it back from other sites' form posts and background requests but sends it on this one, because this request comes from the same site. The bridge reads the session the customer already has, and nothing identifying appears in any URL.

Second, the website answers with CORS headers that name the WHMCS origin exactly, and only when that's the origin asking. MDN's CORS guide explains why it can't be the * wildcard: browsers block a credentialed response that carries one.

origin = request.headers.get("Origin", "")
if origin == BILLING_ORIGIN:
    resp.headers["Access-Control-Allow-Origin"] = BILLING_ORIGIN
    resp.headers["Access-Control-Allow-Credentials"] = "true"
    resp.headers["Vary"] = "Origin"
resp.headers["Cache-Control"] = "no-store"

Transfer codes needed one more decision. Flask's default session is a cookie that's signed but not encrypted, so anyone who can see the request can read it. Process memory won't do either, because the code is typed on one request and read on another, possibly by a different worker. So codes go into a small SQLite store on the server, and the session holds only an opaque random key. A code is kept for two hours at most, removed with its line, and gone when the order completes.

A failed handoff should land back in the basket#

Emptying WHMCS's cart first has a cost: if the first line is refused, the customer is left with an empty cart and no reason. That happened on 15 September 2026 with sanechoice.cloud, a domain WHMCS already holds a record for and won't register again.

Our website never clears its basket at the handoff, so a failed one can be retried. The bridge now counts what landed. If nothing did, it sends the customer back to their basket and names the refused line, which the basket page checks before showing, since it arrived on a URL. If something landed, the customer stays in WHMCS's cart with a note to check it before paying, because that cart is the true state.

Not every failure should stop the handoff. The test we used was whether the customer can still see and fix it on the very next screen.

If this failsThe bridgeBecause
A domain registration or transferStopsA customer must not pay for a domain that never went in
HostingStopsA domain bought without the hosting it was for is the wrong order
The registration termCarries onThe term is on the next screen, ready to change
A quantityCarries onThe line is in the cart, and its quantity is editable
Nameservers or registry answersCarries onThe configuration page asks for them anyway

WHMCS's product add answers HTTP 200 whether or not it added anything, so the bridge can only count a product as "not refused". That errs high, which is the safe direction: the customer stays in front of a cart that might hold something. A handoff that takes longer than 15 seconds gives up the same way.

Hosting goes in by WHMCS's own two steps#

The product add endpoint has a quiet exception. A product in a WHMCS group that requires a domain, which is how our website hosting plans are set up, is dropped without an error: HTTP 200, a redirect, and nothing in the cart. Our first version left those products out of the basket.

On 3 October 2026 hosting got the route WHMCS's own order form takes. The bridge chooses the domain first, saying whether it's in the same basket or one the customer owns. WHMCS redirects to the configuration step for the line it made, the bridge reads the line number from that redirect and posts the billing term against it. No line number means nothing was added, and the handoff stops.

Both halves are tested, and so is WHMCS itself#

The basket and the bridge are in different languages and repositories, and deploy by different means. Nothing connects them but the string. So a contract check, run with the unit tests before every deploy, reads the bridge's JavaScript as text and compares it with the basket's Python.

  • Billing terms and domain names. Both sides must accept the same terms, and agree about the same list of ordinary and hostile names.
  • A real basket. One containing every kind of token is built by the basket's own code and parsed the way the bridge parses it.
  • Deploy order. If the basket writes a token the bridge can't read yet, the check fails with "deploy the bridge first".
made_now = {part.split("~")[0] for part in spec.split(";")}
for k in sorted(made_now - bridge_letters):
    problems.append('the cart writes "%s~" tokens and this bridge does not '
                    "read them -- deploy the bridge first" % k)

If it can't find the other repository, it fails rather than reporting success for a comparison it never made.

None of that can see WHMCS change. The endpoints the bridge uses aren't a documented API, and an upgrade could move them. So a probe script drives the same calls against the live install with a plain browser session, and runs after every WHMCS upgrade. Two of its lessons were expensive:

  • Judge by the outcome, not the page text. The first registration-term check searched the cart for "5 Years" and passed with the call deliberately misspelled, because the period dropdown lists every term whether or not it's chosen. It now reads the subtotal and requires a longer term to cost more.
  • Test with two, not one. Registry answers are keyed by each domain's position in the cart. With one domain the position is always zero, so a mapping mistake is invisible. The probe uses two, each answered with its own name, so a swap shows.

Transfers went live on 12 October 2026, bridge first. That day we put wikipedia.org through as a transfer with a dummy code. It landed on WHMCS's domain configuration page with the code filled in, and the code never appeared in a URL. We emptied the cart afterwards without paying.

What we learned#

  • When you can't post into a system, replay from inside it. A script on its own page has its token and the visitor's session, so the protection stays on. Then watch those endpoints with a probe that drives them for real.
  • Validate on the side that acts. Checks on the sending side are for the customer's benefit. Checks on the receiving side are the ones that count.
  • Count a limit in the unit that travels. Then write the count as a mirror of the function that produces the output, and test that they agree.
  • Keep personal data and secrets off URLs. A credentialed same-site request, answered with CORS for one exact origin, carries them instead. And remember a signed cookie isn't an encrypted one.
  • Send failures back to where the work is still intact, and name what failed. An empty cart with no message is the worst page in any journey.
  • Give a new meaning a new name. An old reader should refuse a token it doesn't know, not misread it. Then deploy the reader before the writer.
  • A check that can't fail is worse than none. Break the thing it guards on purpose, and make sure it notices.

What's next#

We'd still rather use a documented API than a replay. WHMCS 9.1, in beta since 30 September 2026, extends the newer cart API; we haven't retested domain registration against it yet, and will once it's released. Until then the probe tells us whether the replay's endpoints have moved.

If you run WHMCS and want your website and your checkout to feel like one shop, tell us how yours is set up. We'll say what we'd change and quote for the work before we change anything.