Skip to content

JavaScript / TypeScript SDK

The official Cashfin Business SDK for Node.js — fully typed, zero dependencies, with automatic retries and auto-pagination.

Installation

bash
npm install @cashfinbusiness/node
bash
yarn add @cashfinbusiness/node
bash
pnpm add @cashfinbusiness/node

Requirements

  • Node.js 16.x or later
  • TypeScript 4.7+ (optional)

Quick Start

typescript
import Cashfin from "@cashfinbusiness/node";

const cashfin = new Cashfin({
  apiKey: process.env.CASHFIN_API_KEY!,
});

Configuration

typescript
const cashfin = new Cashfin({
  // Required
  apiKey: "cs_your_client_secret",

  // Optional
  timeout: 30000,   // Request timeout in ms (default: 30000)
  maxRetries: 3,    // Retries on failure (default: 3)
  debug: false,     // Log all requests and responses (default: false)

  retryConfig: {
    initialDelay: 1000,  // Initial retry delay in ms
    maxDelay: 30000,     // Maximum retry delay in ms
    factor: 2,           // Exponential backoff factor
  },
});

Shop

Products

typescript
// List products
const products = await cashfin.products.list({
  page: 1,
  limit: 20,
  status: "published",
  type: "product",
});

// Get a single product
const product = await cashfin.products.get("507f1f77bcf86cd799439011");

// Create a product
const newProduct = await cashfin.products.create({
  title: "Premium Widget",
  description: "A high-quality widget",
  price: 1999.99,
  stock: 100,
  type: "product",
  status: "published",
  variants: [
    {
      attributetitle: "Color",
      valuetitle: "Blue",
      valueprice: 1999.99,
      valuestock: 50,
    },
  ],
});

// Update a product — returns { id, modified }
const result = await cashfin.products.update("507f1f77bcf86cd799439011", {
  price: 2499.99,
  stock: 75,
});
console.log(result.modified); // 1

// Fetch the full updated product if needed
const updated = await cashfin.products.get(result.id);

Categories

typescript
// List categories
const categories = await cashfin.categories.list({ status: "active" });

// Create a category
const category = await cashfin.categories.create({
  title: "Electronics",
  description: "Electronic devices and accessories",
  status: "active",
});

// Update a category — returns { id, modified }
const result = await cashfin.categories.update("507f191e810c19729de860ea", {
  description: "Updated description",
});
console.log(result.modified); // 1

Orders

typescript
// Create a checkout order
const order = await cashfin.orders.checkout({
  customeremail: "[email protected]",
  items: [
    { itemid: "507f1f77bcf86cd799439011", quantity: 2, rate: 1999.99 },
  ],
  shippingaddress: {
    name: "John Doe",
    address: "123 Main St",
    city: "Nairobi",
    country: "Kenya",
    phone: "+254712345678",
  },
});
console.log(`Order: ${order.orderno}`);
console.log(`Payment: ${order.paymentlink.shorturl}`);

// List orders
const orders = await cashfin.orders.list({ status: "completed" });

// Get order details
const details = await cashfin.orders.get("507f1f77bcf86cd799439011");

Payments

M-Pesa

typescript
const payment = await cashfin.payments.mpesa({
  amount: 1500,
  phone: "254712345678",
  referenceid: "ORDER-001",
  description: "Payment for Order #001",
});

console.log(`Checkout ID: ${payment.checkoutrequestid}`);

Transactions

typescript
// List transactions
const transactions = await cashfin.transactions.list({
  status: "completed",
  method: "mpesa",
  startdate: "2024-01-01",
  enddate: "2024-01-31",
});

// Get transaction details
const tx = await cashfin.transactions.get("507f1f77bcf86cd799439011");
console.log(tx.transactionno, tx.amount, tx.status);

Receipts

typescript
// List receipts
const receipts = await cashfin.receipts.list({ page: 1, limit: 20 });

// Get receipt details
const receipt = await cashfin.receipts.get("507f1f77bcf86cd799439011");
console.log(receipt.receiptno, receipt.amount);
typescript
// Create a payment link
const link = await cashfin.paymentLinks.create({
  title: "Invoice #INV-001",
  amount: 15000,
  description: "Payment for consulting services",
});
console.log(`Share: ${link.url}`);

// List payment links
const links = await cashfin.paymentLinks.list({ status: "active" });

// Get payment link details
const details = await cashfin.paymentLinks.get("507f1f77bcf86cd799439011");

Invoices

typescript
// Create an invoice
const invoice = await cashfin.invoices.create({
  customerid: "507f1f77bcf86cd799439011",
  items: [
    { name: "Consulting Services", quantity: 10, rate: 5000.0 },
  ],
  title: "Monthly Consulting Invoice",
  duedate: "2024-02-15",
  discount: 10,
  discounttype: "percentage",
});
console.log(`Invoice: ${invoice.invoiceno}`);
console.log(`Payment Link: ${invoice.paymentlink.shorturl}`);

