Pay.js v2 (Beta)

Please Note: This page includes references to features that are still under development. For the currently-supported feature set, see the Pay.js v1 documentation (previously Client JS).

You can use the Pay.js library (previously Client JS) to collect payment information from customers paying online in our simple modern interface. Once payment information is collected, it will tokenize the sensitive data into a single-use payment_key to keep your customer's information secure.

Payment types supported in this library include credit card, checks, and mobile wallets Google Pay and Apple Pay.

This library has a variety of implementations. Some implementations can be dropped into an existing form with little to no customization. Other implementations require greater customization, but also allow developers greater control over the payment flow.

You will find basic examples below for:

To see all of the customizable options for each payment type see their respective reference pages:

(If you are migrating from Pay.js v1 to v2, see this handy Migration Guide for breaking changes.)

Public API Key

In order to use the Pay.js library, you'll need to generate a Public API Key on your merchant account. This can be done by using the Public API Key Endpoint in REST, or using the API Key manager in the merchant console. Please note that the public API key used to create a payment key must match the private API key used to process the transaction that uses it. Click here for more information.

Credit/Debit Card

To add the Payment Card Entry to your site, follow these steps:

Card Container

STEP 1- Create Payment Form

First, you should create the payment form. Be sure to import the Pay.js library and include a container element for the Payment Card Entry iframe.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Payment Form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <h1>My Website Checkout Page</h1>

    <form id="paymentForm" action="/charge" method="post">

        <!-- Other Form Data -->

        <label for="paymentCardContainer">Credit/Debit Card</label>
        <div id="paymentCardContainer">
            <!-- Payment Card iframe will go here -->
        </div>
        <div id="paymentCardErrorContainer">
            <!-- Display error messages here -->
        </div>

        <button>Submit Payment Form</button>

    </form>

    <script src="https://www.usaepay.com/js/v2/pay.js"></script>
</body>
</html>

STEP 2- Instantiate Client

Using a Public API Key, instantiate the client and create an instance of the Payment Card Entry.

// Instantiate Client with Public API Key
let client = new usaepay.Client('<public_key>');

// Instantiate Payment Card Entry
let paymentCard = client.createPaymentCardEntry();

Then, generate the HTML for the Payment Card Entry iframe and add it into the container you created in Step 1.

const paymentCardConfig = {
    //add config here
}

paymentCard.generateHTML(paymentCardConfig);

paymentCard.addHTML('paymentCardContainer');

Please Note: The Payment Card Entry can be configured with custom styling, labels, placeholders, etc. See the Credit/Debit Reference for all configurable options.

STEP 3- Get Payment Key

Once the user has entered their card data and is ready to pay, you will need to tokenize the card information. Create an event handler that sends a request to the gateway for tokenization.

// listen for form to be submitted
let form = document.getElementById('paymentForm');
form.addEventListener('submit', event => {
    event.preventDefault();
    // tokenize payment data
    client.getPaymentKey(paymentCard).then(result => {
        if (result.error) {
            handleError(result.error.message);
        } else {
            handlePaymentKey(result.key);
        }
    }).catch( err => {
        handleError(err.message);
    });
})

After the card information is submitted, the server will return a response. If the request was successful, the server will return a one time use payment_key. This is what you will use in place of card information to safely run the transaction. See an example response below.

{
    "type": "payment_key",
    "key": "a1b2c3d4e5f6g7h8i9j0",
    "creditcard": {
        "number": "123456xxxxxx7890",
        "cardtype": "Visa"
    }
}

STEP 4- Submit Form with Payment Key to Server

The final step is to submit the payment_key and whatever other fields you collected in the payment form to your server to process the transaction. Your server should then process all actions needed to complete the sale, including sending the sale to the gateway for approval. This is normally done using our REST API or one of our language specific libraries. Click here for an example of a REST API sale using a payment key.

function handlePaymentKey(paymentKey) {
    // Insert the payment key into the form so it gets submitted to the server
    var form = document.getElementById('paymentForm');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'payment_key');
    hiddenInput.setAttribute('value', paymentKey);
    form.appendChild(hiddenInput);

    // Submit the form
    form.submit();
}

Error Handling

Payment Card Entry error responses will give a code, message, reason, and type (as shown below) to assist you in handling them as you like. The Pay.js library can be configured to display validation errors from within the Payment Card Entry iframe using the display_errors config option if desired. See the Credit/Debit Reference for more info.

Event Listener Example:

