Git Product home page Git Product logo

node-sdk's Introduction

Global Payments logo

Heartland & Global Payments Node.js SDK

This SDK makes it easy to integrate your Node.js application with our Card Not Present and Card Present APIs.

Solutions

General / Omnichannel

  • API Payment Processing
  • Apple Pay & Google Pay
  • Secure Card Storage & Customer Management
  • Subscriptions / Recurring Billing Solutions
  • Credit, Debit, Gift & Loyalty, and eCheck/ACH

Card Not Present (Ecommerce & MOTO) Specific

  • Minimize PCI compliance requirements with Hosted Payment Solutions
  • 140+ Authorization Currencies & 16 Settlement Currencies
  • 150+ Local Payment Methods Worldwide
  • Account Updater
  • Inbuilt Fraud Prevention Rules
  • 3D Secure, AVS and CVV Checks
  • 260+ Global Enterprise Fraud Rules

Card Present (Terminal & POS) Specific

  • Secure End-To-End Encryption

Requirements

  • Node.js

Installation

Installing the SDK into your solution is usually be done by either using NPM or Yarn.

To install via NPM:

npm install --save globalpayments-api

To install via Yarn:

yarn add globalpayments-api

Documentation and Examples

You can find the latest SDK documentation along with code examples and test cards on the Global Payments and Heartland Developer Hubs.

In addition you can find working examples in the our example code repository.

Quick Tip: The included test suite can be a great source of code samples for using the SDK!

Process a Payment Example

const card = new CreditCardData();
card.number = "4111111111111111";
card.expMonth = "12";
card.expYear = "2025";
card.cvn = "123";

card
  .charge(129.99)
  .withCurrency("EUR")
  .execute()
  .then((response) => {
    const result = response.responseCode;
    const message = response.responseMessage;
  })
  .catch((e) => {
    // handle  errors
  });

Test Card Data

Name Number Exp Month Exp Year CVN
Visa 4263970000005262 12 2025 123
MasterCard 2223000010005780 12 2019 900
MasterCard 5425230000004415 12 2025 123
Discover 6011000000000087 12 2025 123
Amex 374101000000608 12 2025 1234
JCB 3566000000000000 12 2025 123
Diners Club 36256000000725 12 2025 123

Testing Exceptions

During your integration you will want to test for specific issuer responses such as 'Card Declined'. Because our sandbox environments do not actually reach out to issuing banks for authorizations, there are specific transaction amounts and/or card numbers that will trigger gateway and issuing bank responses. Please contact your support representative for a complete listing of values used to simulate transaction AVS/CVV results, declines, errors, and other responses that can be caught in your code. Example error handling code:

card
  .charge(-5)
  .withCurrency("USD")
  .withAddress(address)
  .execute()
  .catch((e) => {
    switch (e.name) {
      case BuilderError.constructor.name:
        // handle builder errors
        break;
      case ConfigurationError.constructor.name:
        // handle errors related to your services configuration
        break;
      case GatewayError.constructor.name:
        // handle gateway errors/exceptions
        break;
      case UnsupportedTransactionError.constructor.name:
        // handle errors when the configured gateway doesn't support
        // desired transaction
        break;
      case ApiError.constructor.name:
      default:
        // handle all other errors
        break;
    }
  });

Contributing

All our code is open sourced and we encourage fellow developers to contribute and help improve it!

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Ensure SDK tests are passing
  4. Commit your changes (git commit -am 'Add some feature')
  5. Push to the branch (git push origin my-new-feature)
  6. Create new Pull Request

License

This project is licensed under the GNU General Public License v2.0. Please see LICENSE.md located at the project's root for more details.

node-sdk's People

Contributors

securesubmit-buildmaster avatar slogsdon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-sdk's Issues

Can't resolve '/netsuite/set-timeout-polyfill'

Anyone have this issue in 2023?

Can't resolve '../netsuite/set-timeout-polyfill' in '..../globalpayments-api/lib/src'

