Hosted Session integration guide

Hosted Session is an integration method that allows control over the layout and styling of your payment page. Card detail fields are hosted iframes ensuring card data never enters your server, lowering your PCI obligations.

The gateway then collects the card details in a temporary payment session which you can reference in your transaction request.

This guide will explain the end to end Client side and Server side implementation.

There are HTML and JavaScript code examples in this guide and the full client side Javascript library definitions can be found here: session.js reference

The server side API reference contains a runnable http request sender and code examples generated in a variety of languages. It can be found here: API reference

Prerequisites

You will need a test merchant account. Please contact the support team for credentials.

Your credentials need to be included in a basic authentication header encoded with base64. The format for the credentials is:

  • Username: merchant.{merchantId}

  • Password: {apiKey}

You must also ensure that your merchant profile is enabled for the Hosted Session service.

Workflow
Workflow

Generating Hosted Session ID on Server side

Create a session by submitting a Create Session API request from your server-side application.

HTTP Method: POST

Request URL: https://test-tyro.mtf.gateway.mastercard.com/api/rest/version/57/merchant/{merchant_id}/session

Authentication: Basic authentication

API Reference: Create Session

It returns the following fields:

  • session.id

A unique session identifier which you must provide on subsequent requests to reference session contents.

  • session.authenticationLimit

The limit you supplied in the request or the gateway’s default value.

  • session.aes256Key

The key you can use to decrypt sensitive data passed to your website via the payer’s browser or mobile device.

  • session.version

You can use this field to implement optimistic locking of the session content.

  • session.updateStatus

A summary of the outcome of the last attempt to modify the session.

Implementing Hosted Session on Client side

1. Create the payment page HTML with JavaScript library

Create the HTML for the payment page and include the correct client Javascript Library session.js.

Make sure to pass the correct API version and the merchant identifier in the JS library path (line 3 highlighted below).

In the following example the API version used is 57 and you will have to replace <MERCHANTID> with the MID provided by Tyro.

Client side HTML
<head>
<!-- INCLUDE SESSION.JS JAVASCRIPT LIBRARY -->
<script src="https://test-tyro.mtf.gateway.mastercard.com/form/version/57/merchant/<MERCHANTID>/session.js"></script>

2. Create credit card fields in the payment page HTML.

Create the HTML elements and set an ID for each field. For example, the Card Number field has the corresponding ID id = "card number" (line 5 highlighted below).

To prevent submission of sensitive data to the merchant server, ensure that sensitive data fields are read-only and do NOT have the name attribute.

Client side HTML
<div>Please enter your payment details:</div>
<h3>Credit Card</h3>
<div>Card Number: <input type="text" id="card-number" class="input-field" title="card number" aria-label="enter your card number" value="" tabindex="1" readonly></div>
<div>Expiry Month:<input type="text" id="expiry-month" class="input-field" title="expiry month" aria-label="two digit expiry month" value="" tabindex="2" readonly></div>
<div>Expiry Year:<input type="text" id="expiry-year" class="input-field" title="expiry year" aria-label="two digit expiry year" value="" tabindex="3" readonly></div>
<div>Security Code:<input type="text" id="security-code" class="input-field" title="security code" aria-label="three digit CCV security code" value="" tabindex="4" readonly></div>
<div>Cardholder Name:<input type="text" id="cardholder-name" class="input-field" title="cardholder name" aria-label="enter name on card" value="" tabindex="5" readonly></div>

Generate iframes using Configure Function

The configuration function (example below) allows you to attach hosted fields to your payment page.

You need to provide the following:

  • field selectors for credit card fields. This is where placeholder text boxes are injected, preventing real information from being passed to the gateway and reducing compliance. Remember that you must make these fields readonly.

  • session (optional). If you do not provide one, the client library creates a payment session.

  • initialized Callback: A call back that fires when configuration is successful

  • formSessionUpdate Callback: A call back that fires whenever the session is updated via formSessionUpdateFromForm().

