Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 22 Next »

Example code and detailed, step-by-step instructions for building a payment page using PayFields.

This page includes a Quickstart section, which provides sample code for a basic payment page using all of the available fields provided by PayFields, an Implementation section, which provides details about how to incorporate PayFields into a custom payment page, and definitions of all of the actions supported by PayFields.

Warning: For increased security measures of the platform, only use a Public Key with your Payfields integration in production environments and only use, and regularly change, Transaction Session Keys for sandbox environment testing.

Getting Started

To get started setting up your PayFields integration, you'll need the following: 

  • Some experience with basic front-end languages - HTML, JavaScript & CSS

  • An IDE such as Visual Studio Code or XCode.

  • A valid API Key or Transaction Session Key

  • An active, fully boarded Merchant ID

In your IDE, create or open an existing HTML file for the payment webpage.

Tip: If you want to skip the tutorial, scroll to the PayFields Quickstart Code below.

1. Import Library Scripts

Add the PayFields external script to import the core PayFields iframe functionality and set the development environment. 

PayFields Sandbox (Test) Environment External Script

<script type="text/javascript" src="https://test-api.payrix.com/payFieldsScript"></script>

PayFields Production Environment External Script

<script type="text/javascript" src="https://api.payrix.com/payFieldsScript"></script>

2. Setup Basic Payment Fields

Add the core PayFields form fields with labels inside the <body> element of the file, where the PayFields customer payment entry form will be displayed via iFrame later.

<div>
   <label for="number">Number:</label>
   <div id="number"></div>
</div>
<div>
   <label for="expiration">Expiration:</label>
   <div id="expiration"></div>
</div>
<div>
   <label for="cvv">CVV:</label>
   <div id="cvv"></div>
</div>
<div>
   <label for="name">Name:</label>
   <div id="name"></div>
</div>
<div>
   <label for="address">Address:</label>
   <div id="address"></div>
</div>

3. Add the Submit Transaction Button

Add the transaction submission button below the Basic Fields you just added.

<button type="button" id="submitBtn" class="btn">Submit Payment</button>

4. Add Authentication Script

Add the first PayFields configuration script to authenticate access at the end of your <body>, replacing the placeholders below with your valid Merchant ID and API Key/Transaction Session Key.

<script> // Authentication
  PayFields.config.apiKey = '01a2bc34de5fg678h90ijk123m456789';
  PayFields.config.merchant = 't1_mer_123abc4d567890efg1h2i34';
</script>

5. Add Transaction Settings Script

Add the next PayFields configuration script to set the basic transaction information about the type of transaction, tokenization status, and amount. 

<script> // Transaction Settings
   PayFields.config.mode = '';
   PayFields.config.txnType = '';
   PayFields.config.amount = 1000;
</script>
 Transaction Settings Parameters

Each valid value available for Transaction Settings Configurations parameters and descriptions for PayFields is displayed below:

PayFields.config

JS Format

Description

Valid Values & Notes

.mode

text

The transaction mode, whether tokenization-only, sale transaction-only, or both.

Valid Values:

  • token - Tokenize payment method with $0 authorization.

  • txn - Perform standard transaction sale.

  • txntoken - Tokenize payment method during a standard transaction sale.

.txnType

text

The type of transaction, a Card sale, Card auth, or eCheck (ACH) payment.

Valid Values:

  • sale - Credit Card Sale

  • auth - Credit Card Authorization-Only

  • ach - eCheck Sale

.amount

number

The amount of the transaction.

Format:

1000 = $10.00

Warning: When setting the amount parameter for the tokenization-only transaction, the value must be a quoted string, i.e. '0' must be used, numeric values will not be recognized.

6. Assign Basic Card Payment Fields to PayFields Inputs

Add the PayFields form field connections to assign your payment form elements from Step 2 to the PayFields inputs to securely iframe them onto the page. 

<script> // Form Field Connections
   PayFields.fields = [
      {
         type: "number",
         element: "#number",
      },
      {
         type: "name",
         element: "#name",
      },
      {
         type: "cvv",
         element: "#cvv",
      },
      {
         type: "expiration",
         element: "#expiration",
      },
      {
         type: "address",
         element: "#address",
      }
   ];
</script>