// add an error event listener to the paymentCard element
paymentCard.addEventListener('error', err => {
    err = JSON.parse(err);
    console.error(err); // for debug when developing
    // error code 0 means there was no issue and you can clear your error. 
    if (err.code === '0') {
        clearError();
    } else {
        handleError(err.message);
    }
});

function handleError(errorMessage) {
    var errorContainerEl = document.getElementById('paymentCardErrorContainer');
    errorContainerEl.textContent = errorMessage;
    errorContainerEl.classList.remove('hidden');
}

function clearError() {
    var errorContainerEl = document.getElementById('paymentCardErrorContainer');
    errorContainerEl.textContent = '';
    errorContainerEl.classList.add('hidden');
}

Error Response Example:

{
    "code":"12",
    "message":"Please enter a valid credit card number.",
    "reason":"card number must be between 13 and 19 digits",
    "type":"cnum"
}

Check (ACH)

To add the Payment Check Entry to your site, follow these steps:

Check Container

STEP 1- Create Payment Form

First, you should create the payment form. Be sure to import the Pay.js library and include a container element for the Payment Check Entry iframe.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Payment Form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <h1>My Website Checkout Page</h1>

    <form id="paymentForm" action="/charge" method="post">

        <!-- Other Form Data -->

        <label for="paymentCheckContainer">Check (ACH)</label>
        <div id="paymentCheckContainer">
            <!-- Payment Check iframe will go here -->
        </div>
        <div id="paymentCheckErrorContainer">
            <!-- Display error messages here -->
        </div>

        <button>Submit Payment Form</button>

    </form>

    <script src="https://www.usaepay.com/js/v2/pay.js"></script>
</body>
</html>

STEP 2- Instantiate Client

Using a Public API Key, instantiate the client and create an instance of the Payment Check Entry.

// Instantiate Client with Public API Key
let client = new usaepay.Client('<public_key>');

// Instantiate Payment Check Entry
let paymentCheck = client.createPaymentCheckEntry();

Then, generate the HTML for the Payment Check Entry iframe and add it into the container you created in Step 1.

const paymentCheckConfig = {
    //add config here
}

paymentCheck.generateHTML(paymentCheckConfig);

paymentCheck.addHTML('paymentCheckContainer');

Please Note: The Payment Check Entry can be configured with custom styling, placeholders, etc. See the Check (ACH) Reference for all configurable options.

STEP 3- Get Payment Key

Once the user has entered their check data and is ready to pay, you will need to tokenize the check information. Create an event handler that sends a request to the gateway for tokenization.

// listen for form to be submitted
let form = document.getElementById('paymentForm');
form.addEventListener('submit', event => {
    event.preventDefault();
    // tokenize payment data
    client.getPaymentKey(paymentCheck).then(result => {
        if (result.error) {
            handleError(result.error.message);
        } else {
            handlePaymentKey(result.key);
        }
    }).catch( err => {
        handleError(err.message);
    });
})

After the check information is submitted, the server will return a response. If the request was successful, the server will return a one time use payment_key. This is what you will use in place of check information to safely run the transaction. See an example response below.

{
    "type": "payment_key",
    "key": "a1b2c3d4e5f6g7h8i9j0",
    "check": {
        "account": "xxxxxx3123",
        "routing": "xxxxxx3123"
    }
}

STEP 4- Submit Form with Payment Key to Server

The final step is to submit the payment_key and whatever other fields you collected in the payment form to your server to process the transaction. Your server should then process all actions needed to complete the sale, including sending the sale to the gateway for approval. This is normally done using our REST API or one of our language specific libraries. Click here for an example of a REST API sale using a payment key.

function handlePaymentKey(paymentKey) {
    // Insert the payment key into the form so it gets submitted to the server
    var form = document.getElementById('paymentForm');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'payment_key');
    hiddenInput.setAttribute('value', paymentKey);
    form.appendChild(hiddenInput);

    // Submit the form
    form.submit();
}

Error Handling

In addition to the error handling included in the above examples, set up a listener on the Payment Check Entry instance for the error event. These events will include an error message when an error has occurred or an empty string when an error has been resolved. You can also listen for the valid and invalid events which include the name of the valid/invalid field.

Event Listener Example:

// listen for errors
paymentCheck.addEventListener('error', errorMessage => {
    console.error(errorMessage); // for debug when developing
    if (errorMessage.length === 0) {
        // an empty string means an issue was resolved and you can clear your error. 
        clearError();
    } else {
        handleError(errorMessage);
    }
});

