+
A Simple Guide for Integrating Plaid with ACHQ Payment Processing
Introduction
ACHQ has partnered with Plaid to provide a simple and secure method for instantly authenticating and tokenizing each of your customers' bank accounts. When you integrate Plaid into your application, your customers will use the Plaid Link client interface to authenticate with their financial institution and select the bank account they wish to use for payment transactions. You will have instant knowledge that the bank account is verified and legitimate.

The Plaid Link client is initiated with a simple drop-in javascript interface that handles input validation, error handling, and multi-factor authentication. Once your customer has authenticated their bank account, Plaid Link provides your application with a Plaid access_token and an ACHQ processor_token which then allows your application to securely initiate an ACH payment via the ACHQ API without needing to store any sensitive banking information.
Integration Overview
The Plaid Link client is initiated with a few lines of javascript code that will be provided to you in this document. Plaid also provides their own Plaid Link client-side libraries for iOS, Android and React and React Native apps.

The client-side javascript code will need to communicate with server-side handlers in your application that will be responsible for:
  • Securely initializing the Plaid Link client through the Plaid API
  • Retrieving Plaid access and processor tokens from the Plaid API once a bank account has been authenticated
  • Initiating a debit or credit ACH payment through the ACHQ API using your Plaid processor token
Althought making a REST API call to Plaid is quite simple, Plaid also provides libraries and SDK's for multiple languages to help facilitate server-side communication with the Plaid API.

Once you have retrieved an authenticated ACHQ processor_token from Plaid, the final step is to initiate an ACH payment transaction through the ACHQ API using the processor_token in place of the customer's normal routing and bank account information.
Getting Started
First you will need an ACHQ account and a Plaid account to take full advantage of this unique integration. You will also need to enable the ACHQ integration in your Plaid account.

If you do not already have an ACHQ merchant account, simply click HERE to begin sending and receiving ACH payments through ACHQ today. If you'd like a tailored solution for your business - drop us a line HERE and we'll be in touch right away. Of course, you will also need to sign up for a Plaid account if you do not already have one.

Once you have a Plaid account, please verify that your Plaid account is enabled for ACHQ integration. Go to the Team Setting -> Integrations section of the Plaid dashboard. If integration is off, simply click the 'Enable' button to enable ACHQ integration.

Also, you will want to make sure that the customer has to select the bank account they want to use from within the Plaid Link client. Go to the Customize -> Select Account section of the Plaid dashboard, select "Enabled for one account" and hit the Publish Changes button.
Understanding the Complete Process Flow
The following is a quick summary of the methods and processes detailed in this document for integrating Plaid Link into your application and submitting tokenized ACH payments through the ACHQ API.
  1. You will install javascript client code to initialize the Plaid Link client on the page where you want to verify and collect your customer's bank account information for payment.
  2. The javascript client code must call a server-side handler on your application that will retrieve a link_token from Plaid.
  3. The javascript client code will use that link_token to instantiate and display the Plaid Link client to your customer.
  4. Your customer will select their bank from the Plaid Link client, authenticate using their banking credentials and then select the bank account they want to use for payment.
  5. After the customer successfully authenticates their credentials and selects the bank account to use for payment, the Plaid Link client will provide a public_token back to the javascript client code.
  6. The javascript client code will then pass that public_token back to a final server-side handler that will be responsible for the following final tasks:
    • Call the Plaid API to exchange the public_token for a Plaid access_token
    • Call the Plaid Processor API to convert the access_token to an ACHQ processor_token
    • Initiate a debit or credit payment through the ACHQ API using the ACHQ processor_token
  7. Finally, your app will respond to your customer with confirmation of ACH payment.
Integration Instructions
1. Drop-in the quickstart javascript code that will initialize and launch the Plaid Link client

Plaid provides a javascript library for initializing their Plaid Link client. A simple script reference to link-initialize.js on the Plaid servers will instantiate their client library.