7. Assign Submit Button Functionality

Now, add the Submit Button script to assign the PayFields.submit() function, submitting the transaction to the platform when the customer submits their payment.

<script> // Submit Button Function
   document.querySelector('#submitBtn').addEventListener('click', function() {
      PayFields.submit()
   });
</script>

8. Add Basic Console Log Responses

Add the scripts below to ensure you can review PayFields responses in your browser console log while testing for basic success or failure responses.

<script> // Success Callback
   PayFields.onSuccess = function(response) {
      console.log(response)
     alert('Payment Successful!')
   }
</script>

<script> // Failure Callback
   PayFields.onFailure = function(err) {
      console.log(err)
      alert('Payment failed. Verify your payment method.')
   }
</script>

Done! Your basic PayFields integration is complete and you can begin to test submitting card payment transactions. 

To further customize and enhance your integration, a PayFields JavaScript Reference is provided below containing detailed information about the available actions, functions, and callbacks offered by PayFields. Individual setup steps are outlined below. You can also find more details about specific setups for functions like tokenization or auth-only options offered through PayFields on our PayFields - Additional Features guide.


Quickstart Setup

Follow the steps below to open a basic checkout page with PayFields already integrated:

  1. Copy the code below into a text editor.

  2. Add your API Key or Transaction Session Key and Merchant ID on lines 37 and 38.

    1. If you need a new Transaction Session Key, visit PayFields Best Practices for steps to generate a new value.

  3. Save the file with a .html extension.

  4. Open the file in your web browser. The page will display all of the fields available for use on your custom payment page: card number, expiration date, CVV, and billing address.

PayFields Quickstart Code

 Click to expand the PayFields Quickstart code.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PayFields Example (Basic)</title>
    <script type="text/javascript" src="https://test-api.payrix.com/payFieldsScript"></script>
    <script type="text /javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
    <!---- PayFields Page and Form Field Element Setup ---->
    <h2>My Payment Page</h2>
    <p>Plesae submit your card payment information below to complete your purchase.</p>
    <div>
        <label for="number">Number:</label>
        <div id="number"></div>
    </div>
    <div>
        <label for="expiration">Expiration:</label>
        <div id="expiration"></div>
    </div>
    <div>
        <label for="cvv">CVV:</label>
        <div id="cvv"></div>
    </div>
    <div>
        <label for="name">Name:</label>
        <div id="name"></div>
    </div>
    <div>
        <label for="address">Address:</label>
        <div id="address"></div>
    </div>
    <button type="button" id="submitBtn" class="btn">Submit Payment</button>
    <!---- PayFields Configurations ---->
    <script> // Authentication
        PayFields.config.apiKey = '01a2bc34de5fg678h90ijk123m456789';
        PayFields.config.merchant = 't1_mer_123abc4d567890efg1h2i34';
    </script>
    <script> // Transaction Settings
        PayFields.config.mode = 'txn';
        PayFields.config.txnType = 'auth';
        PayFields.config.amount = 1000;
    </script>
    <script> // Form Field Connections
        PayFields.fields = [
            {
                type: "number",
                element: "#number",
            },
            {
                type: "name",
                element: "#name",
            },
            {
                type: "cvv",
                element: "#cvv",
            },
            {
                type: "expiration",
                element: "#expiration",
            },
            {
                type: "address",
                element: "#address",
            }
        ];
    </script>
    <script> // Submit Button Function
        document.querySelector('#submitBtn').addEventListener('click', function () {
            PayFields.submit()
        });
    </script>
    <script> // Success Callback
        PayFields.onSuccess = function (response) {
            console.log(response)
            alert('Payment Successful!')
        }
    </script>
    <script> // Failure Callback
        PayFields.onFailure = function (err) {
            console.log(err)
            alert('Payment failed. Verify your payment method.')
        }
    </script>
</body>

</html>

Important Info for Canadian 🇨🇦 Merchants:

  • province fields replace the state fields (see valid values here).

  • postal fields replace zip fields (see valid values here).

  • currency will be in CAD.


PayFields JavaScript Reference

The table below defines all of the actions supported by the PayFields JavaScript library:

External PayFields Script Import Query

Query

Description

Valid Values

?spa

