You’re standing up Enhance Control Panel as the new shared-hosting platform and your billing system needs to provision a customer in under five seconds when checkout completes — create the customer record, attach a subscription, allocate a website with the customer’s chosen domain, set up a mailbox or two, return success. The Enhance UI can do every step, but the UI is not your billing system. The Enhance public API is the right surface; what’s not obvious is how to chain those calls together without leaving half-provisioned customers when one step fails halfway through.
What’s happening
Enhance Control Panel exposes a REST API at the orchestrator (the central control node). It’s documented at the panel’s own /api/docs/ endpoint and authenticated with a bearer token minted in the admin UI. The endpoints you’ll touch most for provisioning are:
POST /api/orgs— create a customer (Enhance calls them “orgs” or “owners”)POST /api/orgs/{org_id}/subscriptions— attach a subscription planPOST /api/orgs/{org_id}/websites— create a website attached to a subscriptionPOST /api/websites/{site_id}/mailboxes— create a mailbox under that website’s mail servicePOST /api/websites/{site_id}/domains— attach an additional domain or subdomain
The catch is that none of these are atomic across the workflow. Step 1 creates the org. Step 2 attaches a subscription. Step 3 creates a website. If step 3 fails — quota exhausted, domain conflict, capacity issue on the assigned app server — you’ve already created an org with a subscription that costs you compute allocation but has no website attached. The provisioning service needs to either retry the whole workflow (idempotently) or compensate by deleting the partially-created resources.
The orchestrator also enforces a rate limit per token. The default in recent Enhance versions is roughly 60 requests per minute per token — fine for occasional provisioning, painful for a backfill of 500 customers. The right approach for bulk imports is one token per worker process, with the request rate held below the limit by design.
How to verify
Get a panel-level admin token from the UI: Settings → Access Tokens → Create. Scope it to the operations the consumer needs.
Sanity-check that the token works:
ORCH="https://panel.example.com"
TOKEN="..."
curl -sH "Authorization: Bearer $TOKEN" "$ORCH/api/orgs?limit=1" | jq
A 200 with an orgs array means you’re authenticated and authorized. A 401 means the token is wrong; a 403 means the token authenticated but lacks the role for the endpoint.
Look at the orchestrator’s request log to confirm calls are arriving from the expected source:
# On the orchestrator host (or via centralized logs)
journalctl -u enhance-orchestrator -f --since '10 minutes ago' | \
grep -E '/api/(orgs|websites|mailboxes)'
Confirm there’s enough capacity on the app-server pool before you trigger a bulk provisioning run:
curl -sH "Authorization: Bearer $TOKEN" "$ORCH/api/app-servers" | \
jq '.app_servers[] | {hostname, cpu_pct: .resource_usage.cpu, disk_used_gb: .resource_usage.disk_used_gb, sites: .website_count}'
If every app server is over 80% disk, your provisioning will start failing partway through and the failure mode looks like “step 3 returns 500.” Add capacity first, then run the import.
The fix
A single Python orchestrator that handles the four-step provisioning idempotently, with retries, rate limiting, and rollback. Save it as /opt/billing/provision-enhance.py:
#!/usr/bin/env python3
# /opt/billing/provision-enhance.py
# Provision a customer in Enhance with idempotency + rollback.
import os, sys, time, json, secrets, string, logging
from urllib.parse import urljoin
import requests
ORCH = os.environ["ENHANCE_ORCH"] # e.g. https://panel.example.com
TOKEN = os.environ["ENHANCE_TOKEN"]
RATE_DELAY = float(os.environ.get("RATE_DELAY", "1.2")) # seconds between calls
MAX_RETRIES = int(os.environ.get("MAX_RETRIES", "3"))
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
log = logging.getLogger("provision")
S = requests.Session()
S.headers.update({
"Authorization": f"Bearer {TOKEN}",
"Accept": "application/json",
"Content-Type": "application/json",
})
def api(method, path, **kwargs):
"""HTTP wrapper with retry on 429/5xx and rate-limit delay."""
url = urljoin(ORCH, path)
last = None
for attempt in range(1, MAX_RETRIES + 1):
time.sleep(RATE_DELAY)
r = S.request(method, url, timeout=30, **kwargs)
last = r
if r.status_code == 429:
ra = int(r.headers.get("Retry-After", "5"))
log.warning("rate limited, sleeping %ds", ra)
time.sleep(ra)
continue
if r.status_code >= 500:
log.warning("server error %d on %s, retry %d", r.status_code, path, attempt)
time.sleep(2 ** attempt)
continue
return r
return last
def find_org_by_external_id(external_id):
"""Idempotency: returns existing org if billing system already created one."""
r = api("GET", f"/api/orgs?external_id={external_id}")
if r.status_code != 200:
return None
orgs = r.json().get("orgs", [])
return orgs[0] if orgs else None
def gen_password():
alpha = string.ascii_letters + string.digits
return "".join(secrets.choice(alpha) for _ in range(24))
def provision(customer):
"""customer = dict with billing fields. Returns dict with provisioned ids."""
external_id = customer["billing_id"]
log.info("provisioning customer billing_id=%s", external_id)
# Step 1 — create org (idempotent via external_id lookup)
existing = find_org_by_external_id(external_id)
if existing:
org_id = existing["id"]
log.info("org already exists id=%s", org_id)
else:
r = api("POST", "/api/orgs", json={
"name": customer["company"],
"owner_email": customer["email"],
"owner_name": customer["contact_name"],
"external_id": external_id,
})
if r.status_code != 201:
log.error("org create failed: %s", r.text)
return {"ok": False, "step": "org", "detail": r.text}
org = r.json()
org_id = org["id"]
log.info("org created id=%s", org_id)
created = {"org_id": org_id, "subscription_id": None,
"website_id": None, "mailbox_ids": []}
try:
# Step 2 — attach subscription
sub_r = api("POST", f"/api/orgs/{org_id}/subscriptions", json={
"plan_id": customer["plan_id"],
"external_id": f"{external_id}-sub",
})
if sub_r.status_code not in (201, 200, 409):
raise RuntimeError(f"subscription create: {sub_r.status_code} {sub_r.text}")
if sub_r.status_code == 409:
# Already attached. Look up.
existing_subs = api("GET",
f"/api/orgs/{org_id}/subscriptions").json().get("subscriptions", [])
sub_id = next((s["id"] for s in existing_subs
if s.get("external_id") == f"{external_id}-sub"), None)
else:
sub_id = sub_r.json()["id"]
created["subscription_id"] = sub_id
log.info("subscription attached id=%s", sub_id)
# Step 3 — create website
site_r = api("POST", f"/api/orgs/{org_id}/websites", json={
"subscription_id": sub_id,
"domain": customer["primary_domain"],
"owner_email": customer["email"],
"create_ssl": True,
"external_id": f"{external_id}-site",
})
if site_r.status_code not in (201, 200):
raise RuntimeError(f"website create: {site_r.status_code} {site_r.text}")
site_id = site_r.json()["id"]
created["website_id"] = site_id
log.info("website created id=%s domain=%s",
site_id, customer["primary_domain"])
# Step 4 — create mailboxes
for mb in customer.get("mailboxes", []):
pw = gen_password()
mb_r = api("POST", f"/api/websites/{site_id}/mailboxes", json={
"local_part": mb["local_part"],
"domain": customer["primary_domain"],
"password": pw,
"quota_mb": mb.get("quota_mb", 5000),
})
if mb_r.status_code not in (201, 200):
raise RuntimeError(f"mailbox {mb['local_part']}: "
f"{mb_r.status_code} {mb_r.text}")
mb_id = mb_r.json()["id"]
created["mailbox_ids"].append({"id": mb_id, "local": mb["local_part"]})
# Stash the password in vault for delivery to the customer
os.system(
f"vault kv put secret/enhance/mailboxes/{external_id}/{mb['local_part']} "
f"value='{pw}' >/dev/null"
)
log.info("mailbox created %s@%s id=%s",
mb["local_part"], customer["primary_domain"], mb_id)
return {"ok": True, "created": created}
except Exception as e:
log.error("provisioning failed, rolling back: %s", e)
rollback(created)
return {"ok": False, "error": str(e), "rolled_back": True}
def rollback(created):
"""Best-effort compensating delete in reverse order."""
for mb in created["mailbox_ids"]:
api("DELETE", f"/api/mailboxes/{mb['id']}")
log.info("rollback: deleted mailbox %s", mb["id"])
if created["website_id"]:
api("DELETE", f"/api/websites/{created['website_id']}")
log.info("rollback: deleted website %s", created["website_id"])
if created["subscription_id"]:
api("DELETE",
f"/api/orgs/{created['org_id']}/subscriptions/{created['subscription_id']}")
log.info("rollback: deleted subscription %s", created["subscription_id"])
# Do NOT delete the org by default; an org without children is cheap and the
# billing system may want to reattach a subscription on the next try.
if __name__ == "__main__":
if len(sys.argv) != 2:
print("usage: provision-enhance.py <customer.json>")
sys.exit(2)
customer = json.load(open(sys.argv[1]))
result = provision(customer)
print(json.dumps(result, indent=2))
sys.exit(0 if result.get("ok") else 1)
A sample customer.json:
{
"billing_id": "cust-2026-00472",
"company": "Acme Widgets Inc",
"contact_name": "Alex Martin",
"email": "alex@acmewidgets.com",
"plan_id": "plan-silver-2026",
"primary_domain": "acmewidgets.com",
"mailboxes": [
{"local_part": "alex", "quota_mb": 10240},
{"local_part": "billing", "quota_mb": 5120},
{"local_part": "support", "quota_mb": 5120}
]
}
Wire it into the billing webhook handler — when checkout completes, the handler writes a customer.json and runs the script. If the script returns non-zero, the handler queues a retry and notifies ops:
ENHANCE_ORCH=https://panel.example.com \
ENHANCE_TOKEN=$(vault kv get -field=value secret/enhance/provisioner/2026-05) \
RATE_DELAY=1.2 \
python3 /opt/billing/provision-enhance.py /tmp/customer-cust-2026-00472.json
For bulk imports — e.g. migrating 500 customers from a legacy panel — split the workload across multiple tokens, one per worker, each with a RATE_DELAY of about 1.2s. Three workers gives you roughly 150 provisioning workflows per minute end-to-end. Don’t try to brute through the rate limit on a single token; the orchestrator will start returning 429 and your retry loop will just burn CPU.
A diagnostic helper that walks an org and prints what’s attached — useful when a provisioning result looks wrong:
def describe_org(org_id):
org = api("GET", f"/api/orgs/{org_id}").json()
subs = api("GET", f"/api/orgs/{org_id}/subscriptions").json().get("subscriptions", [])
sites = api("GET", f"/api/orgs/{org_id}/websites").json().get("websites", [])
print(f"Org {org_id}: {org.get('name')}")
for s in subs:
print(f" Subscription {s['id']} plan={s.get('plan_id')} "
f"state={s.get('state')}")
for w in sites:
print(f" Website {w['id']} domain={w.get('primary_domain')} "
f"state={w.get('state')}")
mbs = api("GET", f"/api/websites/{w['id']}/mailboxes").json().get("mailboxes", [])
for mb in mbs:
print(f" Mailbox {mb['id']} {mb.get('local_part')}@... "
f"quota={mb.get('quota_mb')}MB")
Two operational rules: the provisioning token has no business hitting the suspend/delete endpoints unless your billing logic actually needs them — mint a separate token (different scope, different vault path) for the dunning/termination workflow. And the rollback path should never delete the org itself; orgs are cheap and the billing retry might be seconds away. Deleting the org and then re-creating it generates an inconsistent state in the customer’s email about their new account.
Provisioning pipelines that need to be five-9s reliable across Enhance’s public API — with idempotency, rollback, rate-limit awareness — are exactly the kind of plumbing we ship inside Deployment Management and run under Managed Cloud Ops. Open a scoping call if you’re standing up Enhance behind a billing system.