// listen for validation
paymentCheck.addEventListener('valid', field => {
    // field will be either "routing", "account", "account-verify", "dl-num", or "dl-state"
    console.log('valid: ', field);
});
paymentCheck.addEventListener('invalid', field => {
    // field will be either "routing", "account", "account-verify", "dl-num", or "dl-state"
    console.log('invalid: ', field);
});

function handleError(errorMessage) {
    var errorContainerEl = document.getElementById('paymentCheckErrorContainer');
    errorContainerEl.textContent = errorMessage;
    errorContainerEl.classList.remove('hidden');
}

function clearError() {
    var errorContainerEl = document.getElementById('paymentCheckErrorContainer');
    errorContainerEl.textContent = '';
    errorContainerEl.classList.add('hidden');
}

Apple Pay™

To add Apple Pay to your payment form, follow these steps:

STEP 1- Configure Merchant Account

To ensure your merchant account is properly configured for Apple Pay, you'll need to:

STEP 2- Create Payment Form with Apple Pay Container

Next, you should create the payment form. Be sure to import the Pay.js library and include a container element for the Apple Pay button.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Payment Form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <h1>My Website Checkout Page</h1>

    <form id="paymentForm" action="/charge" method="post">

        <!-- Other Form Data -->

        <div id="applePayContainer">
            <!-- Apple Pay button will go here -->
        </div>
        <div id="applePayErrorContainer">
            <!-- Display error messages here. -->
        </div>

        <button>Submit Payment Form</button>

    </form>

    <script src="https://www.usaepay.com/js/v2/pay.js"></script>
</body>
</html>

STEP 3- Instantiate Client

Using a Public API Key, instantiate the client and create an instance of the Apple Pay Entry.

// Instantiate Client with Public API Key
let client = new usaepay.Client('<public_key>');

let applePayConfig = {
    targetDiv: 'applePayContainer',
    displayName: 'Capsule Corp',
    paymentRequest: {
        total: {
            label: 'Total',
            amount: '1.00',
            type: 'final'
        },
        countryCode: 'US',
        currencyCode: 'USD'
    }
}

// Instantiate Apple Pay Entry
let applePay = client.createApplePayEntry(applePayConfig);

Please Note: The fields in the applePayConfig object in the example above are the bare minimum required for an Apple Pay Entry, but other fields can be included to add line items and/or shipping options, customize the Apple Pay button, etc. See the Apple Pay Reference for all configurable options.

STEP 4- Verify Apple Pay Compatibility and Add Button

After you have created the Apple Pay Entry, verify that Apple Pay is available. This will check the following:

  1. That the customer's browser is compatible with Apple Pay
  2. That the customer has Apple Pay set up on their device.
  3. That your merchant account is successfully configured for Apple Pay (see step #1).

If successful, then add the Apple Pay button to the page.

// check to see if Apple Pay is available
applePay.checkCompatibility().then(res => {
    // add the Apple Pay button to the targetDiv given in the config
    applePay.addButton();
}).catch(err => {
    // handle compatibility error
    console.error(err);
})

STEP 5- Get Payment Key

Now that the Apple Pay button has been rendered on your page, all that's left to do is wait for the user to click the button and complete the payment. Then you can tokenize the Google Pay Entry to create a payment_key and process the transcation.

// listen for Apple Pay session to be successfully completed
applePay.on('applePaySuccess', function() {
    // tokenize payment data
    client.getPaymentKey(applePay).then(result => {
        handlePaymentKey(result);
    }).catch(err => {
        // handle payment key error
        console.error(err);
    });
});

STEP 6- Submit Form and Payment Key to Server

The final step is to submit the payment_key and whatever other fields you collected in the payment form to your server to process the transaction. Your server can then process all actions needed to complete the sale, including sending the sale to the gateway for approval. This is normally done using our REST API or one of our language specific libraries. Click here for an example of a REST API sale using the payment key.

function handlePaymentKey(paymentKey) {
    // Insert the payment key into the form so it gets submitted to the server
    var form = document.getElementById('paymentForm');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'payment_key');
    hiddenInput.setAttribute('value', paymentKey);
    form.appendChild(hiddenInput);

    // Submit the form
    form.submit();
}

Error Handling

The Pay.js library will display any Apple Pay Entry errors from within the iframe, but you can also listen for the applePayError and/or applePayCancelled events to fire if you would like to trigger any additional actions.

// listen for the Apple Pay session to be cancelled
applePay.on('applePayCancelled', function() {
    // do something
});

// listen for any Apple Pay errors
applePay.on('applePayError', function() {
    // do something
});