A boolean determining whether or not the webpage the PayFields external script is being added to is a single-page application

When this query parameter is set, the following occurs:

  • PayFields will not load immediately on page load, and any authentication validation failures will not be displayed in the console log.

  • Use of the PayFields.ready() action is required to reload the PayFields iframes to the webpage. 

Valid Values:

  • 0 - Not an SPA

  • 1 - SPA

Actions

Action

Description

PayFields.submit()

Submits the PayFields data to the platform.

PayFields.swipePopup()

Opens the card swipe popup for card-present payment terminals.

PayFields.clearFields()

Clears all values from all fields.

PayFields.appendTo()

Moves the specified field to a new <div>.

PayFields.reload()

Reappends the PayField with all existing values to the <div> only if the <div> has been removed.

PayFields.restore()

Restores the values if the PayField is moved to a new <div>.

PayFields.unmountAll()

Removes all loaded PayFields iframes and event handlers from the page. Useful for mounting and unmounting PayFields on demand.

PayFields.ready()

Mandatory function to call when using the spa query parameter. Loads PayFields onto the page.

PayFields.jQuery = jQuery.noConflict()

Prevents jQuery from setting any unwanted global variables.

Callbacks

Action

Description

PayFields.onSuccess = (response) => {}

Runs when the API responds with a successful transaction and/or token.

PayFields.onValidationFailure = () => {}

Runs when invalid or incomplete cardholder and/or payment data is entered.

PayFields.onFailure = (response) => {}

Runs when API Key, Transaction Session Key, or Merchant ID fails validation before creating the API call or when the API responds with a failed transaction or token.

PayFields.onFinish = (response) => {}

Runs when the API responds.

PayFields.onRestore = () => {}

Runs when the PayFields.restore() is run.

PayFields.onUnmount = () => {}

Runs when PayFields.unmountAll() is run.

Configurations 

Configuration

Required

Type

Description

PayFields.config.apiKey

Required

string

The API Key or Transaction Session Key used to authenticate the associated Merchant.

PayFields.config.merchant

Required

string

The Merchant ID for the Merchant entity associated with the PayFields-integrated webpage, (e.g. t1_mer_123abc4d567890efg1h2i34).

PayFields.config.mode

Required

string

Whether the payment capture mode set for PayFields is:

  • txn - Transaction-only (txn)

  • txnToken - Transaction & New Token

  • token - New Token-Only/$0 Authorization

PayFields.config.txnType

Required

string

Whether the transaction mode set for PayFields is:

  • sale - Credit Card Sale

  • auth - Credit Card Auth-Only

  • ecsale - eCheck Sale

PayFields.config.amount

Required

numeric string

The total transaction amount charged. Specified in cents. (e.g. 100000= $1000.00)

PayFields.config.order

Optional

number

Sets an order number for interchange data submission.

PayFields.config.tax

Optional

integer

Sets tax amount for interchange data submission.

PayFields.config.discount

Optional

integer

Sets a transaction discount value for interchange data submission.

PayFields.config.additionalData.shipping

Optional

integer

Sets a shipping charge amount for interchange data submission.

PayFields.config.additionalData.duty

Optional

integer

Sets a duty amount for interchange data submission.

PayFrame.config.customer = {}

Optional

object

Sets customer creation information if a customer ID is not provided. 

 

first

Optional

string

Customer first name

middle

Optional

string

Customer middle name

last

Optional

string

Customer last name

company

Optional

string

Customer company if applicable.

custom

Optional

string

Custom field for passing CRM data or other associated identifier within the Merchant business.

email

Optional

string

Customer email address.

phone

Optional

number

Customer phone number.

fax

Optional

number

Customer fax number.

PayFields.config.items = [{}]

Optional

array of objects

Adds an array of items to the order for interchange data submission. 

Item array data is only required when submitting item information.

 

item

Optional

string

The name of the item. Up to 500 characters long.

productCode

Optional

string

The item product code such as UPC, catalog number, or inventory number. Up to 100 characters long.

description

Optional

string

A description of the Item.

quantity

Optional

integer

The quantity of the item included in the Transaction.

um

Optional

number

The "unit of measure" for this item such as each, kilogram, pound, or month.

price

Optional

integer

