@nicotordev/flowcl-pagos
Version:
SDK en TypeScript para integrar pagos con la API de Flow.cl de manera sencilla y segura.
181 lines • 9.18 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = __importDefault(require("axios"));
const qs_1 = __importDefault(require("qs"));
const errors_1 = require("../errors");
const flow_utils_1 = require("../utils/flow.utils");
/**
* Este servicio permite obtener los datos de un Importe.
*/
class FlowInvoices {
/**
* Constructor de la clase FlowClient.
* @param {string} apiKey Clave de API proporcionada por Flow.
* @param {string} secretKey Clave secreta proporcionada por Flow.
* @param {string}baseURL URL base de la API de Flow.
* @throws {FlowAuthenticationError} Si no se proporciona apiKey o secretKey.
*/
constructor(apiKey, secretKey, baseURL) {
this.get = {
/**
* Este servicio permite obtener los datos de un Importe.
* @param invoiceId ID del Importe.
* @returns {Promise<FlowGetInvoiceDataResponse>} Datos del Importe.
* @throws {FlowGetInvoiceDataError} Si hay problemas al obtener los datos del Importe.
* @throws {FlowAPIError} Si hay problemas con la API de Flow.
*/
normal: this.getInvoiceData.bind(this),
/**
* Este servicio permite obtener la lista de invoices vencidos, es decir, aquellos no pagados cuyo due_date este vencido.
* @param {FlowGetOverdueInvoicesRequest} data Datos para obtener los invoices vencidos.
* @returns {Promise<FlowGetOverdueInvoicesResponse>} Lista de invoices vencidos.
* @throws {FlowGetOverdueInvoicesError} Si hay problemas al obtener los invoices vencidos.
* @throws {FlowAPIError} Si hay problemas con la API de Flow.
*/
overdue: this.getOverdueInvoices.bind(this),
};
/**
* Cancela un Importe (Invoice) pendiente de pago
* @param invoiceId ID del Importe
* @returns {Promise<FlowCancelInvoicePendingPaymentReponse>} Respuesta de la API
* @throws {FlowCancelInvoicePendingPaymentError} Si hay problemas al cancelar el Importe
* @throws {FlowAPIError} Si hay problemas con la API de Flow
*/
this.cancelPendingPayment = this.cancelInvoicePendingPayment.bind(this);
/**
* Este servicio permite dar por pagado un Importe (Invoice) cuando el pago no se realiza por Flow.
* @param {FlowRecordExternalPaymentAndMarkInvoicePaidRequest} data Datos para registrar el pago externo y marcar el Importe como pagado.
* @returns {Promise<FlowRecordExternalPaymentAndMarkInvoicePaidResponse>} Respuesta de la API
* @throws {FlowRecordExternalPaymentAndMarkInvoicePaidError} Si hay problemas al registrar el pago externo y marcar el Importe como pagado
* @throws {FlowAPIError} Si hay problemas con la API de Flow
*/
this.recordExternalPaymentAndMarkInvoicePaid = this._recordExternalPaymentAndMarkInvoicePaid.bind(this);
/**
* Este servicio permite reintentar el cobro de un Invoice vencido.
* @param invoiceId ID del Invoice.
* @returns {Promise<FlowRetryOverdueInvoicePaymentResponse>} Respuesta de la API.
* @throws {FlowRetryOverdueInvoicePaymentError} Si hay problemas al reintentar el cobro del Invoice.
* @throws {FlowAPIError} Si hay problemas con la API de Flow.
*/
this.retryOverdueInvoicePayment = this._retryOverdueInvoicePayment.bind(this);
if (!apiKey || !secretKey) {
throw new errors_1.FlowAuthenticationError();
}
this.apiKey = apiKey;
this.secretKey = secretKey;
// Crear una instancia de Axios con la configuración base
this.axiosInstance = axios_1.default.create({
baseURL: `${baseURL}/invoice`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
}
/**
* Realiza una petición a la API de Flow.
* @param {string} endpoint URL del endpoint de la API.
* @param {string} data Datos a enviar en la petición.
* @param {'post' | 'get'} method Método de la petición (POST o GET).
* @param {(e: unknown) => never} error Error a lanzar en caso de error.
* @returns {Promise<T>} Respuesta de la API.
* @throws {FlowAPIError} Si hay problemas con la API de Flow.
* @throws {Error} Si hay problemas al realizar la petición.
*/
async request(endpoint, data, method = 'post', error) {
try {
const allData = {
...data,
apiKey: this.apiKey,
};
const formData = (0, flow_utils_1.generateFormData)(allData, this.secretKey);
const formDataSearchParams = new URLSearchParams(formData);
const response = method === 'post'
? await this.axiosInstance.post(`${endpoint}`, qs_1.default.stringify(formData))
: await this.axiosInstance.get(`${endpoint}?${formDataSearchParams}`);
return response.data;
}
catch (err) {
if (axios_1.default.isAxiosError(err)) {
console.log(err.response?.data);
throw new errors_1.FlowAPIError(err.response?.status || 500, err.message);
}
error(err);
}
}
/**
* Este servicio permite obtener los datos de un Importe.
* @param invoiceId ID del Importe.
* @returns {Promise<FlowGetInvoiceDataResponse>} Datos del Importe.
* @throws {FlowGetInvoiceDataError} Si hay problemas al obtener los datos del Importe.
* @throws {FlowAPIError} Si hay problemas con la API de Flow.
*/
async getInvoiceData(invoiceId) {
return await this.request(`/get`, {
invoiceId,
}, 'get', (err) => {
throw new errors_1.FlowGetInvoiceDataError(err.message);
});
}
/**
* Cancela un Importe (Invoice) pendiente de pago
* @param invoiceId ID del Importe
* @returns {Promise<FlowCancelInvoicePendingPaymentReponse>} Respuesta de la API
* @throws {FlowCancelInvoicePendingPaymentError} Si hay problemas al cancelar el Importe
* @throws {FlowAPIError} Si hay problemas con la API de Flow
*/
async cancelInvoicePendingPayment(invoiceId) {
return await this.request('/cancel', {
invoiceId,
}, 'post', (e) => {
throw new errors_1.FlowCancelInvoicePendingPaymentError(e.message);
});
}
/**
* Este servicio permite dar por pagado un Importe (Invoice) cuando el pago no se realiza por Flow.
* @param {FlowRecordExternalPaymentAndMarkInvoicePaidRequest} data Datos para registrar el pago externo y marcar el Importe como pagado.
* @returns {Promise<FlowRecordExternalPaymentAndMarkInvoicePaidResponse>} Respuesta de la API
* @throws {FlowRecordExternalPaymentAndMarkInvoicePaidError} Si hay problemas al registrar el pago externo y marcar el Importe como pagado
* @throws {FlowAPIError} Si hay problemas con la API de Flow
*/
async _recordExternalPaymentAndMarkInvoicePaid(data) {
const date = data.date;
const validatedDate = (0, flow_utils_1.isValidPaymentReceivedByDate)(date);
if (!validatedDate) {
throw new errors_1.FlowRecordExternalPaymentAndMarkInvoicePaidError('La fecha de pago no esta en formato YYYY-MM-DD');
}
return await this.request('/outsidePayment', data, 'post', (e) => {
throw new errors_1.FlowRecordExternalPaymentAndMarkInvoicePaidError(e.message);
});
}
/**
* Este servicio permite obtener la lista de invoices vencidos, es decir, aquellos no pagados cuyo due_date este vencido.
* @param {FlowGetOverdueInvoicesRequest} data Datos para obtener los invoices vencidos.
* @returns {Promise<FlowGetOverdueInvoicesResponse>} Lista de invoices vencidos.
* @throws {FlowGetOverdueInvoicesError} Si hay problemas al obtener los invoices vencidos.
* @throws {FlowAPIError} Si hay problemas con la API de Flow.
*/
async getOverdueInvoices(data) {
return await this.request('/getOverDue', data, 'get', (e) => {
throw new errors_1.FlowGetOverdueInvoicesError(e.message);
});
}
/**
* Este servicio permite reintentar el cobro de un Invoice vencido.
* @param invoiceId ID del Invoice.
* @returns {Promise<FlowRetryOverdueInvoicePaymentResponse>} Respuesta de la API.
* @throws {FlowRetryOverdueInvoicePaymentError} Si hay problemas al reintentar el cobro del Invoice.
* @throws {FlowAPIError} Si hay problemas con la API de Flow.
*/
async _retryOverdueInvoicePayment(invoiceId) {
return await this.request('/retryToCollect', {
invoiceId,
}, 'post', (e) => {
throw new errors_1.FlowRetryOverdueInvoicePaymentError(e.message);
});
}
}
exports.default = FlowInvoices;
//# sourceMappingURL=flow.invoices.js.map