UNPKG

efi-easy-pix

Version:

A simple Node.js module for integrating with Efipay's PIX API

663 lines (562 loc) 19.2 kB
# Efi Easy Pix A simple Node.js module for integrating with Efipay's PIX API. ## Installation ```bash npm install efi-easy-pix ``` ## Usage ```javascript const EfipayClient = require('efi-easy-pix'); const client = new EfipayClient({ clientId: 'your_client_id', clientSecret: 'your_client_secret', certificatePath: './path/to/your/certificate.p12', sandbox: true // Set to false for production }); // Example: Send PIX async function sendPix() { try { const idEnvio = 'your-unique-id'; const response = await client.sendPix(idEnvio, { valor: '12.34', pagador: { chave: '19974764017', infoPagador: 'Segue o pagamento da conta' }, favorecido: { chave: 'joão@meuemail.com' } }); console.log('PIX sent:', response.data); console.log('Bucket size:', response.bucketSize); console.log('Retry after:', response.retryAfter); } catch (error) { console.error(error); } } // Example: Get sent PIX by e2eId async function getSentPixByE2eId() { try { const e2eId = 'E09089356202210251208APIcdbe38b4'; const pix = await client.getSentPixByE2eId(e2eId); console.log(pix); } catch (error) { console.error(error); } } // Example: Get sent PIX by idEnvio async function getSentPixByIdEnvio() { try { const idEnvio = 'identificadoEnvio123456789'; const pix = await client.getSentPixByIdEnvio(idEnvio); console.log(pix); } catch (error) { console.error(error); } } // Example: List sent PIX async function listSentPix() { try { const pixList = await client.listSentPix({ inicio: '2024-01-01T00:00:00.000Z', fim: '2024-01-31T23:59:59.000Z' }); console.log(pixList); } catch (error) { console.error(error); } } // Example: Generate QR Code async function generateQRCode() { try { const qrCode = await client.generateQRCode({ calendario: { expiracao: 3600 }, devedor: { cpf: '12345678909', nome: 'Francisco da Silva' }, valor: { original: '37.00' }, chave: 'your_pix_key', solicitacaoPagador: 'Cobrança dos serviços prestados.' }); console.log('QR Code content:', qrCode.content); console.log('QR Code image:', qrCode.image.base64); // Convert to buffer if needed const imageBuffer = qrCode.image.toBuffer(); } catch (error) { console.error(error); } } // Example: Generate QR Code with due date async function generateQRCodeWithDueDate() { try { const qrCode = await client.generateQRCodeWithDueDate({ calendario: { dataDeVencimento: '2024-12-31', validadeAposVencimento: 30 }, devedor: { cpf: '12345678909', nome: 'Francisco da Silva' }, valor: { original: '37.00', multa: { modalidade: 2, valorPerc: '15.00' }, juros: { modalidade: 2, valorPerc: '2.00' } }, chave: 'your_pix_key', solicitacaoPagador: 'Cobrança dos serviços prestados.' }); console.log('QR Code content:', qrCode.content); console.log('QR Code image:', qrCode.image.base64); } catch (error) { console.error(error); } } // Example: Get QR Code details async function getQRCodeDetails() { try { const qrCode = await client.generateQRCode({ // ... charge data ... }); const details = await client.getQRCodeDetails(qrCode); console.log(details); } catch (error) { console.error(error); } } // Example: Pay QR Code async function payQrCode() { try { const idEnvio = 'your-unique-id'; const payment = await client.payQrCode(idEnvio, { pagador: { chave: 'a1f4102e-a446-4a57-bcce-6fa48899c1d1', infoPagador: 'Pagamento de QR Code via API Pix' }, pixCopiaECola: '00020101021226830014BR.GOV.BCB.PIX2561qrcodespix.sejaefi.com.br/v2/41e0badf811a4ce6ad8a80b306821fce5204000053000065802BR5905EFISA6008SAOPAULO60070503***61040000' }); console.log(payment); } catch (error) { console.error(error); } } // Example: Create a PIX charge async function createPixCharge() { try { const charge = await client.createCharge({ calendario: { expiracao: 3600 }, devedor: { cpf: '12345678909', nome: 'Francisco da Silva' }, valor: { original: '37.00' }, chave: 'your_pix_key', solicitacaoPagador: 'Cobrança dos serviços prestados.' }); console.log(charge); } catch (error) { console.error(error); } } // Example: Create a PIX charge with specific txid async function createPixChargeWithTxid() { try { const txid = 'your-custom-txid'; const charge = await client.createChargeWithTxid(txid, { calendario: { expiracao: 3600 }, devedor: { cnpj: '12345678000195', nome: 'Empresa de Serviços SA' }, valor: { original: '123.45' }, chave: 'your_pix_key', solicitacaoPagador: 'Cobrança dos serviços prestados.' }); console.log(charge); } catch (error) { console.error(error); } } // Example: Create a PIX charge with due date async function createPixChargeWithDueDate() { try { const txid = 'your-custom-txid'; const charge = await client.createDueDateCharge(txid, { calendario: { dataDeVencimento: '2024-12-31', validadeAposVencimento: 30 }, devedor: { logradouro: 'Alameda Souza, Numero 80, Bairro Braz', cidade: 'Recife', uf: 'PE', cep: '70011750', cpf: '12345678909', nome: 'Francisco da Silva' }, valor: { original: '123.45', multa: { modalidade: 2, valorPerc: '15.00' }, juros: { modalidade: 2, valorPerc: '2.00' }, desconto: { modalidade: 1, descontoDataFixa: [ { data: '2024-11-30', valorPerc: '30.00' } ] } }, chave: 'your_pix_key', solicitacaoPagador: 'Cobrança dos serviços prestados.' }); console.log(charge); } catch (error) { console.error(error); } } // Example: Update a PIX charge with due date async function updatePixChargeWithDueDate() { try { const txid = 'existing-txid'; const updatedCharge = await client.updateDueDateCharge(txid, { valor: { original: '150.00', multa: { modalidade: 2, valorPerc: '10.00' } }, solicitacaoPagador: 'Valor atualizado' }); console.log(updatedCharge); } catch (error) { console.error(error); } } // Example: Get a PIX charge with due date async function getPixChargeWithDueDate() { try { const txid = 'existing-txid'; const charge = await client.getDueDateCharge(txid); console.log(charge); // Get specific revision const revision = 1; const chargeRevision = await client.getDueDateCharge(txid, revision); console.log(chargeRevision); } catch (error) { console.error(error); } } // Example: List PIX charges with due date async function listPixChargesWithDueDate() { try { const charges = await client.listDueDateCharges({ inicio: '2024-01-01T00:00:00Z', fim: '2024-01-31T23:59:59Z', status: 'ATIVA', cpf: '12345678909' }); console.log(charges); } catch (error) { console.error(error); } } // Example: Get PIX transaction async function getPixTransaction() { try { const e2eId = 'E12345678202009091221abcdef12345'; const transaction = await client.getPixTransaction(e2eId, true); console.log(transaction); } catch (error) { console.error(error); } } // Example: List PIX transactions async function listPixTransactions() { try { const transactions = await client.listPixTransactions({ inicio: '2024-01-01T00:00:00Z', fim: '2024-01-31T23:59:59Z' }); console.log(transactions); } catch (error) { console.error(error); } } // Example: Request PIX refund async function requestPixRefund() { try { const e2eId = 'E12345678202009091221abcdef12345'; const refundId = '123456'; const refund = await client.requestRefund(e2eId, refundId, { valor: '7.89' }); console.log(refund); } catch (error) { console.error(error); } } // Example: Get PIX refund async function getPixRefund() { try { const e2eId = 'E12345678202009091221abcdef12345'; const refundId = '123456'; const refund = await client.getRefund(e2eId, refundId); console.log(refund); } catch (error) { console.error(error); } } // Example: Setup webhook with ngrok async function setupWebhook() { try { const WebhookHandler = require('./src/WebhookHandler'); const webhookHandler = new WebhookHandler({ ngrokToken: 'your_ngrok_token', port: 3000, certificatePath: './path/to/your/certificate.p12', sandbox: true }); const webhookUrl = await webhookHandler.start(); console.log('Webhook URL:', webhookUrl); // Configure webhook in Efipay const chave = 'your_pix_key'; await client.configureWebhook(chave, webhookUrl); // Handle webhook events webhookHandler.on('pixReceived', (pix) => { console.log('PIX received:', pix); }); webhookHandler.on('pixRefund', (pix) => { console.log('PIX refund:', pix); }); webhookHandler.on('pixSent', (pix) => { console.log('PIX sent:', pix); }); } catch (error) { console.error(error); } } // Example: Configure webhook with skip-mTLS async function configureWebhookSkipMtls() { try { const chave = 'your_pix_key'; const webhookUrl = 'https://your-domain.com/webhook?hmac=xyz&ignorar='; await client.configureWebhook(chave, webhookUrl, true); } catch (error) { console.error(error); } } // Example: Get webhook information async function getWebhookInfo() { try { const chave = 'your_pix_key'; const webhookInfo = await client.getWebhookInfo(chave); console.log(webhookInfo); } catch (error) { console.error(error); } } // Example: List webhooks async function listWebhooks() { try { const webhooks = await client.listWebhooks({ inicio: '2024-01-01T00:00:00Z', fim: '2024-01-31T23:59:59Z' }); console.log(webhooks); } catch (error) { console.error(error); } } // Example: Resend webhook async function resendWebhook() { try { const response = await client.resendWebhook('PIX_RECEBIDO', [ 'E09089356202412261300API229e5352', 'E09089356202412261300API3149af57' ]); console.log(response); } catch (error) { console.error(error); } } // Example: Configure automatic PIX webhook async function configureAutoPixWebhook() { try { const webhookUrl = 'https://your-domain.com/webhook/auto-pix'; await client.configureAutoPixWebhook(webhookUrl); } catch (error) { console.error(error); } } // Example: Configure automatic PIX charge webhook async function configureAutoPixChargeWebhook() { try { const webhookUrl = 'https://your-domain.com/webhook/auto-pix-charge'; await client.configureAutoPixChargeWebhook(webhookUrl); } catch (error) { console.error(error); } } ``` ## Configuration The `EfipayClient` constructor accepts the following configuration options: - `clientId` (required): Your Efipay client ID - `clientSecret` (required): Your Efipay client secret - `certificatePath` (required): Path to your .p12 certificate file - `sandbox` (optional): Set to `true` for sandbox environment, `false` for production (default: `false`) ## Methods ### PIX Send Methods #### sendPix(idEnvio, pixData) Sends a PIX payment. Returns response data and bucket information. - `idEnvio`: Unique identifier for the PIX sending - `pixData`: PIX sending data including value, payer, and payee information #### getSentPixByE2eId(e2eId) Gets a sent PIX by its end-to-end ID. #### getSentPixByIdEnvio(idEnvio) Gets a sent PIX by its sending ID. #### listSentPix(params) Lists sent PIX payments. Required parameters: - `inicio`: Start date (ISO format) - `fim`: End date (ISO format) ### QR Code Methods #### generateQRCode(chargeData) Generates a QR Code for a PIX charge. Returns a QRCode object with: - `content`: The PIX QR Code content (copy and paste code) - `image`: QRCode image in base64 format #### generateQRCodeWithDueDate(chargeData) Generates a QR Code for a PIX charge with due date. Returns a QRCode object with: - `content`: The PIX QR Code content (copy and paste code) - `image`: QRCode image in base64 format #### getQRCodeDetails(qrCode) Gets details of a PIX QR Code. - `qrCode`: QRCode object returned by generateQRCode methods ### PIX Charge Methods #### createCharge(chargeData) Creates a new PIX charge without a specific txid. #### createChargeWithTxid(txid, chargeData) Creates a new PIX charge with a specific txid. #### updateCharge(txid, chargeData) Updates an existing PIX charge. #### getCharge(txid, revision) Gets a PIX charge by txid. Optionally specify a revision number. #### listCharges(params) Lists PIX charges with optional filters. Required parameters: - `inicio`: Start date (ISO format) - `fim`: End date (ISO format) Optional parameters: - `status`: Charge status - `cpf`: Debtor's CPF - `cnpj`: Debtor's CNPJ ### PIX Charge with Due Date Methods #### createDueDateCharge(txid, chargeData) Creates a new PIX charge with due date. Required parameters: - `txid`: Transaction identifier - `chargeData`: Charge data including: - `calendario.dataDeVencimento`: Due date (YYYY-MM-DD) - `calendario.validadeAposVencimento`: Validity period after due date (in days) #### updateDueDateCharge(txid, chargeData) Updates an existing PIX charge with due date. #### getDueDateCharge(txid, revision) Gets a PIX charge with due date by txid. Optionally specify a revision number. #### listDueDateCharges(params) Lists PIX charges with due date. Required parameters: - `inicio`: Start date (ISO format) - `fim`: End date (ISO format) Optional parameters: - `status`: Charge status - `cpf`: Debtor's CPF - `cnpj`: Debtor's CNPJ ### PIX Transaction Methods #### getPixTransaction(e2eId, showBankCode) Gets a PIX transaction by its end-to-end ID. - `e2eId`: End-to-end ID of the PIX transaction - `showBankCode`: Whether to include bank code in the response (default: false) #### listPixTransactions(params) Lists PIX transactions. Required parameters: - `inicio`: Start date (ISO format) - `fim`: End date (ISO format) #### requestRefund(e2eId, refundId, refundData) Requests a refund for a PIX transaction. Required parameters: - `e2eId`: End-to-end ID of the PIX transaction - `refundId`: ID for the refund - `refundData`: Refund data including: - `valor`: Refund amount #### getRefund(e2eId, refundId) Gets a refund by its ID. - `e2eId`: End-to-end ID of the PIX transaction - `refundId`: ID of the refund ### Generic Request Method #### request(method, endpoint, data) Makes an authenticated request to the Efipay API. - `method`: HTTP method (GET, POST, PUT, DELETE) - `endpoint`: API endpoint path - `data`: Request body data (optional) Returns a Promise that resolves with the API response data and headers. ### Webhook Methods #### configureWebhook(chave, webhookUrl, skipMtls) Configures a webhook for PIX notifications. - `chave`: PIX key - `webhookUrl`: Webhook URL - `skipMtls`: Whether to skip mTLS validation (default: false) #### getWebhookInfo(chave) Gets webhook information for a PIX key. #### listWebhooks(params) Lists webhooks. Required parameters: - `inicio`: Start date (ISO format) - `fim`: End date (ISO format) #### deleteWebhook(chave) Deletes a webhook configuration. #### resendWebhook(type, e2eids) Resends webhook notifications. - `type`: Webhook type (e.g., 'PIX_RECEBIDO') - `e2eids`: Array of end-to-end IDs ### Automatic PIX Webhook Methods #### configureAutoPixWebhook(webhookUrl) Configures webhook for automatic PIX notifications. #### getAutoPixWebhookInfo() Gets automatic PIX webhook information. #### deleteAutoPixWebhook() Deletes automatic PIX webhook configuration. ### Automatic PIX Charge Webhook Methods #### configureAutoPixChargeWebhook(webhookUrl) Configures webhook for automatic PIX charge notifications. #### getAutoPixChargeWebhookInfo() Gets automatic PIX charge webhook information. #### deleteAutoPixChargeWebhook() Deletes automatic PIX charge webhook configuration. ## Error Handling The module throws errors with descriptive messages when: - Required configuration is missing - API requests fail - Authentication fails - Required parameters are missing ## License MIT