React Build
node v18
react-scripts 5.0.1 **tried the 4.0.3 fix, but have other npm dependencies in current project that require 5.0.1

Also ran into a multitude of other console errors that were fixed by adding the following to webpack.config.js

      fallback: {
        "stream": require.resolve("stream-browserify"),
        "https": require.resolve("https-browserify"),
        "http": require.resolve("stream-http"),
        "fs": false,
      },

Cannot find module '../../test/Integration/Gateways/Terminals/RequestIdProvider'

Looks Like test Folder is Missing in the modules,

i checked the Node-modules but didn't find test Folder anywhere

Please Help with this

ERROR :

Error: Cannot find module '../../test/Integration/Gateways/Terminals/RequestIdProvider'
Require stack:

  • /Users/ranvijay/Desktop/RV/test_Global_Pay/node_modules/globalpayments-api/lib/src/Gateways/RestGateway.js
  • /Users/ranvijay/Desktop/RV/test_Global_Pay/node_modules/globalpayments-api/lib/src/Gateways/GpApiConnector.js
  • /Users/ranvijay/Desktop/RV/test_Global_Pay/node_modules/globalpayments-api/lib/src/Gateways/index.js
  • /Users/ranvijay/Desktop/RV/test_Global_Pay/node_modules/globalpayments-api/lib/src/index.js
  • /Users/ranvijay/Desktop/RV/test_Global_Pay/index.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
    at Module._load (node:internal/modules/cjs/loader:985:27)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at require (node:internal/modules/helpers:176:18)
    at Object. (/Users/ranvijay/Desktop/RV/test_Global_Pay/node_modules/globalpayments-api/lib/src/Gateways/RestGateway.js:4:29)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Module.require (node:internal/modules/cjs/loader:1235:19) {
    code: 'MODULE_NOT_FOUND',
    requireStack: [
    '/Users/ranvijay/Desktop/RV/test_Global_Pay/node_modules/globalpayments-api/lib/src/Gateways/RestGateway.js',
    '/Users/ranvijay/Desktop/RV/test_Global_Pay/node_modules/globalpayments-api/lib/src/Gateways/GpApiConnector.js',
    '/Users/ranvijay/Desktop/RV/test_Global_Pay/node_modules/globalpayments-api/lib/src/Gateways/index.js',
    '/Users/ranvijay/Desktop/RV/test_Global_Pay/node_modules/globalpayments-api/lib/src/index.js',
    '/Users/ranvijay/Desktop/RV/test_Global_Pay/index.js'
    ]
    }

MY CODE 🥇

const express = require("express");
const GlobalPayments = require("globalpayments-api");
const app = express();

app.use(express.json());

app.post("/create-payment", async (req, res) => {
try {
const { cardNumber, expiry, cvv, amount } = req.body;
const response = await GlobalPayments.cards.charge({
cardNumber,
expiry,
cvv,
amount,
currency: "USD",
});

if (response.isSuccessful) {
  res.json({ transactionId: response.transactionId });
} else {
  res.status(400).json({ message: response.message });
}

} catch (error) {
res.status(500).json({ message: error.message });
}
});

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

Is This Library Compatible With NextJS?

I'm trying to use Heartland with my backend on NextJS but I'm getting this error:
I'm on Next 14.1, Node 21.6.2, NPM 10.2.4.

Import trace for requested module:
./src/app/api/heartland/credit/route.ts
 ⨯ ./node_modules/globalpayments-api/lib/src/index.js:19:4
Module not found: Can't resolve '../netsuite/set-timeout-polyfill'      

https://nextjs.org/docs/messages/module-not-found

I know I'm able to run it on a regular Node/Express server because I spun one up quickly and it worked fine.
However, when I try to run it through an endpoint on NextJS, it doesn't work.

Has anyone been able to make it work with NextJS?

I've already tried reaching out to [email protected] but haven't heard back yet.

