npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@cgvweb/openpay-node

v3.0.0

Published

Openpay library

Downloads

1

Readme

Logo Openpay

Openpay Node.js

The official SDK for integrating Openpay into your Node.js apps.

API Documentation

Full API documentation available at:

  • México: https://documents.openpay.mx/docs/api/
  • Colombia: https://documents.openpay.co/api/
  • Perú: https://documents.openpay.pe/api-v2/

🚀 Quick Start

Install:

# npm
npm i openpay

# pnpm
pnpm i openpay

# yarn
yarn add openpay

Instantiate:

// ESM / Typescript
import { Openpay } from "openpay";

// CommonJS
const { Openpay } = require("openpay");

const openpay = new Openpay({
  merchantId: process.env.OPENPAY_MERCHANT_ID ?? '',
  privateKey: process.env.OPENPAY_PRIVATE_KEY ?? '',
  isProductionReady: false,
  countryCode: 'mx',
})

// Use the API
await openpay.<resource>.<method>()

✔️ Features

  • ESM and Typescript support
  • Async/await support
  • Production/Sandbox environments
  • Only 1 dependency. Uses ofetch for simple data fetching
  • API errors are thrown by ofetch. Use try/catch to handle them gracefully

[!IMPORTANT] Make sure to review the official documentation for your country to know exactly which API methods are available and country-specific fields that might be required.

✔️ Compatibility

This SDK is built for Node.js v14.0.0 and above, but might be compatible with older versions.

⚙️ Configuration

To instantiate the Openpay SDK, yo need to pass the following configurations:

import { Openpay } from "openpay";

const openpay = new Openpay({
  // Options
});

| Option | Type | Description | | ----------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------- | | merchantId | string | Your unique merchant ID from the Openpay dashboard | | privateKey | string | Your unique private key from the Openpay dashboard | | isProductionReady | boolean | If false, all methods will call the Sandbox API. Otherwise, the Production API will be used. | | countryCode? | "mx" | "co" | "pe" | The country to use the API from. Only México (mx), Colombia (co) and Perú (pe) are supported. Defaults to mx. |

If your application supports multiple countries, or you have multiple merchant accounts, we recommend creating an Openpay instance for each country/merchant to avoid accidentally using the wrong API.

However, if you need to change any of these configurations after instantiation, you can do so with the following methods:

openpay.setMerchantId("new-merchant-id");
openpay.setPrivateKey("new-private-key");
openpay.setProductionReady(true);
openpay.setCountryCode("co");

✔️ Error Handling

Whenever the API returns an error or the SDK is unable to communicate with the API, Openpay will throw a FetchError from ofetch. You can handle any error by wrapping the API call inside of a try/catch block:

import { FetchError } from "ofetch";

try {
  const customer = await openpay.customers.create(input);
} catch (error) {
  if (error instanceof FetchError) {
    console.error("Openpay API error:", error.data);
  }
}

If the FetchError was created by the Openpay API, error.data will have this shape:

| Property | Type | | ----------------------- | ------------------------------------------ | | error.data.category | "request" | "internal" | "gateway" | | error.data.error_code | number | | error.data.description | boolean | | error.data.http_code | number | | error.data.request_id | string | | error.data.fraud_rules? | string[] | undefined |

Any other error that was not caused by the Openpay API, such as connection errors, won't have the same error.data shape and must be handled as an ofetch FetchError.

For detailed descriptions and possible error codes, check out the official documentation.

✔️ Examples

Creating a customer

// Optional. Use type safety
import type { IOpenpay } from "openpay";

const input: IOpenpay.Customers.CreateInput = {
  name: "John",
  last_name: "Doe",
  email: "[email protected]",
  phone_number: "1234567890",
};

try {
  const customer = await openpay.customers.create(input);
  console.log("The newly created customer:", customer);
} catch (error) {
  console.error("Openpay API error:", error);
}

Creating a charge

// Optional. Use type safety
import type { IOpenpay } from "openpay";

const input: IOpenpay.Charge.CreateFromCard = {
  amount: 50,
  method: "card",
  description: "Test existing card charges",
  device_session_id: "fraud-protection-token", // Token from client used for fraud prevention
  customer: {
    name: "John",
    last_name: "Doe",
    email: "[email protected]",
    phone_number: "1234567890",
  },
  card: {
    card_number: "4111111111111111",
    holder_name: "John Doe",
    expiration_year: "29",
    expiration_month: "1",
    cvv2: "110",
  },
};

try {
  const transaction = await openpay.charges.create(input);
  console.log("The newly created transaction:", transaction);
} catch (error) {
  console.error("Openpay API error:", error);
}

[!TIP] For more detailed examples, take a look at the tests folder and the API documentation for your country.

🔧 Contributions

To contribute to this project, fork this repository and install the dependencies with pnpm:

pnpm i

The project uses Biome for linting and formatting. If you are using VS Code, we recommend installing the biomejs.biome extension and to disable Prettier (esbenp.prettier-vscode) if enabled.

🧪 Tests

This project runs tests using Vitest with Typescript.

There are 3 test files available:

Each one of them tests specific methods that are available to their specific country. However, the one with most of the SDK functionality is tests/mexico.spec.ts since it supports most of the API features.

To run the tests, you must create a .env.testing file. Use .env.example as reference. It must contain the following:

| Variable | Description | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | OPENPAY_MERCHANT_ID | Your own unique merchantId from the Openpay Sandbox Dashboard | | OPENPAY_PRIVATE_KEY | Your own unique privateKey from the Openpay Sandbox Dashboard | | OPENPAY_DEVICE_SESSION_ID | A session ID generated by the Openpay.js client for fraud protection | | OPENPAY_WEBHOOK_TEST_URL | To test webhooks, you must pass a valid endpoint that would reply with status 200. We recommend creating a free test url from https://webhook.site |

[!NOTE] Please make sure you use your merchant ID and private key for a SANDBOX environment. All tests will run on sandbox mode, so passing production values will cause every test to fail.

Before running the tests, you must build the package:

pnpm build

Now, you can run the tests for a specific country with their own script:

# For México
pnpm test:mx

# For Colombia
pnpm test:co

# For Perú
pnpm test:pe

[!IMPORTANT] The tests depend on having OPENPAY_MERCHANT_ID and OPENPAY_PRIVATE_KEY from an account created in the country you're running the tests on. For example: if you want to run pnpm test:co, you must use a merchant ID and private key from an account created in Openpay Colombia. Otherwise the tests will fail.

[!NOTE] For México tests, the transfers and fees API's might fail since they require the customer to have funds, but the account created during the test won't have any. If you get a different error, please check your implementation.