Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

facturapi

facturapi6.3kMIT4.8.3TypeScript support: included

Librería oficial de Facturapi. Crea CFDIs timbrados y enviados al SAT, XML y PDF

cfdi, factura, sat, facturación, facturapi

readme

FacturAPI

npm version js-semistandard-style

This is the official HTTP client for https://www.facturapi.io

FacturAPI makes it easy for developers to generate valid Invoices in Mexico (known as Factura Electrónica or CFDI).

If you've ever used Stripe or Conekta, you'll find FacturAPI very straightforward to understand and integrate in your server app.

Compatibility

  • Node.js 12.x or higher
  • Browsers with Fetch API support
  • React Native

Install

npm install --save facturapi

Getting started

Authenticate with your API Key

Make sure you have created your free account on FacturAPI and that you have your API Keys.

// ES6
import Facturapi from 'facturapi';
// CommonJS
const Facturapi = require('facturapi').default;

const facturapi = new Facturapi('YOUR_API_KEY', {
  apiVersion: 'v2', // Optional, say what API version you want to use. Defaults to the latest version.
});

Create a customer

facturapi.customers
  .create({
    legal_name: 'Walter White', // Razón social
    tax_id: 'WIWA761018', // RFC
    email: 'walterwhite@gmail.com', // Optional but useful to send invoice by email
    address: {
      street: 'Av. de los Rosales',
      exterior: '123',
      neighborhood: 'Tepito',
      zip: '06800',
      // city, municipality and state are filled automatically from the zip code
      // but if you want to, you can override their values
      // city: 'México',
      // municipality: 'Cuauhtémoc',
      // state: 'Ciudad de México'
    },
  })
  .then((customer) => {
    // Remember to store the customer.id in your records.
    // You will need it to create an invoice for this customer.
  })
  .catch((err) => console.log(err)); // Handle the error.

Create a product

facturapi.products
  .create({
    product_key: '4319150114', // Clave Producto/Servicio from SAT's catalog. Log in to FacturAPI and use our tool to look it up.
    description: 'Apple iPhone 8',
    price: 20000, // price in MXN.
    // By default, taxes are calculated from the price with IVA 16%
    // But again, you can override that by explicitly providing a taxes array
    // taxes: [
    //   { type: Facturapi.TaxType.IVA, rate: 0.16 },
    //   { type: Facturapi.TaxType.ISR, rate: 0.03666, withholding: true }
    // ]
  })
  .then((product) => {
    // Remember to store the product.id in your records.
    // You will need it to create an invoice for this product.
  })
  .catch((err) => console.log(err)); // Handle the error.

Create an invoice

facturapi.invoices.create({
  customer: 'YOUR_CUSTOMER_ID',
  payment_form: Facturapi.PaymentForm.TRANSFERENCIA_ELECTRONICA, // Constant from SAT's catalog. Check out our documentation to learn more.
  items: [{
    quantity: 1, // Optional. Defaults to 1.
    product: 'YOUR_PRODUCT_ID' // You can also pass a product object instead
  }] // Add as many products as you want to include in your invoice
}).then(invoice => { ... });

Download your invoice