Issues in next.js

Running into an issue with polyfill in next.js

Module not found: Error: Can't resolve '../netsuite/set-timeout-polyfill' in '/node_modules/globalpayments-api/lib/src'

High CPU utilization on "capture"

Hi,

Facing high cpu utilization when executing following code:

const capture = await service.capture(response.transactionId).execute();

Some time CPU utilization crossed 100% mark and server get restart.

Thanks

cardLast4 is undefined when calling CreditCardData.charge

When calling CreditCardData.charge, the response contains a cardLast4 property, but its value is undefined. Is this something we should expect to have access to in the response?

Here's an example:

const {
    Address,
    CreditCardData,
    ServicesConfig,
    ServicesContainer,
} = require('globalpayments-api');

const card = new CreditCardData();
card.token = ...;

const address = new Address();
address.streetAddress1 = ...;
address.postalCode = ...;

const transaction = await card
    .charge(...)
    .withCurrency('USD')
    .withAddress(address)
    .execute();

console.log(transaction);

output:

Transaction {
  responseCode: '00',
  responseMessage: 'APPROVAL',
  authorizedAmount: undefined,
  availableBalance: undefined,
  avsResponseCode: '0',
  avsResponseMessage: 'AVS Not Requested.',
  balanceAmount: undefined,
  cardType: 'Visa',
  cardLast4: undefined,
  cavvResponseCode: undefined,
  commercialIndicator: undefined,
  cvnResponseCode: 'M',
  cvnResponseMessage: 'Match.',
  pointsBalanceAmount: undefined,
  recurringDataCode: undefined,
  referenceNumber: '000000000000',
  transactionDescriptor: undefined,
  transactionReference: TransactionReference {
    transactionId: '0000000000',
    paymentMethodType: 2,
    authCode: 'ABC123'
  }
}

Using AVS

How to I invoke a address verification? Even if I include a customer address in the request for charging a card token, the response is always AVS Not Requested..

ReportingService.findTransactions()

I noticed ReportingService.findTransactions() is not implemented into the SDK. Is there a reason why? or perhaps I am missing it?

Also
When I run ReportingService.activity() to get the transactions, it appears to be returning more than transactions. Is there a way to limit the transactions being returned to just recurring transactions, for example?

Thank You.

Missing Batch Information on CloseBatch

closeBatch has a few issues

  1. The Portico Mapper is not returning the batchId, batchSeqNbr, etc...
  2. The Batch Summary is not coded up correctly to use this information if / when it is returned from the PorticoMapper
  3. Even if you fix those issues to return the BatchId the ReportingService in this version of the API does not Support getting the Activity for a batchId, which is available in Portico and was supported in previous versions of the API.

Thanks

Issuing refund with realex

Hello,

Anyone achieved refund with realex, I can't manage to make it work.
I get
GatewayError: Unexpected Gateway Response: 502 - Mandatory Fields missing: [/request/authcode]. See Developers Guide

I can see builder.authorizationCode but no method to set it

I tried transaction.authorizationCode, refund.authorizationCode, config.authorizationCode and many more

there are methods for "supported" languages https://developer.globalpay.com/api/transaction-management#api-rebate

any hint?

Upgrade Issue - "ServicesConfig is not a constructor"

Tried upgrading from 1.4.9 to 3.7.0.
We were on 1.4.9 with a custom patch due to the PCI compliance issue that has been open here since Sep 15, 2023.

Expected results: API to work as normal.

Actual results: API does not work, throwing "ServicesConfig is not a constructor"

Steps to reproduce: Upgrade from 1.4.9 (working code) to 3.7.0.

Example Code:

const {
Address,
ServicesConfig,
ServicesContainer,
CreditCardData,
Transaction
} = require('globalpayments-api');

