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 🙏

© 2026 – Pkg Stats / Ryan Hefner

fiscapi-node

v1.0.1

Published

SDK officiel Node.js/TypeScript pour l'API FiscAPI - Facturation e-MECeF au Bénin

Downloads

4

Readme

@fiscapi/node

SDK officiel Node.js/TypeScript pour l'API FiscAPI - Facturation e-MECeF au Bénin.

npm version TypeScript

Installation

npm install @fiscapi/node
# ou
yarn add @fiscapi/node
# ou
pnpm add @fiscapi/node

Démarrage rapide

import { FiscApi } from '@fiscapi/node';

// Initialiser le client
const fiscapi = new FiscApi('sk_live_votre_cle_api');

// Créer et normaliser une facture
const invoice = await fiscapi.invoices.create({
  type: 'FV',
  items: [
    {
      name: 'Consultation juridique',
      price: 50000,
      quantity: 1,
      taxGroup: 'B'  // TVA 18%
    }
  ],
  client: {
    name: 'SARL Example',
    ifu: '0201234567890',
    contact: '+229 97 00 00 00'
  }
});

console.log('✅ Facture normalisée!');
console.log('Code MECeF:', invoice.dgiCodeMecf);
console.log('Total TTC:', invoice.totalTtc, 'FCFA');

Configuration

import { FiscApi } from '@fiscapi/node';

// Simple - l'URL de l'API est déjà configurée dans le SDK
const fiscapi = new FiscApi('sk_live_xxx');

// Ou avec options avancées
const fiscapi = new FiscApi({
  apiKey: 'sk_live_xxx',
  timeout: 30000,   // Optionnel (ms)
  version: 'v1'     // Optionnel
});

L'URL de l'API est intégrée au SDK lors du build. Vous n'avez pas besoin de la spécifier.

Référence API

Factures

Créer une facture

const invoice = await fiscapi.invoices.create({
  type: 'FV',              // FV, EV, FA, EA
  pricingMode: 'TTC',      // TTC ou HT
  aib: 'NONE',            // NONE, A (1%), B (5%)
  paymentMode: 'CASH',     // CASH, CARD, TRANSFER, MOBILE, OTHER
  items: [
    {
      name: 'Produit A',
      price: 10000,
      quantity: 2,
      taxGroup: 'B',
      // Pour groupe D (taxe spécifique):
      // taxSpecific: 150,
      // taxSpecificCode: '1002'
    }
  ],
  client: {
    name: 'Client SARL',
    ifu: '0201234567890',  // Optionnel
    contact: '97000000',   // Optionnel
    address: 'Cotonou'     // Optionnel
  }
});

Récupérer une facture

const invoice = await fiscapi.invoices.get('clx123abc');
console.log(invoice.status);    // DRAFT, SUBMITTED, CONFIRMED, ERROR
console.log(invoice.totalTtc);

Lister les factures

const { items, total, hasMore } = await fiscapi.invoices.list({
  status: 'CONFIRMED',
  type: 'FV',
  page: 1,
  limit: 20
});

Créer un avoir

// Avoir complet
const creditNote = await fiscapi.invoices.createCreditNote('invoice_id');

// Ou directement via create() avec la référence
const creditNote = await fiscapi.invoices.create({
  type: 'FA',
  reference: 'FVB0201234567890/00001/2024',
  client: { name: 'Client SARL' }
});

Télécharger le PDF

const pdfBuffer = await fiscapi.invoices.downloadPdf('invoice_id');
fs.writeFileSync('facture.pdf', Buffer.from(pdfBuffer));

Groupes de Taxes

// Lister tous les groupes
const groups = fiscapi.taxGroups.list();
// [{ code: 'A', name: 'Exonéré', rate: 0 }, ...]

// Calculer la TVA
const result = fiscapi.taxGroups.calculateVat(10000, 'B', 'HT');
// { ht: 10000, tax: 1800, ttc: 11800 }

const result2 = fiscapi.taxGroups.calculateVat(11800, 'B', 'TTC');
// { ht: 10000, tax: 1800, ttc: 11800 }

Crédits

// Vérifier le solde
const balance = await fiscapi.credits.getBalance();
console.log(`Crédits: ${balance.available}/${balance.total}`);

if (balance.isLow) {
  console.warn('⚠️ Solde de crédits bas!');
}

