Airpay API integration for a hosted payment journey is not simply a button that sends customers to another website. A reliable implementation must preserve the booking or order before departure, hand off the correct amount, interpret the payment result, and recover when a browser closes between payment and confirmation. The merchant application remains responsible for deciding when an order can progress, even while Airpay hosts the payment interaction.
This guide focuses on Airpay's v4 Simple Transaction journey for website checkout. It describes a practical architecture for travel portals, booking engines, and other order-based systems. Its central rule is straightforward: reaching a return page is a navigation event, not evidence that money was received. Only a validated, matching transaction outcome should trigger payment-dependent business actions.
Define the Payment Boundary Before Building the Redirect
In the hosted model, a customer chooses an offer on the merchant site and is taken to Airpay's payment page to complete the payment. The Airpay v4 Simple Transaction documentation describes this redirect model and a merchant return destination. The customer may navigate back afterward, but browser navigation is neither guaranteed nor an authoritative settlement signal.
Separate three responsibilities. The merchant owns the cart, prices, inventory policy, customer record, and order status. Airpay conducts the hosted payment interaction and reports transaction results. The merchant's backend verifies those results against its own stored expectations before issuing receipts, confirming bookings, or releasing services.
These responsibilities should be visible in the software design. A checkout page can say "Proceeding to secure payment" while the server saves the pending payment attempt. The return page can say "Checking your payment" until the backend has an authoritative answer. A notification handler can update the same attempt even when the customer never returns.
For a travel product, distinguish payment confirmation from supplier confirmation. A successful payment might authorize moving into a flight-ticketing or hotel-booking workflow, but it does not prove that a supplier has issued a ticket or voucher. Keep the payment ledger and fulfilment state separate, with explicit rules for stock changes, booking failures, refunds, and human review.
Give Every Order and Payment Attempt a Stable Identity
Store Business Orders Separately From Gateway Attempts
Model an order as the commercial obligation and a payment attempt as one effort to collect it. An order record needs an internal order ID, customer identity, currency, payable amount, inventory or quote expiry, and business status. A payment attempt needs its own identifier, the merchant-facing orderid sent to Airpay, creation time, requested amount, current gateway status, and any returned Airpay reference.
Airpay identifies orderid as a merchant-generated transaction ID with an alphanumeric length of one to thirty characters. Keep it unique within the appropriate merchant integration scope. For systems that permit a second payment try, use a fresh gateway order reference linked to the same underlying business order, rather than carelessly recycling an unresolved reference.
The distinction becomes critical after a timeout. The booking may remain open while the first payment attempt is still processing. Starting another attempt without checking the first could produce duplicate collections. Add a uniqueness constraint on merchant order references and guard state changes with database transactions or compare-and-set updates.
Persist the Expected Transaction Facts
Capture the intended amount as an exact decimal or integer minor-unit value, not a floating-point approximation. Store the ISO currency, numeric currency code, merchant account, and customer-facing description as they existed when checkout began. Do not infer the amount later from a mutable cart or a newly priced flight search.
Save an immutable request snapshot or a securely redacted digest of it, plus a correlation identifier for logs. Maintain timestamps for initiation, redirect, return, callback, verification, and final resolution. Include an attempt-level error classification so support can distinguish gateway rejection from an internal network failure.
When Airpay returns ap_transactionid, attach it to the same payment attempt as orderid. The first is Airpay's transaction reference; the second is the value the merchant supplied. Index both, preserve their original values, and never substitute one for the other in a reconciliation query.
Create the v4 Simple Transaction Request on the Server
Validate Checkout Inputs Before Generating Payment Data
The merchant backend should calculate the final payable total from trusted pricing records, validate customer data, and confirm that checkout remains eligible. The documented v4 request includes orderid, amount formatted to two decimal places, currency_code, iso_currency, buyer email, buyer phone, and buyer first and last names. The documentation uses numeric currency code 356 and ISO code INR in its examples.
Optional fields include buyer address details, customvar, payment-channel selection through chmod, and return_url. A specified channel restricts which enabled modes appear; omitting it allows the enabled choices. Do not insert channel restrictions without a business reason or assume every listed mode is available for a particular merchant.
Airpay documents that return_url, if supplied, must use a domain matching the merchant's registered domain. Treat the path as a controlled application route, not a place where a buyer can submit arbitrary redirect targets. The page should locate the existing checkout record through server-side session or a signed, opaque reference, rather than trusting editable query parameters for price or status.
Prepare Encryption, Checksum, and Credentials Correctly
The v4 example derives a private key from configured credentials, encrypts JSON payment data, and computes a checksum before submitting the hosted form. The related v4 Encryption guide describes AES-256-CBC and its initialization-vector convention; the Checksum guide specifies sorting request keys, concatenating their values, appending the current date in YYYY-MM-DD format, and hashing with SHA-256.
Use the documented functions and your issued environment credentials, not guessed cipher settings or a hand-edited hash sequence. Date-dependent checksum creation needs a consistent server clock and a tested timezone boundary. Keep the merchant ID, client credentials, username, password, and encryption secret in managed server configuration; never embed these values in a mobile application bundle, source repository, or diagnostic screenshot.
The v4 Simple Transaction endpoint is documented as a POST to https://payments.airpay.co.in/pay/v4/?token=<access_token>. The sample HTML form submits privatekey, merchant_id, encdata, and checksum. Obtain the access token using the documented v4 OAuth2 credentials flow, and use it according to its expiry rather than treating it as permanent.
Generate the form server-side or from a short-lived, server-authorized handoff session. Before showing it, commit the pending attempt to persistent storage. Prevent caches, analytics collectors, and error-reporting middleware from recording confidential request fields or tokenized URLs. If the handoff page is reloaded, either return to the existing unexpired attempt safely or require a deliberate recovery step; avoid creating another payment attempt on every refresh.
Design a Redirect That Remains Understandable to Customers
A transition page should show the order reference, displayed total, and a simple explanation that payment will continue on Airpay. Provide a visible "Continue to payment" control as a fallback if automatic form submission is blocked. Avoid asking the customer to copy a link containing credentials, and never place secret values into a browser-visible support message.
Because hosted payment changes the website context, keep branding and language consistent around the transition. Explain that the customer will return to the merchant site when the payment flow completes. Do not promise that pressing Back or closing the page will cancel an authorization; navigation choices do not necessarily control a payment already submitted to a bank.
Preserve a recoverable internal order route independently of the gateway return route. An authenticated customer should be able to reopen "My bookings" or "My orders" on another device and see the latest server-stored payment state. For guest checkout, use an appropriately protected lookup link or verification step that reveals only that customer's order.
Time out abandoned handoff sessions in the application without automatically declaring the financial attempt failed. Session expiry and transaction failure are different events. If an offer has expired, prevent fulfilment until revalidation, even if a late payment result arrives. Design late-success handling as an explicit exception path rather than silently issuing an invalid travel product.
Verify the Result Instead of Trusting the Return Address
Decrypt the Response Envelope on the Backend
Airpay's v4 Decryption documentation states that API responses use an encrypted AES/CBC/PKCS5PADDING convention and must be decrypted with the provided encryption key. Its example separates an initial sixteen-character IV from the response string, base64-decodes the remaining ciphertext, decrypts with AES-256-CBC, and parses the resulting JSON. Implement that convention using a well-tested cryptographic library, with strict error handling.
The decrypted API envelope may contain status_code, response_code, status, message, and a data object. An API-level success says the request was handled; it is not by itself confirmation that the payer completed the transaction. Read the transaction-specific fields within the verified result. Likewise, HTTP 200 indicates transport success and must never serve as the payment decision.
Do not assume that every return-page visit arrives with an encrypted payload. The browser return and server API response have different roles, and the exact return delivery must be tested against the merchant's configured setup. If a usable response is missing, malformed, or delayed, show a neutral processing state and reconcile through the server rather than trusting the URL path.
Compare References, Integrity Data, and Payment State
The v4 Simple Transaction response documents orderid, ap_transactionid, merchant_id, amount, transaction_payment_status, transaction_status, and ap_SecureHash. Match the merchant order ID, merchant account, amount, and applicable currency to the pending attempt. Reject mismatches into an investigation queue without changing the booking to paid.
Airpay describes a CRC32 calculation for ap_SecureHash using order ID, gateway transaction ID, amount, status, message, merchant ID, and username, with an additional customer VPA value for UPI. Validate the documented sequence as applicable to the received channel and response. Because CRC32 is not a secret-key message authentication code, do not treat its presence alone as independent proof of payment; use a trusted backend status result and all reference checks.
For a standard successful sale, the documented transaction_payment_status can be SUCCESS and numeric transaction_status is 200. Other values include processing 211, failure 400, dropped 401, not-yet-processed 402, incomplete 403, bounced 405, and no records 503. Interpret transaction subtype and transaction type before assuming an authorization means capture or a captured payment means fulfilment is complete.
Apply the decision once. On a verified success, atomically record the result, link the gateway reference, and publish a single downstream fulfilment event. On conflicting or unclear evidence, retain the order in a reviewable state. Never downgrade an already reconciled successful transaction because an older retry, duplicate callback, or stale browser session reports processing.
Map Gateway Outcomes to Clear Return-Page States
Return-page language should reflect what the backend currently knows, not what the address bar suggests. Use server-provided state, refreshed through an authenticated order-status request if needed. The following matrix is a recommended merchant-side presentation policy based on the v4 status vocabulary, not a replacement for verifying the underlying response.
| Verified or observed condition | Customer-facing state | Merchant action |
|---|---|---|
| Matched success, status 200 | Payment received; booking confirmation may still be underway | Record paid once; start permitted fulfilment workflow |
| Processing, status 211 | We're confirming your payment | Keep pending; verify again without collecting twice |
| Failed, status 400 | Payment unsuccessful | Retain order details; offer a guarded retry |
| Dropped 401, not processed 402, incomplete 403, or bounced 405 | Payment not confirmed | Reconcile before deciding whether retry is safe |
| No records, status 503 | We cannot confirm payment yet | Investigate reference and timing; do not infer nonpayment |
| No browser return or invalid response | Status available through order lookup | Use backend notifications and confirmation checks |