The Plaid.create function accepts a configuration parameter that contains the following important structural components:

  • token - a short lived, one-time use 'link_token' that must be unique for each Plaid Link session. The sample code shows how you can use inline jquery to call a server-side handler on your app to obtain this token from Plaid. Sample code and an explanation for obtaining this link_token is provided in the next instruction section of this document.
  • onSuccess - An event handler that fires when the user has successfully authenticated and selected a bank account from within the Plaid Link client. There are two parameters provided to the event handler: public_token and metadata. The public_token value represents the privilege granted to the merchant to access the customer's bank information, but it is meaningless and useless to anybody except the Plaid merchant who initiated the Plaid Link client session.

    The metadata parameter is a JSON object that contains a copy of the public_token, data about the customer's bank, and required information about the customer's bank account(s). If the customer selected their desired bank account for payment while inside the Plaid Link client, the metadata object will include an account_id for that bank account. If an account_id is not provided, the metadata object will contain an array of 'Accounts' for each bank account the customer maintains at that institution.

    If you have not instructed Plaid to require the customer to select a specific bank account for payment from within the Plaid Link client, you will have to use the Accounts array in the metadata object to instead display and capture the ID of the bank account the customer wants to use.  We highly recommend that you see the Getting Started section above for instructions on how to force bank account selection from within the Plaid Link client.

    The onSuccess event handler should call a server-side handler in your app that will be responsible for converting the public_token and the account_id of the selected bank account to an ACHQ processor_token and submitting an ACH payment through the ACHQ API.  Instructions and sample code for this server-side handler are included later in this document.
  • onExit - An event handler that fires when the user exits the Plaid Link client. There are two parameters provided to the event handler: err and metadata. The metadata parameter is discussed already in detail in the onSuccess event handler description above.

    In the event of an error with the Plaid Link client, the err parameter will not be null. Your code here should handle the error and display the appropriate response to your customer. The err parameter will contain the following json components and information:
    • error_type - a broad categorization of the error.
    • error_code - the particular error code. Each error_type has a specific set of error_codes.
    • error_message - a eveloper-friendly representation of the error code.
    • display_message - a user-friendly representation of the error code (null if the error is not related to user action).
Complete documentation for the Plaid.create function can be found at https://plaid.com/docs/link/web/#create.
Plaid Quickstart Javascipt for ACHQ Integration

<button id="link-button" type="button">Link Account</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>
<script type="text/javascript">
    (async function($) {
      var handler = Plaid.create({
        // Call a server-side handler to create a new link_token to initialize Link
        //    Sample code and help for creating this server-side handler are included
        //    in Instruction section #2 of this document
        token: await $.post('/get_link_token');
        onLoad: function() {
          // Optional, called when the Plaid Link client loads
        },
        onSuccess: function(public_token, metadata) {
          // Build a javascript object that contains the customer profile and payment amount from your payment page
          var paymentdata = load_paymentdata();

          // Dynamically add the Plaid metadata to your paymentdata object
          paymentdata['metadata'] = metadata;

          // Send the paymentdata to your app server 
          // to submit your tokenized ACH payment transaction.
          var response = $.post('/process_ach_payment', paymentdata);

          // Handle payment success or failure response to your customer here
        },
        onExit: function(err, metadata) {
          // The user exited the Link flow.
          if (err != null) {
            // The user encountered a Plaid API error prior to exiting.
          }
          // metadata contains information about the institution
          // that the user selected and the most recent API request IDs.
          // Storing this information can be helpful for support.
        },
        onEvent: function(eventName, metadata) {
          // Optionally capture Link flow events, streamed through
          // this callback as your users connect an Item to Plaid.
          // For example:
          // eventName = "TRANSITION_VIEW"
          // metadata  = {
          //   link_session_id: "123-abc",
          //   mfa_type:        "questions",
          //   timestamp:       "2017-09-14T14:42:19.350Z",
          //   view_name:       "MFA",
          // }
        }
      });
      $('#link-button').on('click', function(e) {
        handler.open();
      });
    })(jQuery);

    function load_paymentdata() {
        // Create a javascript object containing your customer's profile and payment information
        // with actual data from your form input fields.  The following data is hard-coded for the example.

        var paymentdata = {};
        paymentdata['customername'] = "Jane Doe";      
        paymentdata['address1'] = "1234 Some Street";
        paymentdata['city'] = "Some City";
        paymentdata['state'] = "FL";
        paymentdata['zip'] = "12345";
        paymentdata['email'] = "[email protected]";
        paymentdata['phone'] = "123-456-7890";
        paymentdata['paymentAmount'] = "200.00";

        return paymentdata;
    }
