Displaying the hosted checkout integration iframe

The hosted checkout integration iframe is an embeddable HTML element that collects a customer's payment information and authorizes the transaction. To enable the iframe on your checkout page or on a webpage in your integration, you need to load the Toast hosted checkout Javascript SDK on the page. To load the SDK, add a script element to the head element of your HTML page.

<head>
      <script src="https://payments.sandbox.eng.toasttab.com/assets/loader.js"></script>
</head>

The script tag adds an object, Toast to the global Javascript window object, from which you can control the payment flow using the hosted checkout integration Javascript SDK functions:

All functions are used when you take a payment using the iframe. For more information on the SDK functions, see SDK functions.

Basic guidelines for using the hosted checkout SDK functions

The core SDK functions are initialize, createPaymentMethod, and confirmPayment. These three functions have success and failure callbacks that are invoked according to their corresponding state. Success and failure callbacks are useful for logging and handling errors.

Callback functions

Callback function

Description

Success callback

(event) => { console.log("Successful callback"), }

Failure callback

(event) => { console.log("Failed callback"), }


SDK functions

Initializing the iframe

Before you call the initialize function, make sure you use the authentication token for the correct environment (sandbox for testing and production for real payments) when you initialize the iframe. Also make sure you use the Toast API authentication credentials for the client browser component of your integration. The client browser API authentication credentials have specific access permissions. You cannot use the API authentication credentials for the server component of your integration when you initialize the iframe.

The initialize function takes your information and inserts the iframe onto your checkout page or onto a webpage in your integration. You use the initialize function after you have created a payment intent or created a setup intent.

  • onInitSuccessCallback: Invoked once the iframe successfully loads. The callback signature accepts no arguments and returns nothing.

  • onInitErrorCallback: Invoked if the iframe fails to load. The callback signature accepts no arguments and returns nothing.

Once the iframe is loaded, the SDK is available as an attribute on the window object called Toast. To initialize the SDK and load the iframe, call this function:

window.Toast.initialize(onInitSuccessCallback, onInitErrorCallback, options) 

To initialize the SDK, you need the merchantId, oauthToken, sessionSecret, and a domElementId that corresponds to an HTML element on your checkout page or webpage in your integration. When the SDK is initialized, this creates the iframe and appends it to the page after the domElementId.

SDK options

Field Name

Type

Description

oauthToken

string

An OAuth bearer authentication token associated with your hosted checkout client credentials. This authentication token can only be obtained from your server and then passed to the client.

domElementId

string

The ID of the HTML element on the page that the iframe should be rendered in.

merchantId

string

The Toast GUID of the merchant (restaurant location) that will receive the payment. This is the same value as the Toast-Restaurant-External-ID header parameter for the Toast REST API request.

sessionSecret

string

Generated when a payment intent or setup intent is successfully created.

acceptAmex

boolean

Indicates if American Express™ credit cards are accepted as a payment method in your checkout flow.


Checkout.js

const checkoutForm = window.Toast
checkoutForm.initialize(
       () => { console.log("Successful initialization callback")}
       () => { console.log(`Failed initialization callback with error ${e?.cause?.message}`);
       }
       {
              merchantId: "e5421b10-cd5c-41ca-9791-0a5037e81cdc",
              oauthToken: "hosted-checkout-oauth-token",
              sessionSecret: "PI_86bbcf0c-b483-4bbc-81bf-c2a9cd2baa2c_SECRET_EqYQ5^CgQWc4J?KBwq2jfv&Ov",
              domElementId: "payment-frame",
              acceptAmex: true
       }
)

Checkout.html

<form>
      <div id="payment-frame">
             <!-- Toast SDK will load the iframe here -->
      </div>
      <button id="submit">Submit</button>
      <div id="error-message">
            <!-- Display error message to your customers here -->
      </div>
</form>

If the iframe was successfully initialized, the iframe will load on your checkout page or on a webpage in your integration. Now you can begin collecting your customer’s payment card details.

Monitoring customer actions

The monitor function observes customer actions that take place within the iframe and sends a message for you to respond to. For example, if your customer finishes entering their payment card details and is ready to checkout, the monitor function sends a message to your integration to enable the checkout button for your customer.

Checkout.js

checkoutForm.monitor({
    { isValid, selectedPaymentMethod } : content 
}) => {
  console.log(`The selected payment method is ${selectedPaymentMethod}`)
 })

