How to run Node JS Sample Code for MLE

Visa Employee

How to run Node JS Sample Code for MLE

In this “How-to” guide, we will show you how to test MLE (Message Level Encryption) enabled APIs using Node JS.


Important Links:


Enable MLE for the API(s) you are interested in.


Login to your Visa Developer Dashboard and go to your project, you should see something like this:




Enable the APIs for which MLE needs to be active in VDP by toggling the API for which MLE needs to be enforced.


In this example, we will enable MLE for Funds Transfer API And Query API as below:





How to get credentials


You can obtain your project credentials by browsing the left side navigation menu of your project and click on “Credentials”.




Next step we will create a Key-ID by clicking on the Generate Key-ID button.




After you have clicked the button, you will get Key-ID. Copy the Key-ID for your reference.

The Key-ID will look like this: 41d9f2a1-xxxx-4xxx-b40c-a0480c2xxxxx




The next step is to add a CSR (Certificate Signing Request). Click on the link "Add CSR" .   


You will be prompt to submit a Certificate Signing Request. 




We have option to Generate a CSR for me (default) or submit your own. In this example we will use the Generate a CSR for me (default) and Click Confirm button.


After submitting the request, you will be prompt to download the Certificate/Copy Private Key. 




After you have downloaded the private key, check the box "I confirm that I've downloaded my certificate key" and click continue. You will see the Status change to "Active".



Expand the Key-ID and you will see the Server Encryption Certificate and Client Encryption Certificate.

Download both certificates and save it.



To be able to make an API call with MLE, you need to have the following

  • Server Encryption Certificate
  • Key-ID
  • Certificate Private Key


How to run Node JS Sample Code for MLE



Step 1 - Create a new project on WebStorm


  • Launch WebStorm, on the WebStorm Welcome Screen, click Create New Project.
  • In the New Project wizard, select Node.js Express App from the list on the left, provide the project Location and click Create.
  • Create a new Javascript file and named it “mle_oct


Refer to How to run Node JS Sample Code using the Hello World API and Mutual SSL for how to create a project with WebStorm and testing VISA APIs using Mutual SSL



Step 2 - Copy the below sample code to the “mle_oct.js” file


  • Install all the required dependencies when prompt by WebStorm. Alternatively you can use NPM (Node Package Manager) to download and install the dependencies.
  • Set the below parameters:


const username = '<YOUR USER ID>';
const password = '<YOUR PASSWORD>';

const key = '<YOUR PRIVATE KEY PATH>';

const mleServerPublicCertificate = '<YOUR MLE SERVER PUBLIC CERTIFICATE PATH>';
const mleClientPrivateKey = '<YOUR MLE CLIENT PRIVATE KEY PATH>';
const keyId = '<YOUR KEY ID>';






 * (c) Copyright 2018 - 2020 Visa. All Rights Reserved.**
 * NOTICE: The software and accompanying information and documentation (together, the “Software”) remain the property of and are proprietary to Visa and its suppliers and affiliates. The Software remains protected by intellectual property rights and may be covered by U.S. and foreign patents or patent applications. The Software is licensed and not sold.*
 *  By accessing the Software you are agreeing to Visa's terms of use ( and privacy policy ( addition, all permissible uses of the Software must be in support of Visa products, programs and services provided through the Visa Developer Program (VDP) platform only ( **THE SOFTWARE AND ANY ASSOCIATED INFORMATION OR DOCUMENTATION IS PROVIDED ON AN “AS IS,” “AS AVAILABLE,” “WITH ALL FAULTS” BASIS WITHOUT WARRANTY OR  CONDITION OF ANY KIND. YOUR USE IS AT YOUR OWN RISK.** All brand names are the property of their respective owners, used for identification purposes only, and do not imply product endorsement or affiliation with Visa. Any links to third party sites are for your information only and equally  do not constitute a Visa endorsement. Visa has no insight into and control over third party content and code and disclaims all liability for any such components, including continued availability and functionality. Benefits depend on implementation details and business factors and coding steps shown are exemplary only and do not reflect all necessary elements for the described capabilities. Capabilities and features are subject to Visa’s terms and conditions and may require development,implementation and resources by you based on your business and operational details. Please refer to the specific API documentation for details on the requirements, eligibility and geographic availability.*
 * This Software includes programs, concepts and details under continuing development by Visa. Any Visa features,functionality, implementation, branding, and schedules may be amended, updated or canceled at Visa’s discretion.The timing of widespread availability of programs and functionality is also subject to a number of factors outside Visa’s control,including but not limited to deployment of necessary infrastructure by issuers, acquirers, merchants and mobile device manufacturers.*

