Overview

Paysafe.js enables merchants to create a customized payment form that complies with the least demanding level of PCI compliance, SAQ-A. All the sensitive payment fields (card number, cvv, and expiry date or expiry year and month) are displayed in an iframe hosted on Paysafe Group's servers, and the user input and storage of the data is handled by Paysafe Group. Paysafe.js makes use of the Payment API REST APIs to handle the payment.

Advantages

  • Complies with PCI SAQ-A, because Paysafe Group handles security for the sensitive fields.
  • Extensive customization options enable you to create your own payment form that matches your website.
  • Create as many translated or localized versions of your payment form as required.
  • Fast page load times.
  • No redirection is required.
  • Embeds naturally and remains invisible.
  • Supports processing payments with 3D Secure-enabled cards.
  • Supports processing of Cards and ApplePay.
  • Gives information on the decline rate of a card brand, so merchant can choose an alternative payment method

Before you Begin

Log in to the Business Portal to procure your Public API key.

Please contact your business relationship manager or reach out to integrations@paysafe.com for your credentials to the Business Portal.

To obtain the Public API key from the Business Portal:

  1. Go to Integrate>API Keys.
  2. For Public Key, click the Copy icon to copy the API key.

Your API key will have the following format:

  • Key Username – MerchantXYZ
  • Key Password – B-tst1-0-51ed39e4-312d02345d3f123120881dff9bb4020a89e8ac44cdfdcecd702151182fdc952272661d290ab2e5849e31bb03deede7e

Use the same API key for all the Payment Methods.

You must Base64 Encode your Public API key before using it in the Payments JS SDK.

The API key is case-sensitive and sent using HTTP Basic Authentication.

To use HTTP Basic Authentication, you must send the API key credentials using the Authorization header with every request. You must construct the Authorization header as follows:

  1. Combine the Key Username and Key Password into a string separated by a colon, e.g., “Key Username:Key Password”.
  2. The resulting string literal is then encoded using Base64.
  3. The authorization method and space (i.e., “Basic”) are then put before the encoded string.

For example, using the Key Username and Password examples above, the header is formed as follows:

Authorization: Basic TWVyY2hhbnRYWVo6Qi10c3QxLTAtNTFlZDM5ZTQtMzEyZDAyMzQ1ZDNmMTIzMTIwODgxZGZmOWJiNDAyMGE4OWU4YWM0NGNkZmRjZWNkNzAyMTUxMTgyZmRjOTU yMjcyNjYxZDI5MGFiMmU1ODQ5ZTMxYmIwM2RlZWRlN2U=

For additional details, please refer here.

Integrating JS

Paysafe JS collects your customer details, such as account information, billing details, and so on. It helps your customers complete the order by processing the payments. Paysafe JS software development kit gives you the freedom to build your custom integration.

Please reach out to our Integrations Support Team at integrations@paysafe.com to set up a test account, and include the supported payments you would like to add to your test account.

Try Now

For a brief demonstration of Paysafe.js, enter a test card number below (for example, 4111 1111 1111 1111), a valid future expiry date, a random three digit CVV, and then click Pay. A successful tokenization attempt will result in the token appearing in the cURL example below, which shows how you can take payment on your server (try this out in a Unix/Cygwin terminal to see the API response). If you have python installed, we recommend that you add the following to the end of the cURL request to format the JSON response clearly | python -mjson.tool

Payment Details

To view the above example in CodePen, click here.

curl -location -request POST 'https://api.test.paysafe.com/paymenthub/v1/payments' \
	- u apiKeyId:apiKeyPassword
	- header 'Content-Type: application/json' \
	- data-raw '{
		"merchantRefNum": "payment-token-demo-1",
		"amount": 5000,
		"currencyCode": "USD",
		"settleWithAuth": true,
		"paymentHandleToken": "CARDS PAYMENT TOKEN RECEIVED FROM CLIENT BROWSER"
}'

