Integrating Moneris Checkout with JavaScript: Handling JSON Response Issues

Integrating Moneris Checkout with JavaScript: Handling JSON Response Issues
Integrating Moneris Checkout with JavaScript: Handling JSON Response Issues

Seamless Integration of Moneris Checkout: Troubleshooting JSON Response

Moneris Checkout is a commonly used payment gateway system that helps businesses expedite online transactions. However, integrating it into your website might be difficult, especially when required data, such as a ticket number, is not returned from a JSON call. Such errors can impede the regular flow of transactions, so debugging is a necessary skill for engineers.

Understanding how to properly configure the checkout is critical when replacing an outdated Hosted Payment Page (HPP) with Moneris and using their JavaScript interface. To provide your clients with a seamless experience, ensure that the page posts transaction details and retrieves accurate responses.

Many developers have trouble following Moneris' integration documentation. The complexity stems from handling callbacks, uploading transaction data, and reading outcomes in real time, all of which are required for a successful integration. As you begin your integration journey, having a clear and well-documented methodology might be beneficial.

In this post, we'll look at how to resolve the issue of missing ticket numbers in your Moneris integration. You'll be better prepared to deal with this issue if you review the necessary code snippets and troubleshooting techniques.

Command Example of use
monerisCheckout() This is the constructor function from the Moneris JavaScript SDK. It initiates the checkout procedure. This script generates a new instance of the Moneris checkout widget, which allows you to embed the payment gateway on your website.
setMode() Specifies the environment for the Moneris transaction. In this example, "qa" refers to a test environment in which you can securely simulate transactions without processing actual payments. This is necessary for testing the integration without actually charging the cards.
setCheckoutDiv() This command associates the Moneris checkout with a specified HTML container (div). By supplying the ID "monerisCheckout", the payment widget is displayed within this div, allowing you to select where the form appears on the page.
setCallback() During the checkout process, assign a function to a specific event. In this scenario, the custom function "myPageLoad" handles the event "page_loaded", allowing developers to run code when the checkout page is completely loaded.
startCheckout() Begin the Moneris checkout process. When called, this function starts the payment flow by rendering the payment form and connecting it to the backend system for processing transactions.
app.post() This is an Express.js route handler that handles POST requests. This script receives payment receipts from the Moneris backend after a transaction is finished, which allows for additional processing such as preserving payment data or issuing confirmations.
bodyParser.json() A middleware function in Express for parsing incoming JSON requests. It is especially critical in this case because Moneris transmits transaction data in JSON format. This command guarantees that the request body is correctly processed for server-side processing.
chai.request() This command is part of the Chai HTTP testing package that sends HTTP requests within test cases. It replicates POST requests to the Moneris payment API during the unit test, allowing the developer to see how the backend handles successful and failed transactions.
expect() A core assertion function in the Chai library. In the context of unit tests, it determines whether particular conditions are satisfied. It is used to ensure that the response status and message returned by the payment endpoint match the intended outcomes.

Understanding the Moneris Checkout Integration and Script Workflow

The front-end script included integrates the Moneris Checkout system into a website via JavaScript. The primary functionality begins with establishing an instance of the Moneris checkout through the monerisCheckout() constructor. This instance serves as an interface between your website and Moneris' payment processing service. The command setMode() specifies whether the environment should be set to "qa" for testing or "live" for production, which is critical during development stages. By selecting "qa," developers can replicate transactions without incurring real-world costs, creating a safe testing ground.

Once the checkout instance is built, the setCheckoutDiv() command connects the Moneris checkout form to a specific HTML div. This is where the payment form will appear on the page. This guarantees that the visual depiction of the payment form shows in a specific region of the website, making the procedure seamless and integrated into your existing design. In our example, the Moneris form is inserted into the div with the ID "monerisCheckout." This div serves as a placeholder for Moneris' dynamically loaded content, which includes client payment input fields and buttons.

The script then executes setCallback(), allowing the developer to configure specific event handling for the checkout process. Specifically, the callback for "page_loaded" is attached to the function myPageLoad, guaranteeing that when the page is fully loaded, extra custom actions (such as logging data) can occur. This function allows for flexibility in how the user experience is handled. Logging the contents of the ex object within myPageLoad() assists developers in debugging by providing real-time feedback on the data Moneris returns.

Finally, the back-end script handles the server-side receipt of payment data. Using Express.js in Node.js, the route app.post() is defined to receive POST requests from Moneris once the transaction is complete. This endpoint processes the returned JSON, checking the response_code to see if the payment was successful. If successful, the transaction data (such as the ticket number) can be logged or entered into a database. By returning suitable status codes and messages, the backend enables smooth connection with the frontend, providing critical feedback to the user, such as whether the transaction succeeded or failed.

Moneris Checkout Integration with JavaScript: Front-End and Back-End Solutions

Front-end solution utilizing JavaScript to incorporate the Moneris Checkout form and handle transaction responses.

// Front-end integration script
// This script embeds the Moneris checkout and processes the transaction result

<script src="https://gatewayt.moneris.com/chktv2/js/chkt_v2.00.js"></script>
<div id="monerisCheckout"></div>
<script>
var myCheckout = new monerisCheckout();
myCheckout.setMode("qa"); // Set environment to QA
myCheckout.setCheckoutDiv("monerisCheckout"); // Define div for checkout
// Add callback for when the page is fully loaded
myCheckout.setCallback("page_loaded", myPageLoad);
// Start the checkout process
myCheckout.startCheckout("");

