Accept payments on any website, in any language.
Conduit handles the entire payment — channels, OTP/PIN prompts, processor routing, bridge rotation and retries — and hands your server one trustworthy JSON answer: was it paid, and how much. Plain HTTPS + JSON: if your stack can make an HTTP request, it can integrate.
How it works
payment.succeededreferenceEverything belongs to exactly one website. Keys, sessions, links, payments, webhook secrets — all scoped to the site that created them. A key from site A cannot read, create or settle anything on site B.
Quickstart
Create a session on your server with your secret key, then send the customer to url.
Create a checkout session
curl http://localhost:8000/api/v1/checkout/sessions \
-H "Authorization: Bearer sk_test_••••••••" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order_1042" \
-d '{
"amount": 150.00,
"currency": "GHS",
"referral": "VIP",
"customer": {"reference": "user_88", "phone": "0241234567"},
"metadata": {"order_id": 1042},
"return_url": "https://yourshop.com/pay/done"
}'
# → {"id": "cs_…", "url": "http://localhost:8000/pay/cs_…", "status": "open", …}// Node 18+ — no SDK needed
const res = await fetch("http://localhost:8000/api/v1/checkout/sessions", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.CONDUIT_SECRET_KEY}`, // sk_test_••••••••
"Content-Type": "application/json",
"Idempotency-Key": `order_${order.id}`,
},
body: JSON.stringify({
amount: order.total,
customer: { reference: String(user.id), phone: user.phone },
referral: req.query.ref, // applies that referral's minimum
metadata: { order_id: order.id },
return_url: "https://yourshop.com/pay/done",
}),
});
const session = await res.json();
if (!res.ok) throw new Error(session.error.message);
res.redirect(session.url); // or open it with conduit.jsimport os, requests
r = requests.post(
"http://localhost:8000/api/v1/checkout/sessions",
headers={
"Authorization": f"Bearer {os.environ['CONDUIT_SECRET_KEY']}", # sk_test_••••••••
"Idempotency-Key": f"order_{order.id}",
},
json={
"amount": str(order.total),
"customer": {"reference": str(user.id), "phone": user.phone},
"metadata": {"order_id": order.id},
"return_url": "https://yourshop.com/pay/done",
},
timeout=15,
)
r.raise_for_status()
session = r.json()
redirect_to = session["url"]<?php
$ch = curl_init("http://localhost:8000/api/v1/checkout/sessions");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("CONDUIT_SECRET_KEY"), // sk_test_••••••••
"Content-Type: application/json",
"Idempotency-Key: order_" . $order["id"],
],
CURLOPT_POSTFIELDS => json_encode([
"amount" => $order["total"],
"customer" => ["reference" => (string) $user["id"], "phone" => $user["phone"]],
"metadata" => ["order_id" => $order["id"]],
"return_url" => "https://yourshop.com/pay/done",
]),
]);
$session = json_decode(curl_exec($ch), true);
header("Location: " . $session["url"]);use Illuminate\Support\Facades\Http;
$session = Http::withToken(config('services.conduit.secret')) // sk_test_••••••••
->withHeaders(['Idempotency-Key' => "order_{$order->id}"])
->post('http://localhost:8000/api/v1/checkout/sessions', [
'amount' => $order->total,
'customer' => ['reference' => (string) $user->id, 'phone' => $user->phone],
'referral' => request('ref'),
'metadata' => ['order_id' => $order->id],
'return_url' => route('pay.done'),
])->throw()->json();
return redirect()->away($session['url']);# views.py
import requests
from django.conf import settings
from django.shortcuts import redirect
def start_payment(request, order_id):
order = Order.objects.get(pk=order_id, user=request.user)
r = requests.post(
f"{settings.CONDUIT_BASE}/api/v1/checkout/sessions", # http://localhost:8000
headers={"Authorization": f"Bearer {settings.CONDUIT_SECRET_KEY}",
"Idempotency-Key": f"order_{order.pk}"},
json={"amount": str(order.total),
"customer": {"reference": str(request.user.pk)},
"referral": request.GET.get("ref"),
"metadata": {"order_id": order.pk},
"return_url": request.build_absolute_uri("/pay/done/")},
timeout=15)
r.raise_for_status()
return redirect(r.json()["url"])body, _ := json.Marshal(map[string]any{
"amount": 150.00,
"customer": map[string]string{"reference": userID, "phone": phone},
"metadata": map[string]any{"order_id": orderID},
"return_url": "https://yourshop.com/pay/done",
})
req, _ := http.NewRequest("POST", "http://localhost:8000/api/v1/checkout/sessions", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("CONDUIT_SECRET_KEY")) // sk_test_••••••••
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "order_"+orderID)
resp, err := http.DefaultClient.Do(req)
if err != nil { return err }
defer resp.Body.Close()
var session struct{ ID, URL string }
json.NewDecoder(resp.Body).Decode(&session)
http.Redirect(w, r, session.URL, http.StatusSeeOther)require "net/http"
require "json"
uri = URI("http://localhost:8000/api/v1/checkout/sessions")
req = Net::HTTP::Post.new(uri, {
"Authorization" => "Bearer #{ENV['CONDUIT_SECRET_KEY']}", # sk_test_••••••••
"Content-Type" => "application/json",
"Idempotency-Key" => "order_#{order.id}"
})
req.body = { amount: order.total, customer: { reference: user.id.to_s },
metadata: { order_id: order.id }, return_url: pay_done_url }.to_json
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |h| h.request(req) }
redirect_to JSON.parse(res.body)["url"], allow_other_host: trueHttpClient client = HttpClient.newHttpClient();
String json = """
{"amount": 150.00, "customer": {"reference": "user_88"},
"metadata": {"order_id": 1042}, "return_url": "https://yourshop.com/pay/done"}
""";
HttpRequest req = HttpRequest.newBuilder(URI.create("http://localhost:8000/api/v1/checkout/sessions"))
.header("Authorization", "Bearer " + System.getenv("CONDUIT_SECRET_KEY")) // sk_test_••••••••
.header("Content-Type", "application/json")
.header("Idempotency-Key", "order_1042")
.POST(HttpRequest.BodyPublishers.ofString(json)).build();
HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
String url = new ObjectMapper().readTree(res.body()).get("url").asText();using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("CONDUIT_SECRET_KEY")); // sk_test_••••••••
http.DefaultRequestHeaders.Add("Idempotency-Key", $"order_{order.Id}");
var res = await http.PostAsJsonAsync("http://localhost:8000/api/v1/checkout/sessions", new {
amount = order.Total,
customer = new { reference = user.Id.ToString() },
metadata = new { order_id = order.Id },
return_url = "https://yourshop.com/pay/done"
});
res.EnsureSuccessStatusCode();
var session = await res.Content.ReadFromJsonAsync<JsonElement>();
return Redirect(session.GetProperty("url").GetString());// Call this from YOUR backend, never from the app (keep sk_ off devices).
final res = await http.post(
Uri.parse('http://localhost:8000/api/v1/checkout/sessions'),
headers: {
'Authorization': 'Bearer ${Platform.environment['CONDUIT_SECRET_KEY']}', // sk_test_••••••••
'Content-Type': 'application/json',
},
body: jsonEncode({'amount': 150, 'customer': {'reference': userId}}),
);
final url = jsonDecode(res.body)['url'];
// In Flutter: open `url` in a WebView / url_launcher and listen for return_url.
Keys & authentication
Send Authorization: Bearer <key>. Each website has its own keys, in two modes and two kinds:
| Key | Where | Can |
|---|---|---|
| sk_live_… / sk_test_… | Your server only | Everything for that website: sessions, payments, referrals, signed links |
| pk_live_… / pk_test_… | Browser / app | Read site config, create browser sessions — only from your registered domains (CORS + origin check) |
Keys can be rolled with a grace period (old key keeps working for up to 7 days) or revoked instantly. Removing a website revokes all its keys.
Site binding & security model
- Database scoping — every session, link and payment row carries its website; API lookups are always filtered by the calling key's website.
- Origin enforcement — payment links and publishable keys are refused unless the request comes from your registered domains (Referer/Origin).
- Frame-ancestors — the checkout can only be embedded in an iframe on your domains.
- Return URLs —
return_url/cancel_urlmust be on your domains. - Signed links — optional HMAC over amount, customer, referral and expiry.
- IP allow-list — optional per-website list for secret-key calls.
- Secrets at rest — gateway keys, bridge secrets and webhook secrets are encrypted (Fernet); API secrets are stored only as SHA-256 hashes.
Checkout sessions
| Field | Type | Notes |
|---|---|---|
| amount | number | Omit to let the customer choose within your limits. If set, it is locked. |
| currency | string | Defaults to the website currency (GHS). |
| referral | string | Referral code — applies that code's minimum/maximum/quick amounts. |
| customer | object | reference (your user id — echoed back), phone, email, name. |
| metadata | object | Up to 4 KB, echoed on the payment and every webhook. |
| channels | string[] | Restrict to channel codes, e.g. ["momo-mtn"]. |
| return_url / cancel_url | url | Must be on your domains. We append conduit_session, conduit_status, conduit_reference. |
| expires_in | int | Seconds, 300 – 604800. Default from platform settings. |
Native in-page embed — no redirect
One script tag with your publishable key. Your button opens the payment as a modal inside your own page (a bottom sheet on phones); it sizes itself to the content, uses your website's theme or deposit-builder design, and never navigates away. Your classic payment links are unaffected — they still open the hosted page and redirect back.
<!-- 1. Once, before </body>. pk_ keys are safe in page source and only work on your domains -->
<script src="http://localhost:8000/js/v1/conduit.js" data-key="pk_live_…" async></script>
<!-- 2. Any button — the modal opens INSIDE your page. No redirect, no new tab. -->
<button data-conduit-pay data-amount="250" data-customer="{{ user.id }}" data-ref="VIP">Deposit</button>
<!-- 3. Or from code -->
<script>
const payment = await Conduit.pay({ amount: 250, customer: { reference: user.id } });
// → { id, reference, amount, charged } (rejects with e.code === "closed" if dismissed)
Conduit.on("success", p => refreshBalance()); // UI only — credit via webhook
</script>Called by the SDK with your pk_ key (origin-checked, CORS). An amount sent from the browser is a prefill the customer can change, unless the website allows browser-set amounts. Behaviour (auto-close, backdrop, drawer/centred, width, bottom sheet) is configured per website in Websites › Native embed. Events: open, success, failed, close, error; buttons also dispatch conduit:success / conduit:cancel DOM events.
conduit.js — open a server-created session as a modal
One script tag. Works with sessions created on your server, or with payment links (still origin-bound).
<!-- 1. Load once -->
<script src="http://localhost:8000/js/v1/conduit.js" defer></script>
<!-- 2a. Session created on your server -->
<button onclick="Conduit.checkout({ session: '{{ session.id }}' })">Pay now</button>
<!-- 2b. Or a payment link (works only on YOUR registered domains) -->
<button data-conduit-link="pl_yourLinkToken" data-conduit-ref="VIP">Deposit</button>
<script>
Conduit.on("success", (p) => {
// UI only — always confirm server-side (webhook or GET /payments/{ref})
location.href = "/wallet?ref=" + p.reference;
});
Conduit.on("close", () => console.log("closed"));
Conduit.on("failed", (p) => console.warn(p.failure));
</script>Events: ready, success, failed, close, return. Browser events are for UX — credit only after server-side confirmation.
Payment links
Create links in the console (Payment links). Each link belongs to one website and refuses to open from any other domain. Add ?ref=CODE for a referral rule, or attach a rule to the link itself.
Signed links
Pre-fill and lock amount, customer and referral without an API call: sign the sorted query string with your website's link signing secret (Websites › Keys). Signed links also bypass the Referer check — your server's signature already proves origin — so they work from emails and apps. Or call POST /api/v1/links/sign.
// Pre-fill & lock a payment link from your server (no API call needed)
import crypto from "node:crypto";
const params = { amount: "250.00", customer_ref: String(user.id), ref: "VIP",
exp: Math.floor(Date.now() / 1000) + 3600 };
const canonical = new URLSearchParams(Object.keys(params).sort().map(k => [k, String(params[k])])).toString();
params.sig = crypto.createHmac("sha256", process.env.CONDUIT_LINK_SECRET).update(canonical).digest("hex");
const url = `http://localhost:8000/l/pl_yourLinkToken?${new URLSearchParams(params)}`;import hashlib, hmac, time
from urllib.parse import urlencode
params = {"amount": "250.00", "customer_ref": str(user.id), "ref": "VIP", "exp": int(time.time()) + 3600}
canonical = urlencode({k: str(params[k]) for k in sorted(params)})
params["sig"] = hmac.new(LINK_SECRET.encode(), canonical.encode(), hashlib.sha256).hexdigest()
url = f"http://localhost:8000/l/pl_yourLinkToken?{urlencode(params)}"$params = ["amount" => "250.00", "customer_ref" => (string) $user->id, "ref" => "VIP", "exp" => time() + 3600];
ksort($params);
$params["sig"] = hash_hmac("sha256", http_build_query($params), getenv("CONDUIT_LINK_SECRET"));
$url = "http://localhost:8000/l/pl_yourLinkToken?" . http_build_query($params);Confirm a payment
After the redirect (or instead of trusting the browser), ask us. /verify also re-checks with the processor right now.
Confirm the payment server-side
curl http://localhost:8000/api/v1/payments/HL-K7QX-LZ9F2K1A8Q \ -H "Authorization: Bearer sk_test_••••••••" # or re-check with the processor right now: curl -X POST http://localhost:8000/api/v1/payments/HL-K7QX-LZ9F2K1A8Q/verify -H "Authorization: Bearer sk_test_••••••••" # or fetch the session you created: curl http://localhost:8000/api/v1/checkout/sessions/cs_… -H "Authorization: Bearer sk_test_••••••••"
const r = await fetch(`http://localhost:8000/api/v1/checkout/sessions/${sessionId}`, {
headers: { Authorization: `Bearer ${process.env.CONDUIT_SECRET_KEY}` },
});
const s = await r.json();
if (s.payment_status === "paid" && !(await alreadyCredited(s.payment.reference))) {
await creditUser(s.customer.reference, s.payment.amount_paid, s.payment.reference);
}s = requests.get(f"http://localhost:8000/api/v1/checkout/sessions/{session_id}",
headers={"Authorization": f"Bearer sk_test_••••••••"}, timeout=15).json()
p = s["payment"]
if s["payment_status"] == "paid":
with transaction.atomic():
# reference is globally unique — use it as your idempotency key
Deposit.objects.get_or_create(reference=p["reference"], defaults={
"user_id": s["customer"]["reference"], "amount": p["amount_paid"]})$ch = curl_init("http://localhost:8000/api/v1/payments/" . urlencode($_GET['conduit_reference']));
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("CONDUIT_SECRET_KEY")]]);
$p = json_decode(curl_exec($ch), true);
if ($p["status"] === "succeeded") {
// INSERT ... ON DUPLICATE KEY (reference) — never credit twice
creditUser($p["customer"]["reference"], $p["amount_paid"], $p["reference"]);
}$p = Http::withToken(config('services.conduit.secret'))
->get('http://localhost:8000/api/v1/payments/'.$request->query('conduit_reference'))->json();
if ($p['status'] === 'succeeded') {
Deposit::firstOrCreate(['reference' => $p['reference']],
['user_id' => $p['customer']['reference'], 'amount' => $p['amount_paid']]);
}def pay_done(request):
ref = request.GET.get("conduit_reference")
p = requests.get(f"{settings.CONDUIT_BASE}/api/v1/payments/{ref}",
headers={"Authorization": f"Bearer {settings.CONDUIT_SECRET_KEY}"}).json()
if p.get("status") == "succeeded":
Deposit.objects.get_or_create(reference=p["reference"], defaults={
"user_id": p["customer"]["reference"], "amount": p["amount_paid"]})
return render(request, "pay_done.html", {"payment": p})req, _ := http.NewRequest("GET", "http://localhost:8000/api/v1/payments/"+ref, nil)
req.Header.Set("Authorization", "Bearer "+os.Getenv("CONDUIT_SECRET_KEY"))
resp, _ := http.DefaultClient.Do(req)
var p struct {
Status string `json:"status"`
Reference string `json:"reference"`
AmountPaid float64 `json:"amount_paid"`
}
json.NewDecoder(resp.Body).Decode(&p)
if p.Status == "succeeded" { creditOnce(p.Reference, p.AmountPaid) }uri = URI("http://localhost:8000/api/v1/payments/#{params[:conduit_reference]}")
req = Net::HTTP::Get.new(uri, "Authorization" => "Bearer #{ENV['CONDUIT_SECRET_KEY']}")
p = JSON.parse(Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }.body)
Deposit.find_or_create_by!(reference: p["reference"]) { |d| d.amount = p["amount_paid"] } if p["status"] == "succeeded"HttpRequest req = HttpRequest.newBuilder(URI.create("http://localhost:8000/api/v1/payments/" + ref))
.header("Authorization", "Bearer " + System.getenv("CONDUIT_SECRET_KEY")).GET().build();
JsonNode p = mapper.readTree(client.send(req, BodyHandlers.ofString()).body());
if ("succeeded".equals(p.get("status").asText())) creditOnce(p.get("reference").asText(), p.get("amount_paid").asDouble());var p = await http.GetFromJsonAsync<JsonElement>($"http://localhost:8000/api/v1/payments/{reference}");
if (p.GetProperty("status").GetString() == "succeeded")
await CreditOnce(p.GetProperty("reference").GetString(), p.GetProperty("amount_paid").GetDecimal());final p = jsonDecode((await http.get(Uri.parse('http://localhost:8000/api/v1/payments/$ref'),
headers: {'Authorization': 'Bearer $secretKey'})).body);
if (p['status'] == 'succeeded') await creditOnce(p['reference'], p['amount_paid']);
Webhooks
Add endpoints per website in the console. Deliveries are signed, logged (status, latency, response) and retried with back-off: 1m → 5m → 15m → 1h → 3h → 6h → 12h → 24h. Endpoints are auto-disabled after 50 consecutive failures (you're notified). Re-deliver any event from the console.
Event types
| payment.succeeded | Money confirmed. Credit your customer (idempotently, by reference). |
| payment.failed | Declined or could not be completed. Nothing was taken. |
| payment.pending | Waiting for the customer to approve on their phone. |
| payment.action_required | OTP / PIN / redirect needed — checkout handles it. |
| payment.expired | No confirmation inside the pending window. |
| session.completed | A checkout session was paid. |
| session.expired | A checkout session closed unpaid. |
| payment.updated | Metadata, tags or attribution changed (API or console). |
| payment.held / payment.released | Risk review: money held out of payroll, then released after approval. |
| session.abandoned | Checkout left unpaid for a while — includes recovery_url to nudge the customer. |
| payment.refunded | A refund succeeded; amount_refunded / refund_status updated. |
| refund.created / refund.succeeded / refund.failed | Refund lifecycle. |
| customer.created / customer.updated | A customer was first seen, edited, blocked or re-assigned. |
| partner.created / partner.updated | Partner directory changes. |
| commission.created | A commission line was written (referrer level or staff share). |
| commission.available | A held line passed its hold period — payable now. |
| commission.paid | You recorded a partner payout. |
| commission.reversed | Clawed back (refund) or voided. |
| payout.paid | The platform paid your balance (payroll). |
| site.paused / site.resumed | Your website's payments were paused or resumed. |
Verify signatures
Conduit-Signature: t=<unix>,v1=<hex> where v1 = HMAC_SHA256(whsec, t + "." + raw_body). Reject if older than 5 minutes. Dedupe on Conduit-Event-Id.
Verify webhook signatures
# Conduit POSTs JSON to your endpoint with: # Conduit-Signature: t=1731240000,v1=<hex HMAC-SHA256(whsec, "t.body")> # Conduit-Event-Id: evt_… (dedupe on this) # Conduit-Event-Type: payment.succeeded # Verify by hand: printf '%s' "1731240000.$BODY" | openssl dgst -sha256 -hmac "$WHSEC" # Reply 2xx within 10 s. Anything else is retried for ~2 days.
import crypto from "node:crypto";
import express from "express";
app.post("/webhooks/conduit", express.raw({ type: "application/json" }), (req, res) => {
const header = req.get("Conduit-Signature") || "";
const { t, v1 } = Object.fromEntries(header.split(",").map(p => p.split("=")));
const expected = crypto.createHmac("sha256", process.env.CONDUIT_WEBHOOK_SECRET)
.update(`${t}.${req.body}`).digest("hex");
const fresh = Math.abs(Date.now() / 1000 - Number(t)) < 300;
if (!fresh || !v1 || !crypto.timingSafeEqual(Buffer.from(v1), Buffer.from(expected)))
return res.sendStatus(400);
const event = JSON.parse(req.body);
if (event.type === "payment.succeeded") creditOnce(event.data.object);
res.sendStatus(200);
});import hashlib, hmac, json, time
def verify(header: str, body: bytes, secret: str, tolerance=300) -> bool:
parts = dict(p.split("=", 1) for p in header.split(","))
t, v1 = int(parts["t"]), parts["v1"]
if abs(time.time() - t) > tolerance:
return False
expected = hmac.new(secret.encode(), f"{t}.".encode() + body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, v1)
# Flask
@app.post("/webhooks/conduit")
def conduit_hook():
if not verify(request.headers.get("Conduit-Signature", ""), request.get_data(), WHSEC):
abort(400)
event = request.get_json()
if event["type"] == "payment.succeeded":
credit_once(event["data"]["object"])
return "", 200<?php
$body = file_get_contents("php://input");
$parts = [];
foreach (explode(",", $_SERVER["HTTP_CONDUIT_SIGNATURE"] ?? "") as $kv) {
[$k, $v] = array_pad(explode("=", $kv, 2), 2, ""); $parts[$k] = $v;
}
$expected = hash_hmac("sha256", $parts["t"] . "." . $body, getenv("CONDUIT_WEBHOOK_SECRET"));
if (abs(time() - (int) $parts["t"]) > 300 || !hash_equals($expected, $parts["v1"] ?? "")) {
http_response_code(400); exit;
}
$event = json_decode($body, true);
if ($event["type"] === "payment.succeeded") creditOnce($event["data"]["object"]);
http_response_code(200);Route::post('/webhooks/conduit', function (Request $request) {
parse_str(str_replace(',', '&', $request->header('Conduit-Signature')), $sig);
$expected = hash_hmac('sha256', $sig['t'].'.'.$request->getContent(), config('services.conduit.webhook'));
abort_unless(abs(time() - (int) $sig['t']) < 300 && hash_equals($expected, $sig['v1'] ?? ''), 400);
$event = $request->json()->all();
if ($event['type'] === 'payment.succeeded') CreditDeposit::dispatch($event['data']['object']);
return response()->noContent();
})->withoutMiddleware([\App\Http\Middleware\VerifyCsrfToken::class]);@csrf_exempt
@require_POST
def conduit_hook(request):
if not verify(request.headers.get("Conduit-Signature", ""), request.body,
settings.CONDUIT_WEBHOOK_SECRET):
return HttpResponseBadRequest()
event = json.loads(request.body)
if event["type"] == "payment.succeeded":
p = event["data"]["object"]
Deposit.objects.get_or_create(reference=p["reference"], defaults={
"user_id": p["customer"]["reference"], "amount": p["amount_paid"]})
return HttpResponse(status=200)func conduitHook(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
parts := map[string]string{}
for _, kv := range strings.Split(r.Header.Get("Conduit-Signature"), ",") {
if k, v, ok := strings.Cut(kv, "="); ok { parts[k] = v }
}
t, _ := strconv.ParseInt(parts["t"], 10, 64)
mac := hmac.New(sha256.New, []byte(os.Getenv("CONDUIT_WEBHOOK_SECRET")))
mac.Write([]byte(parts["t"] + "."))
mac.Write(body)
expected := hex.EncodeToString(mac.Sum(nil))
if abs(time.Now().Unix()-t) > 300 || !hmac.Equal([]byte(expected), []byte(parts["v1"])) {
http.Error(w, "bad signature", 400); return
}
// json.Unmarshal(body, &event) … credit once by reference
w.WriteHeader(200)
}post "/webhooks/conduit" do
body = request.body.read
parts = request.env["HTTP_CONDUIT_SIGNATURE"].to_s.split(",").map { _1.split("=", 2) }.to_h
expected = OpenSSL::HMAC.hexdigest("SHA256", ENV["CONDUIT_WEBHOOK_SECRET"], "#{parts['t']}.#{body}")
halt 400 unless (Time.now.to_i - parts["t"].to_i).abs < 300 &&
Rack::Utils.secure_compare(expected, parts["v1"].to_s)
event = JSON.parse(body)
credit_once(event["data"]["object"]) if event["type"] == "payment.succeeded"
200
endString header = request.getHeader("Conduit-Signature");
Map<String,String> p = Arrays.stream(header.split(","))
.map(s -> s.split("=", 2)).collect(Collectors.toMap(a -> a[0], a -> a[1]));
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(UTF_8), "HmacSHA256"));
String expected = HexFormat.of().formatHex(mac.doFinal((p.get("t") + "." + body).getBytes(UTF_8)));
boolean fresh = Math.abs(Instant.now().getEpochSecond() - Long.parseLong(p.get("t"))) < 300;
if (!fresh || !MessageDigest.isEqual(expected.getBytes(), p.get("v1").getBytes())) return ResponseEntity.badRequest().build();[HttpPost("webhooks/conduit")]
public async Task<IActionResult> Hook() {
var body = await new StreamReader(Request.Body).ReadToEndAsync();
var p = Request.Headers["Conduit-Signature"].ToString().Split(',')
.Select(s => s.Split('=', 2)).ToDictionary(a => a[0], a => a[1]);
using var h = new HMACSHA256(Encoding.UTF8.GetBytes(_secret));
var expected = Convert.ToHexString(h.ComputeHash(Encoding.UTF8.GetBytes($"{p["t"]}.{body}"))).ToLower();
var fresh = Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - long.Parse(p["t"])) < 300;
if (!fresh || !CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(p["v1"])))
return BadRequest();
// deserialize, credit once by reference
return Ok();
}// Webhooks must hit your server — e.g. dart_frog / shelf
final parts = {for (final kv in sig.split(',')) kv.split('=')[0]: kv.split('=')[1]};
final expected = Hmac(sha256, utf8.encode(secret))
.convert(utf8.encode('${parts['t']}.$body')).toString();
if (expected != parts['v1']) return Response(400);
The payment object
{
"object": "payment",
"id": "pay_8Hq2…",
"reference": "HL-K7QX-LZ9F2K1A8Q", // globally unique — your idempotency key
"status": "succeeded", // initiated | action_required | pending | succeeded | failed | expired | reversed
"paid": true,
"livemode": true,
"currency": "GHS",
"amount": 150.0, // what you asked for
"fee": 1.5, "fee_bearer": "merchant",
"charged": 150.0, // what the customer paid
"net": 148.5, // what you net
"amount_paid": 150.0, // confirmed by the processor
"underpaid": false,
"channel": "momo-mtn", "network": "mtn",
"customer": {"reference": "user_88", "phone": "+233241234567", "email": null},
"referral": "VIP",
"session": "cs_…",
"site": {"id": "site_…", "name": "My Shop"},
"metadata": {"order_id": 1042},
"created_at": "2026-11-10T09:12:44+00:00",
"paid_at": "2026-11-10T09:13:02+00:00"
}Minimums, maximums & referral rules
The minimum a customer sees is resolved per payment, highest priority first:
- Referral rule — only when that code is on the payment
- Website minimum
- Organisation minimum
- Platform minimum
A channel's technical floor/ceiling and your plan's per-payment cap are applied on top. GET /api/v1/site returns the effective limits; the console's Referral Inspector shows the full trace.
Listing & timeframes
timeframe: today, yesterday, 3d, 7d, 14d, 30d, 90d, this_month, last_month, this_year, 1y, all, or custom with from/to (YYYY-MM-DD or YYYY-MM-DDTHH:MM). Also q, channel, referral, min, max. Cursor pagination: limit (≤100) + starting_after.
Idempotency
Send Idempotency-Key on POST /checkout/sessions. Retries with the same key and body replay the original response (Idempotent-Replayed: true); the same key with a different body returns 409 idempotency_key_reused.
Errors
{"error": {"type": "invalid_request_error", "code": "amount_below_minimum",
"message": "The minimum amount is 50.00.", "param": "amount",
"doc_url": "http://localhost:8000/docs#error-amount_below_minimum"},
"request_id": "req_…"}| Code | HTTP | Meaning |
|---|---|---|
| missing_api_key | 401 | No Authorization header. |
| invalid_api_key | 401 | Key unknown, expired after a roll, or revoked. |
| secret_key_required | 403 | A pk_ key was used on a server endpoint. |
| origin_not_allowed | 403 | Browser request from a domain not registered on this website. |
| ip_not_allowed | 403 | Server IP not on the website's allow-list. |
| account_inactive | 403 | Organisation pending, suspended or closed. |
| site_removed | 410 | Website was removed; its keys no longer work. |
| site_paused | 423 | Website is paused — show your customer the paused message. |
| amount_below_minimum | 400 | Below the resolved minimum (referral → site → org → platform). |
| amount_above_maximum | 400 | Above the resolved maximum or plan cap. |
| referral_not_found | 400 | Unknown referral code for this website. |
| referral_inactive | 400 | Referral code disabled or expired. |
| url_not_allowed | 400 | return_url / cancel_url not on this website's domains. |
| idempotency_key_reused | 409 | Same Idempotency-Key, different body. |
| insufficient_scope | 403 | Restricted key (rk_) without the scope this endpoint needs. |
| site_required | 400 | Organisation key used on a site-specific call without `site`. |
| feature_disabled | 403 | The feature (refunds, partners, management API…) isn't on your plan. |
| external_id_already_paid | 409 | This external_id (your order id) was already paid on this website. |
| customer_blocked | 403 | The customer is blocked from paying. |
| invalid_refund_amount | 400 | More than the refundable amount. |
| already_commissioned | 409 | Re-attribution refused: void the existing commission lines first. |
| test_mode_only | 403 | Test helpers need a test key. |
| risk_blocked | 403 | Blocked by the risk engine or blocklist — show a neutral message. |
| route_blocked | 403 | A routing rule blocked this payment; message is customer-safe. |
| channel_unavailable | 400 | Unknown channel code for this website, or not allowed on this session. |
| channel_not_available_here | 403 | Location targeting: this method isn't offered where the payer is (or for their phone's country). |
| embed_disabled | 403 | The embedded dashboard isn't enabled for your account by the platform. |
| role_not_found | 404 | No such embed role — create roles in Developers › Embedded dashboard. |
| channel_closed | 400 | Channel closed now (schedule or a scheduled pause); message is customer-safe. |
| rate_limited | 429 | Too many requests per minute for this key. |
| platform_maintenance | 503 | Platform maintenance window. |
| no_gateway | 503 | No gateway available (none granted, all failing). |
Testing
Use sk_test_ keys. Test payments run on the sandbox gateway — no money moves, webhooks still fire (to test endpoints).
| Any valid number | Prompt, then succeeds after ~6 seconds |
| Number ending 000 | Declined by the network |
| Number ending 111 | Asks for OTP — use 123456 |
| Number ending 222 | Asks for PIN — any 4 digits succeed |
| Number ending 999 | Stays pending until it expires |
| Card / bank | Opens a simulated approval page |
Rate limits, request ids & audit
Each key is rate-limited per minute (X-RateLimit-Remaining). Every response carries X-Request-Id; every API call is logged (redacted body, status, latency, origin, idempotency key) and searchable in Developers. Every console change is in the audit log with a field-level diff — including actions taken by platform administrators.
OpenAPI & generated SDKs
The full spec is at /api/v1/openapi.json. Import it into Postman/Insomnia, or generate a typed client for 40+ languages:
npx @openapitools/openapi-generator-cli generate \ -i http://localhost:8000/api/v1/openapi.json -g typescript-fetch -o ./conduit-client # -g python | php | go | ruby | java | csharp | kotlin | swift5 | dart | rust …