The amount charged for this Item. Specified in cents. (e.g. 1000= $10.00)

total

Optional

integer

The total price for the line item. Specified in cents. (e.g. 1000= $10.00)

commodityCode

Optional

number

The commodity code for this Item. Up to 12 characters long.

custom

Optional

string

A custom identifier for this line item. Up to 500 characters long.

discount

Optional

integer

The discount for the line item. Specified in cents. (e.g. 1000= $10.00)

PayFrame.config.billingAddress = {}

Optional

array

Sets known values for the cardholder's billing address that remain hidden on the webpage for interchange data submission.

 

address

Optional

string

Sets the street address.

address2

Optional

string

Sets the unit or suite.

company

Optional

string

Sets the associated company.

city

Optional

string

Sets the city for the cardholder.

state

Optional

string

Sets the state or province, (e.g. NY = New York, ON = Ontario)

zip

Optional

string

Sets a 5-8 digit postal code.

country

Optional

string

Automatically sets the country, USAor CANbased on Merchant entity info. 

email

Optional

string

Sets email address for contact.

phone

Optional

number

Sets phone number for contact.

PayFields.config.additionalData = {}

Optional

array

Allows additional data to be submitted with the transaction.

 

tokenDescription

Optional

string

Custom description of the payment token. Up to 500 characters long.

txnDescription

Optional

string

Custom description of the transaction. Up to 500 characters long.

PayFields.config.invoiceResult = {}

Optional

array

An associated invoice detailing the shipping details for the cardholder.

 

invoice

Optional

string

