Appearance
Card payments with the card element
The card element (mookhpay.js) takes a card payment for a direct charge inside your own checkout page. The payer is not sent to MOOKHPay's hosted page.
The card number and security code are typed into fields that CyberSource, MOOKHPay's card processor, serves in iframes on your page (CyberSource Microform v2). Your page, your JavaScript and your server never see them. CyberSource turns what the payer typed into a short-lived transient token, the element hands that token to MOOKHPay, and MOOKHPay charges it. When the payer's bank wants to check it is them (3-D Secure), the element shows the bank's page over yours and carries on when they are done.
What you build:
| Part | Runs on | Holds |
|---|---|---|
| Create the charge | Your server | Your secret key |
Mount the element and call pay() | Your checkout page | The charge id and its client_secret |
| Confirm and fulfil | Your server | The webhook, or GET /charges/{id} |
The element does not create, read or cancel charges, and it cannot fulfil an order. What it tells your page is a hint for what to show the payer. The charge and its webhook are the truth.
Before you start
| You need | Why |
|---|---|
A secret key with charges:write | Only that scope can create a charge. In an organisation, only an Owner can issue it. See API keys and scopes |
A live key (mkp_live_) | Card charges made with an mkp_test_ key are refused with 400 and code 3004 |
| A deployment with direct charges and cards switched on | MOOKHPay switches on DIRECT_CHARGES_ENABLED, DIRECT_CHARGE_CARDS_ENABLED and its card rail per deployment. Where cards are off, card is 400 and code 3004, and the element's routes do not exist |
| A currency cards take | The card rail takes KES, USD, UGX and RWF, each only where MOOKHPay holds card credentials for it. A charge is in your cluster's currency. Where that currency is not taken, card is 400 and code 3004 |
| Your checkout page's origin on your allowed list | The element refuses to run on any other page. See Allow your checkout pages |
Card charges cannot be tested with a test key
Staging issues only mkp_test_ keys, and every charge made with one is a test charge. MOOKHPay has no card sandbox for test charges yet, so a card charge on an mkp_test_ key is refused with 400 and code 3004 before the element is ever reached. The card element cannot be exercised end to end on staging.
What you can test on staging: your server's create call (a 3004 answer proves the key, scope and body were accepted up to the payment method), the rest of your direct charge integration with mobile money and the test numbers, and your webhook handling. The first real card payment is on production, with a live key. Use a small amount and your own card.
Allow your checkout pages
The element runs only on pages whose origin is on your account's list of allowed origins. The list belongs to the account that owns the key, not to the key, so it survives a key being replaced. There is a live list, used for charges made with an mkp_live_ key, and a test list for mkp_test_ charges. Test charges cannot be card charges today, so only the live list is ever used.
For a charge made on_behalf_of a seller, the element is checked against the platform's list, because the platform's page is the one the element is on.
Rules for each entry:
| Rule | Example |
|---|---|
An exact origin: scheme, host, and a port only when it is not the scheme's own. No path, not even a trailing / | https://shop.example.com |
| Or one wildcard leading label. It matches exactly one label: not the bare domain, not two levels down | https://*.example.com matches https://pay.example.com, but not https://example.com or https://a.b.example.com |
https only. Plain http is accepted only for localhost, 127.0.0.1 or [::1], and only on the test list | http://localhost:5173 (test list only) |
| No IP addresses other than loopback, and no single-label hosts | https://203.0.113.4 is refused |
A wildcard must not cover a whole registry or hosting suffix, such as *.co.ke, *.pages.dev or *.vercel.app | https://*.co.ke is refused |
| At most ten entries |
A list is saved whole: saving replaces it. A list that breaks a rule is refused with 400 and code 3039, and the description names the entry. An empty list refuses every page.
Save the list in the hub: API Integrations, API Keys, Card Payment Pages. Pick Live or Test, choose Edit Pages, put one origin on each line and choose Save Pages. In an organisation, an Owner, Member or Accountant can see and change the pages; anyone else is asked to get one of them to do it. The hub notes on the Test list that it waits until test card payments are switched on. Behind the screen is MOOKHPay's app route PUT /v1/payments/app/card-element-origins/{mode}, which takes a signed-in hub session, not your secret key.
Create the charge on your server
Create a charge with payment_method: { "type": "card" }. No prompt is sent and nothing is charged yet. See Create a charge for every field.
| Field | |
|---|---|
amount | What you receive, in minor units. The card fee is added on top for the payer |
reference | Your order id. One pending charge per reference at a time |
payment_method | { "type": "card" }. Nothing else goes in it |
payer_email | Optional. The payer's receipt address and the card's billing email. A malformed address is 400 and code 1701 |
description, metadata | Optional, as for any charge |
sh
curl -X POST https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY" \
-H "Idempotency-Key: order-8841-card" \
-H "Content-Type: application/json" \
-d '{
"amount": 150000,
"reference": "order-8841",
"description": "Order 8841",
"payment_method": { "type": "card" },
"payer_email": "amina@example.com"
}'js
const res = await fetch(
"https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges",
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}`,
"Idempotency-Key": "order-8841-card",
"Content-Type": "application/json",
},
body: JSON.stringify({
amount: 150000,
reference: "order-8841",
description: "Order 8841",
payment_method: { type: "card" },
payer_email: "amina@example.com",
}),
},
);
const body = await res.json();
if (!body.ok) throw new Error(`${res.status} ${body.code}: ${body.description}`);
const charge = body.data;
const forThePage = {
chargeId: charge.id,
clientSecret: charge.next_action.client_secret,
total: charge.next_action.total,
currency: charge.next_action.currency,
};python
import os
import requests
res = requests.post(
"https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges",
headers={
"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}",
"Idempotency-Key": "order-8841-card",
},
json={
"amount": 150000,
"reference": "order-8841",
"description": "Order 8841",
"payment_method": {"type": "card"},
"payer_email": "amina@example.com",
},
timeout=30,
)
body = res.json()
if not body["ok"]:
raise RuntimeError(f"{res.status_code} {body['code']}: {body['description']}")
charge = body["data"]
for_the_page = {
"chargeId": charge["id"],
"clientSecret": charge["next_action"]["client_secret"],
"total": charge["next_action"]["total"],
"currency": charge["next_action"]["currency"],
}php
<?php
$ch = curl_init("https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("MOOKHPAY_SECRET_KEY"),
"Idempotency-Key: order-8841-card",
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => json_encode([
"amount" => 150000,
"reference" => "order-8841",
"description" => "Order 8841",
"payment_method" => ["type" => "card"],
"payer_email" => "amina@example.com",
]),
]);
$body = json_decode(curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (!$body["ok"]) {
throw new RuntimeException("$status {$body['code']}: {$body['description']}");
}
$charge = $body["data"];
$forThePage = [
"chargeId" => $charge["id"],
"clientSecret" => $charge["next_action"]["client_secret"],
"total" => $charge["next_action"]["total"],
"currency" => $charge["next_action"]["currency"],
];201 Created:
json
{
"ok": true,
"description": "Charge created",
"data": {
"id": "ch_ke_5b0e2d9a7c41f3e86d2a90b1",
"status": "pending",
"test": false,
"amount": 150000,
"currency": "KES",
"fee": 0,
"net": 150000,
"reference": "order-8841",
"description": "Order 8841",
"payment_method": { "type": "card" },
"next_action": {
"type": "use_card_element",
"client_secret": "ch_ke_5b0e2d9a7c41f3e86d2a90b1_secret_Xq3v9Tn0bS2kLw7yPz1aRc4dEf5gHi6jKl8mNo0pQrs",
"expires_at": "2026-11-20T10:30:00.000Z",
"amount": 150000,
"fee": 2500,
"total": 152500,
"currency": "KES"
},
"failure": null,
"receipt_number": null,
"hosted_url": "https://mookhpay.co/checkout/cs_ke_9d41a0c7e2b85f3a6c10e4d2",
"metadata": {},
"expires_at": "2026-11-20T10:30:00.000Z",
"created_at": "2026-11-20T10:00:00.000Z"
}
}next_action field | Meaning |
|---|---|
client_secret | The one credential your page holds: <charge id>_secret_ and 43 characters |
expires_at | When the card attempt ends, 30 minutes after creation by default. The charge's own expires_at is the same time |
amount | What you receive, in minor units |
fee | The card fee, added for the payer |
total | What the payer's card is charged, amount + fee. Show this figure on your Pay button |
currency | The charge's currency |
The client_secret is in this answer and in an idempotent replay of it, and nowhere else. GET /charges/{id} returns next_action without it. A replay of a pending card charge (the same Idempotency-Key and body) returns a new client_secret, and the earlier one stops working at once: MOOKHPay stores only a hash, so it cannot show the first one again.
Hand chargeId, clientSecret, total and currency to this payer's checkout page and to nothing else. Create a new charge for each checkout.
Load the script
Load mookhpay.js from mookhpay.co. Do not serve a copy from your own server: MOOKHPay supports only the versions it publishes there.
Pin a version (recommended):
html
<script
src="https://mookhpay.co/js/v1/1.0.0/mookhpay.js"
integrity="sha384-lXNEMbizKZy3oUHYBsnoCIHU7nuqqgM/pJqPIY+2qeZm+dMAHI6aQJ3dedUIozUk"
crossorigin="anonymous"
></script>The file at a versioned address never changes, so its integrity hash stays valid for as long as the version is served. To move to a new version, change the version in src and the hash together, to the pair published for that version. Keep crossorigin="anonymous": a browser checks the hash of a script from another origin only when it was fetched with CORS.
Or take every 1.x release as it ships:
html
<script src="https://mookhpay.co/js/v1/mookhpay.js"></script>This address always serves the latest 1.x release. Its bytes change with every release, so it cannot carry an integrity hash: a hash pinned to one release makes the browser refuse the next one, and card payments on that page stop. Browsers may keep it for five minutes, so a release reaches your page within five minutes of going out. Use it only if you accept new versions without checking them.
The script defines one global, MookhPay, with MookhPay.card, MookhPay.MookhPayError and MookhPay.version. Do not load it in a sandboxed iframe: a sandboxed frame sends the origin null, which is refused.
Content Security Policy
The element loads CyberSource's Microform v2 script itself, with an integrity hash. If your page sends a Content Security Policy, allow:
| Directive | Origins |
|---|---|
script-src | https://mookhpay.co https://flex.cybersource.com https://testflex.cybersource.com https://h.online-metrix.net |
frame-src | https://flex.cybersource.com https://testflex.cybersource.com https://*.cardinalcommerce.com https://h.online-metrix.net, and your payers' bank pages (https:), which cannot be listed in advance |
connect-src | The payments host the element calls, for example https://payments-ke-staging.mookhpay.co |
form-action | https://*.cardinalcommerce.com https: |
Mount the element and take the payment
html
<form id="pay-form">
<label>Name on card <input id="card-name" autocomplete="cc-name" required /></label>
<div id="card"></div>
<p id="card-message" role="alert"></p>
<button id="pay" type="submit" disabled>Pay</button>
</form>
<script
src="https://mookhpay.co/js/v1/1.0.0/mookhpay.js"
integrity="sha384-lXNEMbizKZy3oUHYBsnoCIHU7nuqqgM/pJqPIY+2qeZm+dMAHI6aQJ3dedUIozUk"
crossorigin="anonymous"
></script>
<script>
const form = document.getElementById("pay-form");
const button = document.getElementById("pay");
const message = document.getElementById("card-message");
fetch("/checkout/8841/card", { method: "POST" })
.then((r) => r.json())
.then(({ chargeId, clientSecret, total, currency }) => {
button.textContent = `Pay ${currency} ${(total / 100).toFixed(2)}`;
const card = MookhPay.card({
chargeId,
clientSecret,
style: {
input: { "font-size": "16px", color: "#111827" },
invalid: { color: "#A8306F" },
},
});
card.on("change", (state) => {
button.disabled = !state.complete;
message.textContent = state.expiry.problem || "";
});
card.on("error", (error) => {
message.textContent = error.message;
button.disabled = true;
});
card.mount("#card");
form.addEventListener("submit", async (event) => {
event.preventDefault();
button.disabled = true;
message.textContent = "";
try {
const result = await card.pay({
cardholderName: document.getElementById("card-name").value,
});
if (result.status === "succeeded" || result.status === "requires_action") {
window.location.assign("/orders/8841/status");
return;
}
message.textContent = result.failure.message;
button.disabled = false;
} catch (error) {
message.textContent = error.message;
button.disabled = error.code === "spent" || error.code === "charge_not_payable";
}
});
});
</script>/checkout/8841/card is your own server route that creates the charge and returns the four values from the previous step. /orders/8841/status is your own page that reads the order from your server, which learns the outcome from the webhook or from GET /charges/{id}.
The browser API
MookhPay.card(options)
Returns a card element. Throws a MookhPayError with code invalid_options when chargeId is not a charge id, when clientSecret does not begin with that charge's id, or when apiBase is not an accepted origin.
| Option | Required | |
|---|---|---|
chargeId | Yes | The charge's id, ch_ke_… or ch_ug_… |
clientSecret | Yes | next_action.client_secret from the create answer |
apiBase | No | The payments host the element calls. Without it the element picks from the charge id: ch_ke_ uses https://payments-ke-staging.mookhpay.co and ch_ug_ uses https://payments-ug-staging.mookhpay.co. Only a bare https origin is accepted, or http on loopback. The defaults are the staging hosts: on production, pass the production payments host MOOKHPay gives you |
style | No | Styles for the text inside the card number and security code iframes: input, ::placeholder, :focus, :disabled, valid, invalid, each an object of CSS properties. Only color, cursor, font, font-family, font-size, font-stretch, font-style, font-variant, font-weight, line-height, opacity, text-shadow, transition, -moz-osx-font-smoothing and -webkit-font-smoothing are kept. input and invalid.color also style the expiry input. Web fonts do not load inside the iframes; use a system font stack |
placeholders | No | { number, expiry, cvv } |
challengeContainer | No | An element or CSS selector to draw the bank's 3-D Secure page in. Without it the element draws it in an overlay over your page |
Keep font-size at 16px or more: below that, iOS Safari zooms the page when a field takes focus and cannot zoom back out of an iframe.
card.mount(...)
Each argument is an element or a CSS selector that is already in the page.
| Call | Layout |
|---|---|
mount(container) | Card number on one row, expiry and security code side by side under it |
mount(number, cvv) | Card number in the first container, expiry and security code side by side in the second |
mount(number, cvv, expiry) | Each in its own container |
Mounting asks MOOKHPay for the card form (POST /charges/{id}/card) and loads CyberSource's fields; ready or error follows. A second mount throws already_mounted, and a selector that finds nothing throws invalid_container.
card.pay({ cardholderName })
Tokenizes the card in CyberSource's fields, runs 3-D Secure when MOOKHPay asks for it, and charges. Pass the name on the card: without it the payment carries no cardholder name.
pay() resolves with one of:
| Result | Meaning | What to do |
|---|---|---|
{ status: "succeeded" } | The card was approved | Show that the payment went through. Fulfil only from the webhook or your server's read of the charge |
{ status: "failed", failure: { code, message } } | This card was not charged | Show failure.message. The payer can correct the card or use another and press Pay again. The element clears the security code and focuses the card number |
{ status: "requires_action" } | The outcome is with MOOKHPay: the payment is being verified or reviewed, or the answer was lost on the way | Do not call pay() again. Send the payer to a status page that reads the charge from your server |
failure.code is one of payer_cancelled (they left their bank's check, or let it time out), insufficient_funds, limit_exceeded, rail_unavailable (the bank or network could not be reached; nothing was taken) or declined. failure.message is safe to show the payer. A risk decline reads as a plain decline.
pay() rejects with a MookhPayError when no charge was attempted:
error.code | Meaning |
|---|---|
incomplete | A field is empty or invalid. error.fields lists them: number, expiry, cvv |
try_again | The card fields failed to produce a token, or MOOKHPay answered 429. From pay(), nothing was sent and the payer can try again. The same code can also arrive through the error event, when a 429 stops the form from starting or reloading; that one is final |
form_expired | The card form outlived its 15 minutes and has been reloaded. The payer types the card again |
network | MOOKHPay could not be reached before charging. Nothing was charged |
busy | A pay() is already running |
not_mounted, not_ready | Mount the element and wait for ready |
spent | This element already has an outcome. Read the charge |
charge_not_payable | The charge has ended, expired or been cancelled, or the secret is wrong |
origin_not_allowed | This page's origin is not on your allowed list |
session_failed, script_failed, fields_failed | The card form could not be started |
destroyed | The element was destroyed |
card.on(event, handler) and card.off(event, handler)
| Event | Payload |
|---|---|
ready | None. The fields can be typed in. Fires again after the form reloads itself |
change | { complete, empty, brand, number: { empty, valid, couldBeValid }, expiry: { empty, valid, problem }, cvv: { empty, valid } }. brand is CyberSource's scheme name (visa, mastercard, amex, discover) or null. expiry.problem is a sentence for the payer once the expiry has been left invalid |
error | A MookhPayError when the card form cannot be started or reloaded: session_failed, script_failed, fields_failed, try_again, network, form_expired, origin_not_allowed or charge_not_payable. The element cannot recover: destroy it, and if the charge is still pending, create a new element with the same chargeId and clientSecret |
challenge | { open: true } when the bank's page is shown, { open: false } when it closes |
No event ever carries a card number, a security code, an expiry or a token.
card.focus(field), card.clear(), card.destroy()
focus takes "number" (the default), "expiry" or "cvv". clear empties all three fields. destroy disposes CyberSource's fields, closes the bank's page if it is open, removes every listener and node the element added, and makes the element unusable.
Destroying the element does not cancel the charge. Your server cancels it with POST /charges/{id}/cancel.
The card form refreshes itself
A CyberSource capture context lasts 15 minutes. The element asks for a new one (POST /charges/{id}/card/refresh) a minute before it ends, while the payer has not pressed Pay. If the context runs out during a payment anyway, pay() reloads the form and rejects with form_expired, and the payer types the card again.
The charge's own lifetime (next_action.expires_at, 30 minutes by default) is a separate limit. After it, every call is refused and the element reports charge_not_payable.
3-D Secure
When MOOKHPay runs 3-D Secure for the payment (the attempt answers payer_auth: true), pay() does this before it resolves:
- Sends the card's transient token to MOOKHPay for the 3-D Secure setup (
POST /charges/{id}/card/payer-auth). Nothing is charged. - Lets Cardinal, the 3-D Secure service, profile the browser in a hidden iframe, for at most ten seconds.
- Charges (
POST /charges/{id}/card/charge). Most banks decide there and then. - If the bank wants to see the payer, shows its page in an iframe, in an overlay or in your
challengeContainer, and emitschallengewithopen: true. Everything inside it belongs to the bank. - When the bank's page finishes, MOOKHPay's return page, loaded in that frame, tells the element, and the element charges once more with
challenge_completed: true. That second call is the one that authorises the payment. The element accepts the signal only from the bank's frame, only from the payments host's origin, and only for this payment.
If the payer presses Cancel, presses Escape on the overlay, or leaves the bank's page open for ten minutes, nothing is charged: pay() resolves failed with payer_cancelled, and they can try again. The element never sends the completing charge on a timeout.
The overlay reads these CSS custom properties: --mookhpay-challenge-backdrop, --mookhpay-challenge-background, --mookhpay-challenge-color, --mookhpay-challenge-muted, --mookhpay-challenge-radius, --mookhpay-challenge-padding, --mookhpay-challenge-max-width, --mookhpay-challenge-font, --mookhpay-challenge-z-index, --mookhpay-challenge-border, --mookhpay-challenge-button-radius and --mookhpay-challenge-frame-radius. Its parts have the classes mookhpay-challenge-overlay, mookhpay-challenge, mookhpay-challenge-title, mookhpay-challenge-text, mookhpay-challenge-frame and mookhpay-challenge-cancel.
Style the fields
The boxes around the fields are yours to style. The element draws:
| Class | What it is |
|---|---|
.mookhpay-card, .mookhpay-row | The layout |
.mookhpay-slot, with .mookhpay-slot--number or .mookhpay-slot--cvv | The box each CyberSource iframe sits in. CyberSource adds flex-microform-focused, flex-microform-invalid, flex-microform-valid and flex-microform-disabled as the payer types |
.mookhpay-expiry | The expiry input. It has aria-invalid="true" once its value is left invalid |
Each also carries data-mookhpay-field="number", "cvv" or "expiry". The default styles read --mookhpay-gap, --mookhpay-field-height, --mookhpay-field-padding, --mookhpay-field-border, --mookhpay-field-radius, --mookhpay-field-background, --mookhpay-field-font, --mookhpay-field-font-size, --mookhpay-field-color, --mookhpay-focus-color, --mookhpay-focus-ring, --mookhpay-invalid-color and --mookhpay-disabled-background. A slot must keep a height: the iframe inside has none of its own.
The expiry input has no name, so it is never sent with your form.
What the element calls
The element calls four routes on the payments host, with the client_secret in the JSON body and never in a URL. They take no API key. See Card element routes for each in full.
| Route | When |
|---|---|
POST /v1/payments/public/charges/{id}/card | On mount: opens the card attempt and gets a capture context bound to your page's origin |
POST /v1/payments/public/charges/{id}/card/payer-auth | During pay(), only when 3-D Secure runs |
POST /v1/payments/public/charges/{id}/card/charge | During pay(): charges the token. A second time with challenge_completed: true after a bank challenge |
POST /v1/payments/public/charges/{id}/card/refresh | Before the capture context's 15 minutes run out |
Each route checks, in this order:
- The charge and the secret. An unknown charge, a wrong or missing secret, and a secret past the charge's
expires_atall answer the same401and code3006, so nobody learns which charges exist. - The
Originheader. A missing header, the literalnull, or an origin not on the list for the charge's mode is403and code2776.Access-Control-Allow-Originis sent, for that one origin, only once it has passed. - The charge is still pending. A charge that has succeeded, failed, expired or been cancelled is
409and code3007.
Of two charge calls at once, only one charges: the attempt is claimed before CyberSource is asked, and the other answers 409 and code 2777. The Idempotency-Key the element sends is not what stops a second charge.
A decline leaves the charge pending
A declined card does not end the charge. It stays pending, the payer can try another card in the same element, and the charge ends only when a card succeeds, you cancel it, or it expires. When it expires, its failure is the last attempt's code (null if no card was ever tried), MOOKHPay sends charge.expired, and, if the element opened a card attempt and nothing is still in flight, payment.failed with that failure. A charge whose element never opened an attempt sends only charge.expired.
A card approved at the bank moves the charge to succeeded only when MOOKHPay has booked the payment, the moment it sends payment.succeeded. That can be a moment after pay() resolved succeeded.
Confirm on your server
Fulfil the order from the webhook or a read of the charge, never from what the page says.
- Webhook.
payment.succeededcarriescharge,reference,metadataandamount(what you receive, without the card fee).payment.failedcarriesfailure. See Event catalogue. - Read. Call
GET /charges/{id}and check thatstatusissucceeded. For a status page that waits on the outcome, poll your own server, and have it read MOOKHPay no more than every two seconds, stopping atexpires_at.
sh
curl https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges/ch_ke_5b0e2d9a7c41f3e86d2a90b1 \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY"js
const chargeId = "ch_ke_5b0e2d9a7c41f3e86d2a90b1";
const res = await fetch(
`https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges/${chargeId}`,
{ headers: { Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}` } },
);
const { data: charge } = await res.json();
if (charge.status === "succeeded") {
console.log(`Order ${charge.reference} is paid`);
}python
import os
import requests
charge_id = "ch_ke_5b0e2d9a7c41f3e86d2a90b1"
res = requests.get(
f"https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges/{charge_id}",
headers={"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}"},
timeout=30,
)
charge = res.json()["data"]
if charge["status"] == "succeeded":
print(f"Order {charge['reference']} is paid")php
<?php
$chargeId = "ch_ke_5b0e2d9a7c41f3e86d2a90b1";
$ch = curl_init("https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges/" . rawurlencode($chargeId));
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("MOOKHPAY_SECRET_KEY")],
]);
$charge = json_decode(curl_exec($ch), true)["data"];
curl_close($ch);
if ($charge["status"] === "succeeded") {
echo "Order {$charge['reference']} is paid\n";
}A charge that expired or was cancelled can still move to succeeded if a payment already under way is approved. Trust the webhook.
Security
- Never send card data to your server. Do not copy anything out of the fields, do not add your own card number or security code inputs, and do not log the element's state. The element never gives your page a card number or security code.
- Treat the
client_secretas a credential for one charge. It can pay that charge and nothing else. Never put it in a URL, a log, browser storage, analytics or an error report. Hand it to this payer's page only. MOOKHPay stores only its hash, and a replay of the create call replaces it. - Never use your secret key in the browser. The
client_secretis the only credential the page holds. - Never call
pay()again afterrequires_action, or after your own timeout. A payment whose answer did not arrive may still go through, and a second attempt can charge the payer twice. The element refuses a secondpay()once it has an outcome, but a page that creates a new element for the same charge gets around that. - Never fulfil an order on the page's word. Use the webhook or
GET /charges/{id}. - Keep the allowed origin list short. Each entry is a page that can take card payments for your charges.
See Security.
Errors
Creating the charge
| HTTP | Code | When | What to do |
|---|---|---|---|
400 | 3004 | Cards are off on this deployment, the key is mkp_test_, or cards do not take this currency | Use a live key on a deployment with cards on, or offer mobile money |
400 | 1701 | A field breaks a rule, such as a malformed payer_email or an unknown field | Fix the body |
401 | 2781 | Missing, malformed, unknown or revoked key | Check the key |
403 | 2941 | The key has no charges:write | Issue a key with it |
409 | 3002 | A charge for this reference is still pending. data.charge names it | Use that charge, or cancel it first |
422 | 3015 | The Idempotency-Key was used with a different body | Use a new key for a new request |
429 | 3005 | Too many charges from this key in an hour | Wait Retry-After seconds |
The full list, including platform refusals, is on Create a charge.
In the element
| What you see | Cause | What to do |
|---|---|---|
error event, or pay() rejects, with origin_not_allowed | 403 2776: this page's origin is not on the list | Save the origin, exactly as the browser sends it |
error event, or pay() rejects, with charge_not_payable | 401 3006 or 409 3007: a wrong or expired secret, or the charge has ended | Read the charge on your server. Create a new charge if the order is still unpaid |
error event with session_failed | The card form could not be started, for example 502 2774 or 422 2771 | Destroy the element and offer to try again |
pay() resolves failed | 402 2723 (declined) or 502 2779 (CyberSource refused; nothing taken) | Show failure.message. The payer can try again |
pay() resolves requires_action | 202 with payment pending or review, 409 2777 or 2773, any other 5xx, or no answer | Do not retry. Wait for the webhook |