Toast.monitor takes in a callback that is executed when the customer inputs payment card details or when the customer selects a payment method for checkout. This callback is called with an InputChangedEvent object.

InputChangedEvent object

{
  "content": {
    "isValid": true, 1 
    "selectedPaymentMethod": "NEW_CARD" 2
  },
  "eventType": ToastIFrameEventType.INPUT_CHANGED
}

1

Indicates that all required fields have been provided and the hosted checkout integration iframe is ready for checkout.

2

The payment method selected. The available values are:

  • NEW_CARD

  • SAVED_CARD

  • APPLE_PAY

  • GOOGLE_PAY


InputChangedEvent

Property

Type

content

InputChangedEventContent


InputChangedEventContent

Value

Type

Description

isValid

boolean

Indicates that all required fields have been provided and the hosted checkout iframe is ready for checkout.

selectedPaymentMethod

string

The payment method selected. The available values are:

  • NEW_CARD

  • SAVED_CARD

  • APPLE_PAY

  • GOOGLE_PAY


Example of the monitor function and callback functions

window.Toast.monitor(myIframeMonitoringCallbackAction)

Fetching payment intent updates

The fetchUpdates function fetches any changes or updates made to the payment intent. The fetchUpdates function should be invoked when any updates are applied to your payment intent, such as updating the amount, applying a tip, etc, or when the iframe needs to be re-rendered to display saved cards after your customer logs into their profile.

Example of the fetchUpdates function

window.Toast.fetchUpdates()

Creating a payment method

The createPaymentMethod function creates a payment method for your customer when they have successfully entered valid payment card details and are ready to proceed with the final amount to be charged upon checkout, or are ready to save a payment card to their profile. A payment method is any method that a customer can use to pay for goods or services, such as payment cards, Apple Pay®, and Google Pay®. All taxes, tips, and discounts should be applied before calling the createPaymentMethod function. When your customer is ready to checkout and enters their payment card details, selects a saved payment card, or selects a digital wallet to complete their transaction, you create a payment method.

Before you call the createPaymentMethod function to create a payment method, your browser client must wait until the monitor function validates the customer's payment card details, such as card number, CVV, and expiration month and year. If the payment card details are valid, the SDK sets the isValid value to true, and your integration sends a message to enable the checkout button or create a payment method that can be charged. The createPaymentMethod function then automatically attaches the payment method to the payment intent or setup intent.

In order to comply with browser security restrictions, the createPaymentMethod and confirmIntent functions should not be called inside asynchronous functions (for example, within setTimeout, Promises). Ensure that createPaymentMethod and confirmIntent functions are called from event handlers tied to actual user gestures (for example, onclick, onmousedown) and not inside asynchronous functions to avoid failures and ensure proper flow.

Important

Certain web browser behaviors such as opening a payment dialog require a user gesture (for example, a button click) to avoid unwanted actions such as unauthorized payments. Apple Pay and Google Pay payments must be initiated by a user gesture to ensure proper security and functionality.

If the createPaymentMethod function fails to create a payment method, the Toast platform returns a The card details you have entered are invalid. Please check your card details and try again. error message.

Checkout.js

window.Toast.createPaymentMethod(
       (e) => {console.log("Successfully created a payment method callback")},
       (e) => {console.log(`Failed to create a payment method callback with error ${e?.cause?.message}`)}
)

To use Apple Pay or Google Pay, you must provide information about additional charges, discounts, and tip amounts when you call the createPaymentMethod function. You provide this information as line items in the lineItems parameters of the createPaymentMethod function. The total amount of the lineItems should add up to the final amount to be charged to the customer. The lineItems appear on Apple Pay and Google Pay's checkout pages.

The createPaymentMethod function accepts two callback functions.

  • onSuccessCallback: returns a CreatePaymentMethodResultEvent instance when the payment method creation succeeds.

  • onFailureCallback: returns an EventErrorContent instance when the payment method creation fails.

CreatePaymentMethodResultEvent

Property

Type

content

CreatePaymentMethodResultEventContent


Depending on the payment method the customer uses to complete their payment, the createPaymentMethod function returns a different CreatePaymentMethodResultEventContent.

CreatePaymentMethodResultEventContent for new cards

Value

Type

Description

paymentMethodType

string

The type of payment method provided by the customer. The payment method is:

  • NEW_CARD