The associated Invoice ID, (e.g. t1_inv_123abc4d567890efg1h2i34

shippingFirst

Optional

string

Cardholder first name. Up to 100 characters long.

shippingMiddle

Optional

string

Cardholder middle name. Up to 100 characters long.

shippingLast

Optional

string

Cardholder last name. Up to 100 characters long.

shippingCompany

Optional

string

Company name. Up to 100 characters long.

shippingAddress1

Optional

string

The first line of the shipping address. Up to 500 characters long.

shippingAddress2

Optional

string

The unit or suite for the shipping address. Up to 500 characters long. 

shippingCity

Optional

string

The shipping address city. Up to 500 characters long.

shippingState

Optional

string

The shipping address state. Up to 500 characters long.

shippingZip

Optional

string

The 5-8 digit shipping address postal code. 

shippingCountry

Optional

string

USA (United States) or CAN (Canada).

shippingPhone

Optional

string

The associate shipping address phone number.

shippingFax

Optional

string

The associate shipping address fax number.

Customizations

Customization

Required

Type

Description

PayFields.customizations.style = {}

Optional

object

Set core CSS design for PayFields through this JavaScript object to maintain full PCI compliance and security while modifying your PayFields design. 

See PayFields CSS Customizations below.

PayFields.customizations.placeholders = {}

Optional

object

Sets the placeholder values that appear in each PayFields form field. 

See Placeholders below.

PayFields.customizations.optionalFields = []

Optional

array

Can be: 

  • '#address1'

  • '#city'

  • '#state'

  • '#zip'

  • '#customer_id'

  • '#routing'

  • '#account_type'

  • '#account_number'

Fields

PayFields.Fields = []

Required

Description

{
   type: 'name',
   element: '#name',
},

Required

The cardholder or checking account holder's name. 

{
   type: 'address',
   element: '#address',
},

Required

The card or account holder's associated address.

{
   type: 'number',
   element: '#number',
},

Required

Credit/Debit card number.

{
   type: 'cvv',
   element: '#cvv',
},

Required

Credit/Debit Card Verification Value (CVV).

{
   type: 'expiration',
   element: '#expiration',
},

Required

Credit/Debit card expiration month and year (MM/YY)

{
   type: 'account_type',
   element: '#account_type',
},

Optional

The type of eCheck account being used for the transaction. 

Valid Values: 

  • 8 - Personal Checking

  • 9 - Personal Savings

  • 10 - Corporate (Business) Checking

  • 11 - Corporate (Business) Savings

{
   type: 'account_number',
   element: '#account_number',
},

Optional

The account number for the customer's eCheck account.

{
   type: 'routing',
element: '#routing',
},

Optional

The routing number for the customer's eCheck account's financial institution.

Note: Adding values: {} to any of the PayFields.fields JavaScript object payment form field connections will automatically prefill the information. You can choose to display or hide this prepopulated information. See the Prefill & Display or Hide Fields section below for more details.


CSS Customizations

PayFields CSS customizations utilize a unique combination of JavaScript and specifically formatted CSS selectors, properties, and their associated values. There are 3 categories of CSS customizations available: Input Elements, Error Span Elements, & Action Elements. 

Note: These options must be set through the PayFields script to ensure full PCI compliance and security. 

To begin setting CSS stylization options, add the following script to your payment webpage: 

PayFields.customizations.style = {}
  • CSS selectors for class or ID must be enclosed in double quotes, followed by a colon before the standard CSS curly bracket like so: ".class": {}

    • Adding multiple classes requires a comma after the closing curly bracket for each selector.

  • CSS properties are formatted as normal with no quotes.

  • CSS property values must be formatted with double quotes and completed with a comma as normal like so when using multiple properties: property: "value",

Your PayFields.customizations.style = {} JavaScript object should match the formatting below:

PayFields.customizations.style = { 
    ".number": { 
        borderStyle: "solid",
        border-radius: "5px"
    },
    ".address-input": {
        borderStyle: "dashed",
        border-radius: "5px"
    },
    ...
}

Warning: CSS pseudo-classes are not supported by PayFields CSS customizations. Example: #name::hover

CSS Input Element Customization 

CSS Input elements are simply the <div> elements added to the basic PayFields page allowing you to customize the look and feel of your integration to match your branding and payment page. 

All CSS input customization options are shown below:

PayFields.customizations.style = {}

Description

".input"

Defines the style for all payment info input fields.

".number"

Defines the style for the card number input field.

".expiration"

Defines the style for the expiration date input field.

".cvv"

Defines the style for the card verification value (CVV) input field.

".name"

Defines the style for the cardholder name input field.

".address-input"

Defines the style for all address info input fields.

".address1"

Defines the style for the cardholder street address input field.

".city"

Defines the style for the cardholder city input field.

".state"

Defines the style for the cardholder state input field.

".zip"

Defines the style for the cardholder postal code input field.

".email"

Defines the style for the cardholder email address input field.

".phone"

Defines the style for the cardholder phone number input field.

CSS Error Span Element Customization

You can further update the input fields by modifying the look and feel of the error messages that appear on the PayFields payment form when incorrect data is provided by a cardholder.

All CSS error span customization options are shown below:

PayFields.customizations.style = {}

Description

".form-error"

Defines the style for the error message shown when incorrect data is submitted for all payment info input fields.

".number-error"

Defines the style for the error message shown when incorrect data is submitted for the card number input field.

".expiration-error"

Defines the style for the error message shown when incorrect data is submitted for the expiration date input field.

".cvv-error"

Defines the style for the error message shown when incorrect data is submitted for the card verification value (CVV) input field.

".name-error"

Defines the style for the error message shown when incorrect data is submitted for the cardholder name input field.

".address-form-error"

Defines the style for the error message shown when incorrect data is submitted for all address info input fields.

".address1-error"

Defines the style for the error message shown when incorrect data is submitted for the cardholder street address input field.

".city-error"

Defines the style for the error message shown when incorrect data is submitted for the cardholder city input field.

".state-error"

Defines the style for the error message shown when incorrect data is submitted for the cardholder state input field.

".zip-error"

Defines the style for the error message shown when incorrect data is submitted for the cardholder postal code input field.

".email-error"

Defines the style for the error message shown when incorrect data is submitted for the cardholder email address input field.

".phone-error"

Defines the style for the error message shown when incorrect data is submitted for the cardholder phone number input field.

CSS Popup Element Customization

To allow full customization, the card icon pop-up, and the iframe card swipe popup, are customizable to allow you to rearrange and reformat your form, styling and specifying the locations of each popup as needed.

All CSS popup element customization options are shown below:

PayFields.customizations.style = {}

Description

".card-icon"

Defines how and where the card icon will appear as the cardholder enters their card, confirming the correct card brand. 

".payFields-iframe-swiper"

Defines how and where the Swipe Your Card icon is displayed on the screen.

  • No labels