How to Use the SDK

  1. Create your custom HTML payment form with the content (text and images) and style you require.
  2. Include the Paysafe.js JavaScript SDK (paysafe.min.js) <script> tag in the <head> element of your HTML payment form.
  3. Add empty container elements (typically <div>) to your HTML for each of the sensitive payment fields: card number, CVV, expiry date, and/or Apple Pay.
  4. Call the SDK fields.setup function with your single-use token API key. The setup function inserts iframes hosted on Paysafe Group's servers inside these containers. These iframes contain input fields to capture the payment data.
  5. Call the SDK instance.show function without any parameters. The show function visualizes the Paysafe JS fields and returns a list of available payment methods.
  6. Finally, add the instance.tokenize function to the Pay button's click event. This returns a single-use payment handle token (the token representing the card data entered by the user is stored in the Payment API). Single-use tokens are valid for only 15 minutes.
  7. Send the token to your merchant server, where the standard Payment API payment endpoint can be used to make payment.

Single-use payment handle tokens are valid for 15 minutes before they expire. You can convert them to a re-usable, multi-use payment handle, which enables you to do things like recurring billing, e.g., pay a subscription or create a "remember me" feature.

Enhancing the Payment Form

You can enhance the Payment form in these ways:

  • You can style the payment fields by providing certain CSS commands as part of the style section of the options object in the fields.setup function.
  • By using the SDK on function to subscribe to events inside the hosted field iframes that correspond to user actions, such as entering an invalid card number or selecting the field (focus); you can then respond to these events in your payment form.

Including the SDK

When you include the SDK <script> tag in the <head> element, either:

  • Include the latest version
  • Include a specific version

Paysafe Group recommends including the latest version of the SDK as you will automatically receive all the latest updates and bug fixes.

Include the Latest Version

To include the latest version of the SDK, use the following:

<head>
    <script src="https://hosted.paysafe.com/js/v1/latest/paysafe.min.js"></script>
</head>

Include a Specific Version

Each version of the SDK is located at https://hosted.paysafe.com/js/version/paysafe.min.js. To include one of these, replace version with the version of the SDK to use; for example:

<head>
    <script src="https://hosted.paysafe.com/js/{version}/paysafe.min.js"></script>
</head>

Paysafe Group maintains compatibility between minor versions. For example, version 1.X.Y is compatible with version 1.V.W, but version 2.A.B would not be compatible with any version 1 release.

Example Payment Form

The following is a simple Paysafe.js code sample that creates a payment form with three sensitive data fields: Card number, Expiry date and CVV; it contains a payment button that triggers tokenization of the user-entered data and (if tokenization was successful) displays the token in the browser console.

