@vitrindigital/node 0.3.1 → 0.4.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 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 VitrinValidationError) {
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');
@@ -164,6 +168,32 @@ try {
164
168
  O cliente faz **retry automático** em `429` e `5xx` com backoff exponencial
165
169
  (default: 3 tentativas). Erros 4xx (exceto 429) não são retentados.
166
170
 
171
+ ### Recusa não é erro de validação
172
+
173
+ A API usa `422` para duas situações opostas, e o SDK as separa em classes
174
+ diferentes:
175
+
176
+ | Classe | O que aconteceu | O que fazer |
177
+ |---|---|---|
178
+ | `VitrinValidationError` | O payload foi rejeitado. **Nada foi enviado ao banco.** | Corrigir os campos (`fieldErrors`) e repetir. |
179
+ | `VitrinRefusedError` | A cobrança **chegou ao emissor** e ele negou. | Exibir `customerMessage`; oferecer retry só se `retryable`. |
180
+
181
+ O discriminador é o código de retorno no corpo (`return_code` / `abecs_code`):
182
+ ele só existe porque houve resposta de autorização.
183
+
184
+ ```ts
185
+ if (err instanceof VitrinRefusedError) {
186
+ showError(err.customerMessage); // texto pronto, em PT-BR
187
+ err.retryable
188
+ ? showRetryButton() // ex.: 51 saldo, 91 emissor fora do ar
189
+ : showCardSwitcher(); // ex.: 82 negada — o mesmo cartão vai negar de novo
190
+ console.log(err.code, err.transactionId); // pra log/suporte
191
+ }
192
+ ```
193
+
194
+ `transactionId` aponta para a Transaction `failed` que registra a tentativa —
195
+ ela também aparece em `GET /transactions/?status=failed` e no painel.
196
+
167
197
  ## Idempotência
168
198
 
169
199
  Inclua `idempotencyKey` em POSTs sensíveis. Se o request chegar duas vezes
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 {
@@ -159,12 +183,29 @@ function mapErrorResponse(status, body, requestId) {
159
183
  if (status === 404) return new VitrinNotFoundError(message, opts);
160
184
  if (status === 429) return new VitrinRateLimitError(message, opts);
161
185
  if (status >= 500) return new VitrinServerError(message, opts);
186
+ if (status === 422) {
187
+ const refusal = extractRefusal(body);
188
+ if (refusal) return new VitrinRefusedError(message, { ...opts, ...refusal });
189
+ }
162
190
  if (status === 400 || status === 422) {
163
191
  const fieldErrors = extractFieldErrors(body);
164
192
  return new VitrinValidationError(message, { ...opts, fieldErrors });
165
193
  }
166
194
  return new VitrinError(message, opts);
167
195
  }
196
+ function extractRefusal(body) {
197
+ if (!body || typeof body !== "object") return void 0;
198
+ const b = body;
199
+ const code = b.return_code ?? b.abecs_code;
200
+ if (typeof code !== "string" || !code) return void 0;
201
+ return {
202
+ code,
203
+ codeDescription: typeof b.return_code_description === "string" ? b.return_code_description : void 0,
204
+ customerMessage: typeof b.customer_message === "string" ? b.customer_message : void 0,
205
+ retryable: b.retryable === true,
206
+ transactionId: typeof b.transaction_id === "string" ? b.transaction_id : void 0
207
+ };
208
+ }
168
209
  function extractErrorMessage(body) {
169
210
  if (!body || typeof body !== "object") return void 0;
170
211
  const b = body;
@@ -511,6 +552,7 @@ var Vitrin = class {
511
552
  VitrinNetworkError,
512
553
  VitrinNotFoundError,
513
554
  VitrinRateLimitError,
555
+ VitrinRefusedError,
514
556
  VitrinServerError,
515
557
  VitrinValidationError,
516
558
  Webhooks
package/dist/index.d.cts CHANGED
@@ -470,7 +470,10 @@ declare const Webhooks: {
470
470
  *
471
471
  * VitrinError — base, qualquer falha conhecida do SDK
472
472
  * ├─ VitrinAuthError — 401/403 (chave inválida ou sem permissão)
473
- * ├─ VitrinValidationError — 400/422 (DRF retornou field errors)
473
+ * ├─ VitrinValidationError — 400/422 sem código de retorno: o payload
474
+ * │ foi rejeitado e NADA foi enviado ao banco
475
+ * ├─ VitrinRefusedError — 422 com código de retorno: a cobrança
476
+ * │ CHEGOU ao emissor e ele negou
474
477
  * ├─ VitrinRateLimitError — 429
475
478
  * ├─ VitrinNotFoundError — 404
476
479
  * ├─ VitrinServerError — 5xx
@@ -500,6 +503,52 @@ declare class VitrinValidationError extends VitrinError {
500
503
  fieldErrors?: Record<string, string[]>;
501
504
  });
502
505
  }
506
+ /**
507
+ * O emissor (ou o antifraude) recusou a cobrança.
508
+ *
509
+ * Diferente de `VitrinValidationError`: aqui a autorização ACONTECEU — a
510
+ * cobrança saiu daqui, chegou ao banco do cliente e voltou negada. O
511
+ * `code` é o código ABECS que prova isso (ou um código interno `VITRIN_*`
512
+ * pra bloqueios de política nossos, como 3DS ausente).
513
+ *
514
+ * Trate pela `customerMessage` (texto pronto, em PT-BR) e pelo `retryable`:
515
+ *
516
+ * ```ts
517
+ * try {
518
+ * await vitrin.charges.create({ ... });
519
+ * } catch (err) {
520
+ * if (err instanceof VitrinRefusedError) {
521
+ * showError(err.customerMessage);
522
+ * err.retryable ? showRetryButton() : showCardSwitcher();
523
+ * }
524
+ * }
525
+ * ```
526
+ */
527
+ declare class VitrinRefusedError extends VitrinError {
528
+ /** Código ABECS do emissor (ex.: '82', 'GD') ou interno ('VITRIN_3DS_MISSING'). */
529
+ readonly code?: string;
530
+ /** Descrição interna do código. Pra log/suporte — não exibir ao pagador. */
531
+ readonly codeDescription?: string;
532
+ /** Texto pronto pra exibir ao cliente final, já adaptado ao motivo. */
533
+ readonly customerMessage?: string;
534
+ /**
535
+ * `true` → o emissor admite nova tentativa com o MESMO cartão.
536
+ * `false` → recusa definitiva; ofereça outro cartão.
537
+ */
538
+ readonly retryable: boolean;
539
+ /** Id da Transaction `failed` que registra a tentativa, quando a API a devolve. */
540
+ readonly transactionId?: string;
541
+ constructor(message: string, opts?: {
542
+ statusCode?: number;
543
+ body?: unknown;
544
+ requestId?: string;
545
+ code?: string;
546
+ codeDescription?: string;
547
+ customerMessage?: string;
548
+ retryable?: boolean;
549
+ transactionId?: string;
550
+ });
551
+ }
503
552
  declare class VitrinRateLimitError extends VitrinError {
504
553
  }
505
554
  declare class VitrinNotFoundError extends VitrinError {
@@ -549,4 +598,4 @@ declare class Vitrin {
549
598
  request<T = unknown>(path: string, options?: Parameters<VitrinClient['request']>[1]): Promise<T>;
550
599
  }
551
600
 
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 };
601
+ 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
@@ -470,7 +470,10 @@ declare const Webhooks: {
470
470
  *
471
471
  * VitrinError — base, qualquer falha conhecida do SDK
472
472
  * ├─ VitrinAuthError — 401/403 (chave inválida ou sem permissão)
473
- * ├─ VitrinValidationError — 400/422 (DRF retornou field errors)
473
+ * ├─ VitrinValidationError — 400/422 sem código de retorno: o payload
474
+ * │ foi rejeitado e NADA foi enviado ao banco
475
+ * ├─ VitrinRefusedError — 422 com código de retorno: a cobrança
476
+ * │ CHEGOU ao emissor e ele negou
474
477
  * ├─ VitrinRateLimitError — 429
475
478
  * ├─ VitrinNotFoundError — 404
476
479
  * ├─ VitrinServerError — 5xx
@@ -500,6 +503,52 @@ declare class VitrinValidationError extends VitrinError {
500
503
  fieldErrors?: Record<string, string[]>;
501
504
  });
502
505
  }
506
+ /**
507
+ * O emissor (ou o antifraude) recusou a cobrança.
508
+ *
509
+ * Diferente de `VitrinValidationError`: aqui a autorização ACONTECEU — a
510
+ * cobrança saiu daqui, chegou ao banco do cliente e voltou negada. O
511
+ * `code` é o código ABECS que prova isso (ou um código interno `VITRIN_*`
512
+ * pra bloqueios de política nossos, como 3DS ausente).
513
+ *
514
+ * Trate pela `customerMessage` (texto pronto, em PT-BR) e pelo `retryable`:
515
+ *
516
+ * ```ts
517
+ * try {
518
+ * await vitrin.charges.create({ ... });
519
+ * } catch (err) {
520
+ * if (err instanceof VitrinRefusedError) {
521
+ * showError(err.customerMessage);
522
+ * err.retryable ? showRetryButton() : showCardSwitcher();
523
+ * }
524
+ * }
525
+ * ```
526
+ */
527
+ declare class VitrinRefusedError extends VitrinError {
528
+ /** Código ABECS do emissor (ex.: '82', 'GD') ou interno ('VITRIN_3DS_MISSING'). */
529
+ readonly code?: string;
530
+ /** Descrição interna do código. Pra log/suporte — não exibir ao pagador. */
531
+ readonly codeDescription?: string;
532
+ /** Texto pronto pra exibir ao cliente final, já adaptado ao motivo. */
533
+ readonly customerMessage?: string;
534
+ /**
535
+ * `true` → o emissor admite nova tentativa com o MESMO cartão.
536
+ * `false` → recusa definitiva; ofereça outro cartão.
537
+ */
538
+ readonly retryable: boolean;
539
+ /** Id da Transaction `failed` que registra a tentativa, quando a API a devolve. */
540
+ readonly transactionId?: string;
541
+ constructor(message: string, opts?: {
542
+ statusCode?: number;
543
+ body?: unknown;
544
+ requestId?: string;
545
+ code?: string;
546
+ codeDescription?: string;
547
+ customerMessage?: string;
548
+ retryable?: boolean;
549
+ transactionId?: string;
550
+ });
551
+ }
503
552
  declare class VitrinRateLimitError extends VitrinError {
504
553
  }
505
554
  declare class VitrinNotFoundError extends VitrinError {
@@ -549,4 +598,4 @@ declare class Vitrin {
549
598
  request<T = unknown>(path: string, options?: Parameters<VitrinClient['request']>[1]): Promise<T>;
550
599
  }
551
600
 
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 };
601
+ 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 {
@@ -125,12 +148,29 @@ function mapErrorResponse(status, body, requestId) {
125
148
  if (status === 404) return new VitrinNotFoundError(message, opts);
126
149
  if (status === 429) return new VitrinRateLimitError(message, opts);
127
150
  if (status >= 500) return new VitrinServerError(message, opts);
151
+ if (status === 422) {
152
+ const refusal = extractRefusal(body);
153
+ if (refusal) return new VitrinRefusedError(message, { ...opts, ...refusal });
154
+ }
128
155
  if (status === 400 || status === 422) {
129
156
  const fieldErrors = extractFieldErrors(body);
130
157
  return new VitrinValidationError(message, { ...opts, fieldErrors });
131
158
  }
132
159
  return new VitrinError(message, opts);
133
160
  }
161
+ function extractRefusal(body) {
162
+ if (!body || typeof body !== "object") return void 0;
163
+ const b = body;
164
+ const code = b.return_code ?? b.abecs_code;
165
+ if (typeof code !== "string" || !code) return void 0;
166
+ return {
167
+ code,
168
+ codeDescription: typeof b.return_code_description === "string" ? b.return_code_description : void 0,
169
+ customerMessage: typeof b.customer_message === "string" ? b.customer_message : void 0,
170
+ retryable: b.retryable === true,
171
+ transactionId: typeof b.transaction_id === "string" ? b.transaction_id : void 0
172
+ };
173
+ }
134
174
  function extractErrorMessage(body) {
135
175
  if (!body || typeof body !== "object") return void 0;
136
176
  const b = body;
@@ -476,6 +516,7 @@ export {
476
516
  VitrinNetworkError,
477
517
  VitrinNotFoundError,
478
518
  VitrinRateLimitError,
519
+ VitrinRefusedError,
479
520
  VitrinServerError,
480
521
  VitrinValidationError,
481
522
  Webhooks
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitrindigital/node",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "SDK oficial Node.js para a API da Vitrin Digital",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",