const express = require('express');
const https = require('https');
const request = require('request');
const app = express();
const bodyParser = require('body-parser');
const path = require('path');
const jose = require('node-jose');
const fs = require('fs');

app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({extended: true}));

const hostname = '';
const port = 443;
const username = '<YOUR USER ID>';
const password = '<YOUR PASSWORD>';
const key = '<YOUR PRIVATE KEY PATH>';

const mleServerPublicCertificate = '<YOUR MLE SERVER PUBLIC CERTIFICATE PATH>';
const mleClientPrivateKey = '<YOUR MLE CLIENT PRIVATE KEY PATH>';
const keyId = '<YOUR KEY ID>';

app.get('/', (req, res) => {

    var options = getOptions();
    options.headers.keyId = keyId;
    options.uri = '';
    options.method = 'POST';
    parameters = getParameters();
    jose.JWK.asKey(fs.readFileSync(mleServerPublicCertificate), 'PEM', {
        "kty": "RSA",
        "alg": "RSA-OAEP-256",
        "kid": keyId,
        enc: "A128GCM",
        key_opts: ["wrapKey", "enc"]
    }).then(function (result) {
        encryptionResult = jose.JWE.createEncrypt({
            format: 'compact',
            contentAlg: 'A128GCM',
            fields: {iat:}
        }, result).update(JSON.stringify(parameters.payload)).final()
            .then(function (data) {
                options.body = {"encData": data.toString()};
      , (err, response, body) => {
                    if (err) {
                        return console.log(err);
                    console.log(`Status: ${response.statusCode}`);
                    console.log(`Encrypted Response: ${JSON.stringify(response.body)}`);

                    jose.JWK.asKey(fs.readFileSync(mleClientPrivateKey), 'PEM').then(function (result) {
                        jose.JWE.createDecrypt(result).decrypt(response.body.encData, {
                            contentAlg: 'A128GCM',
                            alg: 'RSA-OAEP-256'
                        }).then(function (decryptedResult) {
                            options.uri = '' + JSON.parse(decryptedResult.plaintext).transactionIdentifier;
                            request.get(options, (err, response, body) => {
                                if (err) {
                                    console.log(`Errored due to ${err}`);
                                console.log(`Status: ${response.statusCode}`);
                                console.log(`Encrypted Response: ${JSON.stringify(response.body)}`);
            }).catch(function (reason) {
                console.log('Encryption failed due to ');

app.listen(3050, function () {
    console.log('Example app listening on port 3050.');

function getParameters() {
    const parameters = {
        "x-client-transaction-id": "1612321873781263",
        "Accept": "application/json",
        "Content-Type": "application/json"
    parameters.payload = {
        "acquirerCountryCode": "840",
        "acquiringBin": "408999",
        "amount": "124.05",
        "businessApplicationId": "AA",
        "cardAcceptor": {
            "address": {
                "country": "USA",
                "county": "San Mateo",
                "state": "CA",
                "zipCode": "94404"
            "idCode": "CA-IDCode-77765",
            "name": "Visa Inc. USA-Foster City",
            "terminalId": "TID-9999"
        "merchantCategoryCode": "6012",
        "pointOfServiceData": {
            "motoECIIndicator": "0",
            "panEntryMode": "90",
            "posConditionCode": "00"
        "recipientName": "rohan",
        "recipientPrimaryAccountNumber": "4957030420210462",
        "retrievalReferenceNumber": "412770451018",
        "senderAccountNumber": "4957030420210454",
        "senderAddress": "901 Metro Center Blvd",
        "senderCity": "Foster City",
        "senderCountryCode": "124",
        "senderName": "Mohammed Qasim",
        "senderReference": "",
        "senderStateCode": "CA",
        "sourceOfFundsCode": "05",
        "systemsTraceAuditNumber": "451018",
        "transactionCurrencyCode": "USD",
        "transactionIdentifier": "381228649430015"

    return parameters;

function getOptions() {
    const options = {
        hostname: hostname,
        port: port,
        key: fs.readFileSync(key),
        cert: fs.readFileSync(cert),
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': 'Basic ' + new Buffer(username + ':' + password).toString('base64')

        json: true
    options.agent = new https.Agent(options);
    return options;





Step 4 - Compile Your Code 



Want more? Join the Visa Developer Community to get alerts on the latest tutorials, guides and new developer resources. Stay tuned for more in the series.