paymentMethodId

string

The identifier of the payment method.

card

object

The payment card details associated with the payment method, such as:

  • lastFour

  • expiry

  • year

  • month

  • brand

error

string

An error message.


CreatePaymentMethodResultEventContent for new cards that will be saved

Value

Type

Description

paymentMethodType

string

The type of payment method provided by the customer. The payment method is:

  • NEW_CARD

paymentMethodId

string

The identifier of the payment method.

card

object

The payment card details associated with the payment method, such as:

  • lastFour

  • expiry

  • year

  • month

  • brand

setupFutureUsage

string

Used to determine if a customer will save a payment method for future use. The value is:

  • ON_SESSION

error

string

An error message.


CreatePaymentMethodResultEventContent for saved cards

Value

Type

Description

paymentMethodType

string

The type of payment method provided by the customer. The payment method is:

  • SAVED_CARD

paymentMethodId

string

The identifier of the payment method.

error

string

An error message.


CreatePaymentMethodResultEventContent for digital wallets (Apple Pay and Google Pay)

Value

Type

Description

paymentMethodType

string

The type of payment method provided by the customer. The payment method is either:

  • APPLE_PAY

  • GOOGLE_PAY

paymentMethodId

string

The identifier for the payment method.

billingDetails

object

Customer information retrieved from their digital wallet, such as:

  • (customer) name

  • phoneNumber

  • email

card

object

The payment card details associated with the payment method, such as:

  • lastFour

  • expiry

  • year

  • month

  • brand

error

string

An error message.


EventErrorContent

Value

Type

Description

cause

object

Information about the failure to create a payment method. Additional information can be found on the following properties:

  • message

  • developerMessage

retryable

boolean

Indicates if the request to create the payment method can be retried.


Example of the createPaymentMethod function and callback functions

Toast.createPaymentMethod(
            (e) => {
                console.log("Tokenize successful!")
            },
            (e) => {
                console.log("Tokenize failed!")
                console.log(e?.cause?.message)
                yourFunction(e?.cause?.developerMessage)
            },
            [
                {label: "Subtotal", amount: 10}, 
                {label: "Tip", amount: 2}
            ]
        )'

Confirming a payment

Note

The confirmPayment SDK function is deprecated and is replaced by the confirmIntent SDK function.

The confirmPayment function authorizes the payment using the payment method created by the createPaymentMethod function. If the confirmPayment function fails to confirm the payment, the Toast platform returns an An error occurred processing your card payment. error message. To reattempt confirming the payment intent, you must generate a new externalReferenceId and update the payment intent with the new identifier.

Checkout.js

checkoutForm.confirmPayment(
       (e) => {console.log("Successfully confirmed payment intent callback")},
       (e) => {console.log(`Failed to confirm payment intent callback with error ${e?.cause?.message}`)}
) 


You can provide two callbacks to this function to indicate behavior based on whether or not the payment intent was successfully confirmed. Similar to the createPaymentMethod function, the confirmPayment function accepts two callback functions. The callback functions are used to handle successful payment and unsuccessful payment scenarios.

  • onConfirmSuccessCallback: returns a ConfirmIntentResultEvent instance when the payment confirmation succeeds.

  • onConfirmFailureCallback: returns an EventErrorContent instance when the payment confirmation fails.

ConfirmIntentResultEvent for new and saved cards and digital wallets

Value

Type

Description

id

string

The identifier of the payment method.

externalReferenceId

string

The unique identifier of the payment intent generated by the restaurant or integration partner.

sessionSecret

string

A unique and randomized identifier for the payment intent.

amount

integer

The payment amount.

currency

string

Three-letter ISO 4217 currency code, in uppercase.

captureMethod

string

Indicates when funds will be captured from the customer's account.

status

string

The status of the payment intent. The status is:

  • REQUIRES_CAPTURE

paymentMethodId

string

The identifier of the payment method.

creationDate

string

The date and time the payment intent was created. The time zone of the creationDate is UTC.

setupFutureUsage

string

Used to determine if a customer will save a payment method for future use.

customerId

string

The unique identifier of the customer record that identifies the customer in the Toast platform.

amountDetails

object

Details about a tip amount, such as:

  • tip

  • surcharge

  • lineItemModifiers

email

string

Customer email address.

paymentMethodConfigurationDetails

string

