Connect your product as a project.
In Efespay every SaaS product is a project: it has its own key, webhook endpoint, checkout branding, customers and subscriptions, while payments still come together under one business. This guide describes the contract between a project and Efespay.
The API and test environment are in pre-pilot preparation. Live mode opens once the business application is approved.
Project model
A project is not a separate account: connections, rates, routing, risk rules and the team belong to the business. The project carries its own identity and records on top of them.
Business (e.g. Aksungur Yazılım)
├─ provider connections (pc_…: iyzico, Stripe, PayTR, bank virtual POS, test)
└─ projects (prj_…: CasaX, Mühür Mail, PergePOS …)
├─ branding (name, logo, colour, support, website and policy links)
├─ allowed connections (empty = all of the business's connections)
├─ API keys (efp_test_… / efp_live_…, bound to the project)
├─ webhook endpoints
└─ customers, saved cards, payments, refunds, subscriptions, events- The money flow does not change: funds settle to the account of the connection the project uses; Efespay never holds money.
- A project is independent of mode: the same
prj_…id is used in test and live, and records are kept apart by mode. - A project-bound key sees only that project's records, and every record it writes belongs to that project. A business-wide (project-less) key sees every project and may pass
project: "prj_…"when opening a session. - A customer's
external_referenceis unique within a project: the same value in two projects is two different customers. Order references andIdempotency-Keyvalues are also unique per project. - If the project has selected connections (
connections), routing only uses those; the others are excluded in the routing decision with the reasonproject. - Checkout branding comes from the project; any field left empty falls back to the business's checkout settings. Allowed return addresses are the union of the project's and the business's allowed addresses.
- Every
/v1object carriesproject_id: "prj_…" | null, and so does the event envelope. - Revenue that does not go through Efespay (in-app store purchases, bank transfer, cash, manual assignment) is reported to the project as a record only (Payments taken outside Efespay); it does not mix with the money flow or provider figures.
What the project does
Taking payments for a product through Efespay takes five steps. The sections below cover each one.
The webhook handler and the return page call the same completion function. It finds the order by order_reference, checks the amount and currency, and does nothing if the order is already complete.
Payment session
A session is opened with POST /v1/payment-sessions (scope payment_sessions:write). The general fields are in the developer documentation; the fields added for projects are here.
curl https://api.efespay.com/v1/payment-sessions \
-H "Authorization: Bearer $EFESPAY_API_KEY" \
-H "Idempotency-Key: order-65f0c1-1" \
-H "Content-Type: application/json" \
-d '{
"order_reference": "order-65f0c1",
"currency": "TRY",
"description": "Mühür Mail credits",
"line_items": [
{ "name": "1,000 credits", "quantity": 2, "unit_amount_minor": 45000 },
{ "name": "Priority support", "description": "One month", "quantity": 1, "unit_amount_minor": 20000 }
],
"customer": { "external_reference": "merchant_65f0c1", "name": "Örnek A.Ş.", "email": "muhasebe@ornek.com" },
"success_url": "https://muhurmail.com/app/billing/return?session_id={SESSION_ID}",
"cancel_url": "https://muhurmail.com/app/billing"
}'
# amount_minor is omitted: it is the sum of line_items (110000 = ₺1,100.00).Basket line (line_items)
- If
amount_minoris omitted it is the sum of the lines; if given, it must equal that sum (400line_items_amount_mismatch). - It cannot be combined with marketplace
items(400line_items_with_items); an invalid line returns 400invalid_line_itemswithparampointing at the line. - If
localeis omitted, the project's default language is used.
{
"id": "ps_…",
"object": "payment_session",
"kind": "payment",
"status": "open",
"url": "https://efespay.com/pay/ps_…",
"payment_id": "pay_…",
"project_id": "prj_…",
"amount_minor": 110000,
"line_items": [
{
"name": "1,000 credits",
"description": null,
"quantity": 2,
"unit_amount_minor": 45000,
"amount_minor": 90000
},
{
"name": "Priority support",
"description": "One month",
"quantity": 1,
"unit_amount_minor": 20000,
"amount_minor": 20000
}
],
"success_url": "https://muhurmail.com/app/billing/return?session_id=ps_…",
"cancel_url": "https://muhurmail.com/app/billing",
"subscription_id": null,
"subscription": null,
"expires_at": "2026-11-22T11:00:00.000Z"
}- Fields the response adds for projects:
kind,project_id,line_items,success_url,cancel_url,subscription_id,subscription. - Opening a session also opens its payment:
payment_id(pay_…) is set in the first response; payment endpoints and events match on it. success_urlandcancel_urlare the effective addresses with placeholders filled in.subscription_idis set on a subscription session once the payment succeeds; on a card update session it is set from the start.subscriptioncarries the terms of a subscription start session ({ interval, interval_count, amount_minor, plan_reference, quantity }); on other sessions it isnull.
- Lifetime: an unpaid session stays open for 60 minutes by default (
expires_at);expires_in_minuteschanges this to anything from 5 to 10080 minutes. Subscription sessions that Efespay opens stay open for 60 minutes (card update) or 7 days (the billing job's period payment). - Once
expires_athas passed, the page does not start a payment. The reconciliation job (every 5 minutes) marks the session and its paymentexpired, the order lock is released, andpayment.expiredis published for the session's pending payment even if the customer never started paying. If the customer is on the provider's page at that moment, that attempt settles first. metadatais copied to the payment (the payment object andpayment.*events); it is not copied to the subscription.- Amounts are gross: the total charged to the customer, tax included. Efespay has no tax field; the VAT breakdown and the invoice are your product's job (
line_itemsare display only).
Closing an open session
POST /v1/payment-sessions/{id}/cancel (body { reason? }, scope payments:cancel; the same as POST /v1/payments/{id}/cancel, Idempotency-Key recommended) returns the payment_session with status: "cancelled". A session whose payment has not started, or whose last attempt was declined, is closed, the order lock is released (a new session can be opened with the same order_reference) and payment.cancelled is published. A session that cannot be closed returns 409:
POST /v1/payment-sessions/ps_…/cancel
Idempotency-Key: cancel-order-65f0c1
{ "reason": "Customer started a new checkout" }
→ { "id": "ps_…", "object": "payment_session", "status": "cancelled", … }- Recommended pattern: before opening a new session for the same purchase, close the previous one; otherwise both sessions could be paid in two tabs.
- If closing returns 200 or
payment_not_cancellable, open the new session. If it returnspayment_already_succeeded, do not open a new session; complete the previous one. If it returnspayment_in_progressorpayment_uncertain, tell the customer "your payment is being processed". - If a late success arrives from the provider for a closed session, the payment still becomes
succeeded(late_success: true) andpayment.succeededis published: the business refunds it.
How the checkout page behaves
- The page carries the project's name, logo and colour, and lists the basket lines when there are any.
- After a successful payment it shows a receipt summary and a "Back to ‹Project›" button; if
success_urlis set, it goes there automatically after 5 seconds. - The "Cancel" link on the payment form leads to
cancel_url. The session stays open; close it withPOST /v1/payment-sessions/{id}/cancelif you want to. - An expired or cancelled session also offers the way back to
cancel_url. - When a card is declined (
payment.failed) the session stays open; the customer retries in the same session (same payment, new attempt).
The browser returning to success_url is not proof of payment. Learn the status from GET /v1/payment-sessions/{id} or the webhook.
Order reference formats
For the sessions and charges your product opens, order_reference is the value you give. Payments that Efespay opens use the formats below (<id> is the subscription id after sub_):
To route an event, rely on subscription_id rather than the format: it is set on every payment linked to a subscription.
Checkout in a new tab
The Efespay checkout page is never placed in an iframe. Your product opens it in a new tab and follows the result from its own server.
- On click, open an empty tab before the request:
window.open("", "_blank"). That way the popup blocker lets it through. - Your server saves the record as
pending, opens the session and returnsurl; set the tab's location tourl. If anything fails, close the tab. - The main tab switches to a "Payment opened in a new tab" state and polls your own server every 2–3 seconds (or waits for a socket event).
success_urlis a small return page in your product: it has your server verify the session, tells the main tab viaBroadcastChannel("efespay-checkout"), says "You can close this tab" and trieswindow.close().
// Main tab: the "Pay" button handler
async function startCheckout(planId) {
// 1. Open the tab before the request, inside the click, so the popup blocker allows it
const tab = window.open("", "_blank");
try {
// 2. Your server saves the order as pending and opens the Efespay session
const res = await fetch("/api/billing/checkout", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ planId }),
});
if (!res.ok) throw new Error("checkout_failed");
const { url } = await res.json();
tab.location.href = url;
} catch (error) {
tab?.close();
throw error;
}
// 3. Show "Payment opened in a new tab" and poll your own server every 2–3 seconds
showWaitingState();
}
// 4. The return page tells this tab that the payment is confirmed
new BroadcastChannel("efespay-checkout").onmessage = (event) => {
if (event.data?.type === "completed") refreshBilling();
};// success_url page: /app/billing/return?session_id={SESSION_ID}
const sessionId = new URLSearchParams(location.search).get("session_id");
// Your server calls GET /v1/payment-sessions/{id} and runs the same idempotent
// completion function as the webhook handler.
const res = await fetch(`/api/billing/confirm?session_id=${encodeURIComponent(sessionId)}`);
const { paid } = await res.json(); // your own response shape
if (paid) {
new BroadcastChannel("efespay-checkout").postMessage({ type: "completed", sessionId });
}
// The page also says "You can close this tab"; browsers may refuse window.close()
window.close();Mobile apps have no purchase screen (store rules); the app shows the subscription read-only.
Subscriptions
Efespay charges the saved card each period itself; on a connection that cannot save cards with a guarantee (iyzico), it opens the subscription through the provider's own subscription API and mirrors the provider's charges (engine: "provider", Engine differences). The plan catalogue, trials and entitlements stay in the project; Efespay is only told "charge this customer this amount at this interval".
Starting a subscription
POST /v1/payment-sessions
{
"kind": "subscription",
"order_reference": "sub-65f0c1…-1",
"amount_minor": 108000,
"currency": "TRY",
"description": "Mühür Mail Standart — aylık",
"line_items": [{ "name": "Standart paket", "quantity": 10, "unit_amount_minor": 10800 }],
"customer": { "external_reference": "merchant_65f0c1…", "name": "Örnek A.Ş.", "email": "muhasebe@ornek.com" },
"subscription": { "interval": "month", "interval_count": 1, "plan_reference": "standart-monthly", "quantity": 10 },
"success_url": "https://muhurmail.com/app/billing/return?session_id={SESSION_ID}",
"cancel_url": "https://muhurmail.com/app/billing"
}- There are no instalments:
installment_optionsmay only be[1](400installments_not_allowed). capture: "manual"and marketplaceitemsare not available (400invalid_subscription,param: "capture"or"items"). An error in thesubscriptionfield also returns 400invalid_subscription, withparamnaming the field (subscription.interval…).- At least one of the project's connections must be able to carry the subscription: a connection that saves the card with a guarantee (the Efespay test provider, Stripe; Efespay charges) or an iyzico connection with provider-managed subscriptions enabled (iyzico charges, Efespay mirrors; currency TRY, USD or EUR, first period amount equal to
subscription.amount_minor; Engine differences). If there is neither, 409payment_method_unavailable. - The payment only goes through these connections; if both kinds are available, the connection Efespay charges through is preferred.
- The checkout page shows the amount, the interval and that the customer can cancel at any time. The customer cannot pay without ticking the versioned consent (card saving and the subscription authorisation sentence; the two versions are recorded separately).
- Efespay has no trial period: a trial without a card is your product's own record; when it ends, you open the subscription session.
- On a successful payment the subscription (
sub_…) is created in the same transaction. This payment is its first period (subscription_id,subscription_period: 1,period_start/period_end);current_period_startis now andcurrent_period_endis the next period date. - The session's
metadatais copied to the first payment, andsubscription.metadatato the subscription (and to later period payments). - Events arrive in this order:
payment.succeeded,payment_method.created,subscription.created.subscription.createdis published after the card is saved and carriespayment_method_id. - If a late success arrives for an expired or cancelled session, no subscription is created:
payment.succeededarrives with an emptysubscription_id, and the business refunds it.
Subscription object
Changes and cancellation
POST /v1/subscriptions/sub_…
Idempotency-Key: upgrade-65f0c1-15
{ "amount_minor": 162000, "quantity": 15, "plan_reference": "standart-monthly", "proration": "charge_now" }
POST /v1/subscriptions/sub_…/cancel
{ "at_period_end": true, "reason": "Moved to the free plan" }- The calculation is in minor units, as integers. Same interval:
difference = max(0, round((new − old) × remaining_time / period_length)). Rounding is half up, times are in milliseconds, and "period" is the last paid period. - Below 100 minor units nothing is charged and the change is still applied. Downgrades (new ≤ old) are not refunded; the new amount applies from the next period.
- Interval change:
credit = floor(old × remaining_time / period_length),charge = max(0, new − credit); the new period starts now. Charges below 100 minor units are skipped here too;retry_dayslonger than the new period are dropped. - The charge is a payment:
subscription_idset,subscription_period: null,metadata.kind: "proration", order referenceSUB-<id>-ADJ-<n>. It is only made on anactivesubscription with no unpaid period; otherwise 409subscription_state_invalid. - The response is the subscription object with
proration: { amount_minor, payment_id, status }(status:none,succeededoruncertain). If nothing was charged,amount_minor: 0andpayment_id: null. - If the card declines, nothing changes: 402
proration_payment_failed. The body is{ error: { code, message, request_id, failure: { code, message, provider_code }, payment } };paymentis the failed proration payment. - If the result is unknown, the change waits as
pending_change. Meanwhile a new change returns 409subscription_change_pending, and the period charge waits too. If reconciliation finds the charge successful the change is applied, otherwise it is dropped;subscription.updatedis published either way. - If another write (the billing job or another request) wins at the same moment, the result is 409
subscription_state_invalidand nothing changes. - A provider-managed subscription (
engine: "provider") has nocharge_now, no interval change, nopayment_methodchange, no undoing a cancellation and nopauseorresume: Engine differences.
When the difference cannot be charged right away
- When
charge_nowis not possible (the engine lacks it, or there is no card), the error body tells you the way forward:error.fallbackis"change_session"for the same interval and"replace"for an interval change.subscription_proration_unsupportedalso carrieserror.capabilities. - The one recommended pattern: try
charge_now, then fall back to one of the two routes below according to the hint. Both routes work the same on both engines.
Change session
POST /v1/subscriptions/{id}/change-session (scope subscriptions:write, Idempotency-Key recommended) takes { amount_minor?, quantity?, plan_reference?, description?, metadata?, success_url?, cancel_url?, locale? }. An interval field returns 400 change_session_interval_unsupported (fallback: "replace"); an empty body returns 400 subscription_change_empty.
POST /v1/subscriptions/sub_…/change-session
Idempotency-Key: upgrade-65f0c1-15
{
"amount_minor": 162000,
"quantity": 15,
"plan_reference": "standart-monthly",
"success_url": "https://muhurmail.com/app/billing/return?session_id={SESSION_ID}",
"cancel_url": "https://muhurmail.com/app/billing"
}
→ 201 {
"subscription": { "id": "sub_…", "pending_change": { … } },
"session": { "id": "ps_…", "object": "payment_session", "kind": "payment", "url": "https://efespay.com/pay/ps_…" },
"proration": { "amount_minor": …, "payment_id": "pay_…", "status": "requires_payment" }
}- The difference is calculated the same way as
charge_nowfor the same interval. - If there is no difference (a downgrade, the same amount, less than 100 minor units, or no paid period), the change is applied immediately, like
proration: "none": 200{ subscription, session: null, proration: { amount_minor: 0, payment_id: null, status: "none", reason } }, wherereasonisdowngrade,no_amount_change,below_minimumorno_paid_period. - If there is a difference, the response is 201
{ subscription, session, proration: { amount_minor, payment_id, status: "requires_payment" } }.sessionis a hosted one-off payment session (kind: "payment",subscription_idset; 3-D Secure as usual). Any connection that takes normal payments for the project can be used, and no saved card is needed; the card is not saved and the subscription's card does not change. - The change becomes
pending_change(proration.status: "requires_payment",session_id); meanwhile a new change returns 409subscription_change_pending. - It can only be opened on an
activesubscription with no unpaid period; on the provider engine, cancellation must also not be scheduled for period end (otherwise 409subscription_state_invalid). The difference payment is an ordinary payment:subscription_id,subscription_period: null,metadata.kind: "proration",order_referenceSUB-<id>-ADJ-<n>. - Once the payment succeeds, on the
efespayengine the change is applied immediately and the new amount renews from the next period; on theproviderengine the new amount takes effect at the provider from the next period (a plan change) and is applied once confirmed. In both casespayment.succeededarrives first, thensubscription.updated. - If it cannot be confirmed at the provider, the payment stays successful,
pending_change.proration.statusbecomesapplying(retry: { attempts, last_error, next_attempt_at }) and Efespay retries with back-off: 5 min, 15 min, 1 h, 6 h, 12 h, 24 h, 24 h (about 3 days). - Final state: if the retries run out, the subscription ends in the meantime, or a late success arrives after the session was dropped, the pending change is removed,
change_failureis set on the object andsubscription.change_failedis published. Refund the difference (change_failure.payment_id) or send the change again withproration: "none". - If the session is closed without payment (
POST /v1/payment-sessions/{id}/cancel) or expires, the change is dropped (subscription.updated,pending_change: null); nothing changes.
Replacement subscription
- For an interval change (on both engines), a new subscription session is opened with
subscription.replaces: "sub_…". - When the first payment succeeds, the new subscription carries
replacesand the old one is cancelled immediately in the same flow (subscription.cancelled,cancel_reason: "replaced",replaced_by). Event order: the new subscription'ssubscription.createdfirst, then the old one'ssubscription.cancelled. - On the
providerengine the old subscription is cancelled at the provider first. If that cannot be confirmed, the new subscription is still valid; the old one stays live, is marked withreplaced_byandreplacement_cancel(subscription.updated), and Efespay retries until it is confirmed. If the provider charges the old period meanwhile, the usualpayment.succeededandsubscription.renewedarrive; refund it. - Efespay does not calculate refunds or credit; your product decides what the unused time is worth. On the
efespayengine you do this by lowering the first amount (amount_minor); on theproviderengine the first amount must equal the recurring amount (409subscription_first_amount_unsupported), so if there is credit, you refund it.
Cancellation
POST /v1/subscriptions/{id}/cancel takes { at_period_end?, reason? }. at_period_end: true schedules cancellation for the end of the period (subscription.updated) and the subscription becomes cancelled when it arrives. Without it, cancellation is immediate (subscription.cancelled; the unpaid period's session is closed). On immediate cancellation current_period_start and current_period_end do not change (the end of the paid period stays; there is no refund): whether access continues until then or ends right away is your product's decision. Use /pause and /resume to pause and continue.
Card update and overdue payments
POST /v1/subscriptions/{id}/payment-session (optional success_url, cancel_url, locale) returns a payment_session with a url. Efespay sets up the session according to the subscription's state:
- The session only goes through a connection that saves the card with a guarantee; otherwise 409
payment_method_unavailable. - While an early renewal session is open, the same request returns that same session.
- 409
payment_in_progress: the period's payment is in progress. - 409
subscription_state_invalid: the subscription is cancelled or ended; it was paused by the user and a card-only setup is not available; or its cancellation is scheduled for the end of the period. - On a provider-managed subscription the session is always a
kind: "setup"session that opens the provider's card update form: Engine differences.
Customer portal
POST /v1/portal-sessions(scopesubscriptions:write) opens a portal session valid for 60 minutes:{ id: "bps_…", object: "portal_session", url, expires_at }. The customer is given as acus_…id or acustomer_external_reference.return_urlis required and must be on an allowed address. Any flag left out offeatures(cancel,update_payment_method) counts as enabled.urlis returned only in this response: Efespay stores only a digest of the token.Idempotency-Keyis ignored; every request opens a new session.- With the project's branding, the page (
/portal/{token}) shows the customer's subscriptions, payment history and saved cards. The customer can update the card (the card update rules above), cancel the subscription at period end or undo the cancellation, and delete an unused card. - Changes publish the same
subscription.*events (andpayment_method.deleted). - On a provider-managed subscription there is no undoing a cancellation and the card list is empty: Engine differences.
POST /v1/portal-sessions
{
"customer": "cus_…",
"return_url": "https://muhurmail.com/app/billing",
"locale": "tr",
"features": { "cancel": true, "update_payment_method": true }
}
→ { "id": "bps_…", "object": "portal_session", "url": "https://efespay.com/portal/…", "expires_at": "…" }One-off and usage-based charges
- Charge a saved card with
POST /v1/payments:{ payment_method, order_reference, amount_minor, … },Idempotency-Keyrequired, scopepayments:charge. Automatic top-ups and end-of-period usage overages are charged this way. - The card is saved with the customer's consent through
save_payment_method: "optional"or"required"on a payment session. - The card object (and
payment_method.*events) carriescustomer_external_referencealongsidecustomer_id. - In the card list (
GET /v1/payment-methods), acustomer_external_referencethat Efespay has never seen returns 404customer_not_found, not an empty list (the customer record is created with the first session); you can treat it as "no saved cards".
Saved cards
- Saving during payment: pass
save_payment_method: "optional"or"required"andcustomer.external_referenceon the session; the customer consents on the checkout page, andpayment_method.createdarrives once the card is saved. On a subscription session the card is always saved. - Adding a card without a payment:
POST /v1/payment-sessions { kind: "setup", customer: { external_reference }, set_default?, success_url?, cancel_url? }returns aurl(the same checkout page, amount 0, no charge). It only works on a connection that can save a card without an amount (test provider, Stripe); otherwise 409payment_method_unavailable. On this error, hide the "add card" button in your product. The customer portal also has "add card". - Default card: one of the customer's active cards carries
is_default: true. The first saved card is the default; a later card only becomes the default withset_default: trueorPOST /v1/payment-methods/{id}/default. If the default is deleted or expires, the most recently used active card becomes the default (if there is none, there is no default). - Charging the default:
POST /v1/payments { customer_external_reference (or customer: cus_…), order_reference, amount_minor }; do not passpayment_method. Without a default, 409payment_method_default_missingis returned; ask the customer for a card. - Replacing and deleting cards: deleting a card in use returns 409
payment_method_in_use; the error lists the subscriptions using the card and the cards that could replace it (subscriptions,replacements,can_move). First move the subscriptions withPOST /v1/payment-methods/{id}/move-subscriptions { to }, then delete. - Expiry: a card is valid until the end of its expiry month (
expires_at). For a card expiring within 30 days that is used by a subscription, or is the default of a customer with a payment in the last 90 days,payment_method.expiringarrives once (the object carriesexpiring_reason: subscription | defaultand the affectedsubscriptions). - On this event, show the customer an email or in-app warning with a link to a card-adding session (or the portal). When the new card arrives, make it the default with
set_defaultand move the subscriptions withmove-subscriptions(or the customer picks "use this card for my subscriptions" in the portal). - When the month passes, the card becomes
expired(payment_method.expired); a subscription charged to that card pauses at the next period (paused,payment_method_unavailable). - iyzico difference: on an iyzico connection card saving is not reliable (the form depends on the customer's choice) and there is no saving a card without a payment (
kind: "setup"returns 409). Subscriptions on the iyzico engine have no card in Efespay (payment_method_id: null; the card is with iyzico): moving, defaults andpayment_method.expiringdo not apply to them; the card is updated through the card update session above. - If the same card is saved on two connections (e.g. the test provider and Stripe), it is two separate
pm_…records; a token only works on its own connection.
Engine differences
The subscription object's engine field says who charges the periods. Field names, event types and the shape of the object are the same for both engines; the table below lists the differences in behaviour.
efespay: Efespay charges the saved card (a connection that saves cards with a guarantee: the test provider, Stripe).provider: the payment provider's own subscription API charges; Efespay reads the provider and mirrors it onto the same object and events. Today this is iyzico, and it is the usual route for TRY subscriptions.- Efespay chooses the engine, not the project. If both are possible,
efespayis preferred unless a routing rule says otherwise.
What the project does differently
- Handle
subscription.*andpayment.*events with the same handler for both engines. - For a plan change, try
charge_now; then fall back to a change session or a replacement subscription according to the error'sfallbackhint. - Show buttons according to
capabilities(e.g. no "undo cancellation" whenundo_cancel: false). - In a project with a managed connection, do not open subscriptions whose first period is discounted or prorated.
Refunds
A refund is made on the payment. The response is always a refund object; an outcome that is not yet certain arrives as an event.
POST /v1/payments/{id}/refundstakes{ amount_minor?, reason?, metadata? }, scopepayments:refund.metadata(at most 20 keys, same rule as sessions) marks what the refund belongs to; it comes back unchanged on the refund object and inrefund.*events.- The response is always 201
refund, andstatusis one of three values:succeeded,failed(the provider declined,failureis set; this is not an HTTP error) oruncertain. uncertain: no response came from the provider; Efespay queries it and the outcome arrives as arefund.succeededorrefund.failedevent. Do not send the same refund again with a new key.pendingcan only be seen on the record while the request is being processed (GET /v1/payments/{id}/refunds); it is never returned in the response.- Apply the refund to your own record from the event (see Webhooks).
Webhooks
The webhook is the single source of truth. The project's endpoint verifies the signature, deduplicates the event and updates its record from the object's state.
POST https://muhurmail.com/api/webhooks/efespay
Content-Type: application/json
Efespay-Event-Id: evt_…
Efespay-Event-Type: subscription.renewed
Efespay-Signature: t=1795000000,v1=5f2c…{
"id": "evt_…",
"object": "event",
"type": "subscription.renewed",
"created_at": "2026-11-22T10:00:00.000Z",
"mode": "live",
"project_id": "prj_…",
"data": {
"object": {
"id": "sub_…",
"object": "subscription",
"status": "active",
"project_id": "prj_…",
"customer_id": "cus_…",
"customer_external_reference": "merchant_65f0c1",
"plan_reference": "standart-monthly",
"quantity": 10,
"current_period_start": "2026-11-22T10:00:00.000Z",
"current_period_end": "2026-12-22T10:00:00.000Z",
"cancel_at_period_end": false
}
}
}- Verify
Efespay-Signatureagainst the raw body; reject the request iftis older than 5 minutes. - Deduplicate with the signed body's
id(evt_…): the same event can arrive again. TheEfespay-Event-Idheader always equals thisid, but only the body is signed. - Update your record from the state of the object in the event; events can arrive out of order, and an older event never undoes a newer state. Processing is idempotent.
- Return 2xx within 10 seconds; on a processing error return 5xx so Efespay retries.
- A project-bound endpoint receives only that project's events; a project-less endpoint receives all of the business's events.
import crypto from "node:crypto";
export function verifyEfespaySignature(rawBody, header, secret) {
const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
const expected = crypto.createHmac("sha256", secret).update(`${parts.t}.${rawBody}`).digest("hex");
const fresh = Math.abs(Date.now() / 1000 - Number(parts.t)) < 300;
const a = Buffer.from(expected);
const b = Buffer.from(parts.v1 || "");
return fresh && a.length === b.length && crypto.timingSafeEqual(a, b);
}app.post("/api/webhooks/efespay", express.raw({ type: "application/json" }), async (req, res) => {
const raw = req.body.toString("utf8");
// 1. Verify the signature on the raw body (t older than 5 minutes is rejected)
if (!verifyEfespaySignature(raw, req.get("Efespay-Signature"), process.env.EFESPAY_WEBHOOK_SECRET)) {
return res.sendStatus(400);
}
// 2. Deduplicate by the id in the verified body: the same event can arrive more than once.
// The Efespay-Event-Id header always equals it, but only the body is signed.
const event = JSON.parse(raw);
if (await processedEvents.has(event.id)) return res.sendStatus(200); // already processed: 2xx, never 409
try {
// 3. Update your record from the object's state; events can arrive out of order,
// and an older event must not undo a newer state
await applyEfespayObject(event.type, event.data.object);
await processedEvents.add(event.id);
res.sendStatus(200); // 4. answer 2xx within 10 seconds
} catch {
res.sendStatus(500); // any non-2xx answer is retried
}
});Delivery and retries
- Any answer other than 2xx (including 409, other 4xx and 3xx), a timeout (10 seconds) and a connection error count as failures and are retried after 1 min, 5 min, 30 min, 2 h, 6 h, 12 h and 24 h (8 deliveries in total).
- After that the delivery is
failed; it can be resent from the dashboard. - If there is no successful delivery for 3 days, the endpoint is disabled.
- When you have already processed an event, answer 2xx, not 409: a 409 brings the event back for two days.
For a subscription started from the checkout page, the first period arrives with subscription.created and subscription.renewed starts from the second period. For a subscription created through the API (POST /v1/subscriptions), the first charge also produces subscription.renewed. One handler that syncs from the object is enough for all three events (created, renewed, updated). Find your own record from a subscription event by customer_external_reference (or metadata).
When writing to Efespay: Idempotency-Key
- The same
Idempotency-Keywith the same body returns the stored response. - With a different body it returns 409
idempotency_conflict: when retrying after a timeout, do not change the body (amount, metadata and addresses must stay the same). - If the first request is still running, it returns 409
idempotency_in_progress; retry a little later with the same key. - Keys are kept for 24 hours; 5xx responses are not stored.
Registering a tenant's webhook endpoint through the API
Products whose tenants connect their own Efespay account register the tenant's webhook endpoint through the API: POST /v1/webhook-endpoints { url, events?, description? } (scope webhook_endpoints:write). The secret in the response is returned only once; store it in the tenant's record. To manage endpoints, use GET, PATCH and DELETE /v1/webhook-endpoints/{id} and POST /v1/webhook-endpoints/{id}/rotate-secret.
Error codes
Codes added by this contract. The error format and the other codes are in the developer documentation.
Testing
With a test key (efp_test_…) you can try the whole flow without any real money moving.
- In test mode the Efespay test provider is available in every project; card scenarios are the same as the test cards in the developer documentation.
- When charging a saved card, the last two digits of the amount pick the outcome:
51,52,53,54(declined, insufficient funds, expired card and unknown result, in that order). - To see renewals without waiting, use a short interval (
interval: "day"). - Try your webhook endpoint with a test event (
ping) from the project's page in the dashboard.
Payments taken outside Efespay
Some revenue does not go through Efespay. Report it with POST /v1/external-payments so that all of the project's revenue shows up in Efespay reports.
- Covers: in-app store purchases (App Store, Google Play; existing buyers of products that receive store notifications), invoices the customer paid by bank transfer or EFT and you marked as "paid", cash or cheque, and manual plan assignments with a recorded amount.
- API scopes: writing
external_payments:write, readingexternal_payments:read.
What it is not
- It grants no access. The record does not open a subscription or give the user access; your own system (store verification, invoice status) does that. Efespay only keeps the record.
- It moves no money. Efespay never saw this money and cannot refund it.
POST /v1/external-payments/{id}/refundonly records that "the external system refunded it". - It does not replace a payment session. A payment taken through Efespay always goes through
POST /v1/payment-sessions. External records are not in payment lists,payment.*events or provider figures (volume, success rate); reports show them as separateexternalfigures.
Safe to repeat
- The same project,
channelandexternal_id(or, without one, the sameorder_reference) never opens a second record: the existing record comes back with 200, a new one with 201. You can forward a store notification blindly every time it arrives. - If the same identity arrives with a different amount or currency, 409
external_payment_mismatchis returned. amount_minoris in the currency's smallest unit (USD cents, JPY yen);currencyis an ISO 4217 code and is required (it is not limited to the currencies Efespay charges in).- App Store prices are in milli-units (unit × 1000); convert to the smallest unit using the currency's decimal places (USD 4990 → 499 cents, JPY 500000 → 500 yen). Verify the store notification with the store on your server before sending it.
- Events:
external_payment.recorded(only for a new record) andexternal_payment.refunded. An endpoint not subscribed to them does not receive them; a["*"]subscriber does, so answer 2xx to event types you do not recognise as well. The error codes for these endpoints are in the API reference.
# Store renewal, after your server has verified the store notification
POST /v1/external-payments
{
"channel": "app_store",
"external_id": "<transactionId>",
"order_reference": "<your subscription id>",
"amount_minor": 499,
"currency": "USD",
"paid_at": "2026-11-22T10:00:00.000Z",
"customer": { "external_reference": "<your user id>" },
"subscription_reference": "<your subscription id>",
"plan_reference": "<productId>"
}
→ 201 external_payment (new record) or 200 (already recorded)
# Store refund: record that the external system refunded it
POST /v1/external-payments/xp_…/refund
{ "refund_external_id": "refund:<transactionId>", "reason": "App Store refund" }
# Bank transfer marked as paid in your admin panel
POST /v1/external-payments
Idempotency-Key: invoice-paid:inv_1042
{
"channel": "bank_transfer",
"order_reference": "inv_1042",
"amount_minor": 108000,
"currency": "TRY",
"paid_at": "2026-11-22T09:30:00.000Z",
"description": "Invoice 1042, bank transfer",
"customer": { "external_reference": "merchant_65f0c1", "name": "Örnek A.Ş." }
}Let's bring your products onto one platform.
Tell us which product uses which flow, and we will set up the projects, connections and test plan together.