let servicesConfig = new ServicesConfig();
servicesConfig.secretApiKey = "REDACTED";
servicesConfig.developerId = "REDACTED";
servicesConfig.versionNumber = "REDACTED";
servicesConfig.serviceUrl = "https://api2.heartlandportico.com";
servicesConfig.enableLogging = false;
ServicesContainer.configure(servicesConfig);

Floating-point rounding errors when serializing amounts

The numberFormat function in /src/Gateways/RealexConnector.ts doesn't always parse floats correctly, and needs to do some rounding.

For example:
numberFormat(2.28) returns '227.99999999999997'
numberFormat(19.76) returns '1976.0000000000002'

Hosted Solution : Getting payment 508 error in special cases of amount

When I am trying payment with decimal number line 70.1, 70.9, 1230.1, 1230.9. I am getting following payment error. It is working on all other cases.

"508 Invalid characters in AMOUNT field. Please contact the merchant."

This is current code for payment gateway integration.
`

 const PaymentService = require("globalpayments-api");    
 const config = new PaymentService.ServicesConfig();
 config.hostedPaymentConfig = new PaymentService.HostedPaymentConfig();
 config.hostedPaymentConfig.displaySavedCards = true;
 // config.hostedPaymentConfig.cardStorageEnabled = true;
 config.merchantId = conf.globalpayment.merchantId;
 config.channel = conf.globalpayment.channel;
 config.accountId = conf.globalpayment.accountId;
 config.sharedSecret = conf.globalpayment.sharedSecret;
 config.serviceUrl = conf.globalpayment.serviceUrl;
const hostedPaymentData = new PaymentService.HostedPaymentData();
hostedPaymentData.customerKey = consumerData.paymentGatewayId;
hostedPaymentData.customerExists = true;
hostedPaymentData.offerToSaveCard = true;
console.log(hostedPaymentData);
try {
    const service = new PaymentService.HostedService(config);
    console.log(service);
    var vv = service
        .authorize(1)
        .withCurrency('CAD')
        .withOrderId(orderId)
        .withHostedPaymentData(hostedPaymentData);

    console.log(vv)
    let responseStr = service
        .authorize(1)
        .withCurrency('CAD')
        .withOrderId(orderId)
        .withHostedPaymentData(hostedPaymentData)
        .withAmount(amount)
        .serialize();

    console.log(responseStr);
    console.log(typeof responseStr);
    let response = JSON.parse(responseStr);
} catch (error) {
    console.log(error);
}

`
When I checked out the response, I am getting amount in response like 123090.00000000001.So this look like Library floating point mechanism for amount creating issue.

Module Not Found: '../netsuite/set-timeout-polyfill'

I followed instructions:
npm install --save globalpayments-api

In my App I imported:
import * as heartland from "globalpayments-api";

Getting this error when app loads. I am trying to configure globalpayments with my api key.
heartland-error

Any suggestions on how to get this to work? I see this repo hasn't been updated in some time. Do you use another repo that is more up to date? Thanks.

Lambda function

Trying to require this SDK into lambda function (using serverless Next.js app on now.sh), but got error. Can you explain how to add this package in the lambda function?

> Built @now/next:next.config.js [9s]
> POST /api/payment/
> Building @now/node:api/payment/index.js
downloading user files...
{ [Error: EISDIR: illegal operation on a directory, open '/var/folders/15/57zp9_g1503c1wqt_f6h37gw0000gn/T/co.zeit.now/dev/workPaths/0u797co8/api/payment/node_modules/charenc']
  message:
   'EISDIR: illegal operation on a directory, open \'/var/folders/15/57zp9_g1503c1wqt_f6h37gw0000gn/T/co.zeit.now/dev/workPaths/0u797co8/api/payment/node_modules/charenc\'',
  errno: -21,
  code: 'EISDIR',
  syscall: 'open',
  path:
   '/var/folders/15/57zp9_g1503c1wqt_f6h37gw0000gn/T/co.zeit.now/dev/workPaths/0u797co8/api/payment/node_modules/charenc' }

