@movelabs/pix-sicoob
Version:
Cliente PIX para integração com API do Sicoob - Sistema de Cobranças e Pagamentos Instantâneos
292 lines • 11.2 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = exports.SicoobPixClient = void 0;
const axios_1 = __importStar(require("axios"));
const https_1 = __importDefault(require("https"));
const qs_1 = __importDefault(require("qs"));
const zod_1 = require("zod");
const types_1 = require("./types");
/**
* Cliente PIX para integração com API do Sicoob
*
* @example
* ```typescript
* import { SicoobPixClient } from '@movelabs/pix-sicoob';
* import fs from 'fs';
*
* const client = new SicoobPixClient({
* clientId: 'seu-client-id',
* pfxBuffer: fs.readFileSync('certificado.pfx'),
* pfxPassword: 'senha-do-certificado',
* scope: 'cob.write cob.read webhook.read webhook.write',
* debug: true
* });
*
* // Criar cobrança PIX
* const cobranca = await client.createPixCob({
* calendario: { expiracao: 3600 },
* valor: { original: '10.50' },
* chave: 'sua-chave-pix@email.com',
* solicitacaoPagador: 'Pagamento do pedido #123'
* });
* ```
*/
class SicoobPixClient {
constructor(config) {
this.config = config;
this.debug = config.debug ?? false;
this.logger = config.logger;
const httpsAgent = new https_1.default.Agent({
pfx: config.pfxBuffer,
passphrase: this.config.pfxPassword,
});
this.axiosInstanceAuth = axios_1.default.create({
baseURL: "https://auth.sicoob.com.br",
httpsAgent: httpsAgent,
timeout: 5000,
});
this.axiosInstancePix = axios_1.default.create({
baseURL: this.config.baseUrl ?? "https://api.sicoob.com.br/pix/api/v2",
httpsAgent: httpsAgent,
timeout: 5000,
});
}
log(level, message, data) {
if (this.logger) {
this.logger[level](data || {}, message);
return;
}
if (!this.debug && level === "debug")
return;
const timestamp = new Date().toISOString();
const logData = data ? ` ${JSON.stringify(data)}` : "";
console.log(`[${timestamp}] [SICOOB] [${level.toUpperCase()}] ${message}${logData}`);
}
async getAccessToken() {
this.log("debug", "Obtendo token de acesso", {
clientId: this.config.clientId.substring(0, 8) + "...",
});
try {
if (!this.isTokenValid()) {
const data = {
client_id: this.config.clientId,
grant_type: "client_credentials",
scope: this.config.scope,
};
const response = await this.axiosInstanceAuth.post("/auth/realms/cooperado/protocol/openid-connect/token", qs_1.default.stringify(data), {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
this.authResponse = response.data;
this.tokenExpiresAt =
Date.now() + (this.authResponse.expires_in - 60) * 1000;
this.log("info", "Token de acesso obtido com sucesso", {
expiresIn: this.authResponse.expires_in,
scope: this.authResponse.scope,
});
}
return this.authResponse.access_token;
}
catch (error) {
if ((0, axios_1.isAxiosError)(error)) {
this.log("error", "Erro de autenticação", {
status: error.response?.status,
data: error.response?.data,
});
}
else {
this.log("error", "Erro desconhecido na autenticação", { error });
}
throw new Error("Erro ao obter token de acesso");
}
}
isTokenValid() {
if (!this.authResponse) {
this.log("debug", "Nenhuma resposta de autenticação disponível");
return false;
}
if (!this.tokenExpiresAt) {
this.log("debug", "Nenhum timestamp de expiração definido");
return false;
}
if (Date.now() >= this.tokenExpiresAt) {
this.log("debug", "Token expirado", {
expiresAt: new Date(this.tokenExpiresAt).toISOString(),
});
return false;
}
return true;
}
getTokenInfo() {
if (!this.authResponse || !this.tokenExpiresAt) {
return null;
}
return {
token_type: this.authResponse.token_type,
scope: this.authResponse.scope,
expires_in: this.authResponse.expires_in,
expiresAt: new Date(this.tokenExpiresAt),
isValid: this.isTokenValid(),
};
}
async getAuthHeaders() {
return {
client_id: this.config.clientId,
Authorization: `Bearer ${await this.getAccessToken()}`,
"Content-Type": "application/json",
accept: "application/json",
};
}
async getWebhook(chave) {
this.log("debug", "Consultando webhook", { chave });
const response = await this.axiosInstancePix.get(`/webhook/${chave}`, {
headers: await this.getAuthHeaders(),
});
this.log("info", "Webhook consultado com sucesso", {
chave,
webhookUrl: response.data.webhookUrl,
});
return response.data;
}
async setWebhook(chave, webhookUrl) {
this.log("info", "Configurando webhook", { chave, webhookUrl });
await this.axiosInstancePix.put(`/webhook/${chave}`, {
webhookUrl,
}, {
headers: await this.getAuthHeaders(),
});
this.log("info", "Webhook configurado com sucesso", { chave, webhookUrl });
}
async deleteWebhook(chave) {
this.log("info", "Removendo webhook", { chave });
await this.axiosInstancePix.delete(`/webhook/${chave}`, {
headers: await this.getAuthHeaders(),
});
this.log("info", "Webhook removido com sucesso", { chave });
}
async createPixCob(data) {
let validatedData;
let headers;
try {
validatedData = types_1.cobPayloadSchema.parse(data);
headers = await this.getAuthHeaders();
this.log("debug", "Criando cobrança PIX", {
valor: validatedData.valor.original,
chave: validatedData.chave,
solicitacaoPagador: validatedData.solicitacaoPagador,
});
const response = await this.axiosInstancePix.post(`/cob`, validatedData, {
headers,
});
this.log("info", "Cobrança PIX criada com sucesso", {
txid: response.data.txid,
valor: response.data.valor?.original,
status: response.data.status,
});
return response.data;
}
catch (error) {
if (error instanceof zod_1.z.ZodError) {
this.log("error", "Erro de validação ao criar cobrança PIX", {
errors: error.errors,
});
throw new Error("Dados inválidos");
}
if ((0, axios_1.isAxiosError)(error)) {
this.log("error", "Erro HTTP ao criar cobrança PIX", {
status: error.response?.status,
data: error.response?.data,
});
throw new Error(`Erro ao criar cobrança PIX no Sicoob: ${JSON.stringify(error.response?.data, null, 2)}`);
}
this.log("error", "Erro desconhecido ao criar cobrança PIX", { error });
throw new Error("Erro ao criar cobrança PIX");
}
}
async getPixCob(txid) {
this.log("debug", "Consultando cobrança PIX", { txid });
const response = await this.axiosInstancePix.get(`/cob/${txid}`, {
headers: await this.getAuthHeaders(),
});
this.log("info", "Cobrança PIX consultada com sucesso", {
txid,
status: response.data.status,
valor: response.data.valor?.original,
});
return response.data;
}
async getPixCobImagem(txid) {
try {
this.log("debug", "Obtendo imagem QR Code", { txid });
const response = await this.axiosInstancePix.get(`/cob/${txid}/imagem`, {
headers: {
...(await this.getAuthHeaders()),
Accept: "image/png",
},
});
this.log("info", "Imagem QR Code obtida com sucesso", { txid });
return response.data;
}
catch (error) {
this.log("error", "Erro ao obter imagem QR Code do PIX", { txid, error });
throw new Error("Erro ao obter imagem QR Code do PIX");
}
}
async listPix(query) {
this.log("debug", "Listando cobranças PIX", { query });
const response = await this.axiosInstancePix.get(`/cob`, {
headers: await this.getAuthHeaders(),
params: query,
});
this.log("info", "Cobranças PIX listadas com sucesso", {
parametros: query,
total: response.data.cobs?.length || 0,
});
return response.data;
}
}
exports.SicoobPixClient = SicoobPixClient;
exports.default = SicoobPixClient;
// Exportar tipos e classes
__exportStar(require("./types"), exports);
//# sourceMappingURL=index.js.map