Google Pay™

To add the Google Pay Button to your form, follow these steps:

STEP 1- Configure Merchant Account

To configure your account for Google Pay you will need to:

STEP 2- Create Payment Form with Google Pay Container

Next, you should create the payment form. Be sure to import the Pay.js library and include a container element for the Google Pay button. You can optionally import the Google Pay library in your HTML file as well, otherwise the Pay.js library includes a way to import it programatically later on.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Payment Form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- OPTIONAL Google Pay Library Import -->
    <script src="https://pay.google.com/gp/p/js/pay.js"></script>
    <!---------------------------------------->
</head>
<body>
    <h1>My Website Checkout Page</h1>

    <form id="paymentForm" action="/charge" method="post">

        <!-- Other Form Data -->

        <div id="googlePayContainer">
            <!-- Google Pay button will go here. -->
        </div>
        <div id="googlePayErrorContainer">
            <!-- Any error messages will be inserted here. -->
        </div>

        <button>Submit Payment Form</button>

    </form>

     <!-- REQUIRED Pay.js Import -->
    <script src="https://www.usaepay.com/js/v2/pay.js"></script>
    <!----------------------------->
</body>
</html>

STEP 3- Instantiate Client

Using a Public API Key, instantiate the client and create an instance of the Google Pay Entry.

// instantiate Pay.js client with public api key
let client = new usaepay.Client('<public_key>');

let googlePayConfig = {
    targetDiv: 'googlePayContainer',
    paymentDataRequest: {
        transactionInfo: {
            currencyCode: 'USD',
            totalPriceStatus: 'FINAL',
            totalPrice: '1.00'
        },
        merchantInfo: {
            merchantId: '<Google Merchant ID>'
        }
    },
    paymentOptions: {
        environment: 'TEST' // set to PRODUCTION for real transactions
    }
}

// instantiate GooglenPay entry
let googlePay = client.createGooglePayEntry(googlePayConfig);

Please Note: The fields in the googlePayConfig object in the example above are the bare minimum required for a Google Pay Entry, but other fields can be included to add line items and/or shipping options, customize the Google Pay button, etc. See the Google Pay Reference for all configurable options.

STEP 4- Verify Google Pay Compatibility and Add Button

In order for Google Pay to work in the browser, certain requirements must be met. In order to ensure that those requirements are satisfied, run the compatibility check shown below. If the compatibility test is passed, you can then render the Google Pay button.

function checkCompatibility() {
    googlePay.checkCompatibility().then(res => {
        // add the Google Pay button to the targetDiv given in the config
        googlePay.addButton()
    }).catch(err => {
        // handle compatibility error
        console.error(err);
    });
}

Please Note: If you did not import the Google Pay library via script tag in the HTML of your page, then you must import it here before checking for compatibility.

googlePay.loadLibrary().then(res => {
    checkCompatibility();
}).catch(err => {
    // handle library load error
    console.error(err);
});

STEP 5- Get Payment Key

Now that the Google Pay button has been rendered on your page, all that's left to do is wait for the user to click the button and complete the payment. Then you can tokenize the Google Pay Entry to create a payment_key and process the transcation.

// listen for Google Pay session to be successfully completed
googlePay.on('googlePaySuccess', function() {
    // tokenize payment data
    client.getPaymentKey(googlePay).then(result => {
        handlePaymentKey(result);
    }).catch(err => {
        // handle payment key error
        console.error(err);
    })
});

STEP 6- Submit Form and Payment Key to Server

The final step is to submit the payment_key and whatever other fields you collected in the payment form to your server to process the transaction. Your server can then process all actions needed to complete the sale, including sending the sale to the gateway for approval. This is normally done using our REST API or one of our language specific libraries. Click here for an example of a REST API sale using the payment key.

function handlePaymentKey(paymentKey) {
    // Insert the payment key into the form so it gets submitted to the server
    var form = document.getElementById('paymentForm');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'payment_key');
    hiddenInput.setAttribute('value', paymentKey);
    form.appendChild(hiddenInput);

    // Submit the form
    form.submit();
}

Please Note: If you would like to enable 3DS for PAN_ONLY credentials returned via the Google Pay API check out the documentation on VPAS (Verified by Visa) and UCAF (Mastercard Secure Code) and how to include it in the Transaction API.

Error Handling

The Pay.js library will display any Google Pay Entry errors below the Google Pay button, but you can also listen for the googlePayError event to fire if you would like to trigger any additional actions.

googlePay.on('googlePayError', function() {
    // do something
})