pixfast 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +101 -0
  2. package/package.json +26 -0
  3. package/src/index.js +186 -0
package/README.md ADDED
@@ -0,0 +1,101 @@
1
+ # pixfast
2
+
3
+ Cliente JavaScript para usar a API PixFast com comandos simples em PT-BR e ingles.
4
+
5
+ ```bash
6
+ npm install pixfast
7
+ ```
8
+
9
+ ## Uso em PT-BR
10
+
11
+ ```js
12
+ import { criarPixFast } from 'pixfast';
13
+
14
+ const pixfast = criarPixFast({
15
+ tokenPixFast: 'TOKEN_DA_SUA_CONTA_PIXFAST',
16
+ tokenMercadoPago: 'APP_USR_ACCESS_TOKEN_DO_MERCADO_PAGO'
17
+ });
18
+
19
+ const pix = await pixfast.gerarPix({
20
+ produto: 'Plano Mensal',
21
+ idPedido: 'pedido-123',
22
+ preco: 1.5,
23
+ emailPagador: 'cliente@exemplo.com',
24
+ webhookUrl: 'https://seudominio.com/webhook/pix'
25
+ });
26
+
27
+ console.log(pix.dados.pix.copiaECola);
28
+ ```
29
+
30
+ ## Verificar pagamento
31
+
32
+ ```js
33
+ const pagamento = await pixfast.verificarPix(pix.dados.pix.id);
34
+
35
+ if (pagamento.dados.situacao === 'pago') {
36
+ console.log('Pode liberar o pedido');
37
+ }
38
+ ```
39
+
40
+ ## Uso em ingles
41
+
42
+ ```js
43
+ import { createPixFast } from 'pixfast';
44
+
45
+ const pixfast = createPixFast({
46
+ pixFastToken: 'YOUR_PIXFAST_TOKEN',
47
+ mercadoPagoToken: 'APP_USR_MERCADO_PAGO_ACCESS_TOKEN'
48
+ });
49
+
50
+ const pix = await pixfast.createPix({
51
+ product: 'Monthly Plan',
52
+ orderId: 'order-123',
53
+ price: 1.5,
54
+ payerEmail: 'customer@example.com',
55
+ webhookUrl: 'https://yourdomain.com/webhook/pix'
56
+ });
57
+
58
+ const paid = await pixfast.isPaid(pix.dados.pix.id);
59
+ console.log(paid);
60
+ ```
61
+
62
+ ## Funcoes diretas
63
+
64
+ ```js
65
+ import { gerarPix, verificarPix } from 'pixfast';
66
+
67
+ const config = {
68
+ tokenPixFast: 'TOKEN_DA_SUA_CONTA_PIXFAST',
69
+ tokenMercadoPago: 'APP_USR_ACCESS_TOKEN_DO_MERCADO_PAGO'
70
+ };
71
+
72
+ const pix = await gerarPix(config, {
73
+ produto: 'Plano Mensal',
74
+ idPedido: 'pedido-123',
75
+ preco: 1.5,
76
+ emailPagador: 'cliente@exemplo.com'
77
+ });
78
+
79
+ const pagamento = await verificarPix(config, pix.dados.pix.id);
80
+ ```
81
+
82
+ ## Campos aceitos
83
+
84
+ ### `gerarPix` / `createPix`
85
+
86
+ - `produto`, `product`, `productName`, `descricao`, `description`
87
+ - `idPedido`, `pedidoId`, `orderId`, `externalReference`, `id`
88
+ - `preco`, `valor`, `price`, `amount`
89
+ - `emailPagador`, `payerEmail`, `email`
90
+ - `metadados`, `metadata`
91
+ - `webhookUrl`, `webhook`, `notificationUrl`
92
+
93
+ Se `webhookUrl` for enviado, o PixFast repassa essa URL ao Mercado Pago na criacao da cobranca. O access token do Mercado Pago e usado somente na requisicao e nao fica armazenado pelo PixFast.
94
+
95
+ ## Compatibilidade
96
+
97
+ - Node.js 18+ ou navegadores modernos com `fetch`.
98
+ - Modulo ESM: use `import`. CommonJS com `require()` nao e suportado nesta versao.
99
+ - Compatível com a API PixFast atual para gerar PIX e consultar status.
100
+ - Compatível apenas com Mercado Pago como provedor de PIX.
101
+ - PixFast e independente e nao faz parte da equipe do Mercado Pago.
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "pixfast",
3
+ "version": "0.1.0",
4
+ "description": "Cliente simples para usar a API PixFast em PT-BR e ingles.",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": "./src/index.js"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "README.md"
14
+ ],
15
+ "keywords": [
16
+ "pix",
17
+ "pixfast",
18
+ "mercado-pago",
19
+ "pagamentos"
20
+ ],
21
+ "author": "PixFast",
22
+ "license": "MIT",
23
+ "engines": {
24
+ "node": ">=18"
25
+ }
26
+ }
package/src/index.js ADDED
@@ -0,0 +1,186 @@
1
+ const DEFAULT_API_URL = 'https://pixfast.squareweb.app';
2
+
3
+ export class PixFast {
4
+ constructor(config = {}) {
5
+ this.apiUrl = cleanUrl(config.apiUrl || config.urlApi || config.endpoint || DEFAULT_API_URL);
6
+ this.pixFastToken = config.pixFastToken || config.tokenPixFast || config.token;
7
+ this.mercadoPagoToken = config.mercadoPagoToken || config.tokenMercadoPago || config.accessToken || config.apiKey;
8
+ this.fetchImpl = config.fetch || globalThis.fetch;
9
+
10
+ if (!this.fetchImpl) {
11
+ throw new Error('Fetch nao disponivel. Use Node.js 18+ ou informe config.fetch.');
12
+ }
13
+ }
14
+
15
+ configurar(config = {}) {
16
+ if (config.apiUrl || config.urlApi || config.endpoint) {
17
+ this.apiUrl = cleanUrl(config.apiUrl || config.urlApi || config.endpoint);
18
+ }
19
+
20
+ if (config.pixFastToken || config.tokenPixFast || config.token) {
21
+ this.pixFastToken = config.pixFastToken || config.tokenPixFast || config.token;
22
+ }
23
+
24
+ if (config.mercadoPagoToken || config.tokenMercadoPago || config.accessToken || config.apiKey) {
25
+ this.mercadoPagoToken = config.mercadoPagoToken || config.tokenMercadoPago || config.accessToken || config.apiKey;
26
+ }
27
+
28
+ return this;
29
+ }
30
+
31
+ configure(config = {}) {
32
+ return this.configurar(config);
33
+ }
34
+
35
+ async gerarPix(input = {}) {
36
+ return this.createPix(input);
37
+ }
38
+
39
+ async createPix(input = {}) {
40
+ const body = normalizePixInput(input, this.mercadoPagoToken);
41
+ return this.request('/api/pix', {
42
+ method: 'POST',
43
+ body
44
+ });
45
+ }
46
+
47
+ async verificarPix(paymentId, input = {}) {
48
+ return this.checkPix(paymentId, input);
49
+ }
50
+
51
+ async consultarPix(paymentId, input = {}) {
52
+ return this.checkPix(paymentId, input);
53
+ }
54
+
55
+ async checkPix(paymentId, input = {}) {
56
+ const id = paymentId || input.paymentId || input.pagamentoId || input.id;
57
+ if (!id) throw new Error('Informe o paymentId do PIX.');
58
+
59
+ return this.request(`/api/pix/${encodeURIComponent(id)}/check`, {
60
+ method: 'POST',
61
+ body: {
62
+ accessToken: input.mercadoPagoToken || input.tokenMercadoPago || input.accessToken || input.apiKey || this.mercadoPagoToken
63
+ }
64
+ });
65
+ }
66
+
67
+ async getPix(paymentId, input = {}) {
68
+ return this.checkPix(paymentId, input);
69
+ }
70
+
71
+ async estaPago(paymentId, input = {}) {
72
+ const result = await this.checkPix(paymentId, input);
73
+ return Boolean(result.ok && result.dados?.situacao === 'pago');
74
+ }
75
+
76
+ async isPaid(paymentId, input = {}) {
77
+ return this.estaPago(paymentId, input);
78
+ }
79
+
80
+ async request(path, options = {}) {
81
+ this.ensureTokens(options.body);
82
+
83
+ const response = await this.fetchImpl(`${this.apiUrl}${path}`, {
84
+ method: options.method || 'GET',
85
+ headers: {
86
+ 'Content-Type': 'application/json',
87
+ 'Authorization': `Bearer ${this.pixFastToken}`,
88
+ ...(options.headers || {})
89
+ },
90
+ body: options.body ? JSON.stringify(options.body) : undefined
91
+ });
92
+
93
+ const data = await parseResponse(response);
94
+
95
+ if (!response.ok || data?.ok === false) {
96
+ throw new PixFastError(data?.mensagem || 'A API PixFast retornou um erro.', {
97
+ status: response.status,
98
+ code: data?.erro,
99
+ result: data
100
+ });
101
+ }
102
+
103
+ return data;
104
+ }
105
+
106
+ ensureTokens(body = {}) {
107
+ if (!this.pixFastToken) {
108
+ throw new Error('Informe o token PixFast em pixFastToken ou tokenPixFast.');
109
+ }
110
+
111
+ if (!body.accessToken) {
112
+ throw new Error('Informe o access token do Mercado Pago em mercadoPagoToken, tokenMercadoPago ou accessToken.');
113
+ }
114
+ }
115
+ }
116
+
117
+ export class PixFastError extends Error {
118
+ constructor(message, details = {}) {
119
+ super(message);
120
+ this.name = 'PixFastError';
121
+ this.status = details.status;
122
+ this.code = details.code;
123
+ this.result = details.result;
124
+ }
125
+ }
126
+
127
+ export function criarPixFast(config = {}) {
128
+ return new PixFast(config);
129
+ }
130
+
131
+ export function createPixFast(config = {}) {
132
+ return new PixFast(config);
133
+ }
134
+
135
+ export async function gerarPix(config, input) {
136
+ return criarPixFast(config).gerarPix(input);
137
+ }
138
+
139
+ export async function createPix(config, input) {
140
+ return createPixFast(config).createPix(input);
141
+ }
142
+
143
+ export async function verificarPix(config, paymentId, input) {
144
+ return criarPixFast(config).verificarPix(paymentId, input);
145
+ }
146
+
147
+ export async function checkPix(config, paymentId, input) {
148
+ return createPixFast(config).checkPix(paymentId, input);
149
+ }
150
+
151
+ export async function estaPago(config, paymentId, input) {
152
+ return criarPixFast(config).estaPago(paymentId, input);
153
+ }
154
+
155
+ export async function isPaid(config, paymentId, input) {
156
+ return createPixFast(config).isPaid(paymentId, input);
157
+ }
158
+
159
+ function normalizePixInput(input, defaultMercadoPagoToken) {
160
+ return {
161
+ accessToken: input.mercadoPagoToken || input.tokenMercadoPago || input.accessToken || input.apiKey || defaultMercadoPagoToken,
162
+ produto: input.produto || input.product || input.productName || input.descricao || input.description,
163
+ idPedido: input.idPedido || input.pedidoId || input.orderId || input.externalReference || input.id,
164
+ preco: input.preco ?? input.valor ?? input.price ?? input.amount,
165
+ emailPagador: input.emailPagador || input.payerEmail || input.email,
166
+ metadados: input.metadados || input.metadata,
167
+ webhookUrl: input.webhookUrl || input.webhook || input.notificationUrl
168
+ };
169
+ }
170
+
171
+ async function parseResponse(response) {
172
+ const text = await response.text();
173
+ if (!text) return null;
174
+
175
+ try {
176
+ return JSON.parse(text);
177
+ } catch {
178
+ return { ok: false, erro: 'RESPOSTA_INVALIDA', mensagem: text };
179
+ }
180
+ }
181
+
182
+ function cleanUrl(value) {
183
+ return String(value || DEFAULT_API_URL).replace(/\/+$/, '');
184
+ }
185
+
186
+ export default PixFast;