How to reproduce?

  • Create simple nextjs app
  • Choose target to serverless
  • now.json:
{
  "version": 2,
  "name": "sample-nextjs",
  "builds": [
    {
      "src": "static/**",
      "use": "@now/static"
    },
    {
      "src": "next.config.js",
      "use": "@now/next"
    },
    {
      "src": "api/*/index.js",
      "use": "@now/node"
    }
  ],
  "routes": [
    {
      "src": "/_next/static/(?:[^/]+/pages|chunks|runtime)/.+",
      "headers": { "cache-control": "s-maxage=86400, max-age=0" }
    },
    {
      "src": "/product/(?<id>[^/]+)$",
      "dest": "/product?id=$id",
      "headers": { "cache-control": "s-maxage=86400, max-age=0" }
    },
    { "src": "/api/payment", "dest": "/api/payment/" }
  ]
}
  • /api/payment/index.js:
const {
  Address,
  CreditCardData,
  ServicesConfig,
  ServicesContainer,
  TransactionModifier
} = require('globalpayments-api')

module.exports = async (req, res) => {
  res.setHeader('Content-Type', 'application/json')
  res.end(
    JSON.stringify({
      error: 'Some error while charging'
    })
  )
}
  • add script to package.json: "dev": "now dev"
  • run yarn dev and send POST request to localhost:3000/api/payment

[IMPORTANT] PCI Compliance issue in 1.4.9

You need to edit node_modules/globalpayments-api/lib/src/Gateways/XmlGateway.js and comment out the contents of XmlGateway.prototype.log. This is a PCI compliance issue as it saves the entire transaction including all credit card details to disk unencrypted.

Before:

 XmlGateway.prototype.log = function (text) {
        fs.appendFile('logger.txt', text + '\n', function (err) {
            if (err)
                throw err;
        });
    };

After:

 XmlGateway.prototype.log = function (text) {
        /*
        fs.appendFile('logger.txt', text + '\n', function (err) {
            if (err)
                throw err;
        });
        */
       });
   };

Help to Integrate the GlobalPayments in React Native..

I have Looked on the Main Website for both the ANDROID and IOS,

I Read All these Links

IOS : https://developer.globalpay.com/client-side-libraries/ios#ios
ANDROID : https://developer.globalpay.com/client-side-libraries/android#android
SDK : https://developer.globalpay.com/ecommerce/sdks

But all this Didn't help me to integrate this in React native,

If any one have Ever Integrated GlobalPayments in React Native and can help Please Help.

I am trying this for Long Now

Thanks

connect ETIMEDOUT when using remote api

Hi,

I keep getting an ETIMEDOUT when trying to perform card.charge() on your remote api. The api url is https://api.sandbox.realexpayments.com/epage-remote.cgi

The error is:
Error: connect ETIMEDOUT 193.105.253.183:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1129:14) {
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
address: '193.105.253.183',
port: 443
}

The gateway configure fine without issue but card.charge() timesout. I have a valid shared secret and merchant id.

Any suggestions ?

KR, M.

Compilation Error

After adding library from npm i am not able to compile the code . I am getting the flowing error :

Module not found can't resolve 'promise pollyfill'

can't write to logger.txt in production

I am using google cloud functions for deployment. In production when card.charge(2) is trying to write on logger.txt which is not accesible in production. Beacause of that I am getting error in production. In local environment its runninh fine as it has access to logger.txt.
How can i stop it from writing to logger.txt?

NPM install is not installing the last version present in the GitHub master branch

Hi guys,

I have realised that after installing the last version from npm:

npm install globalpayments-api@latest --save

I can see the dependency is installed as 1.3:
"globalpayments-api": "^1.3.1"

but all the cardTypes implementation to get the credit card type using regex committed here:
c3d2b2d#diff-0a5d089d43d995d37f6c131ca958c14c

is not in the local version installed through NPM.

Any ideas? Maybe the NPM repo must be updated too?

Cheers!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.