// List invoices
const invoices = await cashfin.invoices.list({ status: "unpaid" });

// Get invoice
const details = await cashfin.invoices.get("507f1f77bcf86cd799439020");

// Update invoice — returns { id, modified }
const result = await cashfin.invoices.update("507f1f77bcf86cd799439020", { status: "paid" });
console.log(result.modified); // 1

Subscriptions

typescript
// Create a subscription
const subscription = await cashfin.subscriptions.create({
  customerid: "507f1f77bcf86cd799439011",
  items: [{ rate: 2999.0 }],
  billingcycle: "monthly",
  autorenew: true,
  trial: {
    startdate: new Date().toISOString(),
    enddate: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString(),
  },
});
console.log(`Subscription: ${subscription.subscriptionno}`);

// Get subscription
const sub = await cashfin.subscriptions.get("507f1f77bcf86cd799439020");
console.log(`Next Billing: ${sub.nextbillingdate}`);

CRM

Customers

typescript
// Create a customer
const customer = await cashfin.customers.create({
  name: "John Doe",
  email: "[email protected]",
  phone: "+254712345678",
  country: "Kenya",
  currency: "KES",
  type: "individual",
});
console.log(`Customer ID: ${customer.id}`);

// List customers
const customers = await cashfin.customers.list({ type: "individual" });

// Get customer
const details = await cashfin.customers.get("507f1f77bcf86cd799439011");

// Update a customer — returns { id, modified }
const result = await cashfin.customers.update("507f1f77bcf86cd799439011", {
  phone: "+254799000001",
  city: "Mombasa",
});
console.log(result.modified); // 1

Leads

typescript
// Create a lead
const lead = await cashfin.leads.create({
  name: "Alice Mwangi",
  email: "[email protected]",
  phone: "+254712345678",
  company: "Tech Corp",
  source: "website",
  budget: 500000,
});

// List leads
const leads = await cashfin.leads.list({ status: "qualified" });

Contacts

typescript
// Create a contact
const contact = await cashfin.contacts.create({
  name: "Jane Wanjiku",
  email: "[email protected]",
  phone: "+254712345678",
  position: "Procurement Manager",
  companyname: "Acme Corp",
});

// List contacts
const contacts = await cashfin.contacts.list({ search: "Jane" });

// Get contact
const details = await cashfin.contacts.get("507f1f77bcf86cd799439011");

Quotes

typescript
// List quotes (read-only)
const quotes = await cashfin.quotes.list({
  status: "sent",
  customerid: "507f1f77bcf86cd799439011",
});

// Get quote details
const quote = await cashfin.quotes.get("507f1f77bcf86cd799439011");
console.log(quote.quoteno, quote.total, quote.status);

Contracts

typescript
// List contracts (read-only)
const contracts = await cashfin.contracts.list({
  status: "active",
  type: "maintenance",
});

// Get contract details
const contract = await cashfin.contracts.get("507f1f77bcf86cd799439011");
console.log(contract.contractno, contract.amount);

Bookings

typescript
// List bookings (read-only)
const bookings = await cashfin.bookings.list({ status: "scheduled" });

// Get booking details
const booking = await cashfin.bookings.get("507f1f77bcf86cd799439011");
console.log(booking.title, booking.starttime, booking.participant?.email);

Appointments

typescript
// List appointment types (read-only)
const appointments = await cashfin.appointments.list({
  status: "active",
  category: "meeting",
});

// Get appointment type details (includes availability schedule)
const appointment = await cashfin.appointments.get("507f1f77bcf86cd799439011");
console.log(appointment.title, appointment.duration, appointment.bookingurl);

Purchases

Vendors

typescript
// Create a vendor
const vendor = await cashfin.vendors.create({
  name: "Acme Supplies Ltd",
  email: "[email protected]",
  phone: "+254712345678",
  companyname: "Acme Supplies Ltd",
});

// List vendors
const vendors = await cashfin.vendors.list({ search: "Acme" });

// Get vendor
const details = await cashfin.vendors.get("507f1f77bcf86cd799439011");

// Update a vendor — returns { id, modified }
const result = await cashfin.vendors.update("507f1f77bcf86cd799439011", {
  phone: "+254799000001",
  city: "Mombasa",
});
console.log(result.modified); // 1

Expenses

typescript
// Create an expense
const expense = await cashfin.expenses.create({
  title: "Office Supplies",
  amount: 3500,
  category: "office",
  date: "2024-01-15",
  notes: "Purchased pens and notebooks",
});

// List expenses
const expenses = await cashfin.expenses.list({
  status: "approved",
  category: "travel",
  startdate: "2024-01-01",
  enddate: "2024-01-31",
});

// Get expense
const details = await cashfin.expenses.get("507f1f77bcf86cd799439011");

Bills

typescript
// Create a bill
const bill = await cashfin.bills.create({
  vendorid: "507f1f77bcf86cd799439011",
  items: [
    { name: "Office Rent", quantity: 1, rate: 50000 },
    { name: "Utilities", quantity: 1, rate: 8000 },
  ],
  title: "January Office Bills",
  duedate: "2024-02-01",
});
console.log(`Bill: ${bill.billno}`);

