Node.js SDK

Our Node.js SDK provides Promise-based methods for all API endpoints and TypeScript definitions for better development experience. It's designed to be simple, intuitive, and fully compatible with modern JavaScript practices.

Installation

Install the SDK using npm:

npm install @carifinance/sdk

Or using Yarn:

yarn add @carifinance/sdk

Basic usage

CommonJS

const { CariFinanceClient } = require("@carifinance/sdk");

// Initialize with your API key
const cariFinance = new CariFinanceClient("sk_test_51NzaWTBOIWoX8E7wnMd1...");

// The SDK will automatically detect if you're using a test or live key

ES Modules

import { CariFinanceClient } from "@carifinance/sdk";

// Initialize with your API key
const cariFinance = new CariFinanceClient("sk_test_51NzaWTBOIWoX8E7wnMd1...");

// The SDK will automatically detect if you're using a test or live key

Creating charges

You can create a new charge for a single payment:

// Create a charge with async/await
async function createCharge() {
   try {
      const charge = await cariFinance.charges.create({
         amount: 2000, // Amount in cents (e.g., $20.00)
         currency: "usd",
         provider: "card",
         card: {
            token: "tok_visa", // Token obtained from the client-side SDK
         },
         description: "Payment for order #123",
         customer: {
            name: "John Doe",
            email: "john.doe@example.com",
         },
      });

      // Check if charge was successful
      if (charge.status === "succeeded") {
         // Payment was successful
         console.log(`Payment successful! Charge ID: ${charge.id}`);
      } else {
         // Payment failed
         console.log(`Payment failed: ${charge.failure_message}`);
      }
   } catch (error) {
      console.error("Error creating charge:", error);
   }
}

// Or with Promise chains
cariFinance.charges
   .create({
      amount: 2000,
      currency: "usd",
      provider: "card",
      card: { token: "tok_visa" },
      // other parameters...
   })
   .then((charge) => {
      console.log(`Payment successful! Charge ID: ${charge.id}`);
   })
   .catch((error) => {
      console.error("Error creating charge:", error);
   });

Working with customers

You can create and manage customers:

// Create a new customer
const customer = await cariFinance.customers.create({
   name: "Jane Smith",
   email: "jane.smith@example.com",
   phone: "+18765551234",
   address: {
      line1: "123 Main St",
      city: "Roseau",
      country: "DM",
   },
});

// Retrieve a customer
const customer = await cariFinance.customers.retrieve("cus_12345");

// Update a customer
const customer = await cariFinance.customers.update("cus_12345", {
   phone: "+18765559876",
});

// Delete a customer
await cariFinance.customers.delete("cus_12345");

// List customers
const customers = await cariFinance.customers.list({
   limit: 10,
   email: "jane.smith@example.com",
});

TypeScript support

The SDK includes TypeScript type definitions for all objects and methods, providing autocomplete and type checking:

import {
   CariFinanceClient,
   ChargeCreateParams,
   Customer,
} from "@carifinance/sdk";

const cariFinance = new CariFinanceClient("sk_test_51NzaWTBOIWoX8E7wnMd1...");

// Parameters are properly typed
const chargeParams: ChargeCreateParams = {
   amount: 2000,
   currency: "usd",
   provider: "card",
   card: { token: "tok_visa" },
   description: "Typed payment",
};

// Create a charge with proper typing
async function createCharge(): Promise<void> {
   try {
      const charge = await cariFinance.charges.create(chargeParams);

      // All properties are properly typed
      const chargeId: string = charge.id;
      const status: string = charge.status;

      console.log(`Charge created with ID: ${chargeId}`);
   } catch (error) {
      console.error("Error creating charge:", error);
   }
}

// Working with customers with proper typing
async function handleCustomer(customerId: string): Promise<Customer> {
   const customer = await cariFinance.customers.retrieve(customerId);
   return customer;
}

Express.js integration

Here's how to integrate the SDK with an Express.js application:

const express = require("express");
const bodyParser = require("body-parser");
const { CariFinanceClient } = require("@carifinance/sdk");

const app = express();
const port = 3000;

// Initialize the SDK
const cariFinance = new CariFinanceClient(process.env.CARI_FINANCE_API_KEY);

// Middleware
app.use(bodyParser.json());

// Create a payment endpoint
app.post("/api/payments", async (req, res) => {
   try {
      const { token, amount, currency, description } = req.body;

      const charge = await cariFinance.charges.create({
         amount: amount,
         currency: currency || "usd",
         provider: "card",
         card: { token: token },
         description: description || "Payment from Express app",
      });

      res.json({
         success: true,
         charge: charge,
      });
   } catch (error) {
      res.status(400).json({
         success: false,
         error: error.message,
      });
   }
});

// Webhook handling
app.post(
   "/webhooks/cari-finance",
   express.raw({ type: "application/json" }),
   async (req, res) => {
      try {
         const signature = req.headers["cari-finance-signature"];

         // Verify webhook signature
         const event = cariFinance.webhooks.constructEvent(
            req.body,
            signature,
            process.env.CARI_FINANCE_WEBHOOK_SECRET
         );

         // Handle the event
         switch (event.type) {
            case "charge.succeeded":
               const charge = event.data.object;
               console.log(`Charge succeeded: ${charge.id}`);
               // Process the successful charge
               break;
            // Handle other event types
            default:
               console.log(`Unhandled event type: ${event.type}`);
         }

         res.json({ received: true });
      } catch (error) {
         console.error("Webhook error:", error.message);
         res.status(400).send(`Webhook Error: ${error.message}`);
      }
   }
);

app.listen(port, () => {
   console.log(`Server running at http://localhost:${port}`);
});

Additional resources

For more detailed information about the Node.js SDK, refer to these resources:

Was this page helpful?