</script>
2. Create the '/get_link_token' server-side handler to fetch the link_token needed to initialize the Plaid Link client
Code samples from the various client libraries available from Plaid are included in the side pane.

In the event you are using a different programming language, your code will simply need to pass a json string object to one of the following Plaid API url's depending on your implementation mode:

  • Sandbox - https://sandbox.plaid.com/link/token/create
  • Development - https://development.plaid.com/link/token/create
  • Production - https://production.plaid.com/link/token/create
The json payload structure looks like this:

{
  "client_id": "YOUR PLAID CLIENT ID",
  "secret": "YOUR PLAID SECRET",
  "user": {    "client_user_id": "unique-per-user"  },
  "client_name": "Your Plaid App Name",
  "products": ["auth"],
  "country_codes": ["US"],
  "language": "en",
  "webhook": "https://sample-web-hook.com"
}
The response is a simple json object containing the following elements:

{
  "link_token": "link-production-840204-193734",
  "expiration": "2020-03-27T12:56:34.000Z"
}
Your code will return the link_token value to the javascript client to complete the Plaid Link client initialization.

More documentation for the Plaid API /link/token/create endpoint can be found at https://plaid.com/docs/api/tokens/#linktokencreate.
Server-Side Link Token Initialization

// To clone the Plaid API libraries 
// visit https://plaid.com/docs/api/libraries/ 

// Using Express
const express = require('express');
const app = express();
app.use(express.json());

const plaid = require('plaid');

const client = new plaid.Client({
  clientID: process.env.PLAID_CLIENT_ID,
  secret: process.env.PLAID_SECRET,
  env: plaid.environments.sandbox,
});

app.post('/get_link_token', async (request, response) => {
  try {
    // Get the client_user_id by searching for the current user
    const user = await User.find(...);
    const clientUserId = user.id;

    // Create the link_token with all of your configurations
    const tokenResponse = await client.createLinkToken({
      user: {
        client_user_id: clientUserId,
      },
      client_name: 'My App',
      products: ['auth'],
      country_codes: ['US'],
      language: 'en',
      webhook: 'https://webhook.sample.com',
    });

    response.on({ link_token: tokenResponse.link_token });
  } catch (e) {
    // Display error on client
    return response.send({ error: e.message });
  }
});
3. Create the '/process_ach_payment' server-side handler
When your customer has successfully authenticated and selected a bank account from the Plaid Link client, the onSuccess event handler should then call the '/process_ach_payment' server-side handler that will be responsible for converting the public_token and the account_id of the selected bank account to an ACHQ processor_token and submitting an ACH payment through the ACHQ API.

There are 3 steps involved in this process:
  • Exchange the Plaid public_token for a Plaid access_token
  • Use the Plaid access_token to convert the selected account_id to an ACHQ processor_token
  • Submit the ACHQ processor_token through the ACHQ API to create an ACH payment
Code samples from the various client libraries available from Plaid are included in the side pane.

Exchanging the Plaid public_token for a Plaid access_token
If you are not using one of the Plaid language libraries, your code will need to pass a json string object to one of the following Plaid API url's depending on your implementation mode:
  • Sandbox - https://sandbox.plaid.com/item/public_token/exchange
  • Development - https://development.plaid.com/item/public_token/exchange
  • Production - https://production.plaid.com/item/public_token/exchange
The following shows the JSON request and response for the Plaid API /item/public_token/exchange endpoint:

JSON Request Object Example
{
  "client_id": "YOUR PLAID CLIENT_ID",
  "secret": "YOUR PLAID SECRET",
  "public_token": "public-sandbox-5c224a01-8314-4491-a06f-39e193d5cddc"
}

JSON Response Object Example
{
  "access_token": "access-sandbox-de3ce8ef-33f8-452c-a685-8671031fc0f6",
  "item_id": "M5eVJqLnv3tbzdngLDp9FL5OlDNxlNhlE55op",
  "request_id": "Aim3b"
}
More documentation for the Plaid API /item/public_token/exchange endpoint can be found at https://plaid.com/docs/api/tokens/#itempublic_tokenexchange.