The identifier of the payment method configuration.

standingInstructionType

string

Reserved for future use.

offSession

string

Reserved for future use.

latestPayment

object

Information about the latest payment associated with the payment intent, such as:

  • card

  • lastFour

  • expiry

  • year

  • month

  • brand

error

string

An error message.


The callback functions of the confirmPayment function returns a ConfirmIntentResultEvent.

ConfirmIntentResultEvent

{
   "eventType":"CONFIRM_PAYMENT_RESULT",
   "content":{
      "payment":{
         "id":"86bbcf0c-b483-4bbc-81bf-c2a9cd2baa2c",
         "externalReferenceId":"73edc827-0c18-485f-b581-1ef79f93b940",
         "sessionSecret":"PI_86bbcf0c-b483-4bbc-81bf-c2a9cd2baa2c_SECRET_EqYQ5^CgQWc4J?KBwq2jfv&Ov",
         "amount":2000,
         "currency":"USD",
         "captureMethod":"MANUAL",
         "status":"REQUIRES_CAPTURE",
         "paymentMethodId":"924ef04d-cf41-45f7-9df1-a369847e29a2",
         "creationDate":"2023-09-29T16:42:36.239579Z",
         "setupFutureUsage": null,
         "customerId":"4b2dfc5a-88a3-11ee-b9d1-0242ac120002",
         "amountDetails":{
             "tip":100,
             "surcharge":null,
             "lineItemModifiers":null
         },
         "email":"john.smith@email.com",
         "paymentMethodConfigurationDetails":{
             "id":"497f6eca-6276-4993-bfeb-53cbbbba6f08"
         },
         "standingInstructionType":null,
         "offSession": false,
         "latestPayment": { 1
             "card": {
                 "lastFour": "1111",
                 "expiry": {
                     "month": "12", 
                     "year": "27"  
                 }, 
                 "brand": "VISA" 
             }
        }
}

1

The payment card details associated with the payment intent.


EventErrorContent

{
   "cause":{
      "message": "An error occurred processing your card payment.",
      "developerMessage": "A failure occurred while authorizing this payment."
    }
   "retryable": false
}

Example of the confirmPayment function and callback functions

window.Toast.confirmPayment(
    onSuccessCallback: async (e: ConfirmIntentResultEvent) => void,
    onFailureCallback: async (e: EventErrorContent) => void
)

If the payment intent is successfully confirmed, you must apply the externalReferenceId (payment UUID) to a Toast platform order within five minutes of the payment card authorization. After five minutes, the authorization expires and the Toast platform automatically voids the payment. For more information, see Adding payments to an existing check.

Confirming an intent

Note

The confirmIntent SDK function is replacing the confirmPayment SDK function. The section below only covers how to confirm a setup intent using the confirmIntent SDK function. For information on how to confirm a payment intent using the confirmPayment SDK function, see Confirming a payment.

The confirmIntent function is used to associate the payment method with the customer profile. During the confirmation process, the setup intent’s status transitions from REQUIRES_PAYMENT_METHOD to PROCESSING. If the confirmation is successful, the status changes to SUCCEEDED. If the confirmIntent function fails to confirm the setup intent because the payment card details are invalid, the status changes back to REQUIRES_PAYMENT_METHOD. If the payment card details are invalid, you should display an error message requesting that the customer enter a new payment card or to check their payment card details. For more information on the setup intent statuses, see Setup intent statuses.

The confirmIntent function accepts two callback functions. The callback functions are used to handle successful or unsuccessful setup intent scenarios.

Example of the confirmIntent function and callback functions

Toast.confirmIntent(
    onSuccessCallback: async (e: ConfirmIntentResultEvent) => void,
    onFailureCallback: async (e: EventErrorContent) => void
)


ConfirmIntentResultEvent

{
   "eventType":"CONFIRM_INTENT_RESULT",
   "content":{
       "intent":{
       "id": "1fdd6e15-8471-4853-8862-b755a23816d2",
       "customerId": "611c1e47-8ba3-457b-8879-196da2c427ff",
       "paymentMethodId": "7fa44a69-efab-4f78-a71f-9c44b3e9b7f6",
       "status": "SUCCEEDED", 1
       "usage": "ON_SESSION"
       }
   }
}

1

Indicates that the setup intent was successfully confirmed. The payment method is now associated with the customerId and can be used for future payments.