@glopsy/pay
v0.1.1
Published
SDK oficial de Glopsy Pay: crea cobros USDT-BEP20, consulta su estado, verifica webhooks y lee tu saldo.
Maintainers
Readme
@glopsy/pay
SDK oficial de Glopsy Pay para Node.js (TypeScript). Permite a tu tienda crear cobros en USDT-BEP20 desde el servidor, mostrar el checkout a tus clientes y recibir la confirmación por webhook.
- Cero dependencias de runtime (usa
fetchnativo, Node 18+). - Tipado completo en TypeScript.
- Verificación de webhooks con HMAC-SHA256 en tiempo constante.
Instalación
npm install @glopsy/payObtener tu API key
En la app → Credenciales → API (solo cuentas de comercio), o POST /api/team/api-keys. La key tiene el formato gp_live_... y es secreta: usala solo desde tu servidor, nunca en el navegador.
Uso
import { GlopsyPay } from '@glopsy/pay';
const gp = new GlopsyPay({ apiKey: process.env.GLOPSY_API_KEY! });
const charge = await gp.createCharge({
amount: '25.00', // USDT
concept: 'Pedido #123',
ttl_seconds: 86400, // opcional (default 300, máx 7 días)
webhook_url: 'https://tu-tienda.com/webhook/glopsy', // opcional
redirect_url: 'https://tu-tienda.com/gracias', // opcional
});
console.log(charge.url); // https://pay.glopsy.shop/p/<token>Para cobrar en moneda local (la tasa P2P se aplica sola):
await gp.createCharge({ fiat_amount: '100000', fiat_currency: 'COP', concept: 'Pedido #124' });Mostrá charge.url como link, QR o con el widget:
<script src="https://pay.glopsy.shop/widget.js" data-token="<token>" async></script>Referencia
new GlopsyPay({ apiKey, baseUrl?, timeoutMs?, fetch? })| Método | Descripción |
|---|---|
| createCharge(params) | Crea un cobro. Devuelve el Charge con token y url. |
| getCharge(token) | Estado del cobro (pending / paid / expired / canceled). |
| listCharges({ limit? }) | Últimos cobros del comercio. |
| getBalance() | Saldo en USDT (available, blocked, total). |
| getWebhook() | Config del webhook global (incluye config.secret). |
| setWebhook({ url?, active? }) | Configura el webhook global. |
| verifyWebhook(rawBody, signature, secret?) | Valida la firma. |
| constructEvent(rawBody, signature, secret?) | Valida y parsea el evento tipado. |
| loadWebhookSecret() | Cachea el secret para verificar sin pasarlo a mano. |
Webhooks
Al pagarse un cobro, Glopsy Pay envía un POST a tu URL con:
X-Glopsy-Event: charge.paidX-Glopsy-Signature: sha256=<hmac-sha256-hex-del-body>
Verificá siempre la firma sobre el body crudo (sin parsear).
Express
import express from 'express';
import { GlopsyPay } from '@glopsy/pay';
const app = express();
const gp = new GlopsyPay({ apiKey: process.env.GLOPSY_API_KEY! });
// Body crudo SOLO en la ruta del webhook
app.post('/webhook/glopsy', express.raw({ type: 'application/json' }), (req, res) => {
try {
const event = gp.constructEvent(req.body, req.header('X-Glopsy-Signature'), process.env.GLOPSY_WEBHOOK_SECRET);
if (event.event === 'charge.paid') {
// marcar pedido como pagado usando event.data.token / event.data.net
}
res.sendStatus(200);
} catch {
res.sendStatus(400);
}
});El secret lo obtenés con await gp.getWebhook() → config.secret.
Sin webhook también podés consultar con polling:
const charge = await gp.getCharge(token);
if (charge.status === 'paid') { /* listo */ }Redirección post-pago
Pasando redirect_url al crear el cobro, el cliente es llevado a esa URL al pagar (link directo y widget). redirect_delay_ms controla la espera antes de redirigir (default 1500 ms).
Con el widget también se emite un evento para que lo captures a gusto:
<script src="https://pay.glopsy.shop/widget.js" data-token="<token>" async></script>
<script>
document.addEventListener('glopsy-pay:paid', (e) => {
const { token, amount, redirect_url } = e.detail;
// p. ej. mostrar tu propio modal o navegar a otra vista
});
</script>En el widget, data-redirect="https://…" fuerza el destino (o data-redirect="false" para no redirigir y manejar vos el evento).
Manejo de errores
import { GlopsyPayError } from '@glopsy/pay';
try {
await gp.createCharge({ amount: '5.00' });
} catch (err) {
if (err instanceof GlopsyPayError) {
console.error(err.status, err.message, err.body); // ej. 401 "API key inválida o revocada."
}
}status = 0 indica fallo de red o timeout.
Ejemplos
Ver examples/: create-charge.mjs, webhook-server.mjs, poll-until-paid.mjs.
Desarrollo
npm install
npm run build # compila a dist/
npm test # compila y corre los tests