// Vérifier avant un batch
const canProcess = await fiscapi.credits.hasSufficientBalance(50);

Webhooks

// Créer un webhook
const webhook = await fiscapi.webhooks.create({
  url: 'https://myapp.com/webhooks/fiscapi',
  events: ['invoice.confirmed', 'credit.low']
});

// Stocker le secret pour vérification
console.log('Secret:', webhook.secret);

Vérifier les webhooks entrants

// Dans votre handler Express/Next.js
import { FiscApi } from '@fiscapi/node';

const fiscapi = new FiscApi('sk_live_xxx');

export function POST(req) {
  const signature = req.headers['x-fiscapi-signature'];
  const secret = process.env.WEBHOOK_SECRET;

  try {
    const event = fiscapi.webhooks.parseEvent(
      req.body,
      signature,
      secret
    );

    switch (event.type) {
      case 'invoice.confirmed':
        console.log('Facture normalisée:', event.data.id);
        // Mettre à jour votre système...
        break;
      
      case 'credit.low':
        console.log('⚠️ Crédits bas!');
        // Envoyer une alerte...
        break;
    }

    return new Response('OK', { status: 200 });
  } catch (error) {
    console.error('Webhook invalide:', error);
    return new Response('Invalid signature', { status: 401 });
  }
}

Profils Fiscaux

// Lister les profils
const profiles = await fiscapi.fiscalProfiles.list();

const productionProfile = profiles.find(p => 
  p.environment === 'PRODUCTION' && p.hasToken
);

// Vérifier la validité du token
const isValid = await fiscapi.fiscalProfiles.hasValidToken(profile.id);

Types de Factures

| Type | Description | Usage | |------|-------------|-------| | FV | Facture de Vente | Ventes locales au Bénin | | EV | Facture d'Exportation | Ventes à l'export | | FA | Facture d'Avoir (vente) | Annulation de FV | | EA | Facture d'Avoir (export) | Annulation de EV |

Groupes de Taxes

| Code | Nom | Taux | Description | |------|-----|------|-------------| | A | Exonéré | 0% | Produits de première nécessité | | B | Taxable | 18% | Biens et services standard | | C | Exportation | 0% | Ventes export (type EV) | | D | TVA + TS | 18% + TS | Tabac, alcool, etc. | | E | Exception | 0% | Régimes spéciaux | | F | Réservé | - | Usage futur DGI |

Gestion des Erreurs

import { FiscApi, FiscApiError } from '@fiscapi/node';

try {
  const invoice = await fiscapi.invoices.create({ ... });
} catch (error) {
  if (error instanceof FiscApiError) {
    console.error('Erreur API:', error.message);
    console.error('Code:', error.code);
    console.error('Status:', error.status);
    console.error('Détails:', error.details);
  }
}

Codes d'erreur courants

| Code | Description | Solution | |------|-------------|----------| | MISSING_API_KEY | Clé API manquante | Fournir une clé valide | | INVALID_API_KEY | Clé API invalide | Vérifier la clé | | INSUFFICIENT_CREDITS | Crédits insuffisants | Recharger le compte | | VALIDATION_ERROR | Données invalides | Vérifier le payload | | INVOICE_NOT_FOUND | Facture introuvable | Vérifier l'ID | | TIMEOUT | Timeout de requête | Réessayer |

Mode Sandbox

Utilisez une clé de test (sk_test_xxx) pour tester sans impact fiscal :

const fiscapi = new FiscApi('sk_test_xxx');

// Les factures seront marquées simulation=true
const invoice = await fiscapi.invoices.create({ ... });

Support


Pour les Mainteneurs

Build & Publication

# Depuis la racine du projet principal

# Build le SDK
npm run sdk:build

# Publier une nouvelle version
npm run sdk:release        # patch (1.0.0 → 1.0.1)
npm run sdk:release:minor  # minor (1.0.0 → 1.1.0)
npm run sdk:release:major  # major (1.0.0 → 2.0.0)

Configuration requise

Le fichier .env doit contenir :

FISCAPI_SDK_BASE_URL="https://api.fiscapi.com"

Cette URL est injectée dans le SDK au moment du build.

Documentation technique

Voir docs/SDK.md pour la documentation complète de développement.

Licence

MIT © FiscAPI Team