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

@devjuanes/matupay-backend

v2.0.0

Published

Backend modular de pasarelas de pago (Wompi) para múltiples aplicaciones. Librería + servidor HTTP.

Readme

@devjuanes/matupay-backend

npm version license: ISC node

Backend modular de pasarelas de pago para múltiples aplicaciones. Hoy incluye integración completa con Wompi (Colombia): checkout firmado, confirmación de transacciones, webhooks, suscripciones en Firestore y envío opcional de comprobantes por correo.

Funciona de tres formas:

  1. Librería npm — integra pagos en tu backend existente
  2. Servidor standalone — levanta la API con un comando
  3. Middleware Express — monta las rutas en tu app

Tabla de contenidos


Instalación

npm install @devjuanes/matupay-backend

Para desarrollo local del repositorio:

git clone https://github.com/Dev-Juanes/MatuPayBakend.git
cd MatuPayBakend
npm install
cp .env.example .env

Inicio rápido

1. Configura variables de entorno

PAYMENT_APP_ID=mi-app
WOMPI_ENV=test
WOMPI_TEST_PUBLIC_KEY=pub_test_...
WOMPI_TEST_PRIVATE_KEY=prv_test_...
WOMPI_TEST_INTEGRITY_SECRET=test_integrity_...
WOMPI_TEST_WEBHOOK_SECRET=test_events_...
FRONTEND_APP_URL=http://localhost:5173

PAYMENT_PLANS_JSON=[{"id":"basic","amountCop":9900,"period":"monthly","periodMonths":1,"currency":"COP"}]

2. Genera un checkout (librería)

const { createWompiGateway } = require('@devjuanes/matupay-backend')

const gateway = createWompiGateway({
  environment: 'test',
  appId: 'mi-app',
  publicKey: process.env.WOMPI_TEST_PUBLIC_KEY,
  privateKey: process.env.WOMPI_TEST_PRIVATE_KEY,
  integritySecret: process.env.WOMPI_TEST_INTEGRITY_SECRET,
  webhookSecret: process.env.WOMPI_TEST_WEBHOOK_SECRET,
  plans: [
    { id: 'basic', amountCop: 9900, period: 'monthly', periodMonths: 1, currency: 'COP' }
  ],
  defaultRedirectUrl: 'http://localhost:5173/billing/return'
})

const checkout = gateway.createCheckout({
  customerId: 'user_123',
  planId: 'basic'
})

console.log(checkout.checkoutUrl)
// → https://checkout.wompi.co/p/?public-key=...

3. O levanta el servidor HTTP

# Con npx (sin clonar el repo)
npx matupay-server

# O desde el repo clonado
npm run dev

Configuración

| Variable | Descripción | |---|---| | PAYMENT_APP_ID | Identificador de tu app (prefijo en referencias de pago) | | PAYMENT_GATEWAY | Pasarela activa (wompi) | | PAYMENT_PLANS_JSON | Planes y precios en JSON | | WOMPI_ENV | test (sandbox) o prod | | WOMPI_*_PUBLIC_KEY | Llave pública Wompi | | WOMPI_*_PRIVATE_KEY | Llave privada Wompi | | WOMPI_*_INTEGRITY_SECRET | Secreto para firmar checkout | | WOMPI_*_WEBHOOK_SECRET | Secreto para validar webhooks | | FRONTEND_APP_URL | URL de retorno tras el pago | | FIREBASE_* | Credenciales para persistir suscripciones | | INVOICE_MAILER_* | SMTP opcional para comprobantes |

Referencia completa: docs/ENV.md

Ejemplo de planes

[
  {
    "id": "pro_monthly",
    "amountCop": 15000,
    "period": "monthly",
    "periodMonths": 1,
    "currency": "COP"
  },
  {
    "id": "pro_annual",
    "amountCop": 144000,
    "period": "annual",
    "periodMonths": 12,
    "currency": "COP"
  }
]

Si no defines PAYMENT_PLANS_JSON, se usan CASHPRO_MONTHLY_COP y CASHPRO_ANNUAL_COP como fallback.


Uso como librería

Crear gateway desde código

const { createWompiGateway } = require('@devjuanes/matupay-backend')

const gateway = createWompiGateway({ /* config */ })

Crear gateway desde variables de entorno

require('dotenv').config()
const { createGatewayFromEnv } = require('@devjuanes/matupay-backend')