<!-- Basic Paysafe.js example -->
<html>
  <head>
    <!-- include the Paysafe.js SDK -->
    <script src="https://hosted.paysafe.com/js/v1/latest/paysafe.min.js"></script>
    <!-- external style for the payment fields.internal style must be set using the SDK -->
    <style>
      .inputField {
        border: 1px solid #e5e9ec;
        height: 40px;
        padding-left: 10px;
      }
    </style>
  </head>
  <body>
    <!-- Create divs for the payment fields -->
    <div id="cardNumber" class="inputField"></div>
    <p></p>
    <div id="expiryDate" class="inputField"></div>
    <p></p>
    <div id="cvv" class="inputField"></div>
    <p></p>
    <!-- Add a payment button -->
    <button id="payNow" type="button">>Pay now</button>
    <script type="text/javascript">
      // Base64-encoded version the Single-Use Token API key.
      // Create the key below by concatenating the API username and password
      // separated by a colon and Base 64 encoding the result
      var API_KEY = 'Your Base64-encoded Single-use-Token Api Key';
      var options = {
        // You must provide currencyCode to the Paysafe JS SDK to enable the Payment API integration
        currencyCode: "'USD"
        ',
        // select the Paysafe test / sandbox environment
        environment: "'TEST"
        ',
        // Provide a cards merchant toaccount if you have more than one configured for that same API key
        //   accounts: {
        //   default: 0000000000,
        // },
        // set the CSS selectors to identify the payment field divs above
        // set the placeholder text to display in these fields
        fields: {
          cardNumber: {
            selector: '#cardNumber',
            placeholder: 'Card number',
            separator: ' ',
          },
          expiryDate: {
            selector: '#expiryDate',
            placeholder: 'Expiry date',
          },
          cvv: {
            selector: '#cvv',
            placeholder: 'CVV',
            optional: false,
          },
        },
      };
      // initalize the hosted iframes using the SDK setup function
      let demoInstance;
      paysafe.fields.setup(API_KEY, options).then(instance => {
          console.log('Setup instance completed.');
          demoInstance = instance;
          return instance.show();
        }).then(paymentMethods => {
            if (paymentMethods.card && !paymentMethods.card.error) {
              // When the customer clicks Pay Now,
              // call the SDK tokenize function to create
              // a single-use payment token corresponding to the card details entered
              document.getElementById('payNow').addEventListener('click', function(event) {
                    var tokenizationOptions = {
                      amount: 1000,
                      transactionType: 'PAYMENT',
                      paymentType: 'CARD',
                      merchantRefNum: 'merchant-ref-num-' + new Date().getTime(),
                      customerDetails: {
                        billingDetails: {
                          country: 'US',
                          zip: '90210',
                          street: 'Oak Fields 6',
                          city: 'ca',
                          state: 'CA',
                        },
                      },
                    };
                    demoInstance.tokenize(tokenizationOptions).then(result => {
                      // write the Payment token value to the browser console
                      console.log(result.token);
                    }).catch(error => {
                      // display the tokenization error in dialog window
                      alert(JSON.stringify(error));
                    });
                  }, false, .catch(error => {
                    // display any setup errors
                    alert(JSON.stringify(error));
                  });
    </script>
  </body>
</html>

Paysafe.js errors are numbered in the range 9nnn. Errors in the other ranges are generated by the Payment API and may be caused by using an invalid single-use token API key, or by using your server-to-server API key rather than the single-use token API key.

Further Details

The SDK consist of the setup function, several instance function (including several field functions). Click the links below for full details.

FunctionPurpose
Main Functions
setup

Creates the hosted fields instance.

Validates options.

instance.show

Preload any merchant configurations.

Populates the specified containers (typically div containers) on your payment form for each of the sensitive fields.

Sets the style and placeholder text (e.g., Card number) for these fields along with an optional card number separator.

Provides information on which payment methods have loaded successfully and available for use.

instance.tokenizeTriggers the tokenization process that provides a single-use payment handle for use with the Payments API.
instance.onSubscribe to events emitted by the instance.
instance.fields.<fieldname>.onSubscribe to events emitted by a particular field.
Additional Functions
instance.fields.<fieldname>.<event type>Shorthand event registration—a shorthand method of registering for events. This is an alternative to the on function.
instance.getCardBrandRetrieves the current card brand.
instance.cardBrandRecognitionSubscribe to the cardBrandRecognition event.
instance.submitSubscribe to the submit event.
instance.fields.<fieldname>.isEmptyChecks if the named field is empty.
instance.fields.<fieldname>.isValidChecks if the named field is valid.
instance.areAllFieldsValidChecks if all fields are valid.
instance.badBinThe card brand is enabled for transaction salvage and there is a chance that the transaction will be declined
instance.unsupportedCardBrandThe card brand is not configured for the merchant's account
instance.resetCardDetailsClears previously inserted card data in all fields. Optionally expiry date can be prefilled by passing it as argument.

Changelog

VersionDescription
1.13.1

Paysafe.js integration with Payment API launched.

1.14.0Added Saved Cards functionality.
Did you find this page useful?