Payment API Callback Verification and Retry Design for Pakistan
A practical guide for businesses in Pakistan designing secure payment API callbacks. Learn how to verify signatures, handle duplicate and out-of-order events, build reliable retry mechanisms, reconcile uncertain transactions, and define software integration responsibilities.
发布时间:2026-11-07
A payment request and a confirmed payment are not the same thing. An API may accept an order immediately, while its final status arrives later through a callback, also called a webhook. If that callback is forged, lost, duplicated, or processed in the wrong order, a business can release goods incorrectly or leave a valid payment unresolved.
For businesses operating in Pakistan, reliable payment API integration requires more than a reachable callback URL. It needs authenticated events, durable processing, controlled retries, and reconciliation. These controls matter whether a platform supports collections, payouts, merchant operations, or multiple customer-owned payment channels.
This guide explains how to design callback signature verification and a retry mechanism as one coordinated system. The patterns are implementation recommendations, not claims that every payment provider or software deployment supports identical features.
1. Define the Payment Callback Contract First
Before coding, document the event contract for each connected channel. A callback should communicate enough information to identify the transaction, authenticate the sender, and interpret the event without guessing.
- Identity: A stable event ID, provider transaction reference, and merchant order reference.
- Context: Merchant or tenant identity, event type, and schema version.
- Financial data: Amount and currency, using explicitly documented units.
- Timing: Event occurrence time and, where supported, delivery timestamp.
- Authentication: Signature, signature version, and an optional key identifier.
For PKR transactions, explicitly agree whether amounts use decimal rupees or integer minor units. Avoid binary floating-point arithmetic for money. Store operational timestamps consistently, typically in UTC, and use Asia/Karachi when presenting local reports or defining agreed business-day boundaries.
Also distinguish callbacks received from a customer's payment channel from notifications your platform sends to merchants. These are separate delivery paths with separate credentials, retry policies, and support responsibilities.
2. Verify Callback Signatures Before Trusting the Payload
Follow the sender's exact signing specification
Do not invent a verification format for an existing provider. Confirm the required algorithm, signed fields, byte encoding, digest representation, and header names from its integration documentation. If you control both ends, a documented HMAC-SHA-256 design can provide message authentication using a shared secret.
A practical signing input combines the delivery timestamp, stable event ID, and raw request body with unambiguous separators. The event ID and timestamp must be authenticated, not merely included as unsigned headers. Otherwise, an attacker could alter the information used for replay protection or deduplication.
Verify the original request bytes. Parsing JSON and then serializing it again can change whitespace, key order, escaping, or number formatting. Middleware must preserve the raw body used by the sender's signing scheme.
Use a predictable verification sequence
- Require HTTPS and enforce request-size and content-type limits.
- Resolve the expected integration and its verification key from controlled configuration.
- Validate required authentication headers and supported signature versions.
- Check the authenticated timestamp against a documented freshness policy.
- Recompute the signature and compare decoded values using a constant-time comparison function.
- After authentication succeeds, validate the payload schema and transaction context.
Use the documented asymmetric verification process if the sender signs with a private key instead of HMAC. Keep signature algorithms pinned to configuration rather than accepting arbitrary choices from the request.
IP allowlisting can be an additional control where practical, but it does not replace cryptographic verification. Avoid recording secrets, full authorization headers, or unnecessary personal data in logs.
Handle key rotation and replay protection together
Keep secrets in a protected secret store, with separate credentials for production, testing, and distinct integration boundaries. During rotation, allow a controlled overlap between current and retiring keys, then remove the old key.
A short signature freshness window and a long retry window can conflict. When you control the sending protocol, retain the stable event ID and event occurrence time but generate a fresh delivery timestamp and signature for each attempt. If a provider reuses the original signature, follow its documented retry behavior rather than applying an incompatible freshness rule.
Timestamp checks alone cannot stop replay within the accepted window. Persist authenticated event identifiers and make duplicate deliveries harmless. Keep server clocks synchronized and define permitted clock skew explicitly.
3. Separate Callback Receipt from Business Processing
A callback endpoint should not wait for inventory updates, merchant notifications, report generation, or other slow work. Its first responsibility is to authenticate the request and accept it durably.
- Verify the signature and validate the event.
- Write the event to a durable inbox with a unique deduplication key.
- Commit the write before returning the documented success response.
- Process the accepted event asynchronously with recoverable workers.
A useful deduplication scope combines the integration, tenant or merchant where applicable, and event ID. Enforce uniqueness in the database; an application-level check alone can fail when two deliveries arrive simultaneously.
For a valid duplicate already stored durably, return the agreed success acknowledgment without repeating its business effects. If storage is unavailable, do not acknowledge acceptance as though the event were safe. Return a temporary failure according to the integration contract.
When database storage and queue publication are separate operations, use an outbox pattern or a recoverable inbox scanner to avoid losing work between them. Acknowledgment means the event has been accepted, not necessarily that every downstream task has finished.
4. Make Order Updates Idempotent and State-Aware
Payment callbacks commonly offer at-least-once delivery: the same event may arrive repeatedly. Idempotency ensures those repeated deliveries produce one intended business effect.
Event deduplication is only the first layer. A sender may issue different event IDs describing the same transaction outcome. Order updates, ledger postings, fulfillment actions, and merchant notifications therefore need their own uniqueness rules or idempotency controls.
Validate the transaction, not just the signature
A valid signature proves message authenticity under the signing scheme; it does not prove that the event belongs to the expected order. Compare merchant identity, transaction references, amount, currency, and environment before changing financial state. Route mismatches to controlled review rather than silently applying them.
Use explicit state transitions
Define allowed transitions for each transaction type and channel. For example, a delayed pending event should not overwrite a confirmed successful payment. However, a legitimate reversal or refund may require a separate subsequent transition. Do not reduce every lifecycle to a universal ranking of status labels.
Use transactional updates, row locking, or version checks to handle concurrent workers. Where supported, provider sequence numbers can help establish order. Conflicting events should trigger an authoritative status query or reconciliation process, not a decision based only on arrival time.
5. Design a Retry Mechanism with Clear Failure Categories
Retries should recover from temporary faults without amplifying an outage. Separate notification delivery retries, internal processing retries, and retries of payment-creation requests. They solve different problems and can carry very different financial risks.
Retry temporary failures with backoff and jitter
For callbacks your platform sends, connection failures, timeouts, and many server-side errors are usually retryable. Rate-limit responses may also justify retrying while respecting a documented Retry-After instruction.
An illustrative schedule could retry after roughly 30 seconds, 2 minutes, 10 minutes, 30 minutes, and then progressively longer intervals. This is a design example, not a BD Payment service commitment. Set the actual schedule, maximum interval, attempt limit, and total delivery window around operational requirements.
Add randomized jitter so many failed events do not retry together. Apply per-destination concurrency limits and queue isolation so one unavailable merchant endpoint cannot block other merchants. An extended outage may justify a circuit breaker with controlled recovery probes.
Do not retry permanent errors blindly
Malformed payloads, unsupported schemas, and invalid credentials generally need correction. Treat authentication failures as integration incidents rather than generating endless traffic. Classify HTTP responses using the receiver's contract, because status-code meanings can vary.
After the configured limit, move the delivery into a dead-letter or failed-delivery queue. Record its event ID, destination, attempt history, response category, and next action. Controlled redelivery should preserve the original event identity while creating a new delivery attempt and, where applicable, a fresh signature.
Never confuse notification retries with payment retries
A callback timeout does not prove that the payment failed. Retrying a collection or payout creation request without safeguards can create duplicate financial instructions. Use the channel's documented idempotency support where available, and query uncertain transaction status before deciding whether another creation request is appropriate.
6. Reconcile Transactions When Callbacks Are Missing
Even a well-designed callback system needs an independent recovery path. A sender may exhaust its retries, an endpoint may remain unavailable, or a configuration error may prevent delivery entirely.
Identify orders that remain pending beyond a channel-appropriate threshold. Query the customer's connected channel through its available status API, or compare authorized transaction reports where available. Respect query limits and distinguish unknown status from confirmed failure.
Route reconciliation results through the same idempotent state-management rules used for callbacks. If an apparent success has an amount mismatch, missing reference, or contradictory channel status, create an exception instead of forcing a match.
Keep payment status, notification delivery status, and financial reconciliation status separate. A successful collection can have a failed merchant notification, and a delivered notification does not independently establish settlement.
7. Monitor and Test the Full Delivery Lifecycle
Track valid and invalid signatures, duplicate events, acknowledgment latency, queue age, retry volume, exhausted deliveries, and reconciliation exceptions. Use correlation IDs to connect orders, channel references, events, and delivery attempts.
For multi-tenant systems, enforce tenant-scoped access to credentials, events, reports, and transaction queries. If merchants can configure callback destinations, protect against server-side request forgery: restrict destination schemes, block internal network targets, validate resolved addresses, and control redirects.
Before production, test altered bodies, expired timestamps, key rotation, concurrent duplicates, out-of-order events, database failure before acknowledgment, and worker crashes after committing an order update. Also simulate the receiver processing a callback successfully while its HTTP response is lost. That scenario directly tests whether retries are truly harmless.
Define who can rotate keys, replay failed deliveries, change endpoints, and resolve exceptions. Audit these actions and restrict them through role-based permissions.
8. Define BD Payment's Role in the Integration
BD Payment provides payment system software rental, deployment, and technical/API integration. Its software scope can include orders, merchants, collection and payout workflows, multi-channel management, automatic order matching, financial reconciliation, risk management, agents, reports, permissions, and transaction queries.
Businesses can evaluate independent deployment or multi-tenant deployment, together with standard or customized API integration. Callback formats, verification methods, retry policies, monitoring requirements, and operational ownership should be assessed against the customer's selected channels and agreed implementation scope.
Customers use their own payment channels. BD Payment does not provide bank accounts, e-wallet accounts, payment channels, licenses, or regulatory authorization. Software deployment should not be interpreted as confirmation of provider access, partnership, or settlement capability.
For operations in Pakistan, customers should verify applicable regulatory, contractual, privacy, and security obligations with qualified local professionals according to their own business model.
Conclusion
Reliable payment API callbacks combine authenticated messages, durable acceptance, idempotent processing, controlled retries, and independent reconciliation. None of these controls replaces the others. Define the event contract first, test failure scenarios deliberately, and make software, channel, and merchant responsibilities explicit before going live.
Frequently Asked Questions
1. Is HTTPS enough to secure payment callbacks?
No. HTTPS protects transport, but the endpoint still needs a way to authenticate the sender and detect message alteration. Use the channel's documented signature verification method, plus replay protection and transaction-level validation.
2. Should a duplicate callback receive a success response?
Usually yes, if it is authenticated and the original event is already durably accepted. Return the documented acknowledgment without repeating financial or fulfillment actions. Returning failures for valid duplicates can create unnecessary retries.
3. How many callback retry attempts should be configured?
There is no universal number. Choose a bounded schedule based on recovery needs, endpoint capacity, channel behavior, and support coverage. Combine backoff and jitter with alerts, failed-delivery handling, and reconciliation rather than relying on unlimited retries.
4. Can a browser return page confirm payment success?
Not by itself. Browser redirects can be interrupted or manipulated. Use authenticated server-to-server evidence and, when needed, an authoritative status query before treating an order as paid or releasing irreversible value.
5. Does BD Payment provide payment channels for Pakistan?
No. Customers supply their own payment channels. BD Payment provides software rental, deployment, and technical/API integration, with compatibility and implementation requirements assessed for the customer's deployment. It does not supply accounts, channels, licenses, or regulatory authorization.