// List bills
const bills = await cashfin.bills.list({ status: "pending", vendorid: "vendor-id" });

Purchase Orders

typescript
// Create a purchase order
const po = await cashfin.purchaseOrders.create({
  vendorid: "507f1f77bcf86cd799439011",
  items: [
    { name: "Laptops", quantity: 5, rate: 80000 },
    { name: "Mice", quantity: 5, rate: 1500 },
  ],
  title: "IT Equipment Order",
  notes: "Deliver to main office",
});
console.log(`PO: ${po.pono}, Total: ${po.total}`);

// List purchase orders
const orders = await cashfin.purchaseOrders.list({ status: "confirmed" });

Marketing

Campaigns

typescript
// List campaigns (read-only)
const campaigns = await cashfin.campaigns.list({
  status: "sent",
  type: "email",
});

// Get campaign details
const campaign = await cashfin.campaigns.get("507f1f77bcf86cd799439011");
console.log(campaign.name, campaign.totalsent, campaign.opens, campaign.clicks);

Lists

typescript
// Create a contact list
const list = await cashfin.lists.create({
  name: "Newsletter Subscribers",
  description: "Monthly newsletter subscribers from website",
  type: "email",
});

// List all contact lists
const lists = await cashfin.lists.list({ status: "active", type: "email" });

// Get list details (includes live contact count)
const details = await cashfin.lists.get("507f1f77bcf86cd799439011");
console.log(details.name, details.contactcount);

// Add a contact to a list
const contact = await cashfin.lists.addContact("507f1f77bcf86cd799439011", {
  email: "[email protected]",
  firstname: "Alice",
  lastname: "Kamau",
  company: "Example Ltd",
});

Pagination

Manual

typescript
let page = 1;
let hasMore = true;

while (hasMore) {
  const response = await cashfin.products.list({ page, limit: 100 });
  for (const product of response.data) {
    console.log(product.title);
  }
  hasMore = response.meta.hasNext;
  page++;
}

Error Handling

typescript
import Cashfin, {
  CashfinError,
  ValidationError,
  AuthenticationError,
  NotFoundError,
  RateLimitError,
} from "@cashfinbusiness/node";

try {
  await cashfin.products.create({ title: "Widget" });
} catch (error) {
  if (error instanceof ValidationError) {
    console.log("Validation failed:", error.errors);
  } else if (error instanceof AuthenticationError) {
    console.log("Invalid API key");
  } else if (error instanceof NotFoundError) {
    console.log("Resource not found");
  } else if (error instanceof RateLimitError) {
    console.log(`Rate limited. Retry after ${error.retryAfter}s`);
  } else if (error instanceof CashfinError) {
    console.log("API Error:", error.message, error.statusCode);
  }
}

Webhooks

typescript
import { constructWebhookEvent, verifyWebhookSignature } from "@cashfinbusiness/node";

app.post("/webhooks/cashfin", express.raw({ type: "application/json" }), (req, res) => {
  const signature = req.headers["x-cashfin-signature"] as string;
  const payload = req.body.toString();

  try {
    const event = constructWebhookEvent(payload, signature, process.env.WEBHOOK_SECRET!);

    switch (event.type) {
      case "payment.completed":
        handlePayment(event.data);
        break;
      case "order.completed":
        handleOrder(event.data);
        break;
      case "invoice.paid":
        handleInvoice(event.data);
        break;
      case "subscription.renewed":
        handleRenewal(event.data);
        break;
    }

    res.json({ received: true });
  } catch {
    res.status(401).json({ error: "Invalid webhook" });
  }
});

TypeScript Support

All types are exported directly from the package:

typescript
import Cashfin, {
  // Shop
  Product, Category, Order,
  // Payments
  Transaction, Receipt, BusinessPaymentLink, Invoice, Subscription,
  // CRM
  Customer, Lead, Contact, Quote, Contract, Booking, Appointment,
  // Purchases
  Vendor, Expense, Bill, PurchaseOrder,
  // Marketing
  Campaign, MarketingList,
  // Params
  CreateProductParams, UpdateProductParams, ListProductsParams,
  CreateInvoiceParams, UpdateInvoiceParams,
  CreateCustomerParams, UpdateCustomerParams,
  CreateLeadParams, CreateContactParams,
  CreatePaymentLinkParams,
  CreateVendorParams, UpdateVendorParams, CreateExpenseParams,
  CreateBillParams, CreatePurchaseOrderParams,
  CreateMarketingListParams, AddListContactParams,
  // Update result
  UpdateResult,
} from "@cashfinbusiness/node";

Debugging

typescript
const cashfin = new Cashfin({
  apiKey: process.env.CASHFIN_API_KEY!,
  debug: true,  // Logs every request and response to console
});

// Or via environment variable (no code change needed)
// CASHFIN_DEBUG=true node app.js

Cashfin Business API Documentation