// Once you have successfully created your invoice, you can...
const fs = require('fs');
facturapi.invoices.downloadZip(invoice.id) // or downloadPdf or downloadXml
  .then(zipStream => {
    // stream containing the PDF and XML as a ZIP file
    // Save your invoice to a folder
    const myZipFile = fs.createWriteStream('/path/to/destination/folder');
    zipStream.pipe(myZipFile);
    myZipFile.on('finish', () => {
      // Finished downloading, Yay!
    });

Send your invoice by email

// Send the invoice to your customer's email (if any)
facturapi.invoices
  .sendByEmail(invioce.id) // Also returns a Promise
  .then(() => {
    // Successfully sent
  })
  .catch((err) => console.log(err)); // Handle the error.

Documentation

There's more you can do with this library: List, retrieve, update, and remove Customers, Products and Invoices.

Visit the full documentation at http://docs.facturapi.io.

Help

Found a bug?

Please report it on the Issue Tracker

Want to contribute?

Send us your PR! We appreciate your help :)

Contact us!

contacto@facturapi.io

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

[4.8.3] 2025-05-19

Fixed

  • Webhook validation. Now the signature is validated locally in Node and web environments (but not in React Native, where the API is still used).
  • Type fixes for signature validation.

[4.8.2] 2025-04-23

Fixed

  • Fix organizations.uploadLogo and organizations.uploadCertificate methods to accept Buffer or ReadableStream as input in Node.js.

[4.8.1] 2025-04-10

Fixed

  • Fix route for customers.sendEditLinkByEmail method.

[4.8.0] 2025-04-10

Added

  • Webhook events: invoice.created_from_dashboard and customer.edit_link_completed

[4.7.0] 2025-04-04

Added

  • Add customers.sendEditLinkByEmail method to send an edit link to a customer via email.

[4.6.0] 2025-02-25

Added

  • Allow creating edit links for customers, passing query params to create and edit customer methods.
  • Edit link properties for customers.

[4.5.0] 2025-01-07

Added

  • New fields for the Invoice object: received_payment_ids and target_invoice_ids, used to track payments and PPD invoices.

[4.4.4] 2024-12-18

Fixed

  • Added try/catch to conditional import and define "stream" as external.

[4.4.3] 2024-12-13

Fixed

  • Fix conditional import on web environments.

[4.4.2] 2024-11-28

Fixed

  • Fix bug in Node.js environment in which the library was not returning the right kind of stream on download methods.

[4.4.1] 2024-11-12

Fixed

  • Fix bug in which body params were not being sent in the request.

[4.4.0] 2024-11-08

Added

  • Compatibility with browser environments and React Native. Now you can use Facturapi in the browser or in React Native, as long as you have a Fetch API compatible environment.
  • Types for webhooks responses.
  • Add organizations.me method to get the organization information.

Fixed

  • Name of validateSignature parameter "signature".

[4.3.0] 2024-11-04

Added

  • Add types for all method responses. Method parameters are still not typed.

[4.2.0] 2024-10-10

Added

  • List Live Api Keys: listLiveApiKeys for organizations
  • Delete Live Api Keys: deleteLiveApiKey for organizations
  • Validate webhooks responses: validateSignature for webhooks

[4.1.2] 2024-07-15

Added

  • Fix optional params for invoice

[4.1.1] 2024-06-15

Fixed

  • Fix organization.createSeriesGroup and organization.updateSeriesGroup. Thanks to @pastine

[4.1.0] 2024-06-13

Added

  • Methods for CRUD of series
  • Create method for series: organization.createSeriesGroup
  • Read method for your organization series: organization.listSeriesGroup
  • Update method for an specific series: organization.updateSeriesGroup
  • Delete method for an specific series: organization.deleteSeriesGroup

[4.0.0] 2024-05-23

Breaking

  • Remove deprecated method products.keys in favor of catalogs.searchProducts.
  • Remove deprecated method products.units in favor of catalogs.searchUnits.
  • Corrected the name of the method invoices.editDraft to invoices.updateDraft.
  • The rest of the changes are internal and should not affect the public API.

Added

  • We rewrote the the library in TypeScript and now it's partially typed. Most request parameters and responses are not typed yet, but we plan to add more types in future releases.
  • We export all type definitions, so you can use them in your TypeScript projects.
  • New method to copy invoices to a new draft: invoices.copyToDraft.

[3.6.0] 2024-05-23

Added

  • New method to delete certificates from the organization: organizations.deleteCertificate.
  • New query param async in create invoice method:.
  • New methods for draft invoices: invoices.editDraft, invoices.stampDraft.
  • New method to update invoice status with the latest value from the SAT: invoices.updateStatus.

[3.5.0] 2023-12-31

Added

  • Webhooks API

[3.4.0] 2023-10-19

Added

  • Add invoices.downloadCancellationReceiptPdf.

[3.3.0] 2022-12-14

Added

  • Add invoices.downloadCancellationReceiptXml, receipts.sendByEmail and receipts.downloadPdf.

[3.2.0] 2022-01-17

Note: Although this update includes a breaking change, only the minor version will be bumped, since we haven't officially announced the new API version yet.

Breaking

  • Remove organizations.getApiKeys.

Added

  • Add organizations.getTestApiKey, organizations.renewTestApiKey and organizations.renewLiveApiKey.

[3.1.0] 2022-01-17

Added

  • Allow setting the API version in the client constructor.

[3.0.0] 2022-01-16

Breaking

  • Change API version to point to /v2, in order to support CFDI 4.0

[2.7.0] 2021-12-27

Added

  • Support sending params to invoices.cancel method.

[2.6.1] 2021-09-05

Fixed

  • Stop logging request config

[2.6.0] 2021-08-06

Added

  • New endpoint: tools.validateTaxId.

[2.5.0] 2021-04-13

Added

  • Support for Retentions API

Security

  • Updated dependencies to address potential vulnerabilities.

[2.4.0] 2020-12-24 🎄

Added

  • New method on receipts API: createGlobalInvoice

[2.3.1] 2020-05-28

Fixed

  • facturapi.organizations.uploadCertificate only accepted FileStreams. Now it supports any kind of readable Stream, as well as Buffer.

[2.3.0] 2020-05-28

Added

  • Support for receipts API
  • Edit organization's receipts settings
  • Check domain availability
  • Select organization's domain

[2.2.3] 2020-03-05

Fixed

  • Use correct endpoint for catalogs.searchProducts

[2.2.2] 2019-11-29

Added

  • Catalogs API
    • Search product keys using catalogs.searchProducts.
    • Search unit keys using catalogs.searchUnits.

Fixed

  • Updated all dependencies to clear security warnings
  • Previously swallowing messages from non-axios errors

Deprecated

  • product.keys and product.units are deprecated in favor of the new catalogs API, and will be removed on the next major release.

[2.0.0] 2018-08-04

Breaking changes

  • Now you must create the Facturapi instance using the new keyword every time.

Before:

// This was allowed
const facturapi = Facturapi('YOUR_API_KEY');

Now:

// Now you must always use new
const facturapi = new Facturapi('YOUR_API_KEY');

[1.2.0] 2018-08-04

Fixed

  • Reject with an Error, not with an object

[1.1.0] 2018-05-06

Added

  • Support Organizations API

[1.0.0] - 2018-05-01

Added

  • Search product_keys using facturapi.products.keys('your search')
  • Search unit_keys using facturapi.products.units('your search')
  • Constants for PaymentMethod, InvoiceType, InvoiceUse, InvoiceRelation

Breaking changes

  • Now contants should be accessed as static properties from the Facturapi class, instead of from the instance.

Before:

const facturapi = new Facturapi('YOUR_API_KEY');
console.log(facturapi.TaxType.IVA); // > IVA

Now:

console.log(Facturapi.TaxType.IVA); // > IVA

[0.1.3] - 2017-06-20

Fixed

  • Protocol should be HTTPS

[0.1.2] - 2017-06-20

Added

  • First release
  • Wrapper methods for:
    • Customers
    • Products
    • Invoices
  • Added README file