Using the Plaid access_token to convert the selected account_id to an ACHQ processor_token
If you are not using one of the Plaid language libraries, your code will need to pass a json string object to one of the following Plaid API url's depending on your implementation mode:
  • Sandbox - https://sandbox.plaid.com/processor/token/create
  • Development - https://development.plaid.com/processor/token/create
  • Production - https://production.plaid.com/processor/token/create
The following shows the JSON request and response for the Plaid API /processor/token/create endpoint:

JSON Request Object Example
{
    "client_id": "YOUR PLAID CLIENT ID",
    "secret": "YOUR PLAID SECRET",
    "access_token": "access-sandbox-de3ce8ef-33f8-452c-a685-8671031fc0f6",
    "account_id" : "jAE3gXxwwytKVpKqVB3lHpboNnzyNwt1WPVEM",
    "processor": "achq"
}

JSON Response Object Example
{
  "processor_token": "processor-sandbox-0asd1-a92nc",
  "request_id": "xrQNYZ7Zoh6R7gV"
}
More documentation for the Plaid API /processor/token/create endpoint can be found at https://plaid.com/docs/api/processors/#processortokencreate.
The '/process_ach_payment' server-side handler

// To clone the Plaid API libraries 
// visit https://plaid.com/docs/api/libraries/ 

// Using Express
const express = require('express');
const app = express();
app.use(express.json());

const plaid = require('plaid');

const client = new plaid.Client({
  clientID: process.env.PLAID_CLIENT_ID,
  secret: process.env.PLAID_SECRET,
  env: plaid.environments.sandbox,
});

app.post('/process_ach_payment', async (request, response) => {
  try {
   
    // convert the 'public_token' to a Plaid 'access_token'
    const exchangeTokenResponse = await plaidClient
      .exchangePublicToken(request.body.metadata.public_token)
      .catch((err) => {
        // handle error
      });
    const accessToken = exchangeTokenResponse.access_token;

    // Create a processor token for a specific account id.
    const processorTokenResponse = await plaidClient
      .createProcessorToken(accessToken, request.body.metadata.account_id, 'achq')
      .catch((err) => {
        // handle error
      });
    const processorToken = processorTokenResponse.processor_token;

    // Submit the payment to ACHQ
    var achq_response = submit_ACHQ_payment(request.body, processorToken);

    response.send(JSON.parse(achq_response));

  } catch (e) {
    // Display error on client
    response.send({ error: e.message });
  }
});


4. Submit the payment to ACHQ
The final step of the '/process_ach_payment' server-side handler is processing the ACH payment through the ACHQ SpeedChex API and returning a response to the payment form where your client javascript will indicate success or failure submitting the ACH payment.

The ACHQ SpeedChex API needs the following information to process an ACH payment:
  • ACHQ API credentials
  • Customer name and address information
  • Payment amount and other payment specific information
  • Bank account information in one of the following forms:
    • An ACHQ processor_token from Plaid
    • Traditional bank routing and account number
In the event that your customer chooses not use Plaid to authenticate and provide their bank account information in the form of a Plaid processor_token, you can still collect your customer's routing number, bank account number and check type on your payment form and submit that account data through the ACHQ SpeedChex API.

Production API credentials will be provided to you when you setup your ACHQ merchant account. The ACHQ SpeedChex API supports sandbox, development and production modes but through a single API endpoint instead of multiple endpoints like Plaid. Please note the following methods for differentiating and controlling your integration mode for the ACHQ SpeedChex API:

  • Sandbox Mode - ACH payments are sent to a Sandbox account where they are captured, stored and show up in status tracking reports and queries - but they are never sent to the Federal Reserve for processing. You must use the following credentials for sending payments to the Sandbox account
    
    
         MerchantID:        2001
         Merchant_GateID:   test
         Merchant_GateKey:  test
    
  • Development Mode - In Development mode, ACH payments are submitted to the ACHQ API using your production credentials with a TestMode parameter set to "On". Payments submitted in this mode will receive a valid success or failure response, but unlike Sandbox and Production modes - these ACH payments are never stored on the ACHQ platform for processing or made available for reporting and status tracking queries.
  • Production Mode - ACH payments are submitted to the ACHQ API using your production credentials with TestMode set to "Off" or left undefined.  ACH payments submitted in production mode are batched and submitted through the Federal Reserve for processing each business day.