// Function that gets triggered when the page is loaded
function myPageLoad(ex) {
    console.log("Checkout page loaded", ex);
}

// Function to handle the receipt after the payment
function myPaymentReceipt(ex) {
    if(ex.response_code === '00') {
        alert("Transaction Successful: " + ex.ticket);
    } else {
        alert("Transaction Failed: " + ex.message);
    }
}
</script>

Back-End Solution with Node.js and Express: Handling Payment Data

Back-end solution utilizing Node.js and Express to manage Moneris' post-payment data

// Node.js backend script for processing payment receipt data
// This backend handles the response from Moneris and processes it for database storage

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Endpoint to receive the payment result
app.post('/payment-receipt', (req, res) => {
    const paymentData = req.body;

    if (paymentData.response_code === '00') {
        console.log('Payment successful:', paymentData.ticket);
        // Insert into database or further process the payment
        res.status(200).send('Payment success');
    } else {
        console.error('Payment failed:', paymentData.message);
        res.status(400).send('Payment failed');
    }
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Unit Testing the Backend Payment Handling with Mocha and Chai

Backend unit testing with Mocha and Chai to validate money handling functionality

// Unit test for the Node.js backend using Mocha and Chai
// This test checks if the backend properly handles successful and failed transactions

const chai = require('chai');
const chaiHttp = require('chai-http');
const app = require('../app'); 
const expect = chai.expect;
chai.use(chaiHttp);

describe('POST /payment-receipt', () => {
    it('should return 200 for successful payment', (done) => {
        chai.request(app)
            .post('/payment-receipt')
            .send({ response_code: '00', ticket: '123456' })
            .end((err, res) => {
                expect(res).to.have.status(200);
                expect(res.text).to.equal('Payment success');
                done();
            });
    });

    it('should return 400 for failed payment', (done) => {
        chai.request(app)
            .post('/payment-receipt')
            .send({ response_code: '01', message: 'Transaction Declined' })
            .end((err, res) => {
                expect(res).to.have.status(400);
                expect(res.text).to.equal('Payment failed');
                done();
            });
    });
});

Enhancing Moneris Checkout Integration with Customization Options

When working with the Moneris Checkout integration, developers frequently look for methods to personalize the checkout process to improve the user experience. The checkout form's UI components can be customized, which is a lesser-known function. Moneris allows businesses to customize the appearance and layout of the checkout page, allowing them to align it with their branding. This involves modifying button layouts, form fields, and even the wording to make the process easier for end users and increase conversions.

Another factor to examine is the use of transaction kinds other than basic payments. Moneris has capabilities such as pre-authorization, in which a transaction amount is stored on the card but not charged immediately. This functionality is especially important in areas such as hotels and automobile rentals, where final rates can differ. The integration can handle many transaction types using the same API, making it versatile for various use cases.

Security is a top priority in any payment integration, and Moneris Checkout incorporates technologies like tokenization and fraud prevention. Tokenization substitutes sensitive card information with a token, so consumer data is never exposed on your systems. Implementing security measures, such as fraud detection technologies and PCI DSS compliance, can dramatically reduce the risks connected with online transactions.

Common Questions About Moneris Checkout Integration

  1. What is Moneris Checkout?
  2. Moneris Checkout is a payment gateway solution that enables businesses to securely accept payments through their website. It provides customisable checkout forms and accepts a variety of payment ways.
  3. How can I customize the Moneris Checkout form?
  4. The Moneris API allows you to customize the design of the checkout form by changing elements such as buttons and input fields. Use commands like setCustomStyle() to add your brand's style to the form.
  5. What is the importance of setting the environment to "qa"?
  6. Setting the environment to "qa" with setMode("qa") allows you to safely test transactions without processing real payments.
  7. How do I handle a pre-authorization transaction?
  8. To manage pre-authorization, include the action: "preauth" argument in your JSON request. This will place a hold on the customer's card rather than charging it immediately.
  9. What are the security measures provided by Moneris Checkout?
  10. Moneris supports tokenization, which replaces sensitive credit card information with a token. Compliance with PCI DSS assures that your integration meets industry security requirements.

Final Thoughts on Moneris Checkout Integration

To successfully integrate Moneris Checkout with JavaScript, both the front-end and back-end setups must be carefully planned. Providing a good checkout experience for users requires ensuring that transaction details, such as the ticket number, are appropriately captured.

Testing in a QA environment and properly structuring your payment form will help you detect problems early. With the correct technique, you can create a seamless and secure payment procedure that suits your company's goals while assuring client happiness.

References and Resources for Moneris Checkout Integration
  1. This article is based on the Moneris Checkout Integration documentation and API reference. For more detailed information, visit the official Moneris GitHub repository: Moneris Checkout GitHub .
  2. Additional guidance on setting up JavaScript-based payment integrations can be found on the Moneris developer portal: Moneris Developer Portal .
  3. For best practices on handling JSON calls and capturing transaction responses, consult the JavaScript SDK documentation: Moneris JavaScript SDK .