efi-easy-pix
Version:
A simple Node.js module for integrating with Efipay's PIX API
130 lines (113 loc) • 3.69 kB
JavaScript
const express = require('express');
const ngrok = require('ngrok');
const fs = require('fs-extra');
const https = require('https');
class WebhookHandler {
constructor(config) {
this.config = {
ngrokToken: config.ngrokToken,
port: config.port || 3000,
certificatePath: config.certificatePath,
sandbox: config.sandbox || false
};
this.app = express();
this.setupServer();
this.setupRoutes();
}
setupServer() {
const httpsOptions = {
cert: fs.readFileSync(this.config.certificatePath),
key: fs.readFileSync(this.config.certificatePath),
ca: fs.readFileSync(this.config.sandbox
? './certificates/certificate-chain-homolog.crt'
: './certificates/certificate-chain-prod.crt'),
minVersion: 'TLSv1.2',
requestCert: true,
rejectUnauthorized: true
};
this.server = https.createServer(httpsOptions, this.app);
}
setupRoutes() {
this.app.use(express.json());
this.app.post('/webhook', (req, res) => {
if (req.socket.authorized) {
res.status(200).end();
} else {
res.status(401).end();
}
});
this.app.post('/webhook/pix', (req, res) => {
if (req.socket.authorized) {
const pixData = req.body;
this.handlePixNotification(pixData);
res.status(200).end();
} else {
res.status(401).end();
}
});
}
async start() {
try {
await this.server.listen(this.config.port);
console.log(`Server running on port ${this.config.port}`);
const url = await ngrok.connect({
addr: this.config.port,
authtoken: this.config.ngrokToken
});
console.log(`Ngrok tunnel established at: ${url}`);
return url;
} catch (error) {
console.error('Failed to start server:', error);
throw error;
}
}
async stop() {
try {
await ngrok.kill();
await this.server.close();
console.log('Server stopped');
} catch (error) {
console.error('Failed to stop server:', error);
throw error;
}
}
handlePixNotification(pixData) {
const pix = pixData.pix[0];
switch (pix.tipo) {
case 'SOLICITACAO':
this.handlePixSent(pix);
break;
default:
if (pix.devolucoes) {
this.handlePixRefund(pix);
} else {
this.handlePixReceived(pix);
}
}
}
handlePixReceived(pix) {
console.log('PIX Received:', {
endToEndId: pix.endToEndId,
txid: pix.txid,
valor: pix.valor,
horario: pix.horario,
infoPagador: pix.infoPagador
});
}
handlePixRefund(pix) {
console.log('PIX Refund:', {
endToEndId: pix.endToEndId,
txid: pix.txid,
devolucoes: pix.devolucoes
});
}
handlePixSent(pix) {
console.log('PIX Sent:', {
endToEndId: pix.endToEndId,
status: pix.status,
valor: pix.valor,
horario: pix.horario
});
}
}
module.exports = WebhookHandler;