CLICK HERE to view the full documentation for the ACHQ Speedchex REST API endpoint.
DOWNLOAD our PostMan collection for the ACHQ SpeedChex API's to assist with development and testing.
Submit the payment to ACHQ

function submit_ACHQ_payment(paymentData, processorToken) {
    var request = require('request');
    request.post({
      url:     'https://www.speedchex.com/datalinks/transact.aspx',
      headers: {'content-type' : 'application/x-www-form-urlencoded'},
      form:    { "MerchantID": "2001",
                 "Merchant_GateID": "test",
                 "Merchant_GateKey": "test",
                 "Command": "ECheck.ProcessPayment",
                 "CommandVersion": "2.0",
                 "Amount": paymentData.paymentAmount,
                 "SECCode": "WEB",
                 "Customer_IPAddress": "127.0.0.1",
                 "DeliveryWindow": "Standard",
                 "PaymentDirection": "FromCustomer",
                 "Merchant_ReferenceID": "12345",
                 "Description": "Test Transaction",
                 "Billing_CustomerID": "1234567",
                 "Billing_CustomerName": paymentData.customername,
                 "Billing_Address1": paymentData.address1,
                 "Billing_City": paymentData.city,
                 "Billing_State": paymentData.state,
                 "Billing_Zip": paymentData.zip,
                 "Billing_Phone": paymentData.phone,
                 "Billing_Email": paymentData.email,
                 "SendEmailToCustomer": "Yes",
                 "TokenSource": "Plaid",
                 "AccountToken": processorToken,
                 "ResponseType": "JSON"}
        }, 
        function(error, response, body){
            return body;
    });
}
5. Tracking the status of ACH payments
Unlike credit cards, the final funding status of ACH payments cannot be known in real time. In fact, by federal regulations banks are allowed up 3 to 5 business days to send a "Return" notification to reject an ACH payment. Any payments that are not Returned by a customer's bank are deposited to your bank account at the end of your settlement period.

In some rare circumstances, it is possible for a bank to send a Return notification after funds have settled. This type of return is called a "Charge Back" because the customer's money must be charged back from your bank account and returned to the customer.

For this reason, you will want to implement a status update engine that queries the ACHQ SpeedChex API each night for the previous day to find out if any ACH payments were returned, charged back or if they settled to your bank account.

The code samples to the side show how to query the ACHQ SpeedChex Status Tracking API to retrieve status updates each night.

CLICK HERE to view the full documentation for the ACHQ SpeedChex Status Tracking API endpoint.
DOWNLOAD our PostMan collection for the ACHQ SpeedChex API's to assist with development and testing.
Tracking the Status of ACH Payments

    var request = require('request');
    request.post({
      url:     'https://www.speedchex.com/datalinks/transact.aspx',
      headers: {'content-type' : 'application/x-www-form-urlencoded'},
      form:    { "MerchantID": "2001",
                 "Merchant_GateID": "test",
                 "Merchant_GateKey": "test",
                 "Command": "ECheckReports.StatusTrackingQuery",
                 "CommandVersion": "2.0",
                 "TrackingDate": "12012020"}
        }, 
        function(error, response, body){
	    // Parse and process the csv response
            console.log(body);
    });
Solution Provider API Documentation
Software companies, SaaS providers, ISV's and processors can partner with ACHQ to deliver ACH payment processing from within their own software platforms for merchants and organizations. Registration as an ACHQ software partner is required. Once approved, ACHQ partners simply integrate to ACHQ using the Solution Provider API.

CLICK HERE to view the full documentation for the ACHQ Solution Provider REST API endpoint.

CLICK HERE to view the full documentation for the ACHQ Solution Provider Status Tracking API endpoint.

DOWNLOAD our PostMan collection for the ACHQ Solution Provider API's to assist with development and testing.

Please note that the ACHQ Solution Provider API operates on the exact same principles and methods as the Merchant API detailed above. The Solution Provider API is simply an extension of these same processes through a single Solution Provider aggregator account. The code examples and explanations above will still apply with simple modifications to include Solution Provider specific parameters.