@vitrindigital/node 0.3.1 → 0.5.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.
- package/README.md +89 -4
- package/dist/index.cjs +193 -7
- package/dist/index.d.cts +91 -7
- package/dist/index.d.ts +91 -7
- package/dist/index.js +192 -7
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -140,14 +140,18 @@ Toda chamada lança subclasses de `VitrinError`:
|
|
|
140
140
|
|
|
141
141
|
```ts
|
|
142
142
|
import {
|
|
143
|
-
VitrinError, VitrinAuthError, VitrinValidationError,
|
|
143
|
+
VitrinError, VitrinAuthError, VitrinValidationError, VitrinRefusedError,
|
|
144
144
|
VitrinRateLimitError, VitrinNotFoundError, VitrinServerError,
|
|
145
145
|
} from '@vitrindigital/node';
|
|
146
146
|
|
|
147
147
|
try {
|
|
148
148
|
await vitrin.charges.create({ /* ... */ });
|
|
149
149
|
} catch (err) {
|
|
150
|
-
if (err instanceof
|
|
150
|
+
if (err instanceof VitrinRefusedError) {
|
|
151
|
+
// A cobrança CHEGOU ao emissor e ele negou.
|
|
152
|
+
console.log('Recusado:', err.code, err.customerMessage);
|
|
153
|
+
} else if (err instanceof VitrinValidationError) {
|
|
154
|
+
// A cobrança NÃO saiu daqui — o payload foi rejeitado.
|
|
151
155
|
console.log('Campos inválidos:', err.fieldErrors);
|
|
152
156
|
} else if (err instanceof VitrinAuthError) {
|
|
153
157
|
console.log('Chave inválida ou sem permissão');
|
|
@@ -161,8 +165,89 @@ try {
|
|
|
161
165
|
}
|
|
162
166
|
```
|
|
163
167
|
|
|
164
|
-
O cliente faz **retry automático**
|
|
165
|
-
|
|
168
|
+
O cliente faz **retry automático** com backoff exponencial (default: 3
|
|
169
|
+
tentativas), mas só quando repetir não arrisca cobrar duas vezes:
|
|
170
|
+
|
|
171
|
+
| Situação | `GET` (e `PUT`/`DELETE`) | `POST`/`PATCH` |
|
|
172
|
+
|---|---|---|
|
|
173
|
+
| `429` | repete | repete (o limite barra o pedido antes de qualquer efeito) |
|
|
174
|
+
| `5xx` com `retryable: true` | repete | repete (nada foi cobrado) |
|
|
175
|
+
| `5xx` com `retryable: false` | repete | **não repete** |
|
|
176
|
+
| `5xx` sem `retryable` (ex.: 502/504 do proxy) | repete | só no `/charges/` e `/charges/charge-saved/` com `idempotencyKey` |
|
|
177
|
+
| conexão que nem abriu (DNS, conexão recusada) | repete | repete (nada saiu daqui) |
|
|
178
|
+
| tempo esgotado, conexão caída no meio | repete | só no `/charges/` e `/charges/charge-saved/` com `idempotencyKey` |
|
|
179
|
+
| `4xx` (exceto 429) | não repete | não repete |
|
|
180
|
+
|
|
181
|
+
`retryable: true` num 5xx quer dizer **nada foi cobrado**, em todos os
|
|
182
|
+
caminhos de cartão da API: `/checkout/pay/`, `/charges/`,
|
|
183
|
+
`/charges/charge-saved/`, `/orders/create/`, `/checkout/guest/`,
|
|
184
|
+
`/subscriptions/` e one-click.
|
|
185
|
+
|
|
186
|
+
O `502` com `retryable: false` e `payment_status: "processing"` é o resultado
|
|
187
|
+
incerto de uma cobrança de cartão: a resposta do processador se perdeu e **a
|
|
188
|
+
cobrança pode ter sido feita**. O SDK **nunca reenvia** esse POST. Em
|
|
189
|
+
`charges.create()`, `charges.createWithSavedCard()` e `/checkout/pay/`, ele
|
|
190
|
+
consulta `GET /transactions/{transaction_id}/` por até ~60 s (após 2, 4, 8,
|
|
191
|
+
15 e 30 s) e devolve o desfecho:
|
|
192
|
+
|
|
193
|
+
| Desfecho da transação | O que a chamada faz |
|
|
194
|
+
|---|---|
|
|
195
|
+
| paga (`received`/`confirmed`) | devolve a transação: o mesmo objeto do sucesso |
|
|
196
|
+
| recusada pelo emissor | lança `VitrinRefusedError`, como o `422` |
|
|
197
|
+
| ainda incerta no fim do prazo (ou consulta falhando) | lança `VitrinServerError` com `payment_status: "processing"` e `transaction_id` no `body` |
|
|
198
|
+
|
|
199
|
+
O prazo é configurável: `new Vitrin({ apiKey, uncertainWaitMs: 30_000 })`;
|
|
200
|
+
`uncertainWaitMs: 0` desliga a consulta e lança o erro na hora. Uma falha na
|
|
201
|
+
consulta não conta como "não cobrado": o SDK segue consultando até o prazo.
|
|
202
|
+
|
|
203
|
+
Em `/orders/create/`, `/checkout/guest/` e `/subscriptions/` o objeto do
|
|
204
|
+
sucesso (pedido, assinatura) não existe quando o pagamento se confirma depois,
|
|
205
|
+
então o erro é lançado na hora, sem consulta. Nos dois casos, não cobre de
|
|
206
|
+
novo: aguarde o webhook ou consulte a transação.
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
try {
|
|
210
|
+
await vitrin.charges.create({ ... });
|
|
211
|
+
} catch (err) {
|
|
212
|
+
const body = (err as VitrinError).body as Record<string, unknown> | undefined;
|
|
213
|
+
if (err instanceof VitrinServerError && body?.payment_status === 'processing') {
|
|
214
|
+
// NÃO cobre de novo: aguarde o webhook de pagamento desta transação.
|
|
215
|
+
await vitrin.charges.retrieve(String(body.transaction_id));
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
No `/charges/` e no `/charges/charge-saved/`, a Vitrin acha a cobrança pela
|
|
221
|
+
`idempotencyKey` antes de ir ao processador, então ali o SDK repete com
|
|
222
|
+
segurança: a repetição devolve a mesma cobrança (ou o mesmo `502` incerto
|
|
223
|
+
enquanto ela não tem desfecho), nunca uma segunda. Em qualquer outro endpoint a
|
|
224
|
+
chave não impede o segundo efeito, e o SDK não repete.
|
|
225
|
+
|
|
226
|
+
### Recusa não é erro de validação
|
|
227
|
+
|
|
228
|
+
A API usa `422` para duas situações opostas, e o SDK as separa em classes
|
|
229
|
+
diferentes:
|
|
230
|
+
|
|
231
|
+
| Classe | O que aconteceu | O que fazer |
|
|
232
|
+
|---|---|---|
|
|
233
|
+
| `VitrinValidationError` | O payload foi rejeitado. **Nada foi enviado ao banco.** | Corrigir os campos (`fieldErrors`) e repetir. |
|
|
234
|
+
| `VitrinRefusedError` | A cobrança **chegou ao emissor** e ele negou. | Exibir `customerMessage`; oferecer retry só se `retryable`. |
|
|
235
|
+
|
|
236
|
+
O discriminador é o código de retorno no corpo (`return_code` / `abecs_code`):
|
|
237
|
+
ele só existe porque houve resposta de autorização.
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
if (err instanceof VitrinRefusedError) {
|
|
241
|
+
showError(err.customerMessage); // texto pronto, em PT-BR
|
|
242
|
+
err.retryable
|
|
243
|
+
? showRetryButton() // ex.: 51 saldo, 91 emissor fora do ar
|
|
244
|
+
: showCardSwitcher(); // ex.: 82 negada — o mesmo cartão vai negar de novo
|
|
245
|
+
console.log(err.code, err.transactionId); // pra log/suporte
|
|
246
|
+
}
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
`transactionId` aponta para a Transaction `failed` que registra a tentativa —
|
|
250
|
+
ela também aparece em `GET /transactions/?status=failed` e no painel.
|
|
166
251
|
|
|
167
252
|
## Idempotência
|
|
168
253
|
|
package/dist/index.cjs
CHANGED
|
@@ -26,6 +26,7 @@ __export(index_exports, {
|
|
|
26
26
|
VitrinNetworkError: () => VitrinNetworkError,
|
|
27
27
|
VitrinNotFoundError: () => VitrinNotFoundError,
|
|
28
28
|
VitrinRateLimitError: () => VitrinRateLimitError,
|
|
29
|
+
VitrinRefusedError: () => VitrinRefusedError,
|
|
29
30
|
VitrinServerError: () => VitrinServerError,
|
|
30
31
|
VitrinValidationError: () => VitrinValidationError,
|
|
31
32
|
Webhooks: () => Webhooks
|
|
@@ -54,6 +55,29 @@ var VitrinValidationError = class extends VitrinError {
|
|
|
54
55
|
this.fieldErrors = opts.fieldErrors;
|
|
55
56
|
}
|
|
56
57
|
};
|
|
58
|
+
var VitrinRefusedError = class extends VitrinError {
|
|
59
|
+
/** Código ABECS do emissor (ex.: '82', 'GD') ou interno ('VITRIN_3DS_MISSING'). */
|
|
60
|
+
code;
|
|
61
|
+
/** Descrição interna do código. Pra log/suporte — não exibir ao pagador. */
|
|
62
|
+
codeDescription;
|
|
63
|
+
/** Texto pronto pra exibir ao cliente final, já adaptado ao motivo. */
|
|
64
|
+
customerMessage;
|
|
65
|
+
/**
|
|
66
|
+
* `true` → o emissor admite nova tentativa com o MESMO cartão.
|
|
67
|
+
* `false` → recusa definitiva; ofereça outro cartão.
|
|
68
|
+
*/
|
|
69
|
+
retryable;
|
|
70
|
+
/** Id da Transaction `failed` que registra a tentativa, quando a API a devolve. */
|
|
71
|
+
transactionId;
|
|
72
|
+
constructor(message, opts = {}) {
|
|
73
|
+
super(message, opts);
|
|
74
|
+
this.code = opts.code;
|
|
75
|
+
this.codeDescription = opts.codeDescription;
|
|
76
|
+
this.customerMessage = opts.customerMessage;
|
|
77
|
+
this.retryable = opts.retryable ?? false;
|
|
78
|
+
this.transactionId = opts.transactionId;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
57
81
|
var VitrinRateLimitError = class extends VitrinError {
|
|
58
82
|
};
|
|
59
83
|
var VitrinNotFoundError = class extends VitrinError {
|
|
@@ -65,12 +89,13 @@ var VitrinNetworkError = class extends VitrinError {
|
|
|
65
89
|
|
|
66
90
|
// src/client.ts
|
|
67
91
|
var DEFAULT_BASE_URL = "https://api.vitrin.digital/api/v1";
|
|
68
|
-
var SDK_VERSION = "0.
|
|
92
|
+
var SDK_VERSION = "0.5.0";
|
|
69
93
|
var VitrinClient = class {
|
|
70
94
|
baseUrl;
|
|
71
95
|
apiKey;
|
|
72
96
|
timeout;
|
|
73
97
|
maxRetries;
|
|
98
|
+
uncertainWaitMs;
|
|
74
99
|
constructor(opts) {
|
|
75
100
|
if (!opts.apiKey) {
|
|
76
101
|
throw new Error("apiKey \xE9 obrigat\xF3rio");
|
|
@@ -79,6 +104,7 @@ var VitrinClient = class {
|
|
|
79
104
|
this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
80
105
|
this.timeout = opts.timeout ?? 3e4;
|
|
81
106
|
this.maxRetries = opts.maxRetries ?? 3;
|
|
107
|
+
this.uncertainWaitMs = Math.max(0, opts.uncertainWaitMs ?? 6e4);
|
|
82
108
|
}
|
|
83
109
|
/** Helper público pra resources. */
|
|
84
110
|
async request(path, options = {}) {
|
|
@@ -109,7 +135,7 @@ var VitrinClient = class {
|
|
|
109
135
|
lastError = new VitrinNetworkError(
|
|
110
136
|
netErr.name === "AbortError" ? `Timeout ap\xF3s ${this.timeout}ms` : netErr.message || "Falha de rede"
|
|
111
137
|
);
|
|
112
|
-
if (attempt < this.maxRetries &&
|
|
138
|
+
if (attempt < this.maxRetries && shouldRetryNetworkError(method, path, idempotencyKey, err2)) {
|
|
113
139
|
await sleep(backoffMs(attempt));
|
|
114
140
|
continue;
|
|
115
141
|
}
|
|
@@ -129,8 +155,11 @@ var VitrinClient = class {
|
|
|
129
155
|
} catch {
|
|
130
156
|
}
|
|
131
157
|
const err = mapErrorResponse(res.status, parsed, requestId);
|
|
132
|
-
const
|
|
133
|
-
if (
|
|
158
|
+
const uncertainTxId = uncertainTransactionId(method, path, res.status, parsed);
|
|
159
|
+
if (uncertainTxId && this.uncertainWaitMs > 0) {
|
|
160
|
+
return this.resolveUncertain(uncertainTxId, err);
|
|
161
|
+
}
|
|
162
|
+
if (attempt < this.maxRetries && shouldRetryResponse(method, path, idempotencyKey, res.status, parsed)) {
|
|
134
163
|
const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
|
|
135
164
|
await sleep(retryAfter ?? backoffMs(attempt));
|
|
136
165
|
lastError = err;
|
|
@@ -140,6 +169,71 @@ var VitrinClient = class {
|
|
|
140
169
|
}
|
|
141
170
|
throw lastError ?? new VitrinError("Esgotou as tentativas sem erro identificado");
|
|
142
171
|
}
|
|
172
|
+
/**
|
|
173
|
+
* Resultado incerto de cartão: consulta `GET /transactions/{id}/` com
|
|
174
|
+
* backoff (2, 4, 8, 15, 30 s, cortado em `uncertainWaitMs`) até haver
|
|
175
|
+
* desfecho. NUNCA reenvia o POST.
|
|
176
|
+
*
|
|
177
|
+
* O prazo é pelo relógio (`Date.now()`), não pela soma das esperas: cada
|
|
178
|
+
* GET pode levar até o próprio timeout, e sem descontar isso do prazo o
|
|
179
|
+
* pior caso passava longe de `uncertainWaitMs` (~3,5 min com o default).
|
|
180
|
+
* O timeout de cada GET é o menor entre `timeout` e o tempo que ainda
|
|
181
|
+
* falta pro prazo, e com menos de `MIN_GET_BUDGET_MS` restantes o SDK nem
|
|
182
|
+
* tenta mais uma consulta.
|
|
183
|
+
*
|
|
184
|
+
* - paga (`received`/`confirmed`): devolve a transação. É o mesmo objeto
|
|
185
|
+
* que o sucesso do `/charges/`, do `/charges/charge-saved/` e do
|
|
186
|
+
* `/checkout/pay/` devolve (os três respondem com a transação);
|
|
187
|
+
* - recusada (código do emissor): lança `VitrinRefusedError`, como o 422;
|
|
188
|
+
* - ainda incerta no prazo, ou erro em todas as consultas: lança o erro
|
|
189
|
+
* original (`VitrinServerError` com `payment_status: "processing"` e
|
|
190
|
+
* `transaction_id` no `body`). Erro de consulta não prova nada.
|
|
191
|
+
*/
|
|
192
|
+
async resolveUncertain(transactionId, original) {
|
|
193
|
+
const deadline = Date.now() + this.uncertainWaitMs;
|
|
194
|
+
for (const step of UNCERTAIN_BACKOFF_MS) {
|
|
195
|
+
const beforeSleep = deadline - Date.now();
|
|
196
|
+
if (beforeSleep <= 0) break;
|
|
197
|
+
await sleep(Math.min(step, beforeSleep));
|
|
198
|
+
const remaining = deadline - Date.now();
|
|
199
|
+
if (remaining < MIN_GET_BUDGET_MS) break;
|
|
200
|
+
let tx;
|
|
201
|
+
try {
|
|
202
|
+
tx = await this.getOnce(
|
|
203
|
+
`/transactions/${encodeURIComponent(transactionId)}/`,
|
|
204
|
+
Math.min(this.timeout, remaining)
|
|
205
|
+
);
|
|
206
|
+
} catch {
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
const outcome = uncertainOutcome(tx);
|
|
210
|
+
if (outcome === "paid") return tx;
|
|
211
|
+
if (outcome === "refused") throw refusedFromTransaction(tx, original.requestId);
|
|
212
|
+
}
|
|
213
|
+
throw original;
|
|
214
|
+
}
|
|
215
|
+
/** Uma consulta, sem retry próprio (o laço de `resolveUncertain` é o retry). */
|
|
216
|
+
async getOnce(path, timeoutMs = this.timeout) {
|
|
217
|
+
const controller = new AbortController();
|
|
218
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
219
|
+
try {
|
|
220
|
+
const res = await fetch(this.buildUrl(path), {
|
|
221
|
+
method: "GET",
|
|
222
|
+
headers: {
|
|
223
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
224
|
+
Accept: "application/json",
|
|
225
|
+
"User-Agent": `vitrindigital-node/${SDK_VERSION} node/${process.version}`
|
|
226
|
+
},
|
|
227
|
+
signal: controller.signal
|
|
228
|
+
});
|
|
229
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
230
|
+
const body = await res.json();
|
|
231
|
+
if (!body || typeof body !== "object") throw new Error("corpo inv\xE1lido");
|
|
232
|
+
return body;
|
|
233
|
+
} finally {
|
|
234
|
+
clearTimeout(timer);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
143
237
|
buildUrl(path, query) {
|
|
144
238
|
const url = new URL(this.baseUrl + (path.startsWith("/") ? path : `/${path}`));
|
|
145
239
|
if (query) {
|
|
@@ -159,12 +253,29 @@ function mapErrorResponse(status, body, requestId) {
|
|
|
159
253
|
if (status === 404) return new VitrinNotFoundError(message, opts);
|
|
160
254
|
if (status === 429) return new VitrinRateLimitError(message, opts);
|
|
161
255
|
if (status >= 500) return new VitrinServerError(message, opts);
|
|
256
|
+
if (status === 422) {
|
|
257
|
+
const refusal = extractRefusal(body);
|
|
258
|
+
if (refusal) return new VitrinRefusedError(message, { ...opts, ...refusal });
|
|
259
|
+
}
|
|
162
260
|
if (status === 400 || status === 422) {
|
|
163
261
|
const fieldErrors = extractFieldErrors(body);
|
|
164
262
|
return new VitrinValidationError(message, { ...opts, fieldErrors });
|
|
165
263
|
}
|
|
166
264
|
return new VitrinError(message, opts);
|
|
167
265
|
}
|
|
266
|
+
function extractRefusal(body) {
|
|
267
|
+
if (!body || typeof body !== "object") return void 0;
|
|
268
|
+
const b = body;
|
|
269
|
+
const code = b.return_code ?? b.abecs_code;
|
|
270
|
+
if (typeof code !== "string" || !code) return void 0;
|
|
271
|
+
return {
|
|
272
|
+
code,
|
|
273
|
+
codeDescription: typeof b.return_code_description === "string" ? b.return_code_description : void 0,
|
|
274
|
+
customerMessage: typeof b.customer_message === "string" ? b.customer_message : void 0,
|
|
275
|
+
retryable: b.retryable === true,
|
|
276
|
+
transactionId: typeof b.transaction_id === "string" ? b.transaction_id : void 0
|
|
277
|
+
};
|
|
278
|
+
}
|
|
168
279
|
function extractErrorMessage(body) {
|
|
169
280
|
if (!body || typeof body !== "object") return void 0;
|
|
170
281
|
const b = body;
|
|
@@ -192,9 +303,83 @@ function parseRetryAfter(header) {
|
|
|
192
303
|
return null;
|
|
193
304
|
}
|
|
194
305
|
var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
306
|
+
var DEDUPLICATED_PATHS = /* @__PURE__ */ new Set(["/charges/", "/charges/charge-saved/"]);
|
|
307
|
+
var NEVER_CONNECTED_CODES = /* @__PURE__ */ new Set([
|
|
308
|
+
"ECONNREFUSED",
|
|
309
|
+
"ENOTFOUND",
|
|
310
|
+
"EAI_AGAIN",
|
|
311
|
+
"EHOSTUNREACH",
|
|
312
|
+
"ENETUNREACH",
|
|
313
|
+
"UND_ERR_CONNECT_TIMEOUT"
|
|
314
|
+
]);
|
|
315
|
+
function normalizePath(path) {
|
|
316
|
+
const p = path.split("?")[0];
|
|
317
|
+
const withSlash = p.startsWith("/") ? p : `/${p}`;
|
|
318
|
+
return withSlash.endsWith("/") ? withSlash : `${withSlash}/`;
|
|
319
|
+
}
|
|
320
|
+
function isIdempotentMethod(method) {
|
|
321
|
+
return IDEMPOTENT_METHODS.has(method.toUpperCase());
|
|
322
|
+
}
|
|
323
|
+
function serverDeduplicates(path, idempotencyKey) {
|
|
324
|
+
return Boolean(idempotencyKey) && DEDUPLICATED_PATHS.has(normalizePath(path));
|
|
325
|
+
}
|
|
326
|
+
function neverConnected(err) {
|
|
327
|
+
const cause = err?.cause;
|
|
328
|
+
if (!cause) return false;
|
|
329
|
+
if (cause.code && NEVER_CONNECTED_CODES.has(cause.code)) return true;
|
|
330
|
+
return Array.isArray(cause.errors) && cause.errors.length > 0 && cause.errors.every((e) => Boolean(e?.code && NEVER_CONNECTED_CODES.has(e.code)));
|
|
331
|
+
}
|
|
332
|
+
function shouldRetryNetworkError(method, path, idempotencyKey, err) {
|
|
333
|
+
if (isIdempotentMethod(method)) return true;
|
|
334
|
+
if (neverConnected(err)) return true;
|
|
335
|
+
return serverDeduplicates(path, idempotencyKey);
|
|
336
|
+
}
|
|
337
|
+
function shouldRetryResponse(method, path, idempotencyKey, status, body) {
|
|
338
|
+
if (status !== 429 && status < 500) return false;
|
|
339
|
+
if (isIdempotentMethod(method) || status === 429) return true;
|
|
340
|
+
const retryable = body && typeof body === "object" ? body.retryable : void 0;
|
|
341
|
+
if (retryable === true) return true;
|
|
342
|
+
if (retryable === false) return false;
|
|
343
|
+
return serverDeduplicates(path, idempotencyKey);
|
|
344
|
+
}
|
|
345
|
+
var UNCERTAIN_BACKOFF_MS = [2e3, 4e3, 8e3, 15e3, 3e4];
|
|
346
|
+
var MIN_GET_BUDGET_MS = 1e3;
|
|
347
|
+
var TRANSACTION_RESULT_PATHS = /* @__PURE__ */ new Set(["/charges/", "/charges/charge-saved/", "/checkout/pay/"]);
|
|
348
|
+
var PAID_STATUSES = /* @__PURE__ */ new Set(["received", "confirmed"]);
|
|
349
|
+
var REFUSED_STATUSES = /* @__PURE__ */ new Set(["failed", "canceled", "expired"]);
|
|
350
|
+
var UNCERTAIN_CODE = "VITRIN_PROVIDER_UNCERTAIN";
|
|
351
|
+
function uncertainTransactionId(method, path, status, body) {
|
|
352
|
+
if (isIdempotentMethod(method) || status < 500) return void 0;
|
|
353
|
+
if (!TRANSACTION_RESULT_PATHS.has(normalizePath(path))) return void 0;
|
|
354
|
+
if (!body || typeof body !== "object") return void 0;
|
|
355
|
+
const b = body;
|
|
356
|
+
if (b.payment_status !== "processing" || b.retryable !== false) return void 0;
|
|
357
|
+
return typeof b.transaction_id === "string" && b.transaction_id ? b.transaction_id : void 0;
|
|
358
|
+
}
|
|
359
|
+
function uncertainOutcome(tx) {
|
|
360
|
+
const status = String(tx.status ?? "");
|
|
361
|
+
if (PAID_STATUSES.has(status)) return "paid";
|
|
362
|
+
if (REFUSED_STATUSES.has(status)) {
|
|
363
|
+
const refusal = tx.refusal;
|
|
364
|
+
if (refusal?.code === UNCERTAIN_CODE) return "pending";
|
|
365
|
+
return "refused";
|
|
366
|
+
}
|
|
367
|
+
return "pending";
|
|
368
|
+
}
|
|
369
|
+
function refusedFromTransaction(tx, requestId) {
|
|
370
|
+
const refusal = tx.refusal ?? {};
|
|
371
|
+
const str = (v) => typeof v === "string" && v ? v : void 0;
|
|
372
|
+
const description = str(refusal.description) ?? str(refusal.message);
|
|
373
|
+
return new VitrinRefusedError(description ?? "Pagamento n\xE3o autorizado.", {
|
|
374
|
+
statusCode: 422,
|
|
375
|
+
body: tx,
|
|
376
|
+
requestId,
|
|
377
|
+
code: str(refusal.code),
|
|
378
|
+
codeDescription: description,
|
|
379
|
+
customerMessage: str(refusal.customer_message),
|
|
380
|
+
retryable: refusal.retryable === true,
|
|
381
|
+
transactionId: str(tx.id)
|
|
382
|
+
});
|
|
198
383
|
}
|
|
199
384
|
function backoffMs(attempt) {
|
|
200
385
|
const base = 250 * Math.pow(2, attempt);
|
|
@@ -511,6 +696,7 @@ var Vitrin = class {
|
|
|
511
696
|
VitrinNetworkError,
|
|
512
697
|
VitrinNotFoundError,
|
|
513
698
|
VitrinRateLimitError,
|
|
699
|
+
VitrinRefusedError,
|
|
514
700
|
VitrinServerError,
|
|
515
701
|
VitrinValidationError,
|
|
516
702
|
Webhooks
|
package/dist/index.d.cts
CHANGED
|
@@ -5,11 +5,15 @@
|
|
|
5
5
|
* - Adicionar headers padrão (Authorization, User-Agent, Content-Type)
|
|
6
6
|
* - Serializar/deserializar JSON
|
|
7
7
|
* - Mapear erros HTTP pra `VitrinError`*
|
|
8
|
-
* - Retry automático
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
8
|
+
* - Retry automático (até 3 tentativas, backoff exponencial) SÓ quando é
|
|
9
|
+
* seguro — ver `shouldRetryResponse` e `shouldRetryNetworkError`:
|
|
10
|
+
* - GET/HEAD/PUT/DELETE: 429, 5xx, timeout e erro de rede;
|
|
11
|
+
* - POST/PATCH: 429, 5xx com `retryable: true` no corpo, ou conexão
|
|
12
|
+
* que nem abriu. Nunca em timeout de leitura nem em 5xx sem
|
|
13
|
+
* `retryable: true` (o 502 incerto de cartão diz `retryable: false`:
|
|
14
|
+
* a cobrança pode ter saído, e repetir é débito duplo);
|
|
15
|
+
* - exceção: `/charges/` e `/charges/charge-saved/` com
|
|
16
|
+
* Idempotency-Key, que o servidor deduplica pela chave.
|
|
13
17
|
* - Idempotency-Key opcional pra POSTs (evita duplo-débito quando o cliente
|
|
14
18
|
* retenta uma chamada que já chegou no servidor)
|
|
15
19
|
*/
|
|
@@ -22,6 +26,13 @@ interface VitrinClientOptions {
|
|
|
22
26
|
timeout?: number;
|
|
23
27
|
/** Max retries em 429/5xx. Default: 3. */
|
|
24
28
|
maxRetries?: number;
|
|
29
|
+
/**
|
|
30
|
+
* Quanto tempo (ms) o SDK consulta o desfecho de uma cobrança de cartão com
|
|
31
|
+
* resultado incerto (502 com `payment_status: "processing"`) antes de
|
|
32
|
+
* desistir. Default: 60000. `0` desliga (lança o erro na hora). O POST
|
|
33
|
+
* nunca é reenviado. Ver `resolveUncertain`.
|
|
34
|
+
*/
|
|
35
|
+
uncertainWaitMs?: number;
|
|
25
36
|
}
|
|
26
37
|
interface RequestOptions {
|
|
27
38
|
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
@@ -35,9 +46,33 @@ declare class VitrinClient {
|
|
|
35
46
|
private readonly apiKey;
|
|
36
47
|
private readonly timeout;
|
|
37
48
|
private readonly maxRetries;
|
|
49
|
+
private readonly uncertainWaitMs;
|
|
38
50
|
constructor(opts: VitrinClientOptions);
|
|
39
51
|
/** Helper público pra resources. */
|
|
40
52
|
request<T = unknown>(path: string, options?: RequestOptions): Promise<T>;
|
|
53
|
+
/**
|
|
54
|
+
* Resultado incerto de cartão: consulta `GET /transactions/{id}/` com
|
|
55
|
+
* backoff (2, 4, 8, 15, 30 s, cortado em `uncertainWaitMs`) até haver
|
|
56
|
+
* desfecho. NUNCA reenvia o POST.
|
|
57
|
+
*
|
|
58
|
+
* O prazo é pelo relógio (`Date.now()`), não pela soma das esperas: cada
|
|
59
|
+
* GET pode levar até o próprio timeout, e sem descontar isso do prazo o
|
|
60
|
+
* pior caso passava longe de `uncertainWaitMs` (~3,5 min com o default).
|
|
61
|
+
* O timeout de cada GET é o menor entre `timeout` e o tempo que ainda
|
|
62
|
+
* falta pro prazo, e com menos de `MIN_GET_BUDGET_MS` restantes o SDK nem
|
|
63
|
+
* tenta mais uma consulta.
|
|
64
|
+
*
|
|
65
|
+
* - paga (`received`/`confirmed`): devolve a transação. É o mesmo objeto
|
|
66
|
+
* que o sucesso do `/charges/`, do `/charges/charge-saved/` e do
|
|
67
|
+
* `/checkout/pay/` devolve (os três respondem com a transação);
|
|
68
|
+
* - recusada (código do emissor): lança `VitrinRefusedError`, como o 422;
|
|
69
|
+
* - ainda incerta no prazo, ou erro em todas as consultas: lança o erro
|
|
70
|
+
* original (`VitrinServerError` com `payment_status: "processing"` e
|
|
71
|
+
* `transaction_id` no `body`). Erro de consulta não prova nada.
|
|
72
|
+
*/
|
|
73
|
+
private resolveUncertain;
|
|
74
|
+
/** Uma consulta, sem retry próprio (o laço de `resolveUncertain` é o retry). */
|
|
75
|
+
private getOnce;
|
|
41
76
|
private buildUrl;
|
|
42
77
|
}
|
|
43
78
|
|
|
@@ -470,7 +505,10 @@ declare const Webhooks: {
|
|
|
470
505
|
*
|
|
471
506
|
* VitrinError — base, qualquer falha conhecida do SDK
|
|
472
507
|
* ├─ VitrinAuthError — 401/403 (chave inválida ou sem permissão)
|
|
473
|
-
* ├─ VitrinValidationError — 400/422
|
|
508
|
+
* ├─ VitrinValidationError — 400/422 sem código de retorno: o payload
|
|
509
|
+
* │ foi rejeitado e NADA foi enviado ao banco
|
|
510
|
+
* ├─ VitrinRefusedError — 422 com código de retorno: a cobrança
|
|
511
|
+
* │ CHEGOU ao emissor e ele negou
|
|
474
512
|
* ├─ VitrinRateLimitError — 429
|
|
475
513
|
* ├─ VitrinNotFoundError — 404
|
|
476
514
|
* ├─ VitrinServerError — 5xx
|
|
@@ -500,6 +538,52 @@ declare class VitrinValidationError extends VitrinError {
|
|
|
500
538
|
fieldErrors?: Record<string, string[]>;
|
|
501
539
|
});
|
|
502
540
|
}
|
|
541
|
+
/**
|
|
542
|
+
* O emissor (ou o antifraude) recusou a cobrança.
|
|
543
|
+
*
|
|
544
|
+
* Diferente de `VitrinValidationError`: aqui a autorização ACONTECEU — a
|
|
545
|
+
* cobrança saiu daqui, chegou ao banco do cliente e voltou negada. O
|
|
546
|
+
* `code` é o código ABECS que prova isso (ou um código interno `VITRIN_*`
|
|
547
|
+
* pra bloqueios de política nossos, como 3DS ausente).
|
|
548
|
+
*
|
|
549
|
+
* Trate pela `customerMessage` (texto pronto, em PT-BR) e pelo `retryable`:
|
|
550
|
+
*
|
|
551
|
+
* ```ts
|
|
552
|
+
* try {
|
|
553
|
+
* await vitrin.charges.create({ ... });
|
|
554
|
+
* } catch (err) {
|
|
555
|
+
* if (err instanceof VitrinRefusedError) {
|
|
556
|
+
* showError(err.customerMessage);
|
|
557
|
+
* err.retryable ? showRetryButton() : showCardSwitcher();
|
|
558
|
+
* }
|
|
559
|
+
* }
|
|
560
|
+
* ```
|
|
561
|
+
*/
|
|
562
|
+
declare class VitrinRefusedError extends VitrinError {
|
|
563
|
+
/** Código ABECS do emissor (ex.: '82', 'GD') ou interno ('VITRIN_3DS_MISSING'). */
|
|
564
|
+
readonly code?: string;
|
|
565
|
+
/** Descrição interna do código. Pra log/suporte — não exibir ao pagador. */
|
|
566
|
+
readonly codeDescription?: string;
|
|
567
|
+
/** Texto pronto pra exibir ao cliente final, já adaptado ao motivo. */
|
|
568
|
+
readonly customerMessage?: string;
|
|
569
|
+
/**
|
|
570
|
+
* `true` → o emissor admite nova tentativa com o MESMO cartão.
|
|
571
|
+
* `false` → recusa definitiva; ofereça outro cartão.
|
|
572
|
+
*/
|
|
573
|
+
readonly retryable: boolean;
|
|
574
|
+
/** Id da Transaction `failed` que registra a tentativa, quando a API a devolve. */
|
|
575
|
+
readonly transactionId?: string;
|
|
576
|
+
constructor(message: string, opts?: {
|
|
577
|
+
statusCode?: number;
|
|
578
|
+
body?: unknown;
|
|
579
|
+
requestId?: string;
|
|
580
|
+
code?: string;
|
|
581
|
+
codeDescription?: string;
|
|
582
|
+
customerMessage?: string;
|
|
583
|
+
retryable?: boolean;
|
|
584
|
+
transactionId?: string;
|
|
585
|
+
});
|
|
586
|
+
}
|
|
503
587
|
declare class VitrinRateLimitError extends VitrinError {
|
|
504
588
|
}
|
|
505
589
|
declare class VitrinNotFoundError extends VitrinError {
|
|
@@ -549,4 +633,4 @@ declare class Vitrin {
|
|
|
549
633
|
request<T = unknown>(path: string, options?: Parameters<VitrinClient['request']>[1]): Promise<T>;
|
|
550
634
|
}
|
|
551
635
|
|
|
552
|
-
export { type Balance, type ConstructEventOptions, type Currency, type Customer, type EntityType, type Organization, type PaginatedList, type PaymentMethod, type Plan, type Product, type RequestOptions, type ScheduledReceivable, type ScheduledReceivablesResponse, type Subscription, type Transaction, type TransactionStatus, Vitrin, VitrinAuthError, type VitrinClientOptions, VitrinError, VitrinNetworkError, VitrinNotFoundError, VitrinRateLimitError, VitrinServerError, VitrinValidationError, type WebhookEvent, Webhooks };
|
|
636
|
+
export { type Balance, type ConstructEventOptions, type Currency, type Customer, type EntityType, type Organization, type PaginatedList, type PaymentMethod, type Plan, type Product, type RequestOptions, type ScheduledReceivable, type ScheduledReceivablesResponse, type Subscription, type Transaction, type TransactionStatus, Vitrin, VitrinAuthError, type VitrinClientOptions, VitrinError, VitrinNetworkError, VitrinNotFoundError, VitrinRateLimitError, VitrinRefusedError, VitrinServerError, VitrinValidationError, type WebhookEvent, Webhooks };
|
package/dist/index.d.ts
CHANGED
|
@@ -5,11 +5,15 @@
|
|
|
5
5
|
* - Adicionar headers padrão (Authorization, User-Agent, Content-Type)
|
|
6
6
|
* - Serializar/deserializar JSON
|
|
7
7
|
* - Mapear erros HTTP pra `VitrinError`*
|
|
8
|
-
* - Retry automático
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
8
|
+
* - Retry automático (até 3 tentativas, backoff exponencial) SÓ quando é
|
|
9
|
+
* seguro — ver `shouldRetryResponse` e `shouldRetryNetworkError`:
|
|
10
|
+
* - GET/HEAD/PUT/DELETE: 429, 5xx, timeout e erro de rede;
|
|
11
|
+
* - POST/PATCH: 429, 5xx com `retryable: true` no corpo, ou conexão
|
|
12
|
+
* que nem abriu. Nunca em timeout de leitura nem em 5xx sem
|
|
13
|
+
* `retryable: true` (o 502 incerto de cartão diz `retryable: false`:
|
|
14
|
+
* a cobrança pode ter saído, e repetir é débito duplo);
|
|
15
|
+
* - exceção: `/charges/` e `/charges/charge-saved/` com
|
|
16
|
+
* Idempotency-Key, que o servidor deduplica pela chave.
|
|
13
17
|
* - Idempotency-Key opcional pra POSTs (evita duplo-débito quando o cliente
|
|
14
18
|
* retenta uma chamada que já chegou no servidor)
|
|
15
19
|
*/
|
|
@@ -22,6 +26,13 @@ interface VitrinClientOptions {
|
|
|
22
26
|
timeout?: number;
|
|
23
27
|
/** Max retries em 429/5xx. Default: 3. */
|
|
24
28
|
maxRetries?: number;
|
|
29
|
+
/**
|
|
30
|
+
* Quanto tempo (ms) o SDK consulta o desfecho de uma cobrança de cartão com
|
|
31
|
+
* resultado incerto (502 com `payment_status: "processing"`) antes de
|
|
32
|
+
* desistir. Default: 60000. `0` desliga (lança o erro na hora). O POST
|
|
33
|
+
* nunca é reenviado. Ver `resolveUncertain`.
|
|
34
|
+
*/
|
|
35
|
+
uncertainWaitMs?: number;
|
|
25
36
|
}
|
|
26
37
|
interface RequestOptions {
|
|
27
38
|
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
@@ -35,9 +46,33 @@ declare class VitrinClient {
|
|
|
35
46
|
private readonly apiKey;
|
|
36
47
|
private readonly timeout;
|
|
37
48
|
private readonly maxRetries;
|
|
49
|
+
private readonly uncertainWaitMs;
|
|
38
50
|
constructor(opts: VitrinClientOptions);
|
|
39
51
|
/** Helper público pra resources. */
|
|
40
52
|
request<T = unknown>(path: string, options?: RequestOptions): Promise<T>;
|
|
53
|
+
/**
|
|
54
|
+
* Resultado incerto de cartão: consulta `GET /transactions/{id}/` com
|
|
55
|
+
* backoff (2, 4, 8, 15, 30 s, cortado em `uncertainWaitMs`) até haver
|
|
56
|
+
* desfecho. NUNCA reenvia o POST.
|
|
57
|
+
*
|
|
58
|
+
* O prazo é pelo relógio (`Date.now()`), não pela soma das esperas: cada
|
|
59
|
+
* GET pode levar até o próprio timeout, e sem descontar isso do prazo o
|
|
60
|
+
* pior caso passava longe de `uncertainWaitMs` (~3,5 min com o default).
|
|
61
|
+
* O timeout de cada GET é o menor entre `timeout` e o tempo que ainda
|
|
62
|
+
* falta pro prazo, e com menos de `MIN_GET_BUDGET_MS` restantes o SDK nem
|
|
63
|
+
* tenta mais uma consulta.
|
|
64
|
+
*
|
|
65
|
+
* - paga (`received`/`confirmed`): devolve a transação. É o mesmo objeto
|
|
66
|
+
* que o sucesso do `/charges/`, do `/charges/charge-saved/` e do
|
|
67
|
+
* `/checkout/pay/` devolve (os três respondem com a transação);
|
|
68
|
+
* - recusada (código do emissor): lança `VitrinRefusedError`, como o 422;
|
|
69
|
+
* - ainda incerta no prazo, ou erro em todas as consultas: lança o erro
|
|
70
|
+
* original (`VitrinServerError` com `payment_status: "processing"` e
|
|
71
|
+
* `transaction_id` no `body`). Erro de consulta não prova nada.
|
|
72
|
+
*/
|
|
73
|
+
private resolveUncertain;
|
|
74
|
+
/** Uma consulta, sem retry próprio (o laço de `resolveUncertain` é o retry). */
|
|
75
|
+
private getOnce;
|
|
41
76
|
private buildUrl;
|
|
42
77
|
}
|
|
43
78
|
|
|
@@ -470,7 +505,10 @@ declare const Webhooks: {
|
|
|
470
505
|
*
|
|
471
506
|
* VitrinError — base, qualquer falha conhecida do SDK
|
|
472
507
|
* ├─ VitrinAuthError — 401/403 (chave inválida ou sem permissão)
|
|
473
|
-
* ├─ VitrinValidationError — 400/422
|
|
508
|
+
* ├─ VitrinValidationError — 400/422 sem código de retorno: o payload
|
|
509
|
+
* │ foi rejeitado e NADA foi enviado ao banco
|
|
510
|
+
* ├─ VitrinRefusedError — 422 com código de retorno: a cobrança
|
|
511
|
+
* │ CHEGOU ao emissor e ele negou
|
|
474
512
|
* ├─ VitrinRateLimitError — 429
|
|
475
513
|
* ├─ VitrinNotFoundError — 404
|
|
476
514
|
* ├─ VitrinServerError — 5xx
|
|
@@ -500,6 +538,52 @@ declare class VitrinValidationError extends VitrinError {
|
|
|
500
538
|
fieldErrors?: Record<string, string[]>;
|
|
501
539
|
});
|
|
502
540
|
}
|
|
541
|
+
/**
|
|
542
|
+
* O emissor (ou o antifraude) recusou a cobrança.
|
|
543
|
+
*
|
|
544
|
+
* Diferente de `VitrinValidationError`: aqui a autorização ACONTECEU — a
|
|
545
|
+
* cobrança saiu daqui, chegou ao banco do cliente e voltou negada. O
|
|
546
|
+
* `code` é o código ABECS que prova isso (ou um código interno `VITRIN_*`
|
|
547
|
+
* pra bloqueios de política nossos, como 3DS ausente).
|
|
548
|
+
*
|
|
549
|
+
* Trate pela `customerMessage` (texto pronto, em PT-BR) e pelo `retryable`:
|
|
550
|
+
*
|
|
551
|
+
* ```ts
|
|
552
|
+
* try {
|
|
553
|
+
* await vitrin.charges.create({ ... });
|
|
554
|
+
* } catch (err) {
|
|
555
|
+
* if (err instanceof VitrinRefusedError) {
|
|
556
|
+
* showError(err.customerMessage);
|
|
557
|
+
* err.retryable ? showRetryButton() : showCardSwitcher();
|
|
558
|
+
* }
|
|
559
|
+
* }
|
|
560
|
+
* ```
|
|
561
|
+
*/
|
|
562
|
+
declare class VitrinRefusedError extends VitrinError {
|
|
563
|
+
/** Código ABECS do emissor (ex.: '82', 'GD') ou interno ('VITRIN_3DS_MISSING'). */
|
|
564
|
+
readonly code?: string;
|
|
565
|
+
/** Descrição interna do código. Pra log/suporte — não exibir ao pagador. */
|
|
566
|
+
readonly codeDescription?: string;
|
|
567
|
+
/** Texto pronto pra exibir ao cliente final, já adaptado ao motivo. */
|
|
568
|
+
readonly customerMessage?: string;
|
|
569
|
+
/**
|
|
570
|
+
* `true` → o emissor admite nova tentativa com o MESMO cartão.
|
|
571
|
+
* `false` → recusa definitiva; ofereça outro cartão.
|
|
572
|
+
*/
|
|
573
|
+
readonly retryable: boolean;
|
|
574
|
+
/** Id da Transaction `failed` que registra a tentativa, quando a API a devolve. */
|
|
575
|
+
readonly transactionId?: string;
|
|
576
|
+
constructor(message: string, opts?: {
|
|
577
|
+
statusCode?: number;
|
|
578
|
+
body?: unknown;
|
|
579
|
+
requestId?: string;
|
|
580
|
+
code?: string;
|
|
581
|
+
codeDescription?: string;
|
|
582
|
+
customerMessage?: string;
|
|
583
|
+
retryable?: boolean;
|
|
584
|
+
transactionId?: string;
|
|
585
|
+
});
|
|
586
|
+
}
|
|
503
587
|
declare class VitrinRateLimitError extends VitrinError {
|
|
504
588
|
}
|
|
505
589
|
declare class VitrinNotFoundError extends VitrinError {
|
|
@@ -549,4 +633,4 @@ declare class Vitrin {
|
|
|
549
633
|
request<T = unknown>(path: string, options?: Parameters<VitrinClient['request']>[1]): Promise<T>;
|
|
550
634
|
}
|
|
551
635
|
|
|
552
|
-
export { type Balance, type ConstructEventOptions, type Currency, type Customer, type EntityType, type Organization, type PaginatedList, type PaymentMethod, type Plan, type Product, type RequestOptions, type ScheduledReceivable, type ScheduledReceivablesResponse, type Subscription, type Transaction, type TransactionStatus, Vitrin, VitrinAuthError, type VitrinClientOptions, VitrinError, VitrinNetworkError, VitrinNotFoundError, VitrinRateLimitError, VitrinServerError, VitrinValidationError, type WebhookEvent, Webhooks };
|
|
636
|
+
export { type Balance, type ConstructEventOptions, type Currency, type Customer, type EntityType, type Organization, type PaginatedList, type PaymentMethod, type Plan, type Product, type RequestOptions, type ScheduledReceivable, type ScheduledReceivablesResponse, type Subscription, type Transaction, type TransactionStatus, Vitrin, VitrinAuthError, type VitrinClientOptions, VitrinError, VitrinNetworkError, VitrinNotFoundError, VitrinRateLimitError, VitrinRefusedError, VitrinServerError, VitrinValidationError, type WebhookEvent, Webhooks };
|
package/dist/index.js
CHANGED
|
@@ -20,6 +20,29 @@ var VitrinValidationError = class extends VitrinError {
|
|
|
20
20
|
this.fieldErrors = opts.fieldErrors;
|
|
21
21
|
}
|
|
22
22
|
};
|
|
23
|
+
var VitrinRefusedError = class extends VitrinError {
|
|
24
|
+
/** Código ABECS do emissor (ex.: '82', 'GD') ou interno ('VITRIN_3DS_MISSING'). */
|
|
25
|
+
code;
|
|
26
|
+
/** Descrição interna do código. Pra log/suporte — não exibir ao pagador. */
|
|
27
|
+
codeDescription;
|
|
28
|
+
/** Texto pronto pra exibir ao cliente final, já adaptado ao motivo. */
|
|
29
|
+
customerMessage;
|
|
30
|
+
/**
|
|
31
|
+
* `true` → o emissor admite nova tentativa com o MESMO cartão.
|
|
32
|
+
* `false` → recusa definitiva; ofereça outro cartão.
|
|
33
|
+
*/
|
|
34
|
+
retryable;
|
|
35
|
+
/** Id da Transaction `failed` que registra a tentativa, quando a API a devolve. */
|
|
36
|
+
transactionId;
|
|
37
|
+
constructor(message, opts = {}) {
|
|
38
|
+
super(message, opts);
|
|
39
|
+
this.code = opts.code;
|
|
40
|
+
this.codeDescription = opts.codeDescription;
|
|
41
|
+
this.customerMessage = opts.customerMessage;
|
|
42
|
+
this.retryable = opts.retryable ?? false;
|
|
43
|
+
this.transactionId = opts.transactionId;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
23
46
|
var VitrinRateLimitError = class extends VitrinError {
|
|
24
47
|
};
|
|
25
48
|
var VitrinNotFoundError = class extends VitrinError {
|
|
@@ -31,12 +54,13 @@ var VitrinNetworkError = class extends VitrinError {
|
|
|
31
54
|
|
|
32
55
|
// src/client.ts
|
|
33
56
|
var DEFAULT_BASE_URL = "https://api.vitrin.digital/api/v1";
|
|
34
|
-
var SDK_VERSION = "0.
|
|
57
|
+
var SDK_VERSION = "0.5.0";
|
|
35
58
|
var VitrinClient = class {
|
|
36
59
|
baseUrl;
|
|
37
60
|
apiKey;
|
|
38
61
|
timeout;
|
|
39
62
|
maxRetries;
|
|
63
|
+
uncertainWaitMs;
|
|
40
64
|
constructor(opts) {
|
|
41
65
|
if (!opts.apiKey) {
|
|
42
66
|
throw new Error("apiKey \xE9 obrigat\xF3rio");
|
|
@@ -45,6 +69,7 @@ var VitrinClient = class {
|
|
|
45
69
|
this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
46
70
|
this.timeout = opts.timeout ?? 3e4;
|
|
47
71
|
this.maxRetries = opts.maxRetries ?? 3;
|
|
72
|
+
this.uncertainWaitMs = Math.max(0, opts.uncertainWaitMs ?? 6e4);
|
|
48
73
|
}
|
|
49
74
|
/** Helper público pra resources. */
|
|
50
75
|
async request(path, options = {}) {
|
|
@@ -75,7 +100,7 @@ var VitrinClient = class {
|
|
|
75
100
|
lastError = new VitrinNetworkError(
|
|
76
101
|
netErr.name === "AbortError" ? `Timeout ap\xF3s ${this.timeout}ms` : netErr.message || "Falha de rede"
|
|
77
102
|
);
|
|
78
|
-
if (attempt < this.maxRetries &&
|
|
103
|
+
if (attempt < this.maxRetries && shouldRetryNetworkError(method, path, idempotencyKey, err2)) {
|
|
79
104
|
await sleep(backoffMs(attempt));
|
|
80
105
|
continue;
|
|
81
106
|
}
|
|
@@ -95,8 +120,11 @@ var VitrinClient = class {
|
|
|
95
120
|
} catch {
|
|
96
121
|
}
|
|
97
122
|
const err = mapErrorResponse(res.status, parsed, requestId);
|
|
98
|
-
const
|
|
99
|
-
if (
|
|
123
|
+
const uncertainTxId = uncertainTransactionId(method, path, res.status, parsed);
|
|
124
|
+
if (uncertainTxId && this.uncertainWaitMs > 0) {
|
|
125
|
+
return this.resolveUncertain(uncertainTxId, err);
|
|
126
|
+
}
|
|
127
|
+
if (attempt < this.maxRetries && shouldRetryResponse(method, path, idempotencyKey, res.status, parsed)) {
|
|
100
128
|
const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
|
|
101
129
|
await sleep(retryAfter ?? backoffMs(attempt));
|
|
102
130
|
lastError = err;
|
|
@@ -106,6 +134,71 @@ var VitrinClient = class {
|
|
|
106
134
|
}
|
|
107
135
|
throw lastError ?? new VitrinError("Esgotou as tentativas sem erro identificado");
|
|
108
136
|
}
|
|
137
|
+
/**
|
|
138
|
+
* Resultado incerto de cartão: consulta `GET /transactions/{id}/` com
|
|
139
|
+
* backoff (2, 4, 8, 15, 30 s, cortado em `uncertainWaitMs`) até haver
|
|
140
|
+
* desfecho. NUNCA reenvia o POST.
|
|
141
|
+
*
|
|
142
|
+
* O prazo é pelo relógio (`Date.now()`), não pela soma das esperas: cada
|
|
143
|
+
* GET pode levar até o próprio timeout, e sem descontar isso do prazo o
|
|
144
|
+
* pior caso passava longe de `uncertainWaitMs` (~3,5 min com o default).
|
|
145
|
+
* O timeout de cada GET é o menor entre `timeout` e o tempo que ainda
|
|
146
|
+
* falta pro prazo, e com menos de `MIN_GET_BUDGET_MS` restantes o SDK nem
|
|
147
|
+
* tenta mais uma consulta.
|
|
148
|
+
*
|
|
149
|
+
* - paga (`received`/`confirmed`): devolve a transação. É o mesmo objeto
|
|
150
|
+
* que o sucesso do `/charges/`, do `/charges/charge-saved/` e do
|
|
151
|
+
* `/checkout/pay/` devolve (os três respondem com a transação);
|
|
152
|
+
* - recusada (código do emissor): lança `VitrinRefusedError`, como o 422;
|
|
153
|
+
* - ainda incerta no prazo, ou erro em todas as consultas: lança o erro
|
|
154
|
+
* original (`VitrinServerError` com `payment_status: "processing"` e
|
|
155
|
+
* `transaction_id` no `body`). Erro de consulta não prova nada.
|
|
156
|
+
*/
|
|
157
|
+
async resolveUncertain(transactionId, original) {
|
|
158
|
+
const deadline = Date.now() + this.uncertainWaitMs;
|
|
159
|
+
for (const step of UNCERTAIN_BACKOFF_MS) {
|
|
160
|
+
const beforeSleep = deadline - Date.now();
|
|
161
|
+
if (beforeSleep <= 0) break;
|
|
162
|
+
await sleep(Math.min(step, beforeSleep));
|
|
163
|
+
const remaining = deadline - Date.now();
|
|
164
|
+
if (remaining < MIN_GET_BUDGET_MS) break;
|
|
165
|
+
let tx;
|
|
166
|
+
try {
|
|
167
|
+
tx = await this.getOnce(
|
|
168
|
+
`/transactions/${encodeURIComponent(transactionId)}/`,
|
|
169
|
+
Math.min(this.timeout, remaining)
|
|
170
|
+
);
|
|
171
|
+
} catch {
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
const outcome = uncertainOutcome(tx);
|
|
175
|
+
if (outcome === "paid") return tx;
|
|
176
|
+
if (outcome === "refused") throw refusedFromTransaction(tx, original.requestId);
|
|
177
|
+
}
|
|
178
|
+
throw original;
|
|
179
|
+
}
|
|
180
|
+
/** Uma consulta, sem retry próprio (o laço de `resolveUncertain` é o retry). */
|
|
181
|
+
async getOnce(path, timeoutMs = this.timeout) {
|
|
182
|
+
const controller = new AbortController();
|
|
183
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
184
|
+
try {
|
|
185
|
+
const res = await fetch(this.buildUrl(path), {
|
|
186
|
+
method: "GET",
|
|
187
|
+
headers: {
|
|
188
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
189
|
+
Accept: "application/json",
|
|
190
|
+
"User-Agent": `vitrindigital-node/${SDK_VERSION} node/${process.version}`
|
|
191
|
+
},
|
|
192
|
+
signal: controller.signal
|
|
193
|
+
});
|
|
194
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
195
|
+
const body = await res.json();
|
|
196
|
+
if (!body || typeof body !== "object") throw new Error("corpo inv\xE1lido");
|
|
197
|
+
return body;
|
|
198
|
+
} finally {
|
|
199
|
+
clearTimeout(timer);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
109
202
|
buildUrl(path, query) {
|
|
110
203
|
const url = new URL(this.baseUrl + (path.startsWith("/") ? path : `/${path}`));
|
|
111
204
|
if (query) {
|
|
@@ -125,12 +218,29 @@ function mapErrorResponse(status, body, requestId) {
|
|
|
125
218
|
if (status === 404) return new VitrinNotFoundError(message, opts);
|
|
126
219
|
if (status === 429) return new VitrinRateLimitError(message, opts);
|
|
127
220
|
if (status >= 500) return new VitrinServerError(message, opts);
|
|
221
|
+
if (status === 422) {
|
|
222
|
+
const refusal = extractRefusal(body);
|
|
223
|
+
if (refusal) return new VitrinRefusedError(message, { ...opts, ...refusal });
|
|
224
|
+
}
|
|
128
225
|
if (status === 400 || status === 422) {
|
|
129
226
|
const fieldErrors = extractFieldErrors(body);
|
|
130
227
|
return new VitrinValidationError(message, { ...opts, fieldErrors });
|
|
131
228
|
}
|
|
132
229
|
return new VitrinError(message, opts);
|
|
133
230
|
}
|
|
231
|
+
function extractRefusal(body) {
|
|
232
|
+
if (!body || typeof body !== "object") return void 0;
|
|
233
|
+
const b = body;
|
|
234
|
+
const code = b.return_code ?? b.abecs_code;
|
|
235
|
+
if (typeof code !== "string" || !code) return void 0;
|
|
236
|
+
return {
|
|
237
|
+
code,
|
|
238
|
+
codeDescription: typeof b.return_code_description === "string" ? b.return_code_description : void 0,
|
|
239
|
+
customerMessage: typeof b.customer_message === "string" ? b.customer_message : void 0,
|
|
240
|
+
retryable: b.retryable === true,
|
|
241
|
+
transactionId: typeof b.transaction_id === "string" ? b.transaction_id : void 0
|
|
242
|
+
};
|
|
243
|
+
}
|
|
134
244
|
function extractErrorMessage(body) {
|
|
135
245
|
if (!body || typeof body !== "object") return void 0;
|
|
136
246
|
const b = body;
|
|
@@ -158,9 +268,83 @@ function parseRetryAfter(header) {
|
|
|
158
268
|
return null;
|
|
159
269
|
}
|
|
160
270
|
var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
271
|
+
var DEDUPLICATED_PATHS = /* @__PURE__ */ new Set(["/charges/", "/charges/charge-saved/"]);
|
|
272
|
+
var NEVER_CONNECTED_CODES = /* @__PURE__ */ new Set([
|
|
273
|
+
"ECONNREFUSED",
|
|
274
|
+
"ENOTFOUND",
|
|
275
|
+
"EAI_AGAIN",
|
|
276
|
+
"EHOSTUNREACH",
|
|
277
|
+
"ENETUNREACH",
|
|
278
|
+
"UND_ERR_CONNECT_TIMEOUT"
|
|
279
|
+
]);
|
|
280
|
+
function normalizePath(path) {
|
|
281
|
+
const p = path.split("?")[0];
|
|
282
|
+
const withSlash = p.startsWith("/") ? p : `/${p}`;
|
|
283
|
+
return withSlash.endsWith("/") ? withSlash : `${withSlash}/`;
|
|
284
|
+
}
|
|
285
|
+
function isIdempotentMethod(method) {
|
|
286
|
+
return IDEMPOTENT_METHODS.has(method.toUpperCase());
|
|
287
|
+
}
|
|
288
|
+
function serverDeduplicates(path, idempotencyKey) {
|
|
289
|
+
return Boolean(idempotencyKey) && DEDUPLICATED_PATHS.has(normalizePath(path));
|
|
290
|
+
}
|
|
291
|
+
function neverConnected(err) {
|
|
292
|
+
const cause = err?.cause;
|
|
293
|
+
if (!cause) return false;
|
|
294
|
+
if (cause.code && NEVER_CONNECTED_CODES.has(cause.code)) return true;
|
|
295
|
+
return Array.isArray(cause.errors) && cause.errors.length > 0 && cause.errors.every((e) => Boolean(e?.code && NEVER_CONNECTED_CODES.has(e.code)));
|
|
296
|
+
}
|
|
297
|
+
function shouldRetryNetworkError(method, path, idempotencyKey, err) {
|
|
298
|
+
if (isIdempotentMethod(method)) return true;
|
|
299
|
+
if (neverConnected(err)) return true;
|
|
300
|
+
return serverDeduplicates(path, idempotencyKey);
|
|
301
|
+
}
|
|
302
|
+
function shouldRetryResponse(method, path, idempotencyKey, status, body) {
|
|
303
|
+
if (status !== 429 && status < 500) return false;
|
|
304
|
+
if (isIdempotentMethod(method) || status === 429) return true;
|
|
305
|
+
const retryable = body && typeof body === "object" ? body.retryable : void 0;
|
|
306
|
+
if (retryable === true) return true;
|
|
307
|
+
if (retryable === false) return false;
|
|
308
|
+
return serverDeduplicates(path, idempotencyKey);
|
|
309
|
+
}
|
|
310
|
+
var UNCERTAIN_BACKOFF_MS = [2e3, 4e3, 8e3, 15e3, 3e4];
|
|
311
|
+
var MIN_GET_BUDGET_MS = 1e3;
|
|
312
|
+
var TRANSACTION_RESULT_PATHS = /* @__PURE__ */ new Set(["/charges/", "/charges/charge-saved/", "/checkout/pay/"]);
|
|
313
|
+
var PAID_STATUSES = /* @__PURE__ */ new Set(["received", "confirmed"]);
|
|
314
|
+
var REFUSED_STATUSES = /* @__PURE__ */ new Set(["failed", "canceled", "expired"]);
|
|
315
|
+
var UNCERTAIN_CODE = "VITRIN_PROVIDER_UNCERTAIN";
|
|
316
|
+
function uncertainTransactionId(method, path, status, body) {
|
|
317
|
+
if (isIdempotentMethod(method) || status < 500) return void 0;
|
|
318
|
+
if (!TRANSACTION_RESULT_PATHS.has(normalizePath(path))) return void 0;
|
|
319
|
+
if (!body || typeof body !== "object") return void 0;
|
|
320
|
+
const b = body;
|
|
321
|
+
if (b.payment_status !== "processing" || b.retryable !== false) return void 0;
|
|
322
|
+
return typeof b.transaction_id === "string" && b.transaction_id ? b.transaction_id : void 0;
|
|
323
|
+
}
|
|
324
|
+
function uncertainOutcome(tx) {
|
|
325
|
+
const status = String(tx.status ?? "");
|
|
326
|
+
if (PAID_STATUSES.has(status)) return "paid";
|
|
327
|
+
if (REFUSED_STATUSES.has(status)) {
|
|
328
|
+
const refusal = tx.refusal;
|
|
329
|
+
if (refusal?.code === UNCERTAIN_CODE) return "pending";
|
|
330
|
+
return "refused";
|
|
331
|
+
}
|
|
332
|
+
return "pending";
|
|
333
|
+
}
|
|
334
|
+
function refusedFromTransaction(tx, requestId) {
|
|
335
|
+
const refusal = tx.refusal ?? {};
|
|
336
|
+
const str = (v) => typeof v === "string" && v ? v : void 0;
|
|
337
|
+
const description = str(refusal.description) ?? str(refusal.message);
|
|
338
|
+
return new VitrinRefusedError(description ?? "Pagamento n\xE3o autorizado.", {
|
|
339
|
+
statusCode: 422,
|
|
340
|
+
body: tx,
|
|
341
|
+
requestId,
|
|
342
|
+
code: str(refusal.code),
|
|
343
|
+
codeDescription: description,
|
|
344
|
+
customerMessage: str(refusal.customer_message),
|
|
345
|
+
retryable: refusal.retryable === true,
|
|
346
|
+
transactionId: str(tx.id)
|
|
347
|
+
});
|
|
164
348
|
}
|
|
165
349
|
function backoffMs(attempt) {
|
|
166
350
|
const base = 250 * Math.pow(2, attempt);
|
|
@@ -476,6 +660,7 @@ export {
|
|
|
476
660
|
VitrinNetworkError,
|
|
477
661
|
VitrinNotFoundError,
|
|
478
662
|
VitrinRateLimitError,
|
|
663
|
+
VitrinRefusedError,
|
|
479
664
|
VitrinServerError,
|
|
480
665
|
VitrinValidationError,
|
|
481
666
|
Webhooks
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vitrindigital/node",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "SDK oficial Node.js para a API da Vitrin Digital",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -21,7 +21,8 @@
|
|
|
21
21
|
"build": "tsup src/index.ts --format esm,cjs --dts --clean",
|
|
22
22
|
"test": "vitest run",
|
|
23
23
|
"test:watch": "vitest",
|
|
24
|
-
"lint": "tsc --noEmit"
|
|
24
|
+
"lint": "tsc --noEmit",
|
|
25
|
+
"prepublishOnly": "npm run lint && npm test && npm run build"
|
|
25
26
|
},
|
|
26
27
|
"keywords": ["vitrin", "vitrin-digital", "pagamentos", "pix", "boleto", "checkout"],
|
|
27
28
|
"author": "Vitrin Digital",
|