Scope and confidentiality
EXCOIN completed a payment gateway implementation and an extension for crypto payments. The client name, delivery dates, volumes, processors, supported networks and contractual terms cannot be disclosed. The following technical analysis presents public engineering principles and representative decisions; it is not a diagram of the confidential production stack. A reader should not infer a particular provider or measured result from an architectural pattern.
The work is broader than adding a checkout button. A payment path connects the order, authorisation, receipt of value, confirmation, refund, accounting evidence and support. Crypto adds a network, asset, address, transaction, chain confirmation and sometimes conversion into a settlement currency. Events can be late, repeated or arrive out of order. The system therefore needs an explicit state model and an auditable history rather than a single boolean called paid.
From business requirements to an API contract
Merchant, payer and operator each need a different view. Merchants create payment intents, offer methods, inspect status, refund and match receipts to orders. Payers need a clear amount, currency, validity period and final confirmation. Operators need exception queues, reconciliation and access controls. This produces an inventory of operations shaped by the customer's workflow, rather than a direct copy of one processor's endpoints.
The public API specifies monetary units, merchant identity, idempotency keys, correlation IDs, actionable errors and a status that can be read again. Request acceptance and final processing have separate responses. If a provider times out, the gateway cannot assert either success or failure. An unknown outcome triggers verification at the source, while the caller can safely retry a status query without creating a second payment.
The payment state machine
A payment intent, attempt, processor transaction, actual receipt and commercial order are different entities. One order may have several failed attempts, but the business rule determines which result is effective. Explicit transitions cover creation, awaiting payer action, processing, confirmation, failure, expiry, refund and partial refund. Each transition needs an owner and evidence, such as an authenticated provider event or a settlement record.
A late webhook cannot turn a confirmed payment back into an in-progress one. Duplicate events are recognised by provider identifier and event version. When a webhook and active query disagree, source-of-truth rules decide what to trust. Order fulfilment remains separate: a successful payment does not prove that stock allocation, invoicing or delivery have completed.
Card payments and data responsibility
For cards, the first architectural question is who captures and processes card numbers. A hosted payment page or provider component may reduce the application's exposure, but it does not remove every merchant obligation. PCI DSS scope depends on the actual architecture and contractual allocation of responsibilities. The gateway stores processor tokens or references, keeps sensitive authentication data out of its application and controls scripts on the payment page.
Authorisation, capture, void, dispute and refund are separate processes with different timing. The API and operator console should not erase those distinctions behind one generic paid label. Support staff need a bounded transaction history and useful decline reasons, but they do not need access to a full card number or internal secrets to answer a complaint.
Choosing the crypto payment model
A crypto extension can use a specialist intermediary or accept assets directly into wallets controlled by the operator. The first approach delegates some infrastructure and conversion; the second adds key custody, addresses, chain monitoring, treasury operations and potentially different regulatory duties. Each asset-and-network pair needs its own approval. Saying that a gateway supports crypto does not explain who holds funds or what the merchant ultimately receives.
The payer needs an unambiguous asset, network, amount, address or secure wallet connection, and an expiry time. A wrong chain, token or memo can result in loss or expensive manual recovery. A wallet's send action is not payment completion. The gateway distinguishes broadcast detection, required confirmations, provider acceptance and final settlement. Confirmation policy depends on the actual network and asset.
Quotes, expiry and amount mismatches
When an order is denominated in fiat but the payer sends a digital asset, a quote defines rate, fees, issuance time and validity. Price movement before chain confirmation cannot silently become an extra charge. The merchant must also decide whether it receives the asset, a stablecoin or fiat after conversion, because the answer changes treasury and accounting flows.
Underpayments, overpayments, late deposits and a second transfer to the same address are first-class cases. Each needs a state, evidence and support path. Automatic return is not always safe: the sending address may not be controlled by the payer, and a transfer on another network might be impossible. The design separates automatic closure of clear cases from manual approval of exceptions.
Webhooks and idempotency
Providers deliver asynchronous events and may retry them. The receiver verifies signature or equivalent authentication, timing and event ID before placing the event into durable processing. An HTTP acknowledgement only means receipt, not completed business processing. The worker must be repeatable and update state atomically after a crash. An unauthenticated notification must never settle an order.
Idempotency is required across both boundaries. Repeating the client request returns the same intent; retrying a provider call cannot capture funds twice. A key is scoped to merchant, operation, amount and a defined period, and cannot be recycled for another purchase. The design also accounts for a provider response arriving after the caller has timed out.
Ledger and reconciliation
An intent record is not a ledger. An internal ledger preserves immutable movements, currency, time, provider reference, fees, refunds, conversion and merchant relationship. Corrections create a new entry with reason and approval. Balances are reconciled against processor, bank or chain according to the chosen model. This exposes receipts without orders and orders marked paid without corresponding value.
Reconciliation runs routinely and after incidents. It distinguishes timing gaps from true mismatches, maintains an exception queue and names an owner. A chain transaction may be final while fiat settlement is still pending; these statuses must remain distinct. Merchant reporting needs gross amount, rate, fee, net amount and settlement state, with appropriate protection of personal information.
Refunds and disputes
Cards and crypto do not share a refund mechanism. A card processor can handle partial refunds; an on-chain return is a new transfer with a fee, address decision and wrong-network risk. The operator interface must lead staff through the correct method. Payers should know the expected return path before approval, not only when a refund fails.
Every refund links to the original payment, remaining refundable amount, reason, approver and execution proof. Double-clicking in the console must not create two payouts. After an uncertain send, the actual provider or chain state is inspected before retrying. Dispute handling also separates the contested amount from other merchant settlement and records communications.
Identity, risk and legal boundaries
Payer, merchant, support, finance and operations permissions are separate. Changing a settlement account, withdrawal address, asset or limit demands stronger controls than viewing status. Risk detection looks at unusual retries, order/payment mismatches and refund abuse. Decisions need an explanation for authorised support staff without revealing defence thresholds to an attacker.
Crypto services can fall under different legal regimes depending on custody, conversion and geography. MiCA is relevant in the EU, but naming it does not classify a particular product. The client's legal team and licensed providers must establish identity checks, monitoring and contractual responsibilities before a method goes live. This engineering study is not a legal opinion or a claim that EXCOIN holds a financial licence.
Security and secret management
API keys, webhook secrets and any wallet signing material stay outside source code. Access is service-scoped, environment-specific, rotatable and logged. Operator actions use multifactor authentication, separate roles and a second approval for sensitive changes. Replay protection, amount validation and rate limits also apply to internal calls; trust boundaries do not stop at the public API.
The crypto branch requires a separate custody threat model. If an external provider holds keys, the contract and integration determine responsibility and incident procedure. If the system controls keys, signing separation, withdrawal limits, address controls, recovery and compromise response are essential. Neither private keys nor complete access tokens belong in audit logs.
Testing and controlled release
Tests cover successful cards and crypto, refusal, timeout, duplicate webhook, wrong network, underpayment, overpayment, expiry, refund and disagreement between confirmation and settlement. Provider sandboxes are useful but may not reproduce chain finality, real settlement or incidents. Production release starts with limited amounts and a constrained merchant or segment, alongside manually reviewed reconciliation.
Before widening a method, operators review completion rate, age of pending states, exception count, settlement delay and manual interventions. Client metrics are not disclosed here. The stronger acceptance test is whether one payment can be explained from order through statement and a difficult exception can be resolved without losing money or audit evidence.
Checkout as a user journey
Checkout explains what is being bought, in which currency, from whom and when the order becomes final. Switching methods must not lose the order. A hosted payment link is tied to one intent and expiry; returning to the browser is not proof of payment. Interrupted customers resume only if the original intent remains valid.
Crypto checkout needs more than a QR code. The payer must identify asset, network, amount, network fee and quote expiry. The interface warns about a wrong network and shows a verifiable state instead of an animation that pretends finality. Accessibility, language and mobile use are acceptance criteria; copy controls reduce address typing errors.
Method routing and availability
Available methods depend on merchant, currency, country, product and provider agreement. Routing rules are versioned and testable; a missing method has an explanation. During an outage another method can be offered only while preserving the order and clearly obtaining payer agreement. The system must not silently redirect a payment to different terms.
Provider failover requires protection against double capture. Before switching, the first attempt's state is checked and unknown outcomes resolved. Operations can see why a route was selected and which provider owns the authoritative status. Global availability is bounded by actual product and provider permissions.
Amount precision and monetary units
Amounts use minor currency units or exact decimal types with explicit scale. Fiat, tokens with different decimals and network fees must not pass through ordinary floating point arithmetic. The contract defines rounding and who bears residual differences. Merchant statements reconstruct original price, discount, tax information, rate, fees and net settlement.
Zero or negative amounts, excessive decimal places, currency changes after a quote and refunds greater than received value are required boundary tests. Localised punctuation must not change the accounting number. An inconsistency pauses the payment for investigation rather than being silently corrected.
Chain monitoring and reorganisations
A chain watcher holds checkpoints by network and block, matches transfers to intents and verifies the token contract. Native transfers and token events are not equivalent. It catches up after RPC outages and can switch providers without losing or double-counting deposits. Reusing one address for many payments complicates matching and needs an unambiguous key.
A reorganisation can replace previously observed blocks. Seen is not confirmed. The project defines a confirmation policy and behaviour if a transaction disappears. A discrepancy after final acceptance is an incident, not an invisible rewrite. Indexer, processor and ledger share correlation IDs.
Addresses, keys and treasury
Receiving addresses follow the chosen custody model. Their link to an order cannot change without audit. If the system creates wallets, online deposit detection is separated from outgoing signing. Withdrawal limits, address allowlists and dual approval protect value. Keys never enter logs, errors or analytics.
Treasury rules decide when assets move, convert or remain held. Every batch connects receipts, fees and outcome. An internal wallet transfer is not a new customer payment and cannot duplicate ledger income. Balances are reconciled by network and asset; a similarly named token on two chains is not one accounting item.
Merchant payouts
Taking value from a payer and paying the merchant are separate operations. Payout follows settlement conditions after fees, refunds and reserves. The console distinguishes planned, sent, confirmed and failed transfers. Changing a bank account or destination wallet needs strong authentication, history and a delay that can expose fraud.
After a payout failure, the real bank, provider or chain state is checked before retry. Idempotency and available balance constrain repetition. Merchants receive the items forming a batch and the reason for a hold. A ledger states the obligation to the merchant independently of the sending worker.
Fraud versus technical failure
A risk signal is not a system error. Repeated cards, rapid address changes, many refunds or unusual deposits may need review. Automated decisions have inputs, rule versions and an authorised appeal path. Payers receive a neutral message without learning defensive thresholds. Technical failures cannot be disguised as suspicion.
In digital assets, the source of funds and service classification require the client's legal assessment. Technology can record evidence and workflow but should not invent legal duties or a verdict about a person. Open cases need an owner and deadline so funds are not held because an alert was forgotten.
Support and explainability
From one ID, support should find order, intent, attempts, provider events, on-chain hash, refund and payout. Views mask data and respect the employee role. Customers need a clear answer: awaiting chain confirmation, declined, accepted or under exception review. Unknown outcomes must not come with invented completion times.
Manual interventions carry a reason and evidence. Staff cannot set success because a customer sent a wallet screenshot. It may be attached to a case, but authoritative receipt is checked at the provider or chain. The audit trail must still explain a complaint months later.
Incident scenarios and degraded operation
Runbooks distinguish checkout, processor, webhook, RPC, conversion provider and ledger database outages. Each states whether new intents can be accepted, pending payments shown or refunds made. Without confirmation, orders cannot be released as paid. Recovery revisits pending intents and reconciles against sources.
A backup provider is not automatic zero downtime. Its statuses, limits and legal scope may differ. Switchover is rehearsed for a concrete method and currency, including in-flight payments. Incident reports capture impact, timeline, refund decisions and reconciliation; a green healthcheck alone does not close a financial incident.
Personal data and retention
Payment data can include identity, IP address, invoice details and sensitive support notes. Each field needs purpose, access role and retention based on actual contracts and law. Development logs and analytics should not copy full webhook payloads. Data transfers to providers require clarity on roles and regions.
Deletion requests must account for accounting and blockchain records that cannot simply be erased. The design minimises personal information on-chain and separates identity from public hashes. Retention jobs remove temporary exports and diagnostic payloads without destroying mandatory financial evidence. Qualified client counsel approves the policy.
Migrating an existing gateway
An extension starts by mapping old states, identifiers and open refunds. New crypto methods cannot change the meaning of card history. An adapter can serve both generations, but events show schema version. Merchants migrate in segments with a path back for unsettled payments.
Migration is not judged only by new transaction count. Ledger agreement with the old processor, historical receipts and support for old disputes matter. Checksums and samples become evidence. Missing legacy data must be disclosed by the new interface instead of invented.
Versioning, contracts and partners
A second provider can sit behind a stable API only while status meanings stay stable. New methods may need network, memo, expiry or confirmation fields; these cannot disappear into unvalidated JSON. Contract tests protect existing merchants from status changes and duplicate orders.
Each partner has its own errors, webhooks, limits, reversals and settlement. Its adapter maps to domain events while preserving restricted original evidence. On termination, in-flight payments, refunds and history still need handling. Removing a configuration is not the same as settling liabilities.
Operations and future extensions
Running the gateway requires an incident owner, provider contacts, runbooks for outages, backlog handling, daily reconciliation and recovery procedures. Monitoring separates API availability, method success, webhook queues, unmatched payments and payouts. Alerts point to a named role and response, while checkout status comes from the authoritative payment record rather than whichever callback arrived last.
A new asset, network or processor passes the same contract and acceptance matrix: units, precision, finality, fees, refunds, legal roles, test cases and operational owner. One successful test payment is insufficient. Invoicing, accounting, support, monitoring and safe withdrawal of the new method must also be verified without disturbing previously accepted payments.
General technical references
These links explain general principles. They do not document the client's confidential implementation.