Client side HTML
PaymentSession.configure({
    fields: {
        // ATTACH HOSTED FIELDS TO YOUR PAYMENT PAGE FOR A CREDIT CARD
        card: {
            number: "#card-number",
            securityCode: "#security-code",
            expiryMonth: "#expiry-month",
            expiryYear: "#expiry-year",
            nameOnCard: "#cardholder-name"
        }
    },
    //SPECIFY YOUR MITIGATION OPTION HERE
    frameEmbeddingMitigation: ["javascript"],
    callbacks: {
        initialized: function(response) {
            // HANDLE INITIALIZATION RESPONSE
        },
        formSessionUpdate: function(response) {
            // HANDLE RESPONSE FOR UPDATE SESSION
            if (response.status) {
                if ("ok" == response.status) {
                    console.log("Session updated with data: " + response.session.id);

Handling successful initialization result

If result.status=="ok"


       // An ok response
{
    "status":"ok",
}
       

The hosted fields are successfully attached to your payment page. You could use this to hide the payment page with a loading screen or gif until the fields are configured.

Handling error in initialization result

If result.status=="system_error" or result.status=="request_timeout"

// An error response (system_error)
{
    "status": "system_error",  
    "message": "System error message." 
}
// An error response (request_timeout)
{
    "status" : "request_timeout", 
    "message": "Request timeout error message."
}

An error has occurred while attaching the hosted fields. You should retry after a short period or display an error message if unsuccessful.

Update Session with card details

The updateSessionFromForm() function will store the payment details in each field into a payment session. This can be used to update the session as it is being filled out or after the user presses the submit/pay button.

Create Client side HTML

function pay() {
    // UPDATE THE SESSION WITH THE INPUT FROM HOSTED FIELDS
    PaymentSession.updateSessionFromForm('card');
}

Handling update session callback

This function is invoked in response to the PaymentSession.updateSessionFromForm(paymentType) function. It contains the result parameter. You must check the result.status value to determine if the operation was successful or not.

successful session update via formSessionUpdate(result)

If result.status=="ok"

The session now contains the collected card details.

// An ok response
{
    "status":"ok",
    "merchant": "TESTMERCHANT",
    "session": {
        "id": "SESSION000218450948092491657986"
        "updateStatus":"SUCCESS",
        "version":"e3f144ce02"
    },
    "sourceOfFunds": {
        "provided": {
            "card": {
                "brand": "MASTERCARD",
                "expiry": {
                    "month": "5",
                    "year": "21"
                },
                "fundingMethod": "DEBIT",
                "nameOnCard": "John Smith",
                "number": "512345xxxxxx8769",
                "scheme": "MASTERCARD"
            }
        },
        "type": "CARD"
    },   
    "version": "43"
}

Handling session update error

If result.status=="fields_in_error"

The payer input is invalid and you should prompt the payer to update their input. The errors response structure contains information about the invalid fields.

       // An error response (fields_in_error)
{
    "status": "fields_in_error",  
    "session": {
        "id": "SESSION000218450948092491657986"
    },
    "errors": {
        "cardNumber": "invalid",
        "securityCode": "invalid"  
    },
    version: "43"
}

If result.status=="system_error" or result.status=="request_timeout"

An error has occurred when processing the update. You should retry the session update after a short period.

// An error response (system_error)
{
 "status": "system_error",  
 "session": {
     "id": "SESSION000218450948092491657986"
 },
 "errors": {
     "message": "System error message." 
 },
 "version": "43"
}
// An error response (request_timeout)
{
 "status" : "request_timeout", 
 "session": {
     "id": "SESSION000218450948092491657986"
 },
 "errors": {
     "message": "Request timeout error message."
 },
 "version": "43"
}

NOTE: The returned payment session (session.id) is used to perform a tokenization or a payment transaction which will be explained in next step.

Implementing Server side payment request

Make payment request to Tyro payment gateway using the following

  • session ID

that has been updated with the card details that you have obtained from the client’s browser.

  • order ID

Each order needs a unique ID, you can use the same id your shopping cart uses to identify the order or generate a UUID specifically for the payment.

  • transaction ID

Each transaction attempt will need a unique ID. For example if you try a transaction and it declines or encounters an error a new transaction ID should be used for any follow up attempts. You can use the same id your shopping cart uses to identify the order or generate a UUID specifically for the payment.

HTTP Method: PUT

Request URL: https://test-tyro.mtf.gateway.mastercard.com/api/rest/version/58/merchant/{merchantId}/order/{orderid}/transaction/{transactionid}

Authentication: Basic authentication.

Depends upon the workflow you are after, you can use one of the following transaction operations.

Pay This operation effectively combines an Authorize and a Capture into one message. A single transaction authorizes the payment and charge the card holder.

API Reference: Pay with Session

Authorize This operation verifies your payer’s card details, checks that your payer has sufficient funds available against their line of credit, and attempts to reserve the requested funds. The payer’s credit limit is reduced by the authorized amount, and the funds are reserved for a period of time (in most cases 5-8 days), as determined by the card scheme and the payer’s card issuing rules.

API Reference: Auth with Session

NOTE: If Authorization is used, then you have to CAPTURE it to charge the card holder.

API Reference: CAPTURE

If you want to cancel the authorization, you must VOID it.

API Reference: VOID

Request example
{
  "apiOperation": "PAY",
  "order": {
    "amount": "100",
    "currency": "AUD"
  },
  "sourceOfFunds": {
    "type": "CARD"
  },
  "transaction": {
    "reference": "478a14c1-64b9-454b-81c3-b4ca1cb86385"
  },
  "session": {
    "id": "SESSION000XXXXXXXXXXXXXX"
  }
}
Response example
{
  "device": {
    "browser": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36",
    "ipAddress": "XXXX"
  },
  "gatewayEntryPoint": "WEB_SERVICES_API",
  "merchant": "TESTTYRO_3DS",
  "order": {
    "amount": 100,
    "authenticationStatus": "AUTHENTICATION_NOT_IN_EFFECT",
    "chargeback": {
      "amount": 0,
      "currency": "AUD"
    },
    "creationTime": "2020-10-27T06:32:48.137Z",
    "currency": "AUD",
    "id": "Order1234www5",
    "lastUpdatedTime": "2020-10-27T06:32:50.178Z",
    "merchantAmount": 100,
    "merchantCategoryCode": "5999",
    "merchantCurrency": "AUD",
    "status": "CAPTURED",
    "totalAuthorizedAmount": 100,
    "totalCapturedAmount": 100,
    "totalRefundedAmount": 0
  },
  "response": {
    "acquirerCode": "APPROVED",
    "gatewayCode": "APPROVED"
  },
  "result": "SUCCESS",
  "sourceOfFunds": {
    "provided": {
      "card": {
        "brand": "VISA",
        "expiry": {
          "month": "12",
          "year": "23"
        },
        "fundingMethod": "CREDIT",
        "issuer": "JPMORGAN CHASE BANK, N.A.",
        "nameOnCard": "minu",
        "number": "411111xxxxxx1111",
        "scheme": "VISA",
        "storedOnFile": "NOT_STORED"
      }
    },
    "type": "CARD"
  },
  "timeOfLastUpdate": "2020-10-27T06:32:50.178Z",
  "timeOfRecord": "2020-10-27T06:32:48.149Z",
  "transaction": {
    "acquirer": {
      "batch": 1,
      "id": "TYRO",
      "merchantId": "TYRO_318"
    },
    "amount": 100,
    "authenticationStatus": "AUTHENTICATION_NOT_IN_EFFECT",
    "authorizationCode": "00    ",
    "currency": "AUD",
    "id": "tranID_12345sdw",
    "receipt": "20102710",
    "reference": "478a14c1-64b9-454b-81c3-b4ca1cb86385",
    "source": "INTERNET",
    "stan": "10",
    "terminal": "123",
    "type": "PAYMENT"
  },
  "version": "57"
}

Testing and Go Live

Testing Overview

Testing can be done using test merchant account provided by Tyro specific to your business case.

Tyro test simulator is configured to generate predictable results based on the transaction request and card details you supply.

Test Card Numbers

Card Brand Card Number
Mastercard 5111111111111118
Mastercard 2223000000000023
Visa 4012000033330026
AMEX 371449635398431

Use following Expiry dates to simulate transaction response codes

Expiry Date Result
05/21 Approved
05/22 Declined
04/27 Expired_Card
08/28 Timed_Out
01/37 Acquirer_System_Error
02/37 Unspecified_Failure
05/37 Unknown

Commence Live Payments

After you have tested your integration and received your production merchant ID, you can process live transactions. To move your integration from the test profile to the production profile, you will need to update the following with your production values.

  • Merchant ID
  • API Credentials
  • API End URL
  • Javascript Library path

It is recommended to perform several production test transactions, using a real credit card, through your production profile, and validate that transactions settle correctly into the expected bank account before you Live.

Working Example

Server side Payment Request

Take Session ID from the above example and add to the sessionId environment variable. This will use the card details captured in the session to process a test payment.

Send requests directly from the browser (CORS must be enabled)
$$.env
3 variables not set
merchantId
orderId
transactionId
sessionId