const gateway = createGatewayFromEnv()
const checkout = gateway.createCheckout({ customerId: 'u1', planId: 'basic' })

Consultar transacción

const tx = await gateway.fetchTransaction('12345-67890')
if (tx.status === 'APPROVED') {
  // activar acceso premium
}

Validar webhook manualmente

const isValid = gateway.verifyWebhook(req.body)
if (!isValid) return res.status(401).end()

const event = gateway.parseWebhookEvent(req.body)
// event.transactionId, event.reference, event.status, ...

Referencia completa: docs/LIBRARY.md


Servidor HTTP

Standalone

npx matupay-server
# o
npm start

Montar en Express existente

const express = require('express')
const { createApp } = require('@devjuanes/matupay-backend')

const app = express()
app.use('/payments', createApp()) // rutas en /payments/api/billing/...
app.listen(3000)

Autenticación

Define API_TOKEN en el entorno. Todas las rutas /api/* (excepto webhooks) requieren:

Authorization: Bearer tu_token

API REST

| Método | Ruta | Descripción | |---|---|---| | GET | /api/health | Estado del servicio | | GET | /api/billing/plans | Planes configurados | | POST | /api/billing/checkout-link | Generar link de pago | | POST | /api/billing/confirm-transaction | Confirmar pago (polling) | | POST | /api/billing/webhook/wompi | Webhook de Wompi | | GET | /api/billing/status/:uid | Estado de suscripción |

Crear checkout

curl -X POST http://localhost:4100/api/billing/checkout-link \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_TOKEN" \
  -d '{
    "uid": "user_123",
    "email": "[email protected]",
    "planId": "pro_monthly"
  }'

Referencia completa con ejemplos de respuesta: docs/API.md


Webhooks Wompi

  1. En el dashboard de Wompi, configura la URL de eventos:

    https://tu-dominio.com/api/billing/webhook/wompi
  2. Usa el secreto de eventos en tu .env:

    WOMPI_PROD_WEBHOOK_SECRET=prod_events_...
  3. El servidor valida el checksum, activa la suscripción en Firestore y envía comprobante si el correo está habilitado.

En producción, confía en el webhook como fuente principal. confirm-transaction sirve como respaldo desde el frontend.


Firebase y suscripciones

Configura Firebase Admin para persistir el estado:

FIREBASE_PROJECT_ID=mi-proyecto
FIREBASE_SERVICE_ACCOUNT_FILE=./firebase-admin.json

Estructura en Firestore:

users/{uid}
  └── subscription: { status, planId, periodEndMs, ... }
  └── subscription_payments/{transactionId}: { amountCop, paidAtMs, ... }

Correo de facturación

Activa el envío automático de comprobante tras un pago aprobado:

INVOICE_MAILER_ENABLED=true
INVOICE_MAILER_HOST=smtp.gmail.com
INVOICE_MAILER_PORT=465
INVOICE_MAILER_SECURE=true
[email protected]
INVOICE_MAILER_PASS=contraseña-de-aplicacion
INVOICE_MAILER_FROM="Mi App <[email protected]>"
INVOICE_BRAND_NAME=Mi App

También puedes llamarlo manualmente:

const { sendPaymentInvoice } = require('@devjuanes/matupay-backend')

await sendPaymentInvoice({
  to: '[email protected]',
  customerName: 'Juan',
  planId: 'pro_monthly',
  amountCop: 15000,
  transactionId: 'txn_123',
  reference: 'mi-app_pro_monthly_user_123_...'
})

Múltiples aplicaciones

Despliega una instancia por app con su propio .env:

| App | PAYMENT_APP_ID | Credenciales | Planes | |---|---|---|---| | MatuAI | matuai | Wompi comercio A | Pro mensual/anual | | MatuCash | matucash | Wompi comercio B | Premium mensual |

Cada instancia genera referencias únicas: {appId}_{planId}_{customerId}_{timestamp}


Documentación extendida

| Documento | Contenido | |---|---| | docs/ENV.md | Todas las variables de entorno | | docs/API.md | Referencia HTTP con ejemplos | | docs/LIBRARY.md | API de la librería |


Producción

npm run pm2:start
npm run pm2:logs

Requiere PM2 instalado globalmente. Ver ecosystem.config.cjs en el repositorio.


Licencia

ISC — Dev Juanes