TNS Payments Developer Portal ## Sections • [Home](https://developer.pay.tnsi.com/hosted-checkout/supported-libraries.md): Welcome to the TNS developer portal. You'll find comprehensive guides and documentation to help you start working with TNS as quickly as possible, as well as support if you get stuck. Let's jump right instead step • [HMAC Authentication](https://developer.pay.tnsi.com/hosted-checkout/hmac-authentication.md): Every request to TNS Gateway API is to be authenticated by HMAC by creating a signature of the request payload using API Key and Secret provided by TNS. How to generate hmac APIKey (Provided by TNS) Secret (Provided by TNS) Take the timestamp at the time of signing Get data/ payload (which will be sent as request body) as string Concatenate APIKey “:” timestamp “:” payload Generate HMAC by using Secret provided by TNS HMAC should be generated by using SHA512 algorithm. Here's a simple example of HMAC calculation using JavaScript: To use CryptoJS.HmacSHA512 , you need to ensure that you have the necessary prerequisites set up, including the proper installation and importation of the crypto-js library. Include the CryptoJS library in your HTML file: Add the following tag to your HTML file to load CryptoJS from a CDN. Javascript <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.2.0/crypto-js.min.js"></script> Javascript function generateHMAC(apiKey, secret, requestBody) { var time = new Date().getTime(); var rawSignature = apiKey + ":" + time + ":" + requestBody; var signature = signHMAC(rawSignature, secret); return signature; } function signHMAC(rawSignature, secret) { const signature = CryptoJS.HmacSHA512(rawSignature, secret); const hexSignature = CryptoJS.enc.Hex.stringify(signature); return hexSignature; } After generating the HMAC hash, the following headers need to be included in the REST API Request. Title Description Title Field Description Required Example Value apikey The API Key provided by TNS. Yes ba81c80ad011cd918b946f7e957b1b70cc25f14405d1e7801e892e1561295493 timestamp The time stamp taken at the time of signing. Yes 1715322040 hmac Generated HMAC Hash value. Yes e24e1bfe76b1c846c10c3079ea47202913ad04d66a1434b26470010427dda2d9 User-Agent Identifies the client application making the request. Must include the application name and version (for example, MyPOS/2.1.0 ). This value is not validated but is used for identification and troubleshooting purposes. Yes MyPOS/2.1.0 Important: The User-Agent header is mandatory for all API requests. Requests without a valid User-Agent will be rejected. This header helps TNS identify your integration for support and troubleshooting purposes. • [Hosted Checkout](https://developer.pay.tnsi.com/hosted-checkout/ecomm/hosted-checkout.md): Quickly configure your checkout page to securely accept payments. Pre-built hosted page readily available to integrate with your online website or mobile applications. Hosted Checkout integration involves two parts: server-side integration and client-side integration. In the client-side integration, you specify non-editable <div> elements for payment information in your checkout flow, maintaining your UI's look and feel. Our SDK then replaces these with a secure iframe that captures card data. When our SDK is called from your client, the card data is sent to our servers, transactions are processed and transient tokens are issued. Introduction Hosted Checkout is a proprietary JavaScript SDK from TNS, designed to provide merchants with an iframe for seamless integration into their ecommerce websites. This integration facilitates secure online payments while keeping sensitive payment data out of the merchant's server. Rather than entering card data directly on the merchant's website, TNS handles the card data, enhancing security and compliance. How it works Hosted Checkout integration involves two parts: server-side integration and client-side integration. In the client-side integration, you specify non-editable elements for payment information in your checkout flow, maintaining your UI's look and feel. Our SDK then replaces these with a secure iframe that captures card data. When our SDK is called from your client, the card data is sent to our servers, transactions are processed and transient tokens are issued. The server-side integration is needed to authenticate your session. You can also use tokens issued by TNS to execute transactions. What we offer Title Description Pre-built payment form to embed into your checkout flow Simple integration with online web application and mobile application Built-in validation of payment fields Tokenization allowing a secure token to be returned for future transactions without asking the cardholder to enter their card details again Google Pay, Apple Pay, PayPal and other Global Alternative Payment Methods (APM) Embedded Fraud options such as 3DS2 Authentication, Google reCAPTCHA & Address Verification Service (AVS - United States ) Sample Hosted Checkout Integration Steps 1 Start Checkout When the customer is ready to pay or clicks the checkout button, the merchant's online application requests the checkout page from its server. 2 Create Session The merchant's server initiates a secure session to the Payment Orchestration Session API, specifying the type of payment transaction amount, display configuration, and merchant credentials, all secured by signing the request with HMAC. 3 Checkout Page The merchant's server sends the checkout page with the payment form to the online application. 4 Initialized Hosted Checkout The merchant's online application initializes Hosted Checkout with the specified initialization parameters. 5 Hosted Checkout iframe Once initialized, the Hosted Checkout SDK replaces the payment form linked to the specified container ID with a Hosted Checkout Iframe that contains elements for capturing payment data. 6 Submit Transaction The customer enters payment card details into the iframe and clicks Pay button. Hosted Checkout collects card information, processes the transaction and sends the results back to the online application via callbacks. 7 Process Transaction Response The transaction response received for the transactions, which will contain the transaction identifier that can be used for secondary transactions like void, capture and refunds. See Secondary Transactions for more information. Using our SDK, you can integrate a payment form in just two steps and begin accepting payments on your website or mobile application. Step 1 - Create Hosted Checkout Session When utilizing our Hosted Checkout system, initiate a session and embed our scripts on your webpage. Subsequently, our iframe will automatically render. The initial step involves creating a session. For illustrative purposes, we will showcase this process using our test credentials in the demonstration environment to offer a fundamental example. Please refer to the following cURL request to commence a session. For more information on the request fields or to see the cURL request in multiple languages, see Create Session Request section of our documentation. This curl request example contains the minimum mandatory fields required to get a successful session. We have successfully generated our session ID, which will remain active for a period of up to 15 minutes before it expires and cannot be used. JSON 201 Created { "sessionId": "cf896190-32fb-44d5-819e-7f9eb0ec8f2f" } Step 2 - Create a sample HTML page to embed the Hosted Checkout iframe Now we need to create a basic HTML page to embed our checkout iframe. This involves incorporating script references and a '' element to showcase the iframe. Let's proceed by creating an HTML page titled index.html. Subsequently, let's insert the specified script references within the '' segment of our page. It is imperative to substitute [YOUR_SESSION_ID] with the session ID obtained from the API request mentioned earlier. The containerId can be any chosen ID, as long as it corresponds to the ID of the '' designated for displaying the iframe. Our example operates in the UAT environment, with en_US as the selected locale. Now add the following HTML to the '' section of our page. Make sure the id of the '' matches the containerId used above. HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Hosted Checkout Demo</title> <!-- Initialize exports --> <script> var exports = {}; </script> <!-- Hosted Checkout SDK --> <script src="https://checkout.uat.pay.tnsi.com/sdk/index.js"></script> <!-- Demo Script --> <script> document.addEventListener("DOMContentLoaded", function () { var hostedCheckoutSdk = new exports.HostedCheckoutSDK(); hostedCheckoutSdk.initialize({ containerId: "hosted-checkout", sessionId: [YOUR SESSION ID], environment: "uat", onApprove: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onError: function (error) { console.log(JSON.stringify(error)); // use the error object for subsequent actions }, onSessionExpired: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onSessionError: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onInvalidData: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onGooglePayAuthorized: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onGooglePayCanceled: function () { // no response object; handle cancellation }, onGooglePayError: function (error) { console.log(JSON.stringify(error)); // use the error object for subsequent actions }, onPaypalAuthorized: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onPaypalCaptured: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onPaypalCanceled: function () { // no response object; handle cancellation }, onApplePayAuthorized: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onApplePayCanceled: function () { // no response object; handle cancellation }, onApplePayError: function (error) { console.log(JSON.stringify(error)); // use the error object for subsequent actions } }); }); </script> </head> <body> <div id="hosted-checkout"></div> </body> </html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Hosted Checkout Demo</title> <!-- Initialize exports --> <script> var exports = {}; </script> <!-- Hosted Checkout SDK --> <script src="https://checkout.uat.pay.tnsi.com/sdk/index.js"></script> <!-- Demo Script --> <script> document.addEventListener("DOMContentLoaded", function () { var hostedCheckoutSdk = new exports.HostedCheckoutSDK(); hostedCheckoutSdk.initialize({ containerId: "hosted-checkout", sessionId: [YOUR SESSION ID], environment: "uat", onApprove: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onError: function (error) { console.log(JSON.stringify(error)); // use the error object for subsequent actions }, onSessionExpired: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onSessionError: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onInvalidData: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onGooglePayAuthorized: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onGooglePayCanceled: function () { // no response object; handle cancellation }, onGooglePayError: function (error) { console.log(JSON.stringify(error)); // use the error object for subsequent actions }, onPaypalAuthorized: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onPaypalCaptured: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onPaypalCanceled: function () { // no response object; handle cancellation }, onApplePayAuthorized: function (response) { console.log(JSON.stringify(response)); // use the response object for subsequent actions }, onApplePayCanceled: function () { // no response object; handle cancellation }, onApplePayError: function (error) { console.log(JSON.stringify(error)); // use the error object for subsequent actions } }); }); </script> </head> <body> <div id="hosted-checkout"></div> </body> </html> Now just use a browser to display the index.html file. You should see the Hosted Checkout Form, and you're ready to submit a test payment. Step 4 - Handle Transaction Response You've successfully integrated Hosted Checkout with your checkout process. You'll now receive a response that is sent via the onApprove callback method as configured in the SDK initialization above. Refer to the sample transaction response messages in our API documentation for the API methods. You can refer to the Parameters & Callbacks page to ensure your application handles negative scenarios with the integration. That's It, You're Done! For more detailed information on configuration, formatting options and callbacks, refer to the specific pages within the Hosted Checkout section • [Perform Transaction](https://developer.pay.tnsi.com/hosted-checkout/ecomm/hosted-checkout/perform-transaction.md): This API request is designed to perform a transaction and have optionally have a token returned which can be used when the cardholder returns to perform a transcation. The session mode is PERFORM_TRANSACTION The token can be used instead of having to have the cardholder re-enter their actual card number each time they return to purchase an item. The value of the token should be specified in the tokens array. This request uses our test credentials running in our demo environment. Use our language box to see sample code in popular programming languages. When you use this payload in the API Explorer, the timestamp and HMAC will be automatically assigned by the API Explorer. You will need to provide the secret for this API Key in the API Explorer. • [Account Verification](https://developer.pay.tnsi.com/hosted-checkout/ecomm/hosted-checkout/account-verification.md): This API request is designed to perform a transaction and have optionally have a token returned which can be used when the cardholder returns to perform a transcation. The session mode is PERFORM_TRANSACTION The token can be used instead of having to have the cardholder re-enter their actual card number each time they return to purchase an item. The value of the token should be specified in the tokens array. This request uses our test credentials running in our demo environment. Use our language box to see sample code in popular programming languages. Run in API Explorer When you use this payload in the API Explorer, the timestamp and HMAC will be automatically assigned by the API Explorer. You will need to provide the secret for this API Key in the API Explorer. • [Status](https://developer.pay.tnsi.com/hosted-checkout/ecomm/hosted-checkout/status.md): This API request is designed to allow you to check the status/outcome of a transaction. In the event that a customer has closed their browser, of a network issue occured, you can check if the session is completed or not. It would be best practice to set a checkoutSessionTimeout when creating sessions for hosted checkout. If no response is received within the Session Timeout window, then you can query this endpoint to find the outcome. • [Create Token](https://developer.pay.tnsi.com/hosted-checkout/ecomm/hosted-checkout/create-token.md): This operation allows a Hosted Checkout form to be generated, where the cardholder will enter their cards details, allowing a token to be generated and returned to the merchant. A common use-case is where the token will be used when creating an account on your website/app, but not purchase any goods. Please note that no transaction is being placed during this operation. It's also not guaranteed that the card number entered is a valid card. This request uses our test credentials running in our demo environment. Use our language box to see sample code in popular programming languages. • [Update Token](https://developer.pay.tnsi.com/hosted-checkout/ecomm/hosted-checkout/update-token.md): This operation allows a user to update information associated with their token. A tokenId needs to be provided when the mode sessionMode is UPDATE_TOKEN . This request requires test credentials running in our demo environment. Use our language box to see sample code in popular programming languages. Run in API Explorer When you use this payload in the API Explorer, the timestamp and HMAC will be automatically assigned by the API Explorer. You will need to provide the secret for this API Key in the API Explorer. Following is a sample request to update an existing token. • [Card Hash](https://developer.pay.tnsi.com/hosted-checkout/ecomm/hosted-checkout/card-hash.md): This request uses our test credentials running in our demo environment. Use our language box to see sample code in popular programming languages. Run in API Explorer When you use this payload in the API Explorer, the timestamp and HMAC will be automatically assigned by the API Explorer. You will need to provide the secret for this API Key in the API Explorer. Following is a sample request to generate Card Hash in Hosted Fields. • [Parameters and Callbacks](https://developer.pay.tnsi.com/hosted-checkout/ecomm/hosted-checkout/parameters-and-callbacks.md): The hosted checkout system uses a post Message-based communication pattern between the iframe (hosted checkout) and the parent window (merchant's website). Here's how the callback system operates: Communication Flow SDK Initialization : The merchant initializes the SDK with callback functions Iframe Creation : SDK creates an iframe pointing to the hosted checkout Event Listening : SDK listens for message events from the iframe Callback Triggering : Hosted checkout triggers callbacks by posting messages to the parent window Callback Execution : SDK receives messages and executes the corresponding callback functions Javascript var hostedCheckoutSdk = new exports.HostedCheckoutSDK(); hostedCheckoutSdk.initialize({ containerId: "hosted-checkout", sessionId: [YOUR SESSION ID], environment: "uat", onApprove: function (response) { console.log(JSON.stringify(response)); //use the response object for subsequent actions }, onError: function (error) { console.log(JSON.stringify(error)); //use the error object for subsequent actions }, onSessionExpired: function (response) { console.log(JSON.stringify(response)); //use the response object for subsequent actions }, onSessionError: function (response) { console.log(JSON.stringify(response)); //use the response object for subsequent actions }, onInvalidData: function (response) { console.log(JSON.stringify(response)); //use the response object for subsequent actions }, onGooglePayAuthorized: function (response) { console.log(JSON.stringify(response)); //use the response object for subsequent actions }, onGooglePayCanceled: function () { //onGooglePayCanceled should not send back any response object. This section should be utilized for subsequent actions }, onGooglePayError: function (error) { console.log(JSON.stringify(error)); //use the error object for subsequent actions }, onPaypalAuthorized: function (response) { console.log(JSON.stringify(response)); //use the response object for subsequent actions }, onPaypalCaptured: function (response) { console.log(JSON.stringify(response)); //use the response object for subsequent actions }, onPaypalCanceled: function () { //onPaypalCanceled should not send back any response object. This section should be utilized for subsequent actions }, onApplePayAuthorized: function (response) { console.log(JSON.stringify(response)); //use the response object for subsequent actions }, onApplePayCanceled: function () { //onApplePayCanceled should not send back any response object. This section should be utilized for subsequent actions }, onApplePayError: function (error) { console.log(JSON.stringify(error)); //use the error object for subsequent actions } }); Parameters for Hosted Checkout SDK Initialization containerId : The id of the in the html page where the iframe to be displayed. sessionId : The sessionId from the response of Create Session request environment : This field is required only when we are doing tests or development. In Production/Live, this field should not be passed. Supported Callbacks: All callbacks Core transaction callbacks onApprove: handlePaymentApproval onSuccess: handlePaymentSuccess onDecline: handlePaymentDecline onCancel: handlePaymentCancel onError: handlePaymentError Session management callbacks onSessionExpired: handleSessionExpired onSessionTimedOut: handleSessionTimeout onSessionError: handleSessionError onServerUnavailable: handleServerUnavailable onInvalidData: handleInvalidData 3D Secure callbacks on3DS2Challenge: handle3DS2Challenge on3DS2Frictionless: handle3DS2Frictionless on3DS2Error: handle3DS2Error Apple Pay callbacks onApplePayAuthorized: handleApplePayAuthorized onApplePayCanceled: handleApplePayCanceled onApplePayError: handleApplePayError onApplePayValidation: handleApplePayValidation Google Pay callbacks onGooglePayAuthorized: handleGooglePayAuthorized onGooglePayCanceled: handleGooglePayCanceled onGooglePayError: handleGooglePayError onGooglePayValidation: handleGooglePayValidation PayPal callbacks onPaypalAuthorized: handlePayPalAuthorized onPaypalCaptured: handlePayPalCaptured onPaypalCanceled: handlePayPalCanceled onPaypalError: handlePayPalError onPaypalValidation: handlePayPalValidation UI/UX callbacks onBackToCart: handleBackToCart onStartInitialization: handleStartInitialization onEndInitialization: handleEndInitialization onPaySubmit: handlePaySubmit Callbacks supported General: onApprove : Callback for Approved card transaction, APM's (excluding ApplePay,GooglePay & PayPal), Token Transactions. onSuccess: Callback for successful operations such as Token Creation, Token Update, Card Hash operations. onDecline : When transactions are declined onCancel : When transaction has been cancelled (e.g. user has cancelled the 3DS2 challenge, or when an APM page has been cancelled) onError : Callback for error scenarios when attempting to process the request Session specific: onSessionExpired : Callback for when session is expired or invalid onSessionTimedOut : Callback to notify the checkout session timed out after configured timeout period. onServerUnavailable : Callback for when server becomes unavailable while precessing the transaction. onSessionError: Callback for when an error occurs within the checkout session itself onServerUnavailable : The payment server is temporarily unavailable. onInvalidData: Invalid or malformed data is submitted. 3DS2 specific: on3DS2Challenge : Handle 3DS2 challenge flow and display challenge interface to user on3DS2Frictionless: Handle frictionless 3DS2 authentication completion. on3DS2Error : An error occurs during 3D Secure 2.0 authentication. ApplePay, GooglePay & PayPal: onApplePayAuthorized : Callback for Approved Apple Pay transaction. onApplePayCanceled : Callback for when the user cancels an Apple Pay transaction. onApplePayError : Callback for error in processing an Apple Pay transaction. onApplePayValidation : Callback for validation response from Apple Pay. onGooglePayAuthorized : Callback for Approved Google Pay transaction. onGooglePayCanceled : Callback for when the user cancels a Google Pay transaction. onGooglePayError : Callback for error in processing a Goole Pay transaction. onGooglePayValidation : Callback for validation response from Google Pay. onPaypalAuthorized : Callback for Approved PayPal transaction. onPaypalCaptured : Callback for when Capture is completed for a PayPal transaction. onPaypalCanceled : Callback for when the user cancels a PayPal transaction. onPaypalError : Callback for error in processing a PayPal transaction. onPaypalValidation : Callback for validation response from PayPal. Hosted Checkout specific: onStartInitialization : Checkout initialization begins. onEndInitialization : Checkout initialization completes. UI/UX Callbacks: onBackToCart: User clicks "Back to Cart" or similar navigation. onPaySubmit: User submits payment and custom validation is required (only if callbackPaySubmit is enabled in session). Special Events Hosted checkout supports special events which allow merchants to have greater flexibility of the user experience. readyForPay(state) Signals to the checkout whether the merchant's page is ready for payment. true = merchant form is valid, payment can proceed. false = merchant form is invalid, payment should be blocked. Requires: waitForReadyState = true in the hosted checkout session configuration. How it works: Initially the ready state is false. As the user fills in merchant-side form fields, the merchant should validate and call readyForPay(true) once all fields are valid. If the user subsequently invalidates a field (e.g. clears a required input), the merchant should call readyForPay(false) to re-block payment. The merchant can call this method multiple times — the checkout respects the latest value. onPayNotReady(response) Triggered when waitForReadyState = true, the ready state is still false, and the user clicks any pay button (credit card or APM) within the checkout. Use case: Inform the user that the merchant-side form is incomplete, or highlight invalid fields. Pay Now: Purpose: Triggers payment processing from the parent window/merchant site for card payments. Triggered from: Merchant calls sdk.payNow() method How it works: When payNow() is called on the SDK, it posts a PAY_NOW message to the iframe. The iframe listens for this message and triggers the payment submission flow. This is useful when the pay button is hidden in the iframe and controlled from the parent page. This is required only if " showPayButon " is false within the hosted checkout session Pay Submit Validated Purpose: Sends validation result back to iframe after onPaySubmit callback How it works: After the onPaySubmit callback completes, the SDK posts this message back to the iframe with the validation result. The iframe then either proceeds with payment (if "SUCCESS") or cancels (for any other value). This is required only when "callbackPaySubmit" is true. Approved Response JSON { "type": "APPROVE", "data": { "authCode": "OK1249", "approvedAmount": "58.53", "accountFirst6": "499977", "accountLast4": "9004", "hostNetwork": "1", "expiryMonth": "12", "expiryYear": "2034", "cardHolderName": "sivam k", "avs": { "avsResult": "Y" }, "clientTransactionId": "88af81f2-6b37-4e6a-8105-46180b713c39", "transactionDateUtc": "2024-07-12T06:13:51.522Z", "tnsResponseCode": "00", "tnsResponseText": "TRANSACTION_APPROVED", "hostResponseCode": "00", "hostResponseText": "APPROVAL", "token": "6485251555209004", "status": "00: APPROVAL", "stan": "458045", "transactionId": "d75f422e-ec8a-44b2-84a2-7b5a94d9a1df", "subtotalAmount": "32", "totalAmount": "58.53", "surchargeAmount": "12.00", "taxAmount": "14.53", "requestId": "742ba5fd-679a-92d0-a275-30c3d79ba4f8", "successful": true } } • [Mandatory and Optional Content](https://developer.pay.tnsi.com/hosted-checkout/ecomm/hosted-checkout/mandatory-and-optional-content.md): Mandatory fields for Create Session Request Schema JSON { "sessionMode": "PERFORM_TRANSACTION", "transactionType": "PAYMENT", "transactionInitiator": "CARDHOLDER", "transactionMode": "ECOMMERCE", "merchantId": "M11000000000148", "order": { "lineItemList": [ { "lineItem": "4409", "lineItemDescription": "Sun Glasses", "quantity": 2, "lineItemCost": "10.00" } ], "metadata": [ { "name": "exampleKey1", "value": "exampleValue1" }, { "name": "exampleKey2", "value": "exampleValue2" } ] "country": "US", "currency": "USD", "subtotal": "20.00" }, "cardBrands": [ { "card": "VISA" }, { "card": "MASTERCARD" }, { "card": "AMEX" }, { "card": "DISCOVER" } ] } Mandatory Fields Note: The User-Agent header is required when calling the session creation endpoint from your server. Title Description Session Mode Specifies the purpose of the session request. Field: sessionMode PERFORM_TRANSACTION : Perform a payment transaction and generate a token for the card number. CREATE_TOKEN : Generate a token for the card number without running a payment transaction. UPDATE_TOKEN : Update the token information. GENERATE_CARDHASH : Allows a UI to be presented for card number and expiry entry, this will generate a one-way cardhash of the details Transaction Type Specifies what transaction to be performed. Field: transactionType PAYMENT : A sale transaction involves both authorization and capture of funds simultaneously, commonly utilized by merchants who provide goods instantly, such as retail stores where customers receive their purchases immediately. PRE_AUTH : An authorization transaction involves verifying the card's validity and ensuring sufficient funds in the cardholder's account without transferring funds. To complete the transfer from the cardholder to the merchant, the approved transaction must be captured. Merchants commonly use authorization transactions when goods are delivered post-purchase. ACCOUNT_VERIFICATION : Zero-value account verification enables merchants to check the status of an account and its validity without impacting their open-to-buy limit. Transaction Mode Specifies the payment channel. Field: transactionMode ECOMMERCE : The Hosted Checkout page is being request for online transaction in the checkout process of the merchant's website or application. MOTO : The Hosted Checkout page is being request to process a Mail-Order-Telephone-Order transaction. The default value is ECOMMERCE. Transaction Initiator Specifies who initiated the transaction. Field: transactionInitiator CARDHOLDER : The cardholder is accessing the checkout page to request the establishment of a session for using Hosted Checkout. MERCHANT : The merchant is requesting this session to process a transaction on behalf of the cardholder. When using Merchant, prior consent need to have been provided by the cardholder with an Stored Credential Agreemement Type according to VISA & Mastercard Scheme rules for the MIT Framework. The default value is CARDHOLDER. Merchant ID TNS provided unique merchant identifier Field: merchantId Merchant Identifier merchantId : This is the provided unique merchant identifier from TNS. This is not to be confused with the Financial Institutions Merchant ID as provided from the Acquirer. Order Information about the order items. At least one item should be provided. Field: order For more information on the order item list, please refer to Hosted Checkout Session Request section. There are optional order configuration to include tax and surcharges. Please refer to below Optional Fields and Configuration section of this page. Card Brand Field: cardBrand This is list of card brands to be displayed in the iframe & surcharge amount or percentage. It is essential to indicate the accepted card brands during the checkout process. Failure to include at least one brand will result in no cards being accepted. Card card : Card brand to be displayed in the checkout page. Optional Fields and Configurations JSON /*Optional Fields*/ { "order": { "cardBrands": [ { "card": "VISA", "surchargeAmount": "0.00" }, { "card": "MASTERCARD", "surchargeAmount": "0.00" }, { "card": "AMEX", "surchargePercentage": "0.00" }, { "card": "DISCOVER", "surchargePercentage": "0.00" }, { "card": "JCB", "surchargePercentage": "0.00" } ], "metadata": [ { "name":"meta1", "value":"value1" }, { "name":"meta2", "value":"value2" } ] }, "tax": "2.00" }, "displayConfig": { "theme": "light", "headerText": "The shades you need", "pageTitle": "Buy Sunglasses", "footerText": "Need receipt for returns", "logoUrl": "https://tnsi.com/wp-content/uploads/2022/09/brand.svg", "logoAltText": "TNS", "showCart":false, "showAmounts":true, "showHeaderBar":”false, "showFooterBar":false, }, "billingAddress": { "firstName": "John", "lastName": "Doe", "addressLine1": "123 Market Street", "city": "San Francisco", "state": "CA", "phone": "4155551234", "email": "john.doe@example.com", "zipCode": "94105", "country":"US" }, "shippingAddress": { "firstName": "John", "lastName": "Doe", "addressLine1": "123 Market Street", "city": "San Francisco", "state": "CA", "phone": "4155551234", "email": "john.doe@example.com", "zipCode": "94105", "country":"US" }, "storedCredentialAgreementType": "UNSCHEDULED", "cardAuthenticationMode": "AVS_OPTIONAL", "createCardHash": true, "hashTypes": [ "TRUNCATED_SALTED_SHA1_DECIMAL", "TRUNCATED_SALTED_SHA1_HEX", "TRUNCATED_SALTED_SHA1_DECIMAL_CREDIT", "SHA1_OF_SHA256" ] } The following table shows the different configuration options to customize the Hosted Checkout Iframe. All the fields are optional. Group Description Card Authentication Mode Card verification used for 3DS2 or AVSField: cardAuthenticationMode Default Value: NONE This field is to specify whether we need to perform card validation using AVS (Address Verification Service) or 3DS2 (3DSecure2). Note: AVS has limited acquirer support, predominantly within the United States. AVS_OPTIONAL : This value displays the address fields in the Hosted Checkout Iframe. The address fields will be optional for user to input. AVS_REQUIRED : This value displays the address fields in the Hosted Checkout Iframe. The address fields will be marked as mandatory. Without user enters the value in the address fields, the iframe will not allow to process the transaction. NONE : No card validation needs to performed. No address fields will be displayed in the iframe. Save Card Whether the card will be saved for future use. Field: allowToSaveCard This field is to specify whether the card will be saved for future usage using tokenization. The cardholder can select previously stored cards. Is is important that the user provides consent to store the card. allowToSaveCard : Hosted Checkout will display a checkbox allowing the user to save their card for future usage. Tokens Field: tokens This allows the merchant to provide a list of Token ID's which are to be displayed to the cardholder when presented with the hosted checkout page. The Token needs to have been provided in a prior transaction and stored within the same token vault for the customer. Up to 5 tokens can be be supplied. tokens : ["456445111111114564",""5432111111116432"] Stored Credential Agreement Type Field: storedCredentialAgreementType When choosing to store a card, concent needs to be obtained form the cardholder, including the reason for storing the card. A separate agreement will be required for each type of agreement. storedCredentialAgreementType : The following options are available: Unscheduled - For the purpose of a variable amount and variable frequency. Recurring - For the purpose of a fixed amount and frequency. A Merchant Initiated Transaction can be performed using the Online REST API. Instalment - For the purpose of splitting a transaction into instalments. Confirm with your TNS Account Manager if Instalments are supported with your acquirer of choice. Meta Data Field: metadata metadata metadata : This allows for transactional Meta Data allows for tagging additional information against a transaction. This can later be used for reporting or smart routing. The format is a name:value pair. A name should be unique and of a length no longer than 50. The value should not exceed a length of 100. A maximum of 50 name/value pairs can be included on a single transaction. key name : The name of the column key/column. value value : the value for the associated name Tax Additional amounts configuration Field: tax Tax tax : The absolute amount of tax computed. The tax is computed on the subtotal of the order. key pageTitle : This is the text to be displayed at the top of the iframe. Logo Image logoUrl : This is the url address of an image to displayed as the logo. The logo will be displayed at the top of the page, near the page title. Card Brand Field: cardBrand Surcharge amount and surcharge percentage are optional fields provided under each card brands. User may provide fixed surchargeAmount or surchargePercentage for specific card brands. Surcharge Amount surchargeAmount : Fixed surcharge amount for each card brand. Surcharge Percentage surchargePercentage : Applicable surcharged percentage for each card brand. Display Configuration Field: displayConfig The following are the fields to configure the appearance of the Hosted Checkout Iframe. Theme theme : Specifies whether to use dark theme or light theme. Allowed values are ‘dark’ and ‘light’. Default value is light. Page Title pageTitle : This is the text to be displayed at the top of the iframe. Logo Image logoUrl : This is the url address of an image to displayed as the logo. The logo will be displayed at the top of the page, near the page title. Logo Text logoAltText : This is the text to be displayed when the user hovers the mouse pointer over the logo image. Header headerText : This is the text to be displayed just below the page title. Header Bar showHeaderBar : Whether a bar is shown between the header text and the payment form within the iFrame. Footer footerText : This is the text to be displayed at the bottom of the iframe. Footer Bar showFooterBar : Whether a bar is shown between the footer text and the payment form within the iframe show amount showAmounts : true/false - Whether the transaciton amount and breakdown is displayed to the cardholder within the hosted checkout form. Use case for not displaying is if the amount is shown to the user outside of the payment form show cart showCart : Whether the items included in the cart are displayed to the user as part of the hosted checkout form Basket Icon showBasketIcon : true/false - Whether a basket icon is displayed when the cart functionality is enabled. Back to cart showbackToCartButton : true/false - Whether a back to cart option is displayed to the cardholder Back to cart label backToCartButtonLabel : The button label to show to the cardholder Save card label allowToSaveCardLabel : The label displayed to the cardholder when they check whether the card will be saved for future transactions Wait for ready state waitForReadyState - When true, the checkout page will not allow payment submission until the merchant signals readiness via callback readyForPay(true). Use this when the merchant page has its own form fields that must be validated before payment can proceed. Enable Pay After Ready - enablePayAfterReady Works with waitForReadyState only. When true, all pay buttons within the checkout iFrame are disabled until readyForPay(true) is called. Local local : This field is required for Apple Pay and Google Pay and is also used to set the language that Hosted Checkout will use for field labels and messaging to the end user. Billing Address Field: billingAddress This billing address will be used for the purposes of 3DS2 Authentication or Address Verification Services (AVS) if enabled. firstName : Customer’s first name. This name must be the same as the name on the card. lastName : Customer’s last name. This name must be the same as the name on the card. addressLine1 : The billing address in which the cardholder is located. addressLine2 : Used for additional address information. addressLine3 : Used for additional address information. city : Locality or city in the billing address state : The state or administrative area code for the country (in ISO 3166-2 format). e.g. CA phone : The email : The email address of the billing contact zipCode : The zip code/post code of the billing contact. country : The country code for the billing address (in ISO 3166-1 alpha-2 code) e.g. US Shipping Address Field: shippingAddress This billing address will be used for the purposes of 3DS2 Authentication or Address Verification Services (AVS) if enabled. firstName : Customer’s first name of the recipeint of the goods. lastName : Customer’s last name of the recipient of the goods addressLine1 : The shipping address of the goods addressLine2 : Used for additional address information. addressLine3 : Used for additional address information. city : Locality or city of the shipping address state : The state or administrative area code for the country (in ISO 3166-2 format). e.g. CA phone : The phone number associated with the shipping address email : The email address of the recipient of the goods zipCode : The zip code/post code associated with the shipping address. country : The country code of the goods (in ISO 3166-1 alpha-2 code) e.g. US Card Hash Field: createCardHash A cardhash (one way hash) of the PAN/Expiry Date to uniquely identify a card createCardHash : true/false Cardhash Types Field: hashTypes Please contact TNS for more information on different card hash types. • [Google Pay](https://developer.pay.tnsi.com/hosted-checkout/ecomm/hosted-checkout/alternative-payment-methods/google-pay.md): To support the Google Pay payment method in Hosted Checkout, it must be enabled for the merchant in the TNS Merchant Configuration. This can be activated through the Merchant Portal. Additionally, the client-side script must implement the Google Pay callback methods as part of the Hosted Checkout initialization. How It Works The Hosted Checkout will display Google Pay buttons within the iframe. When the customer clicks on the Google Pay button, the Google Pay checkout page appears. The customer chooses a card from his/her Google Wallet for this payment transaction. After the payment is completed at the Google Pay checkout, the onGooglePayAuthorized callback is specified in the hostedCheckoutSdk.initialize method will trigger the transaction response. If the transaction type is PAYMENT , The TNS system immediately captures the authorization. If the transaction type is PRE_AUTH , the TNS system will not capture the payment immediately. Instead, the merchant can capture the transaction later through the Merchant Portal. The callback methods are onGooglePayAuthorized onGooglePayError onGooglePayCanceled onGooglePayAuthorized This callback is invoked on successful Google Pay transaction JSON { "type": "GOOGLE_PAY_AUTHORIZED", "data": { "authCode": "OK5250", "approvedAmount": "250.00", "accountFirst6": "411111", "accountLast4": "1111", "hostNetwork": "1", "expiryMonth": "12", "expiryYear": "2027", "cardHolderName": "GooglePay", "clientTransactionId": "9f7de94b-8734-45ff-9831-352c92b64a33", "transactionDateUtc": "2025-06-30T11:04:03", "tnsResponseCode": "00", "tnsResponseText": "TRANSACTION_APPROVED", "hostResponseCode": "000", "hostResponseText": "APPROVAL", "token": "4111116558031111", "status": "success", "stan": "327197", "transactionId": "b34c56d5-85fe-4562-ad54-3bbef5c77727", "requestId": "43136627-263d-9f4a-b0cb-5770b885a33f", "responseType": "GooglePay", "successful": true } } onGooglePayError This callback is invoked when the there is an error in process the Google Pay transaction. The error object is passed as a parameter in the callback. JSON { "type": "GOOGLE_PAY_ERROR", "data": { "approvedAmount": "0.00", "accountFirst6": "411111", "accountLast4": "1111", "hostNetwork": "1", "expiryMonth": "12", "expiryYear": "2026", "cardHolderName": "GooglePay", "clientTransactionId": "0af08b31-abc8-462e-b84c-7b7ad96b6645", "transactionDateUtc": "2024-07-31T15:21:18.644Z", "tnsResponseCode": "AV234", "tnsResponseText": "PRE-AUTHORISATION FAILED", "hostResponseCode": "A1", "hostResponseText": "DBT T.O. RETRY", "status": "failure", "stan": "907293", "transactionId": "4c292eef-6797-4018-be24-ea27bb66e7b2", "requestId": "bfd2a70a-ae82-9f6d-ab04-310b55a3070d", "responseType": "GooglePay", "successful": false } } onGooglePayCanceled This callback is invoked when user cancels the transaction in the Google Pay checkout page. There is no parameters for this callback method. Google Pay Test Cards Enabling Google Pay TEST environment integrations with realistic test card data requires joining the googlepay-test-mode-stub-data Google Group. This grants access to the built-in test card suite when your frontend is configured with environment: 'TEST'. Prerequisites A Google account (either personal or test-specific) logged into your browser. Your integration targets the TEST environment using PaymentsClient or equivalent with: environment: 'TEST' Basic familiarity with your platform's Google Pay setup (Web, Android, iOS, etc.). Step-by-Step Guide Visit the following link and join the group: Group Link Verify Access: With the same Google account, initiate a payment with your app or a Google Pay sample page. In the payment sheet, you should now see test cards (AMEX, VISA, MasterCard, DISCOVER) and U.S.-based billing/shipping addresses. For more details or demo visit: https://developers.google.com/pay/api/web/guides/resources/demos Leaving the Group (Optional): To revert to your live card data for TEST environment, go back to the group page My membership settings Leave group. Once removed, the test suite is disabled and your real cards reappear, though still in the TEST environment. Integration Checklist - Why This Matters The test card suite is critical to complete Google's integration checklist, verifying flows without using real cards. Mock cards are typically limited to PAN_ONLY and U.S.-style addresses. Troubleshooting If no test cards show up: Confirm your app is using environment: 'TEST'. Make sure you're logged in with the correct Google account. Try leaving and rejoining the group or re-logging into the Google Play services/app. • [Apple Pay](https://developer.pay.tnsi.com/hosted-checkout/ecomm/hosted-checkout/alternative-payment-methods/apple-pay.md): To support the Apple Pay payment method in Hosted Checkout, it must be enabled for the merchant in the TNS Merchant Configuration. This can be activated through the Merchant Portal. Additionally, the client-side script must implement the Apple Pay callback methods as part of the Hosted Checkout initialization. How It Works The Hosted Checkout will display Apple Pay buttons within the iframe. When the customer clicks on the Apple Pay button, the Apple Pay checkout page appears. The customer chooses a card from his/her Apple Wallet to use for this payment transaction. After the payment is completed at the Apple Pay checkout, the onApplePayAuthorized callback is specified in the hostedCheckoutSdk.initialize method will trigger the transaction response. If the transaction type is PAYMENT , The TNS system immediately captures the authorization. If the transaction type is PRE_AUTH , the TNS system will not capture the payment immediately. Instead, the merchant can capture the transaction later through the Merchant Portal. The callback methods are onApplePayAuthorized onApplePayError onApplePayCanceled onApplePayAuthorized This callback is invoked on a successful Apple Pay transaction JSON { "type": "APPLE_PAY_AUTHORIZED", "data": { "authCode": "OK3099", "approvedAmount": "39.13", "accountFirst6": "481436", "accountLast4": "5999", "hostNetwork": "1", "expiryMonth": "08", "expiryYear": "2030", "cardHolderName": "ApplePay", "clientTransactionId": "5cd4359c-a5eb-4151-a838-19e0fabefde8", "transactionDateUtc": "2024-08-02T16:19:56.173Z", "tnsResponseCode": "00", "tnsResponseText": "TRANSACTION_APPROVED", "hostResponseCode": "00", "hostResponseText": "APPROVAL", "token": "8773771191205999", "status": "success", "stan": "503470", "transactionId": "2e0ad975-54d5-4a41-8234-9beca177f26f", "requestId": "dacd153e-7c71-956a-8f38-ff01ba3810b9", "successful": true } } onApplePayError This callback is invoked when the there is an error in process the Apple Pay transaction. The error object is passed as a parameter in the callback. onApplePayCanceled This callback is invoked when user cancels the transaction in the Apple Pay checkout page. There is no parameters for this callback method. • [PayPal](https://developer.pay.tnsi.com/hosted-checkout/ecomm/hosted-checkout/alternative-payment-methods/paypal.md): To support the PayPal payment method in Hosted Checkout, it must be enabled for the merchant in the TNS Merchant Configuration. This can be activated through the Merchant Portal. Additionally, the client-side script must implement the PayPal callback methods as part of the Hosted Checkout initialization. How It Works The Hosted Checkout will display PayPal buttons within the iframe. When the customer clicks on the PayPal button, the PayPal checkout page appears. The customer must log into their PayPal account to complete the payment. Once the payment is finalized at the PayPal checkout, depending on the transaction type specified in the session creation request, the appropriate PayPal callbacks will be triggered with the transaction response. In the session creation request, if the transaction type is specified as PAYMENT , the authorized PayPal transaction will be captured. Upon successful capture, the onPaypalCaptured callback, as outlined in the hostedCheckoutSdk.initialize method will be invoked with the PayPal response. If the transaction type is PRE_AUTH , the TNS system will not capture the payment immediately, the onPaypalAuthorized callback specified in the hostedCheckoutSdk.initialize method will trigger with the PayPal response. The merchant can capture the PayPal transaction later through the Merchant Portal. The callback methods are onPaypalAuthorized onPaypalCaptured onPaypalCanceled onPaypalAuthorized This callback is called when the transactions is authorized by PayPal. JSON { "orderId": "7D6165341G568664S", "merchantId": "M11000000000148", "paypalResponse": { "status": "Payment successful", "orderId": "37B83453PG742964R", "transactionId": "6f4d8d23-32b5-425d-b80f-a90cab02562d", "tnsResponseText": "TRANSACTION_APPROVED", "hostResponseText": "COMPLETED", "receiptData": "5KIDUJ", "requestId": "31aed4a5-8732-9868-9816-6bc89d68684e" } } onPaypalCaptured This callback is called, when the authorized PayPal transaction is captured by TNS system. JSON { "orderId": "7D6165341G568664S", "merchantId": "M11000000000148", "paypalResponse": { "status": "Payment successful", "orderId": "5T586626AG526770E", "transactionId": "77c5111e-d106-4fb3-81c6-d7e498a27ede", "tnsResponseText": "TRANSACTION_APPROVED", "hostResponseText": "COMPLETED", "receiptData": "YR753W", "requestId": "7c0853a0-5883-9373-8d50-e03def95fefb" } } onPaypalCanceled This callback is invoked when user cancels the transaction in the PayPal checkout page. There is no parameters for this callback method. • [Custom CSS](https://developer.pay.tnsi.com/hosted-checkout/ecomm/hosted-checkout/custom-css.md): Through the use of an App-custom.css file, merchants can tailor the look and feel of the hosted checkout to better align with the website which the hosted checkout would be embedded. This includes styling of colors, borders, input fields, buttons, dividers, and section. By offering controlled CSS overrides without exposing sensitive payment logic, Hosted Checkout strikes a balance between security and flexibility—enabling merchants to deliver a branded checkout journey that feels seamlessly integrated with their site while preserving the integrity of the payment flow. Guide All the changes listed below can be implemented in the App-custom.css file. Background Color & Text Color The background-color property sets the background color of the body, and the color property sets the text color for all content on the page. CSS body{background-color: #BED9C4;color: #000;} Outline Border The outer border color of this section can be changed through above CSS. CSS .tnsi-payment-options-div {border: 1px solid #aaa;} Input Fields The background-color property sets the background color of the input fields, the color property sets the text color of the user’s input, and the border-color property sets the border color of the input fields. These styles apply to all input fields in the hosted checkout. CSS .tnsi-input-box { border: 1px solid #A1BDA7 !important; background-color: #DFF0E3 !important; color: #000000 !important; } Input Fields - Placeholder text color The color property sets the placholder color of the user’s input CSS .tnsi-input-box::placeholder{ color: #959595; } Input Fields - on focus This CSS applies when the input is focused—that is, when the user clicks on the input to type, the input’s style changes accordingly. CSS .tnsi-input-box:focus { border-color: #557e5d !important; box-shadow: none !important; background-color: #DFF0E3 !important; } Button Colors - General This color is applied to the text that appears with the horizontal bar. The button’s background color and text color can be customized here to any color desired. CSS .tnsi-button button.pay-button:hover { background-color: #fff; color: #000; } Button Colors - Hover When we hover over the button them from above css background color and color will change CSS .tnsi-button button.pay-button:hover { background-color: #fff; color: #000; } Saved Card Logo This CSS applies to the icon, allowing us to change the image background color and adjust the border radius CSS .tnsi-saved-card-div .tnsi-saved-card-image{ background-color: #fff; border-radius: 24px; } Express Checkout Styling - Text This color is applied to the text that appears with the horizontal bar. CSS .horizontal-ruler-with-text span { color:#000 } Express Checkout Styling - Border The border color can be managed using the CSS defined above. CSS .horizontal-ruler-with-text hr { border-color: #aaa; } Footer - Border This property sets the color of the top border. CSS .footer { border-top: 1px solid #3b3c3c; } Main Title The border of the title section can be customized from this css. CSS .tnsi-page-title { border-bottom: 1px solid #3b3c3c; } Shopping Cart - Background & border This section allows customization of both the background color and the border. CSS .tnsi-shopping-item-list { border: 1px solid #aaa; background-color: #DFF0E3; } Shopping Cart -Divider This section allows you to control the color of all borders. CSS .section-hr { border-top: 1px solid #aaa; } • [Payment & Token APIs](https://developer.pay.tnsi.com/hosted-checkout/ecomm/online-rest-api.md): The TNS PayOrch platform provides a range of APIs specifically created for handling online card-not-present transactions across multiple channels such as websites, mobile applications, shopping cart checkout pages, and telephone transactions. Through TNS's APIs, users can effectively oversee the complete lifecycle of online transactions and produce detailed reports for customers via our PayOrch Merchant Portal. For a list of supported transaction types, see our Online REST API documentation. Additionally, you have the opportunity to explore each transaction type using our API Explorer. • [Account Verification](https://developer.pay.tnsi.com/hosted-checkout/ecomm/online-rest-api/primary-transactions/account-verification.md): Account Verification (sometimes referred to as Zero-Authorization) is a transaction which is best practice to confirm that a payment card is valid and can be used for future transactions without placing a financial charge on the cardholder. Typically performed as a zero-authorization (Account Verification) transaction, it validates key card details such as the card number, expiry date, and security checks with the issuer while verifying that the account is active and available for use. Merchants commonly use Account Verification to: Store card credentials for future use in compliance with card scheme requirements. Register a card on a customer account before future billing, such as subscriptions, delayed charges, or trial periods. Verify card validity and customer intent without requiring an immediate payment, helping reduce fraud and failed future transactions. Because no funds are captured and typically no hold is placed on the cardholder's account, Account Verification provides a secure, low-friction method for confirming card details before subsequent merchant-initiated or customer-initiated transactions occur. All REST API calls are authenticated using HMAC. See Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Authorization](https://developer.pay.tnsi.com/hosted-checkout/ecomm/online-rest-api/primary-transactions/authorization.md): An authorization transaction is conducted to validate a card with the cardholder's issuing bank and confirm the card's validity and available funds. This process does not instantly transfer funds but temporarily reserves the funds in the cardholder's account if sufficient fund is available. To complete the transfer from the cardholder's account to the merchant's account, the authorized transaction must be captured . The captured amount may be equal or lower than the authorized sum. TNS only supports a single Capture transaction for an Authorization. If the merchant wishes to capture an amount higher than the authorized sum, they have the option to conduct an Incremental Authorization transaction using the authorized amount as a base and then proceed to capture the total amount comprising the authorized sum and the incremental value. Authorization transactions are commonly used by merchants in situations where goods are dispatched post-purchase, or where the final amount is unknown when the initial authorization takes place. There is limited availability of Incremental Authorizations depending on the merchants industry, card type and acquirer used. Please contact TNS if you require further information. The provided transaction sample outlines the necessary mandatory fields for approval. For more information on additional functionality and optional fields, see Request Format . For more information on all possible responses, success and error codes, see Response Format . All REST API calls are authenticated using HMAC. See Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Sale](https://developer.pay.tnsi.com/hosted-checkout/ecomm/online-rest-api/primary-transactions/sale.md): A sale transaction can be explained as authorization and capture of funds at the same time. The sale transactions are usually used by merchants who deliver the goods almost immediately like retail stores where the customer receives the goods immediately. In ecommerce scenario, the user or the cardholder directly enters the card data during the checkout process. In the payment information section of the request, the card details are provided in the respective fields. The sample transaction here lists the required mandatory fields to get the transaction approved. The provided transaction sample outlines the necessary mandatory fields for approval. For more information on additional functionality and optional fields, see Request Format . For more information on all possible responses, success and error codes, see Response Format . All REST API calls are authenticated using HMAC. See Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Capture](https://developer.pay.tnsi.com/hosted-checkout/ecomm/online-rest-api/secondary-transactions/capture.md): A capture or otherwise known as completion transaction, is to finalize the original authorization transaction. The original authorization transaction identifier and the authorized amount are mandatory to process a capture transaction. For more info on additional functionality and optional fields, see Request Format . For more information on all possible responses, success and error codes, see Response Format . All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. To test this sample capture request, start by initiating an authorize transaction. Upon approval of the authorize transaction, retrieve the transactionId & approvedAmount from the response. Use the transactionId as the originalTransactionId and approvedAmount as the originalTransactionAmount before proceeding with the transaction. Use transactionAmount to capture the desired transaction value. Entry mode is optional for capture transactions. The system will utilize the entry mode of the original transaction unless specifically overwritten in the request. • [Refund](https://developer.pay.tnsi.com/hosted-checkout/ecomm/online-rest-api/secondary-transactions/refund.md): A refund transaction is where the merchant wishes to refund an original credit card transaction to the customer. It allows merchants to reimburse customers for returned merchandise, canceled services, or other situations where a refund is warranted. In the linked refund original transaction identifier has to be provided. A linked refund can be a partial or full amount of the original transaction. There can be multiple partially linked refunds for a single transaction. For more info on additional functionality and optional fields, see Request Format . For more information on all possible responses, success and error codes, see Response Format . All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. To test this sample linked refund request, start by initiating a sale transaction. Upon approval of the sale transaction, retrieve the transactionId & approvedAmount from the response. Use the transactionId as the originalTransactionId and approvedAmount as optionally the originalTransactionAmount before proceeding with the transaction. You can also optionally provide the token for the transaction. Not including the token will fall back to retrieving the payment details from the original transaction. Entry mode is optional for linked-refund transactions. The system will utilize the entry mode of the original transaction unless specifically overwritten in the request. • [Reversal](https://developer.pay.tnsi.com/hosted-checkout/ecomm/online-rest-api/secondary-transactions/reversal.md): Reversal, also known as authorization reversal, occurs when an authorization is initially granted but subsequently reversed, either in full or in part, due to factors such as product/service unavailability, fraudulent transactions, or customer change of mind. For more info on additional functionality and optional fields, see Request Format . For more information on all possible responses, success and error codes, see Response Format . All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. To test this sample reversal request, start by initiating an authorize transaction. Upon approval of the authorize transaction, retrieve the transactionId & approvedAmount from the response. Use the transactionId as the originalTransactionId and approvedAmount as the originalTransactionAmount before proceeding with the transaction. Entry mode is optional for reversal transactions. The system will utilize the entry mode of the original transaction unless specifically overwritten in the request. • [Void](https://developer.pay.tnsi.com/hosted-checkout/ecomm/online-rest-api/secondary-transactions/void.md): Void transactions are conducted on a sale transaction. To reverse a sale transaction before settlement takes place, the merchant must initiate a void transaction, referencing the original sale transaction. The void transaction amount should exactly match the original transaction amount. Partial void is not supported by the system. For more info on additional functionality and optional fields, see Request Format . For more information on all possible responses, success and error codes, see Response Format . All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. To test this sample void request, start by initiating a sale transaction. Upon approval of the sale transaction, retrieve the transactionId & approvedAmount from the response. Use the transactionId as the originalTransactionId and approvedAmount as the originalTransactionAmount before proceeding with the transaction. Entry mode is optional for void transactions. The system will utilize the entry mode of the original transaction unless specifically overwritten in the request. • [Incremental](https://developer.pay.tnsi.com/hosted-checkout/ecomm/online-rest-api/secondary-transactions/incremental.md): An Incremental transaction adjusts the original authorization amount when there is a change in the total transaction amount. This type of transaction is typically used in scenarios where the final cost of goods or services cannot be accurately predicted at the time of the initial authorization. For more information on all possible responses, success and error codes, see Response Format . All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. To test this sample incremental request, start by initiating an authorize transaction. Upon approval of the authorize transaction, retrieve the transactionId from the response. Use the transactionId as the originalTransactionId as the before proceeding with the transaction. transactionAmount should be used as the incremented amount. • [Token-Based Authorization](https://developer.pay.tnsi.com/hosted-checkout/ecomm/online-rest-api/token-transactions/token-based-authorization.md): An authorization transaction is conducted to validate a card with the cardholder's issuing bank and confirm the card's validity and available funds. This process does not instantly transfer funds but temporarily reserves the funds in the cardholder's account if sufficient fund is available. To complete the transfer from the cardholder's account to the merchant's account, the authorized transaction must be captured. The captured amount may be lower than the authorized sum, and merchants can choose to capture portions of the authorized amount on multiple occasions. Also, if the merchant wishes to capture an amount higher than the authorized sum, they have the option to conduct an incremental transaction using the authorized amount as a base and then proceed to capture the total amount comprising the authorized sum and the incremental value. Authorization transactions are commonly employed by merchants in situations where goods are dispatched post-purchase. In token-based authorization, card information is not required. Instead, a token value must be provided, which can be acquired from any previous transactions. The provided transaction sample outlines the necessary mandatory fields for approval. For more info on additional functionality and optional fields, see Request Format . For more information on all possible responses, success and error codes, see Response Format . All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Token-Based Sale](https://developer.pay.tnsi.com/hosted-checkout/ecomm/online-rest-api/token-transactions/token-based-sale.md): A sale transaction can be explained as authorization and capture of funds at the same time. The sale transactions are usually used by merchants who deliver the goods almost immediately like retail stores where the customer receives the goods immediately. In token-based sale transactions, card information is not required. Instead, a token value must be provided, which can be acquired from any previous transactions. The provided transaction sample outlines the necessary mandatory fields for approval. For more info on additional functionality and optional fields, see Request Format . For more information on all possible responses, success and error codes, see Response Format . All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Token-Based Merchant Initiated Sale](https://developer.pay.tnsi.com/hosted-checkout/ecomm/online-rest-api/token-transactions/token-based-merchant-initiated-sale.md): This is a Merchant Initiated Transaction, where the merchant has obtained prior agreement to perform transactions on behalf of the customer. In token-based sale transactions, card information is not required. Instead, a token value must be provided, which can be acquired from any previous transactions. The provided transaction sample outlines the necessary mandatory fields for approval. For more info on additional functionality and optional fields, see Request Format . For more information on all possible responses, success and error codes, see Response Format . All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Token-Based Refund](https://developer.pay.tnsi.com/hosted-checkout/ecomm/online-rest-api/token-transactions/token-based-refund.md): A refund transaction is where the merchant has to return the money to the customer. It allows merchants to reimburse customers for returned merchandise, canceled services, or other situations where a refund is warranted. When perforing a refund when linked to an original transaction, you will need to provide the originalTransaction group with the originalTransactionId as returned from the original transaction where payment was performed. An unlinked refund, also known as a standalone refund, is a type of refund transaction where the refund is not directly associated with a specific previous transaction. Instead, it is processed as a separate, standalone refund transaction without any direct reference to a previous purchase. Unlinked refunds are commonly used in situations where the refund amount is not tied to a specific previous transaction or where the merchant prefers to process refunds independently of the original transaction. For example, if a customer requests a refund for a subscription fee or membership dues, the merchant may issue an unlinked refund without referencing a specific purchase transaction. In token-based refund transactions, card information is not required. Instead, a token value must be provided, which can be acquired from any previous transactions. The provided transaction sample outlines the necessary mandatory fields for approval. For more info on additional functionality and optional fields, see Request Format . For more information on all possible responses, success and error codes, see Response Format . All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Pay By Link](https://developer.pay.tnsi.com/hosted-checkout/ecomm/pay-by-link.md): Create and send secure, customizable payment links that allow merchants to collect payments from customers via email or SMS. These links direct customers to a hosted payment page where they can complete transactions using their preferred payment methods, with options to tailor messaging, redirect URLs, and link validity for a seamless payment experience. Overview Pay By Link enables merchants to collect payments from customers by sending a secure payment link via email or SMS. The customer clicks the link, which opens a hosted payment page where they can complete the transaction using their preferred payment method. The transaction amount, message displayed to the user and optional redirects can be customized to tailor the customer experience. This eliminates the need for merchants to build and maintain their own checkout pages or process sensitive card data, reducing PCI scope and operational complexity. 1 Merchant creates PayByLink session (via Portal or API) A PayByLink session can be generated either manually via the TNS Merchant Portal, or via an API Integration for those with a software development team. The below is an example of how a Pay By Link - 2 Customer Receives Link via Email, SMS or Both The link will be received near real-time via the delivery method selected. The text included within the email and SMS can be customized. 3 Customer clicks link → TNS Hosted Payment Page opens TNS Hosted Payment Page will be presented with your specific branding and logos. 4 Customer selects payment method and enters details The customer will enter their credit card details to perform payment. Alternatively they can select one of the Alternative Payment Methods that TNS supports. Here is an example where Credit Card & GooglePay have been enabled: 5 3DS2 Secure authentication (if applicable) For Credit Card Transactions, 3DS2 Authentication can be enabled if required. 6 Payment processed The payment will be processed according to the payment method the cardholder selected. 7 Customer will see the result message OR is redirected to merchant URL Once completed, there are two options available depending on your preference. Redirect the user to your webpage. A different landing page should be made available for Approved, Declined or Error Transaction results. The TNS Hosted Payment Page can show a customized message to the customer. For example - Thank you for your payment. Here is a sample of the transaction result page: 8 Merchant receives payment confirmation The merchant can monitor transaction reports which TNS makes available for all merchants. Alternatively, you can have webhook events enabled, this delivers transaction results in near real-time to your backend server. An example of the PayByLink Report can be seen below. You can also Resend the link if it has expired. Key Features Benefit Description No Website Required Accept payments without having to writing code to integrate your website to perform payments Reduced PCI Scope Card data is handled entirely by the hosted payment page Multi-Channel Delivery Send links via email, SMS, or retrieve the URL directly. This can be also be turned into a QR Code Customisable Branding Control over logos, branding, and basic text/colors Flexible Expiry Links can be configured to expire after minutes or days Digital Wallet Support Google Pay, Apple Pay, and PayPal available on the payment page 3DS2 for secure fraud protection Optional built into the form to provide strong customer authentication to combat fraud Optional Card Storage Optional tokenization for future transactions Use Cases Call Centre / Phone Orders Send a payment link during or after a phone call instead of taking card details verbally (MOTO). Reduces fraud risk and PCI compliance burden. Email Invoicing Embed a payment link directly in digital invoices for immediate payment collection. Social Media / Messaging Share links via WhatsApp, Facebook Messenger, or any messaging platform to enable conversational commerce. In-Store Hybrid Accept a deposit in-store, then follow up with a Pay By Link for the remaining balance. Recurring Payment Setup Use the initial Pay By Link transaction to tokenize a card, then process future recurring payments using the stored token. Ad-hoc Charges Quickly generate a link which can be shared to your customers for any purpose your business requires Supported Features Delivery Methods Email Link sent via email to the customer's email address SMS Link sent via SMS to the customer's phone number QR Turn the link into a QR code to accept payments from a users mobile device Digital Wallets ApplePay & GooglePay Ability to enable ApplePay & GooglePay eCommere methonds to the customer PayPal PayPal can be enabled on the page, allowing seamless integration and acceptance Additional APM's TNS has access to hundreds of APM's globally. If there is a specific APM which within your region that you would like to accept, please contact the TNS Sales team. Link Expiry PayByLink sessions can have a specific expiry duration, depending on your business needs. Title Description Unit Description Minute Link expires after specified number of minutes (e.g., 20 minutes) Day Link expires after specified number of days Display & Branding Configuration The payment page appearance is fully customisable: Title Description Element Description Header Text Custom text displayed at the top of the page Logo URL Merchant logo displayed on the payment page Page Title Browser tab/page title Footer Text Custom text in the footer area Pay Button Label Custom label for the payment button Cancel Button Label Custom label for the cancel/back button Result Messages Custom messages displayed to the customer after payment completion. These will only be displayed if you do not support Redirect URL's to your own website. Title Description Scenario Configurable Message (examples) Approved "Transaction is Approved. Contact Merchant for more details" Declined "Transaction is Declined. Contact Merchant for more details" Error "Transaction Error. Contact Merchant for more details" Link Expired "Link Expired. Contact Customer Care" Redirect URLs After payment completion, customers can optionally be redirected to merchant-controlled URLs: Title Purpose approvedUrl Customer redirected here on successful payment declinedUrl Customer redirected here if payment is declined errorUrl Customer redirected here on payment error cancelUrl Customer redirected here if they cancel the payment When a redirect occurs to your website after a user had attempted to pay, additional parameters will be included in the redirect url. The parameters included in the URL redirect include: Parameter Description status The status of the transaction. e.g. approved, declined event The callback event that occured after processing the transaction sessionId The session id for the PayByLink Session transactionId The transactionId returned for the transaction dateTime The date/time in which the transaction was performed referenceId merchantReference passed while creating pay by link session It's important that the parameters included on a redirect url are not used for assessing the approval/decline of the transaction as these are client side and can be manipulated by users. instead you should rely on the Webhook Notification directly to your server, status check call, or reports from our merchant portal Note: URLs can be configured by TNS as part of your setup which will take precedance over those supplied in your PayByLink Session Metadata Merchants can optionally attach custom key-value metadata to each payment link for reconciliation and tracking purposes. This information can then be enabled in the Merchant Portal for reporting purposes. One or more custom key-value pairs can be associated with a transaction. JSON "metadata": [ { "name": "Order", "value": "product" } ] API Specification API Endpoint Description https://checkout.uat.pay.tnsi.com/v1/session/paybylink/create UAT Pre-production https://checkout.ap.paymentgateway.tnsi.com/v1/session/paybylink/create LIVE - Production Asia Pacific https://checkout.eu.paymentgateway.tnsi.com/v1/session/paybylink/create LIVE - Production Europe https://checkout.us.paymentgateway.tnsi.com/v1/session/paybylink/create LIVE - Production North America • [Recurring Payments](https://developer.pay.tnsi.com/hosted-checkout/ecomm/recurring-payments.md): The TNS Recurring Payments API empowers businesses to seamlessly manage subscription-based and repeat billing models with secure, automated transactions. Designed for scalability and compliance, this API enables merchants to store customer payment credentials securely using tokenization, and initiate recurring charges without requiring repeated customer input. By integrating with the Recurring Payments API, businesses can streamline their payment workflows, reduce friction in the customer experience, and ensure consistent revenue collection—all while maintaining PCI DSS compliance and leveraging robust authentication protocols. • [Credit Card Recurring Payment](https://developer.pay.tnsi.com/hosted-checkout/ecomm/recurring-payments/credit-card-recurring-payment.md): This request creates a Recurring Payment Schedule using a credit card. The given payment method must be specified as CREDITCARD. The credit card number will be tokenized and a recurring schedule will be created. All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Token Recurring Payment](https://developer.pay.tnsi.com/hosted-checkout/ecomm/recurring-payments/token-recurring-payment.md): This request is to create a Recurring Payment Schedule using a token instead of real card data. The given payment method must be specified as CREDITCARD. All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Update Recurring Payment](https://developer.pay.tnsi.com/hosted-checkout/ecomm/recurring-payments/update-recurring-payments.md): This request updated a Recurring Payment schedule. Please see the following sample request for all the possible fields that can be updated. All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Update Recurring Token Payment](https://developer.pay.tnsi.com/hosted-checkout/ecomm/recurring-payments/update-recurring-token-payment.md): This request updated a Recurring Payment schedule. Please see the following sample request for all the possible fields that can be updated. All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Search Recurring Payment](https://developer.pay.tnsi.com/hosted-checkout/ecomm/recurring-payments/search-recurring-payment.md): Recurring payment search allows users to identify existing recurring payment plans based on various criteria. For more information regarding the available search filters, please refer to the API documentation section below. All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Get Recurring Payment](https://developer.pay.tnsi.com/hosted-checkout/ecomm/recurring-payments/get-recurring-payment.md): This request is to retrieve an existing Recurring Payment schedule from our system. All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Create Daily Recurring Payment](https://developer.pay.tnsi.com/hosted-checkout/ecomm/recurring-payments/create-daily-recurring-payment.md): This request sets up a Daily Recurring Payment Schedule using a credit card. The payment method must be designated as CREDITCARD. The provided credit card number will be tokenized, and a Recurring Payment Schedule will be created based on this tokenization. This example request establishes a Daily Recurring Payment Schedule to charge the specified card every day, starting from 15th June 2024 and continuing until 15th September 2024. All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Create Weekly Recurring Payment](https://developer.pay.tnsi.com/hosted-checkout/ecomm/recurring-payments/create-weekly-recurring-payment.md): This request sets up a Weekly Recurring Payment Schedule using a credit card. The payment method must be designated as CREDITCARD. The provided credit card number will be tokenized, and a Recurring Payment Schedule will be created based on this tokenization. This example request sets up a Weekly Recurring Payment Schedule to charge the specified card every Monday, starting from 17th June 2024 and continuing until 12th December 2024. All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Create Monthly Recurring Payment](https://developer.pay.tnsi.com/hosted-checkout/ecomm/recurring-payments/create-monthly-recurring-payment.md): This request sets up a Monthly Recurring Payment Schedule using a credit card. The payment method must be specified as CREDITCARD. The provided credit card number is tokenized, and a Recurring Payment Schedule is established. This example request schedules a recurring charge on the 5th of each month, starting from 15th June 2024 and continuing until 15th June 2025. All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Create Yearly Recurring Payment](https://developer.pay.tnsi.com/hosted-checkout/ecomm/recurring-payments/create-yearly-recurring-payment.md): This request creates a Yearly Recurring Payment Schedule using a credit card. The payment method must be specified as CREDITCARD. The provided credit card number is tokenized, and a Recurring Payment Schedule is established based on this token. This example request sets up a Recurring Payment Schedule to charge the specified card annually on the 1st of July, starting from the 23rd of May 2024. The payment will recur five times, concluding effectively on the 1st of July 2028. In this request, instead of specifying an ending date, we have indicated the number of times the payment should recur using the field frequency . All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Webhook Notifications](https://developer.pay.tnsi.com/hosted-checkout/supporting-apis/webhook-notifications.md): Webhook Notifications deliver real-time HTTP POST callbacks to your server when payment events occur on the TNS Payment Orchestration platform. Instead of polling for transaction status, your system receives instant notification when a payment is approved or declined. The below steps will help you to get started with setting up Webhooks 1 Ensure you have an API Key with Webhook Access Your merchant account must have an API key with permission to "Webhook Notifications". If you are receiving a permission error, please contact TNS. API Keys can be found in the Account Management > API Keys section of the TNS Payment Orchestration Portal Click on “Test" 2 Configure a Webhook Endpoint In the Merchant Portal, navigate to your merchant account and select the “Webhooks” tab. You can configure up to 5 active webhook endpoints per merchant. Click Add Endpoint and provide the following information: Title Description Field Description URL Your HTTPS endpoint that will receive notifications. Must use Display Name A friendly name for this endpoint (e.g. "Production Order Processor"). This allows you to recognise why the webhook event was created. API Key Select one of your API keys with webhook access. This key is used to sign deliveries. Event Categories Choose which events to receive: approved, declined, or both. 3 Implement Your Endpoint Your endpoint must: Accept HTTP POST requests with a JSON body Respond with an HTTP 2xx status code within 15 seconds to acknowledge receipt Be accessible via HTTPS (HTTP URLs are rejected) 4 Test Connectivity & Receive a Test Notification After saving your webhook, you can perform a connectivity and sample webhook test. Identify the webhook you want to test Click the accordion menu Click on "Test" If successful, you will receive the webhook notification on your server. If failed, you will receive a failure toast message. Successful : Failure : • [Webhook Format](https://developer.pay.tnsi.com/hosted-checkout/supporting-apis/webhook-notifications/webhook-format.md): Event Categories The event category that you subscribed for within the Webhook Merchant Portal setup. Title Description Category Triggered When approved Transaction status is APPROVED declined Transaction status is anything other than APPROVED (HOST_DECLINED, INVALID etc) Each event also includes the transaction action (SALE, AUTHORIZATION, CAPTURE, REFUND, VOID, REVERSAL etc) so you can distinguish event types within each category. Event Payload Format Each webhook delivery is an HTTP POST with a JSON body: JSON { "id": "550e8400-e29b-41d4-a716-446655440000", "type": "approved", "created": "2024-11-14T22:13:20Z", "merchantId": "M10000000000001", "data": { "transactionId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "action": "SALE", "status": "APPROVED", "isApproved": true, "amount": 1500, "currency": "USD", "cardType": "VISA", "firstSix": "411111", "lastFour": "1111", "responseCode": "00", "responseText": "Approved", "authCode": "ABC123", "originalTransactionId": null, "clientReference": "ORDER-12345", "receiptNumber": "RN000001" } } Payload Fields Title Description Title Field Type Description id string (UUID) Unique event identifier. Use this for idempotency. type string Event category: approved or declined created string (ISO 8601) Timestamp of the event merchantId string Your TNS merchant identifier. Note - this will be different to your Acquirers Bank Merchant ID. data.transactionId string (UUID) The transaction identifier data.action string Transaction action: SALE, AUTHORIZATION, CAPTURE, LINKED_REFUND, VOID data.status string Transaction status: APPROVED, HOST_DECLINED, INVALID, SUSPECT data.isApproved boolean Whether the transaction was approved. TRUE,FALSE data.amount integer Amount in minor currency units (e.g. 1500 = $15.00) data.currency string ISO 4217 currency code (e.g. EUR, USD, GBP) data.cardType string Card scheme: VISA, MASTERCARD, AMEX, etc. data.firstSix string First 6 digits of the card number data.lastFour string Last 4 digits of the card number data.responseCode string TNS platform response code data.responseText string Human-readable response description data.authCode string Authorisation code (present when approved) data.originalTransactionId string Original transaction reference (for subsequent transactions such as refunds, voids, captures) data.clientReference string Your merchant-supplied reference data.receiptNumber string TNS receipt number • [Verify Signature](https://developer.pay.tnsi.com/hosted-checkout/supporting-apis/webhook-notifications/verify-signature.md): Every webhook delivery includes three HTTP headers for signature verification: Title Description Header Description hmac HMAC-SHA256 signature of the signing data apikey The API key identifier used for signing timestamp Unix epoch milliseconds at time of signing Verification Algorithm Extract the apikey, timestamp, and hmac headers from the request Read the raw request body (the JSON payload) Construct the signing data: {apikey}:{timestamp}:{body} Compute HMAC-SHA256 of the signing data using your API key's secret Compare your computed signature with the hmac header value Sample Code Java Java import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; public boolean verifyWebhook(String apiKey, String timestamp, String hmacHeader, String body, String secret) { String signingData = apiKey + ":" + timestamp + ":" + body; Mac mac = Mac.getInstance("HmacSHA256"); SecretKeySpec keySpec = new SecretKeySpec( secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); mac.init(keySpec); byte[] hash = mac.doFinal(signingData.getBytes(StandardCharsets.UTF_8)); String computed = bytesToHex(hash); return computed.equalsIgnoreCase(hmacHeader); } Python Python import hmac import hashlib def verify_webhook(api_key: str, timestamp: str, hmac_header: str, body: str, secret: str) -> bool: signing_data = f"{api_key}:{timestamp}:{body}" computed = hmac.new( secret.encode('utf-8'), signing_data.encode('utf-8'), hashlib.sha256 ).hexdigest() return hmac.compare_digest(computed.lower(), hmac_header.lower()) Node.js Plain text const crypto = require('crypto'); function verifyWebhook(apiKey, timestamp, hmacHeader, body, secret) { const signingData = `${apiKey}:${timestamp}:${body}`; const computed = crypto .createHmac('sha256', secret) .update(signingData) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(computed, 'hex'), Buffer.from(hmacHeader, 'hex') ); } const crypto = require('crypto'); function verifyWebhook(apiKey, timestamp, hmacHeader, body, secret) { const signingData = `${apiKey}:${timestamp}:${body}`; const computed = crypto .createHmac('sha256', secret) .update(signingData) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(computed, 'hex'), Buffer.from(hmacHeader, 'hex') ); } Replay Protection To guard against replay attacks, verify that the timestamp header is within an acceptable window (e.g. 5 minutes) of your server's current time: Plain text long receivedTimestamp = Long.parseLong(timestampHeader); long now = System.currentTimeMillis(); if (Math.abs(now - receivedTimestamp) > 300_000) { // 5 minutes // Reject — potential replay attack } long receivedTimestamp = Long.parseLong(timestampHeader); long now = System.currentTimeMillis(); if (Math.abs(now - receivedTimestamp) > 300_000) { // 5 minutes // Reject — potential replay attack } Retry Behaviour If your endpoint fails to respond with a 2xx status within 15 seconds, the platform retries delivery with exponential backoff: Title Description Attempt Delay After Failure 1st retry 1 minute 2nd retry 5 minutes 3rd retry 30 minutes 4th retry 2 hours 5th retry 8 hours 6th retry 24 hours After all 6 retries are exhausted, the delivery is marked as permanently failed. Automatic Endpoint Disabling If 5 consecutive events all permanently fail delivery (all retries exhausted for each), the endpoint is automatically disabled. You will need to re-enable it manually in the Merchant Portal after resolving the issue. When you re-enable a disabled endpoint, delivery resumes for new events only — events that occurred while the endpoint was disabled are not retroactively delivered. • [Best Practices](https://developer.pay.tnsi.com/hosted-checkout/supporting-apis/webhook-notifications/best-practices.md): Every webhook delivery includes three HTTP headers for signature verification: Title Description Header Description hmac HMAC-SHA256 signature of the signing data apikey The API key identifier used for signing timestamp Unix epoch milliseconds at time of signing Verification Algorithm Extract the apikey, timestamp, and hmac headers from the request Read the raw request body (the JSON payload) Construct the signing data: {apikey}:{timestamp}:{body} Compute HMAC-SHA256 of the signing data using your API key's secret Compare your computed signature with the hmac header value Sample Code Java Java Python Python import hmac import hashlib def verify_webhook(api_key: str, timestamp: str, hmac_header: str, body: str, secret: str) -> bool: signing_data = f"{api_key}:{timestamp}:{body}" computed = hmac.new( secret.encode('utf-8'), signing_data.encode('utf-8'), hashlib.sha256 ).hexdigest() return hmac.compare_digest(computed.lower(), hmac_header.lower()) Node.js Plain text const crypto = require('crypto'); function verifyWebhook(apiKey, timestamp, hmacHeader, body, secret) { const signingData = `${apiKey}:${timestamp}:${body}`; const computed = crypto .createHmac('sha256', secret) .update(signingData) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(computed, 'hex'), Buffer.from(hmacHeader, 'hex') ); } const crypto = require('crypto'); function verifyWebhook(apiKey, timestamp, hmacHeader, body, secret) { const signingData = `${apiKey}:${timestamp}:${body}`; const computed = crypto .createHmac('sha256', secret) .update(signingData) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(computed, 'hex'), Buffer.from(hmacHeader, 'hex') ); } Replay Protection To guard against replay attacks, verify that the timestamp header is within an acceptable window (e.g. 5 minutes) of your server's current time: Plain text long receivedTimestamp = Long.parseLong(timestampHeader); long now = System.currentTimeMillis(); if (Math.abs(now - receivedTimestamp) > 300_000) { // 5 minutes // Reject — potential replay attack } long receivedTimestamp = Long.parseLong(timestampHeader); long now = System.currentTimeMillis(); if (Math.abs(now - receivedTimestamp) > 300_000) { // 5 minutes // Reject — potential replay attack } Retry Behaviour If your endpoint fails to respond with a 2xx status within 15 seconds, the platform retries delivery with exponential backoff: Title Description Attempt Delay After Failure 1st retry 1 minute 2nd retry 5 minutes 3rd retry 30 minutes 4th retry 2 hours 5th retry 8 hours 6th retry 24 hours After all 6 retries are exhausted, the delivery is marked as permanently failed. Automatic Endpoint Disabling If 5 consecutive events all permanently fail delivery (all retries exhausted for each), the endpoint is automatically disabled. You will need to re-enable it manually in the Merchant Portal after resolving the issue. When you re-enable a disabled endpoint, delivery resumes for new events only — events that occurred while the endpoint was disabled are not retroactively delivered. • [Transaction Details](https://developer.pay.tnsi.com/hosted-checkout/supporting-apis/reporting-api-home/transaction-details.md) • [Transactions using Blacklisted Cards](https://developer.pay.tnsi.com/hosted-checkout/supporting-apis/reporting-api-home/transactions-using-blacklisted-cards.md): A blacklist report offers a detailed list of all transactions attempted using a blacklisted credit card by the merchant or at a higher level. The TNS system records all transaction information involving a blacklisted credit card for subsequent actions. All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Transaction Summary Data](https://developer.pay.tnsi.com/hosted-checkout/supporting-apis/reporting-api-home/transaction-summary-data.md): The summary report allows you to generate merchant-wise summary reports that provide an overview of your transactions over a specified period. These reports help you analyze overall transaction trends and performance, making it easier to track and manage your business activities. All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [Settlement Data](https://developer.pay.tnsi.com/hosted-checkout/supporting-apis/reporting-api-home/settlement-data.md): Settlement report API offers a comprehensive overview of the total transaction amounts and counts involved in the Settlement process, which is executed by the Settlement Engine. Please consult the sample request format section for a detailed list of available fields that can be used as search criteria. The Settlement Report summary feature enables you to generate in-depth reports on all transactions processed by the settlement engine for either all merchant accounts or specific ones. This report provides detailed insights into the total transaction amount for each merchant, categorized by card type and transaction type. By applying various filters, you can tailor the reports to focus on the data that is most pertinent to your requirements. All REST API calls are authenticated using HMAC. See the Authentication Headers section to learn how to sign the payload using HMAC and the mandatory headers required for each request. • [HMAC Authentication](https://developer.pay.tnsi.com/hosted-checkout/resources/hmac-authentication-1.md): Every request to TNS Gateway API is to be authenticated by HMAC by creating a signature of the request payload using API Key and Secret provided by TNS. How to generate hmac APIKey (Provided by TNS) Secret (Provided by TNS) Take the timestamp at the time of signing Get data/ payload (which will be sent as request body) as string Concatenate APIKey “:” timestamp “:” payload Generate HMAC by using Secret provided by TNS HMAC should be generated by using SHA512 algorithm. Here's a simple example of HMAC calculation using JavaScript: To use CryptoJS.HmacSHA512 , you need to ensure that you have the necessary prerequisites set up, including the proper installation and importation of the crypto-js library. Include the CryptoJS library in your HTML file: Add the following tag to your HTML file to load CryptoJS from a CDN. Javascript <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.2.0/crypto-js.min.js"></script> Javascript function generateHMAC(apiKey, secret, requestBody) { var time = new Date().getTime(); var rawSignature = apiKey + ":" + time + ":" + requestBody; var signature = signHMAC(rawSignature, secret); return signature; } function signHMAC(rawSignature, secret) { const signature = CryptoJS.HmacSHA512(rawSignature, secret); const hexSignature = CryptoJS.enc.Hex.stringify(signature); return hexSignature; } After generating the HMAC hash, the following headers need to be included in the REST API Request. Title Description Title Field Description Required Example Value apikey The API Key provided by TNS. Yes ba81c80ad011cd918b946f7e957b1b70cc25f14405d1e7801e892e1561295493 timestamp The time stamp taken at the time of signing. Yes 1715322040 hmac Generated HMAC Hash value. Yes e24e1bfe76b1c846c10c3079ea47202913ad04d66a1434b26470010427dda2d9 User-Agent Identifies the client application making the request. Must include the application name and version (for example, MyPOS/2.1.0 ). This value is not validated but is used for identification and troubleshooting purposes. Yes MyPOS/2.1.0 Important: The User-Agent header is mandatory for all API requests. Requests without a valid User-Agent will be rejected. This header helps TNS identify your integration for support and troubleshooting purposes. • [Response Codes](https://developer.pay.tnsi.com/hosted-checkout/resources/response-codes.md): Response codes provide a consistent, host-independent view of transaction outcomes by standardising codes returned by upstream hosts. Use the codes, human-readable messages, and practical guidance to interpret outcomes and determine how your application should respond. Column meanings: tnsResponseCode - the tnsResponseCode value returned to clients. tnsResponseText - the human-readable text returned alongside the code Description - what the code means in practice and the expected client behaviour. Codes are grouped by prefix and sorted within each group: Approval Declines Host-categorised declines (mapped from the acquirer/issuer decline codes) Fuel / Fleet-specific Declines HTTP Response Codes: It's important to note that HTTP status code and Response Codes answer two different questions: The HTTP status describes whether the API call itself was accepted and processed The TNS Response Codes describes the outcome of the payment itself, and is carried inside the response body. A declined card is a perfectly successful API call. It returns HTTP 200 with a decline code in the body. The HTTP layer is not used to signal decline. Approval Title Description Description tnsResponseCode tnsResponseText Description 00 Approved Transaction was fully approved by the issuer. H08 Approved - honor with identification Approved on condition the cardholder's identity is verified. Complete the sale after checking ID. H10 Partial approval The issuer approved only part of the requested amount. Collect the remainder via another tender or reverse. General Response Codes The below response codes are generated where the transaction is declined prior to going to the upstream host. Title Description Title tnsResponseCode tnsResponseText Description G03 Invalid merchant configuration The merchant/terminal is not configured correctly at the gateway (e.g. missing acquirer setup). Not retryable by the cardholder; requires operational/config fix. G04 Card blacklisted The card is on the gateway blacklist and was blocked before reaching the host. Do not retry with the same card. G12 Invalid transaction data The request reached the gateway but contained data that is invalid for the transaction type. Fix the request before retrying. G13 Currency mismatch The transaction currency does not match what the merchant/terminal is permitted to process. Correct the currency and retry. G25 Reversal not required A reversal was requested but is unnecessary because the original was not found or was not approved. Treat as handled; no further action needed. G26 Original transaction not found The referenced original transaction (for capture/refund/reversal) could not be located. Check the reference before retrying. G30 Invalid request format The request was malformed and could not be parsed/validated by the gateway. Fix the request structure and retry. G31 Invalid host response The host replied but the response could not be interpreted by the gateway. Outcome uncertain; treat as a host-side failure. G40 Transaction not supported The requested transaction type/function is not supported for this configuration. Do not retry as-is. G57 Authorization failed Gateway-level authorization checks failed for the request. Not approved; review request/permission. G58 Operation not allowed The operation is not permitted for this terminal/merchant. Not retryable without a config change. G68 Host read timeout Payorch connected but did not receive the host response in time. Outcome unknown; a reversal may be triggered. Do not assume approval. G91 Host connection timeout The gateway could not establish a connection to the host. Transaction did not complete; safe to retry later. G94 Duplicate advice already processed This advice message duplicates one already processed. No further action; the original outcome stands G95 Duplicate transaction A transaction with the same key was already submitted. Do not resubmit; look up the original result. G96 Host response error The host returned an error condition the gateway classified as a system/host error. Outcome uncertain; treat as failed. G97 Gateway processing error An internal error occurred in the gateway while processing. Transaction not completed; retry may be possible after investigation. G99 Smart routing block Smart routing rules blocked the transaction before it was sent to a host. Not approved; governed by routing configuration. Host Response Codes (Hxx) The below standardized response codes are mapped from an upsteam host into the below format. Title Description Description tnsResponseCode tnsResponseText Description 00 Approved Transaction was fully approved by the issuer. H01 Refer to card issuer - call issuer The issuer declined and asked the merchant to contact them for authorization. Do not simply retry; follow the call-issuer process. H04 Capture card - pick up The issuer declined and instructed the terminal to retain the card. Do not return the card; do not retry. H05 Host declined Generic issuer decline (do not honour) with no more specific reason. Not approved; a different card may be needed. H08 Approved - honor with identification Approved on condition the cardholder's identity is verified. Complete the sale after checking ID. H10 Partial approval The issuer approved only part of the requested amount. Collect the remainder via another tender or reverse. H30 Host invalid request The host rejected the request as malformed/invalid. Not approved; correct the request. H41 Lost card - pick up Card reported lost; issuer instructed pickup. Retain the card; do not retry. H43 Stolen card - pick up Card reported stolen; issuer instructed pickup. Retain the card; do not retry. H51 Insufficient funds Declined because the account lacks available funds. Suggest another card/tender; retry may succeed later. H54 Expired card Declined because the card has expired. Request a valid card. H55 Incorrect PIN The PIN entered was wrong. Prompt the cardholder to re-enter the PIN and retry. H56 PIN change required The issuer requires the cardholder to change their PIN before transacting. H57 Transaction not permitted to cardholder The issuer does not permit this transaction type for this cardholder. Not approved; try a different transaction/card. H59 Suspected fraud The issuer flagged suspected fraud; the gateway auto-reverses. Do not retry with the same card. H61 Exceeds withdrawal limit Declined for exceeding the permitted amount/withdrawal limit. Retry with a lower amount or another card. H63 Security violation The issuer declined for a security-rule violation; the gateway auto-reverses. Not approved. H65 Fallback required Additional authentication is required. Depending on client capability, retry with chip, PIN, CVV, or 3DS. H66 PIN required A PIN is required to complete this transaction. Prompt for PIN and retry. H68 Host suspect The host response arrived too late, so the final state is uncertain. Do not assume approval; reconcile before retrying. H75 PIN tries exceeded The allowed number of PIN attempts was exceeded; may warrant card pickup. Do not keep retrying the PIN. H91 Issuer unavailable The issuer or switch was unreachable/inoperative. Transaction not completed; safe to retry later. H96 Host error The host reported a system malfunction. Outcome uncertain; treat as failed and retry later Fuel / fleet codes (Fxx) Specific response codes for Fleet/Fuel Merchants. Title Description Title Code tnsResponseText Description F01 Invalid vehicle Declined because the vehicle identifier supplied is not valid for the fleet card. F02 Invalid driver Declined because the driver identifier supplied is not valid for the fleet card. F03 Invalid product Declined because the fuel/merchandise product is not permitted on this card. F04 Exceeds transaction total limit per product class Declined because the transaction total exceeds the limit for that product class. F05 Over daily limit Declined because the card's daily spend/usage limit has been exceeded. F06 Invalid date or time Declined because the transaction date/time is outside the card's permitted window. F07 Exceeds quantity Declined because the requested quantity exceeds the card's permitted amount. F08 Invalid prompt entry Declined because a fuel-site prompt (e.g. odometer, ID) was answered with invalid data. F09 Invalid track 2 data Declined because the card's track 2 data is invalid or unreadable. F10 Voyager ID problem Declined due to a problem with the Voyager fleet card identification. F11 Invalid odometer Declined because the odometer reading entered is invalid. F12 Invalid restriction code Declined because a card restriction code prevents this purchase. F13 Pay at pump not allowed Declined because the card is not permitted to pay at the pump; go inside to pay. F14 Over fuel limit Declined because the fuel amount exceeds the card's fuel limit. F15 Over cash limit Declined because the cash portion exceeds the card's cash limit. F16 Fuel price error Declined due to a fuel price error/mismatch at the site. F17 Over repair limit Declined because the repair/service amount exceeds the card's limit. F18 Over additive limit Declined because the additive amount exceeds the card's limit. F19 Invalid user Declined because the user identifier supplied is not valid for the card. F20 Driver's License or ID is Required Declined because a driver's licence or ID must be supplied to proceed. F21 Fuel only Declined for non-fuel items; the card is restricted to fuel purchases only. F22 Received prompts do not match expected values Declined because the site prompt responses did not match the values the card expected. F23 Extended prompting required Declined because additional (extended) prompts must be completed before approval. TNS Host Simulator - Sandbox & UAT The TNS Host Simulator lets you build and test your integration with TNS Payment Orchestration without connecting to a real acquirer. It works with Hosted Checkout, Rest API's and Terminal API's. The simulator sends back correctly structured responses, so you can check how your application handles approvals, declines, errors and slow responses. Note: The simulator is only available in sandbox & UAT environments. It can't be used in production. Getting started Within the sandbox environment, your merchant account will be setup with the simulator with a default mode where the response code returned is based on the transaction amount. When creating a Developer Hub Project for test case generation, you can override the response codes. Default mode: response set by the transaction amount In Default mode, the cents part of the amount decides the result. For example, a transaction for 1.51 comes back as Insufficient Funds . Each response includes two codes: hostResponseCode : the code returned by the simulated host (acquirer). It's for information only. tnsResponseCode : the standard TNS response code. It's the same across every acquirer TNS supports. Your application should make decisions based on this code. Amount (cents) Example amount hostResponseCode tnsResponseCode (standardized) Result Description .00 1.00 00 00 Approved Approved .08 1.08 08 H08 Approved Approved with identification .51 1.51 51 H51 Declined Insufficient funds .55 1.55 55 H55 Declined Incorrect PIN .65 1.65 65 H65 Declined Additional authentication required .91 1.91 91 H91 Declined Issuer unavailable .96 1.96 96 H96 Declined System error Any other value 1.23 Varies H05 Declined Host decline Run most of your tests in Default mode. Because you choose the result through the amount, you can run your whole test set without changing any settings. Always approve (or always return one specific response) To get the same result every time, whatever the amount, you can set your account to auto-approve regardless of the cent value. If you use the Dev Hub within the Sandbox Developer Portal, open your project and go to Response Simulation and pick a code from the Response Code Simulation list (for example, 00 – Approve or 051 – Decline Insufficient Funds ). Important: While this mode is set, the transaction amount is ignored. To go back to amount-based responses, go to Response Code Simulation and set back to Default . Simulating a delayed response (timeouts) To test how your application copes with a slow or timed-out host, set the response mode simulation to the timeout you want to set. Things to test with this setting: Your application's client-side timeout and retry behaviour. Reversal handling, where your application doesn't get a response in time. Messages shown to the cardholder or operator while waiting. To stop the delay, set the Timeout Delays back to Default . Things to remember These settings apply to all transcations for the specific mercahnt id. Anyone else testing with the same merchant will see the same forced responses or delays. Always set things back to Default when you finish a specific test case. If you need help setting up the simulator, contact TNS Support. • [Test Cards](https://developer.pay.tnsi.com/hosted-checkout/resources/test-cards.md): VISA Title Card Number: 4111 1111 1111 1111 Expiration Date: Any future date CVV: Any 3-digit number Card Number: 4012 8888 8888 1881 Expiration Date: Any future date CVV: Any 3-digit number Card Number: 4222 2222 2222 2222 Expiration Date: Any future date CVV: Any 3-digit number MASTERCARD Title Card Number: 5555 5555 5555 4444 Expiration Date: Any future date CVV: Any 3-digit number Card Number: 5105 1051 0510 5100 Expiration Date: Any future date CVV: Any 3-digit number Card Number: 5432 1234 5678 9876 Expiration Date: Any future date CVV: Any 3-digit number AMERICAN EXPRESS Title Card Number: 3782 822463 10005 Expiration Date: Any future date CID (Card Identification Number): Any 4-digit number Card Number: 3714 496353 98431 Expiration Date: Any future date CID (Card Identification Number): Any 4-digit number Card Number: 3411 726629 87061 Expiration Date: Any future date CID (Card Identification Number): Any 4-digit number DISCOVER Title Card Number: 6011 0000 0000 0004 Expiration Date: Any future date CVV: Any 3-digit number Card Number: 6011 1111 1111 1117 Expiration Date: Any future date CVV: Any 3-digit number Card Number: 6011 0000 0000 0009 Expiration Date: Any future date CVV: Any 3-digit number DINERS CLUB Title Card Number: 3056 9309 0259 04 Expiration Date: Any future date CVV: Any 3-digit number Card Number: 3600 6666 3333 44 Expiration Date: Any future date CVV: Any 3-digit number Card Number: 3852 0000 0232 37 Expiration Date: Any future date CVV: Any 3-digit number JCB Title Card Number: 3530 1113 3330 0000 Expiration Date: Any future date CVV: Any 3-digit number Card Number: 3566 0020 2036 0505 Expiration Date: Any future date CVV: Any 3-digit number Card Number: 3530 1113 3330 0000 Expiration Date: Any future date CVV: Any 3-digit number UNION PAY Title Card Number: 6250 9460 0000 0016 Expiration Date: Any future date CVV: Any 3-digit number Card Number: 6250 9470 0000 0014 Expiration Date: Any future date CVV: Any 3-digit number Card Number: 6222 8212 3456 0017 Expiration Date: Any future date CVV: Any 3-digit number