The successful screen should show the merchant order reference, an appropriate receipt or payment reference, the paid amount, and what will happen next. Keep sensitive identifiers, full card data, and internal diagnostics off the page. A paid transaction that is awaiting ticket issuance should not be labelled "Ticket confirmed."
For a pending result, explain that customers should not immediately repeat payment. Offer a safe way to refresh status, contact support, or return to the order overview. Failure screens can allow retry only after the server checks that the previous attempt is not still progressing. A retry must never be triggered merely by refreshing the result page.
Recover With Notifications and Server-Initiated Confirmation
Handle Callbacks Without Depending on an Open Browser
The documented v4 IPN Callback sends transaction updates to a merchant endpoint. Configure and protect that endpoint independently from the customer return page. Treat callbacks as untrusted input until reference, amount, merchant identity, status, and documented secure-hash checks are complete. Log the event identifier or a stable fingerprint so duplicate delivery cannot repeat business actions.
Acknowledge validly received notifications promptly and move fulfilment work to a durable queue. If the order update fails, retain a retryable internal event rather than discarding the status. Expect events to arrive after the customer leaves, and design for reordered deliveries. The callback is useful because the browser may be closed, but it should not eliminate deliberate reconciliation of ambiguous results.
Use Order Confirmation for Unresolved Transactions
Airpay's v4 Order Confirmation API provides a merchant-side transaction status pull using an orderid, ap_transactionid, or retrieval reference number. Its documentation specifically says this API operates for live merchant IDs and not sandbox merchant IDs. Do not write a sandbox test that assumes this verification endpoint works there.
A reconciliation worker can revisit unresolved attempts after a short delay, then at increasing intervals within an operationally defined window. Query by the stored merchant reference when the Airpay transaction ID has not arrived. Decrypt the API response using the documented convention, validate its transaction data, and update the order only if the result matches the attempt.
Set a bounded number of automated checks and escalate prolonged uncertainty for manual investigation. "No records" is not a reliable assertion that no debit occurred, particularly soon after an interrupted checkout. Prevent repeated collections until policy permits a new attempt, and provide support staff with the exact order and gateway references needed to investigate.
Recover Interrupted, Abandoned, and Duplicate Journeys
Consider several separate interruption points: the customer leaves before submitting the hosted form; closes Airpay after choosing a payment mode; completes authorization but loses network access before returning; lands on the return route while the callback is late; or opens the same receipt link twice. Each case needs a resumable merchant order record, not a new order created from browser history.
Before form submission, the attempt can be marked prepared. After handoff, it becomes awaiting result. Following a verified processing response, it remains pending. Only a verified final result should move it into paid or a justified unsuccessful state. An expiry timer may mark the user session abandoned while leaving financial reconciliation active.
When the customer returns to the merchant site later, look up the existing order and show the best known status. If still unresolved, trigger or schedule a backend confirmation check. Avoid storing sole recovery evidence in local browser storage: device changes, privacy settings, and cleared cookies make that unreliable. Use authenticated accounts or carefully protected guest recovery mechanisms.
Support personnel need a controlled "recheck payment" action that queries the authoritative integration path, not an "approve payment" button that simply edits the order flag. Administrative overrides, if business policy permits them, require authorization, reason codes, independent evidence, and audit trails. A late successful payment for an expired booking should enter an exception workflow rather than automatically booking unavailable inventory.
Worked Hypothetical Example: A Travel Booking Payment
The following scenario is illustrative only; the order, amount, buyer, and transaction references are invented. A customer selects a refundable hotel package priced at INR 12,450.00. The travel portal creates internal booking TRIP8421 and first payment attempt PAY8421A. It sends Airpay merchant orderid TT8421A, amount 12450.00, currency code 356, and ISO currency INR.
The backend stores the expected details, encrypts the v4 payload, generates the checksum, and prepares the hosted POST. The customer submits payment but loses mobile connectivity before navigating back. The merchant does not receive a browser return and displays no premature "paid" indication. The attempt remains awaiting a trusted result.
Later, an appropriately validated callback or live Order Confirmation response reports merchant reference TT8421A, hypothetical Airpay reference 76543210, amount 12450.00, transaction_payment_status of SUCCESS, and transaction_status of 200. The integration checks the merchant account, amount, order ID, response integrity, and transaction type before marking the attempt paid.
The portal then starts its separate hotel supplier confirmation process. When the customer reopens booking TRIP8421, the page states "Payment received; hotel confirmation in progress." A duplicate callback later arrives with the same gateway reference; the handler records it without charging again or sending a second supplier instruction. If the supplier cannot honour the quote, the booking follows the merchant's documented service-recovery and refund process.
Operational Controls and Acceptance Tests
Protect Information Across Logs, Pages, and Services
Serve every merchant page and callback over HTTPS. Verify that sensitive credentials remain restricted to server workloads and that secrets can be rotated without changing order history. Avoid exposing the entire decrypted gateway payload to the customer. Store only operationally necessary payment fields, redact personal information in logs, and apply retention and access controls to audit records.
Keep correlation logs for handoff creation, POST preparation, return receipt, callback receipt, verification lookup, status transition, and fulfilment dispatch. Record failures with enough context to diagnose invalid credentials, checksum mismatches, decryption errors, unexpected amounts, and provider timeouts. Do not record raw encryption keys, full card numbers, authentication tokens, or unredacted personal profiles.
Test the Lifecycle, Not Only the Success Screen
Test valid and invalid order references, incorrect amount and currency, mismatched merchant ID, tampered response fields, expired credentials, duplicated callbacks, and delayed processing transitions. Test browsers with JavaScript disabled so the handoff has a manual submit option, and verify that refreshing either the handoff page or the return page cannot create another collection.
Simulate closing the tab immediately after the payment submit, losing connectivity during the return, receiving an IPN before the browser return, and receiving conflicting updates out of order. Confirm that the user can recover the same order from another browser. For live-only Order Confirmation behavior, plan controlled production verification with suitable operational safeguards rather than inventing a sandbox result.
Acceptance criteria should be measurable: no order becomes paid from a URL alone; every paid attempt matches the saved merchant, amount, currency, and order reference; each Airpay transaction ID links to one reconciled attempt; repeated callbacks are idempotent; uncertain attempts remain recoverable; and supplier fulfilment fires once, only after the correct payment conditions have been met.
Finally, monitor pending-attempt age, mismatch counts, verification error rates, duplicated-event frequency, and the time between payment completion and customer-visible status. These measures show whether the integration is dependable beyond the happy path. For TravelTech365 projects, the practical deliverable is not merely a working redirect: it is an auditable payment handoff that preserves customer trust, protects order integrity, and provides a recovery route whenever the browser journey breaks.
