@vitrindigital/node 0.2.0 → 0.3.1
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 +18 -0
- package/dist/index.cjs +6 -1
- package/dist/index.d.cts +55 -2
- package/dist/index.d.ts +55 -2
- package/dist/index.js +6 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -24,6 +24,16 @@ const vitrin = new Vitrin({
|
|
|
24
24
|
|
|
25
25
|
Use a chave `vd_test_*` em desenvolvimento e `vd_live_*` em produção.
|
|
26
26
|
|
|
27
|
+
## Organizações LLC (US)
|
|
28
|
+
|
|
29
|
+
Se a org é uma **US LLC** (`entity_type: "llc"`), os valores são em **USD**
|
|
30
|
+
(campo `currency` nas transações); os métodos default são **cartão** e **Pix
|
|
31
|
+
cross-border** (o cliente paga em BRL, a LLC recebe em USD). A liquidação é
|
|
32
|
+
**automática**: os endpoints de saldo/recebíveis/transferências retornam
|
|
33
|
+
`{ auto_payout: true }` em vez de saldo retido (não há saque/antecipação
|
|
34
|
+
manual). O onboarding inclui verificação de identidade (KYC), hospedada ou
|
|
35
|
+
embedded. Veja `docs/api/onboarding-llc.md` e `docs/api/differences-cnpj-llc.md`.
|
|
36
|
+
|
|
27
37
|
## Recursos
|
|
28
38
|
|
|
29
39
|
### Clientes
|
|
@@ -160,6 +170,14 @@ Inclua `idempotencyKey` em POSTs sensíveis. Se o request chegar duas vezes
|
|
|
160
170
|
(retry de rede, deploy etc), a Vitrin reconhece pela chave e devolve a mesma
|
|
161
171
|
resposta — sem cobrar duas vezes.
|
|
162
172
|
|
|
173
|
+
Vale em `charges.create()` e `charges.createWithSavedCard()`. A chave é escopada
|
|
174
|
+
por organização (a sua nunca colide com a de outro lojista) e aceita até 128
|
|
175
|
+
caracteres.
|
|
176
|
+
|
|
177
|
+
Use um identificador **seu** e estável — número do pedido, id do carrinho. A
|
|
178
|
+
proteção vem de a chave se repetir no retry; um UUID novo a cada tentativa não
|
|
179
|
+
protege de nada.
|
|
180
|
+
|
|
163
181
|
```ts
|
|
164
182
|
await vitrin.charges.create({
|
|
165
183
|
customer_id: 'cus_1',
|
package/dist/index.cjs
CHANGED
|
@@ -109,7 +109,7 @@ var VitrinClient = class {
|
|
|
109
109
|
lastError = new VitrinNetworkError(
|
|
110
110
|
netErr.name === "AbortError" ? `Timeout ap\xF3s ${this.timeout}ms` : netErr.message || "Falha de rede"
|
|
111
111
|
);
|
|
112
|
-
if (attempt < this.maxRetries) {
|
|
112
|
+
if (attempt < this.maxRetries && canRetryAfterNetworkError(method, idempotencyKey)) {
|
|
113
113
|
await sleep(backoffMs(attempt));
|
|
114
114
|
continue;
|
|
115
115
|
}
|
|
@@ -191,6 +191,11 @@ function parseRetryAfter(header) {
|
|
|
191
191
|
if (!Number.isNaN(seconds)) return seconds * 1e3;
|
|
192
192
|
return null;
|
|
193
193
|
}
|
|
194
|
+
var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
|
|
195
|
+
function canRetryAfterNetworkError(method, idempotencyKey) {
|
|
196
|
+
if (IDEMPOTENT_METHODS.has(method.toUpperCase())) return true;
|
|
197
|
+
return Boolean(idempotencyKey);
|
|
198
|
+
}
|
|
194
199
|
function backoffMs(attempt) {
|
|
195
200
|
const base = 250 * Math.pow(2, attempt);
|
|
196
201
|
return base + Math.floor(Math.random() * base * 0.5);
|
package/dist/index.d.cts
CHANGED
|
@@ -6,6 +6,10 @@
|
|
|
6
6
|
* - Serializar/deserializar JSON
|
|
7
7
|
* - Mapear erros HTTP pra `VitrinError`*
|
|
8
8
|
* - Retry automático em 429 e 5xx (até 3 tentativas, backoff exponencial)
|
|
9
|
+
* - Retry em timeout/erro de rede SÓ quando é seguro: método idempotente
|
|
10
|
+
* (GET/HEAD/PUT/DELETE) ou POST/PATCH com Idempotency-Key. Sem isso o
|
|
11
|
+
* retry de um POST cria uma segunda cobrança — o timeout não diz que o
|
|
12
|
+
* servidor deixou de processar, só que a resposta se perdeu.
|
|
9
13
|
* - Idempotency-Key opcional pra POSTs (evita duplo-débito quando o cliente
|
|
10
14
|
* retenta uma chamada que já chegou no servidor)
|
|
11
15
|
*/
|
|
@@ -43,8 +47,42 @@ declare class VitrinClient {
|
|
|
43
47
|
* Mantidos como interfaces genéricas (em vez de unions super-precisas) pra
|
|
44
48
|
* que mudanças não-quebra-API no backend não exijam major bump no SDK.
|
|
45
49
|
*/
|
|
46
|
-
|
|
50
|
+
/** ISO 4217. BRL é o default histórico; USD/EUR/GBP habilitados com orgs LLC. */
|
|
51
|
+
type Currency = 'BRL' | 'USD' | 'EUR' | 'GBP';
|
|
52
|
+
/** Tipo jurídico da organização. CNPJ = subconta Safe2Pay (Brasil),
|
|
53
|
+
* LLC = Stripe Connect (US/internacional). */
|
|
54
|
+
type EntityType = 'cnpj' | 'llc';
|
|
55
|
+
/**
|
|
56
|
+
* Métodos de pagamento suportados pela plataforma.
|
|
57
|
+
*
|
|
58
|
+
* A disponibilidade por org é dinâmica — sempre cheque
|
|
59
|
+
* `Organization.enabled_payment_methods`. Por tipo de entidade:
|
|
60
|
+
*
|
|
61
|
+
* - CNPJ (BR): PIX, PIX_AUTOMATIC, BOLETO, CREDIT_CARD (default).
|
|
62
|
+
* - LLC (US): CREDIT_CARD por default. PIX está disponível cross-border
|
|
63
|
+
* (o cliente paga em BRL, a liquidação é em USD) como opt-in habilitado
|
|
64
|
+
* pela Vitrin. BOLETO NÃO se aplica a LLC (é Brasil-only). Os demais
|
|
65
|
+
* métodos abaixo (cartão internacional / ACH / wallets / Klarna /
|
|
66
|
+
* Afterpay) são reservados para evolução e podem não estar habilitados.
|
|
67
|
+
*/
|
|
68
|
+
type PaymentMethod = 'PIX' | 'PIX_AUTOMATIC' | 'BOLETO' | 'CREDIT_CARD' | 'CARD_INTERNATIONAL' | 'ACH_DEBIT' | 'SEPA_DEBIT' | 'APPLE_PAY' | 'GOOGLE_PAY' | 'KLARNA' | 'AFTERPAY';
|
|
47
69
|
type TransactionStatus = 'pending' | 'confirmed' | 'received' | 'overdue' | 'refunded' | 'chargeback' | 'failed' | 'canceled';
|
|
70
|
+
/**
|
|
71
|
+
* Representa a organização (subconta) dona da API key em uso.
|
|
72
|
+
*
|
|
73
|
+
* Nota: `default_currency` é derivado de `entity_type` no backend e pode
|
|
74
|
+
* ainda não estar exposto pelo serializer — a declaração aqui é
|
|
75
|
+
* forward-compatible para quando o backend passar a emiti-lo.
|
|
76
|
+
*/
|
|
77
|
+
interface Organization {
|
|
78
|
+
id: string;
|
|
79
|
+
name: string;
|
|
80
|
+
entity_type: EntityType;
|
|
81
|
+
default_currency: Currency;
|
|
82
|
+
enabled_payment_methods?: PaymentMethod[];
|
|
83
|
+
created_at: string;
|
|
84
|
+
updated_at: string;
|
|
85
|
+
}
|
|
48
86
|
interface Customer {
|
|
49
87
|
id: string;
|
|
50
88
|
name: string;
|
|
@@ -94,6 +132,11 @@ interface Subscription {
|
|
|
94
132
|
canceled_at: string | null;
|
|
95
133
|
created_at: string;
|
|
96
134
|
updated_at: string;
|
|
135
|
+
/** LLC: moeda da assinatura (USD). Ausente/BRL para CNPJ. */
|
|
136
|
+
currency?: Currency;
|
|
137
|
+
/** LLC: secret de confirmação da 1ª cobrança — quando presente, confirme
|
|
138
|
+
* com Stripe.js (cartão/SCA) antes da assinatura ficar ativa. */
|
|
139
|
+
client_secret?: string | null;
|
|
97
140
|
}
|
|
98
141
|
interface Transaction {
|
|
99
142
|
id: string;
|
|
@@ -106,6 +149,16 @@ interface Transaction {
|
|
|
106
149
|
platform_fee: string;
|
|
107
150
|
provider_fee: string;
|
|
108
151
|
billing_type: PaymentMethod;
|
|
152
|
+
/** ISO 4217. Default herdado de `Organization.default_currency` na criação. */
|
|
153
|
+
currency: Currency;
|
|
154
|
+
/** LLC: secret de confirmação — cartão (SCA/3DS) ou PIX (QR); confirme com
|
|
155
|
+
* Stripe.js quando presente. Ausente para cobranças síncronas/CNPJ. */
|
|
156
|
+
client_secret?: string | null;
|
|
157
|
+
/** PIX-LLC cross-currency: o cliente vê BRL (`presentment_*`) e a LLC escritura
|
|
158
|
+
* em USD (`currency`/`amount`); `exchange_rate` é o câmbio aplicado. */
|
|
159
|
+
presentment_currency?: Currency | null;
|
|
160
|
+
presentment_amount?: string | null;
|
|
161
|
+
exchange_rate?: string | null;
|
|
109
162
|
installments: number;
|
|
110
163
|
status: TransactionStatus;
|
|
111
164
|
pix_qr_code?: string;
|
|
@@ -496,4 +549,4 @@ declare class Vitrin {
|
|
|
496
549
|
request<T = unknown>(path: string, options?: Parameters<VitrinClient['request']>[1]): Promise<T>;
|
|
497
550
|
}
|
|
498
551
|
|
|
499
|
-
export { type Balance, type ConstructEventOptions, type Customer, 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 };
|
|
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 };
|
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,10 @@
|
|
|
6
6
|
* - Serializar/deserializar JSON
|
|
7
7
|
* - Mapear erros HTTP pra `VitrinError`*
|
|
8
8
|
* - Retry automático em 429 e 5xx (até 3 tentativas, backoff exponencial)
|
|
9
|
+
* - Retry em timeout/erro de rede SÓ quando é seguro: método idempotente
|
|
10
|
+
* (GET/HEAD/PUT/DELETE) ou POST/PATCH com Idempotency-Key. Sem isso o
|
|
11
|
+
* retry de um POST cria uma segunda cobrança — o timeout não diz que o
|
|
12
|
+
* servidor deixou de processar, só que a resposta se perdeu.
|
|
9
13
|
* - Idempotency-Key opcional pra POSTs (evita duplo-débito quando o cliente
|
|
10
14
|
* retenta uma chamada que já chegou no servidor)
|
|
11
15
|
*/
|
|
@@ -43,8 +47,42 @@ declare class VitrinClient {
|
|
|
43
47
|
* Mantidos como interfaces genéricas (em vez de unions super-precisas) pra
|
|
44
48
|
* que mudanças não-quebra-API no backend não exijam major bump no SDK.
|
|
45
49
|
*/
|
|
46
|
-
|
|
50
|
+
/** ISO 4217. BRL é o default histórico; USD/EUR/GBP habilitados com orgs LLC. */
|
|
51
|
+
type Currency = 'BRL' | 'USD' | 'EUR' | 'GBP';
|
|
52
|
+
/** Tipo jurídico da organização. CNPJ = subconta Safe2Pay (Brasil),
|
|
53
|
+
* LLC = Stripe Connect (US/internacional). */
|
|
54
|
+
type EntityType = 'cnpj' | 'llc';
|
|
55
|
+
/**
|
|
56
|
+
* Métodos de pagamento suportados pela plataforma.
|
|
57
|
+
*
|
|
58
|
+
* A disponibilidade por org é dinâmica — sempre cheque
|
|
59
|
+
* `Organization.enabled_payment_methods`. Por tipo de entidade:
|
|
60
|
+
*
|
|
61
|
+
* - CNPJ (BR): PIX, PIX_AUTOMATIC, BOLETO, CREDIT_CARD (default).
|
|
62
|
+
* - LLC (US): CREDIT_CARD por default. PIX está disponível cross-border
|
|
63
|
+
* (o cliente paga em BRL, a liquidação é em USD) como opt-in habilitado
|
|
64
|
+
* pela Vitrin. BOLETO NÃO se aplica a LLC (é Brasil-only). Os demais
|
|
65
|
+
* métodos abaixo (cartão internacional / ACH / wallets / Klarna /
|
|
66
|
+
* Afterpay) são reservados para evolução e podem não estar habilitados.
|
|
67
|
+
*/
|
|
68
|
+
type PaymentMethod = 'PIX' | 'PIX_AUTOMATIC' | 'BOLETO' | 'CREDIT_CARD' | 'CARD_INTERNATIONAL' | 'ACH_DEBIT' | 'SEPA_DEBIT' | 'APPLE_PAY' | 'GOOGLE_PAY' | 'KLARNA' | 'AFTERPAY';
|
|
47
69
|
type TransactionStatus = 'pending' | 'confirmed' | 'received' | 'overdue' | 'refunded' | 'chargeback' | 'failed' | 'canceled';
|
|
70
|
+
/**
|
|
71
|
+
* Representa a organização (subconta) dona da API key em uso.
|
|
72
|
+
*
|
|
73
|
+
* Nota: `default_currency` é derivado de `entity_type` no backend e pode
|
|
74
|
+
* ainda não estar exposto pelo serializer — a declaração aqui é
|
|
75
|
+
* forward-compatible para quando o backend passar a emiti-lo.
|
|
76
|
+
*/
|
|
77
|
+
interface Organization {
|
|
78
|
+
id: string;
|
|
79
|
+
name: string;
|
|
80
|
+
entity_type: EntityType;
|
|
81
|
+
default_currency: Currency;
|
|
82
|
+
enabled_payment_methods?: PaymentMethod[];
|
|
83
|
+
created_at: string;
|
|
84
|
+
updated_at: string;
|
|
85
|
+
}
|
|
48
86
|
interface Customer {
|
|
49
87
|
id: string;
|
|
50
88
|
name: string;
|
|
@@ -94,6 +132,11 @@ interface Subscription {
|
|
|
94
132
|
canceled_at: string | null;
|
|
95
133
|
created_at: string;
|
|
96
134
|
updated_at: string;
|
|
135
|
+
/** LLC: moeda da assinatura (USD). Ausente/BRL para CNPJ. */
|
|
136
|
+
currency?: Currency;
|
|
137
|
+
/** LLC: secret de confirmação da 1ª cobrança — quando presente, confirme
|
|
138
|
+
* com Stripe.js (cartão/SCA) antes da assinatura ficar ativa. */
|
|
139
|
+
client_secret?: string | null;
|
|
97
140
|
}
|
|
98
141
|
interface Transaction {
|
|
99
142
|
id: string;
|
|
@@ -106,6 +149,16 @@ interface Transaction {
|
|
|
106
149
|
platform_fee: string;
|
|
107
150
|
provider_fee: string;
|
|
108
151
|
billing_type: PaymentMethod;
|
|
152
|
+
/** ISO 4217. Default herdado de `Organization.default_currency` na criação. */
|
|
153
|
+
currency: Currency;
|
|
154
|
+
/** LLC: secret de confirmação — cartão (SCA/3DS) ou PIX (QR); confirme com
|
|
155
|
+
* Stripe.js quando presente. Ausente para cobranças síncronas/CNPJ. */
|
|
156
|
+
client_secret?: string | null;
|
|
157
|
+
/** PIX-LLC cross-currency: o cliente vê BRL (`presentment_*`) e a LLC escritura
|
|
158
|
+
* em USD (`currency`/`amount`); `exchange_rate` é o câmbio aplicado. */
|
|
159
|
+
presentment_currency?: Currency | null;
|
|
160
|
+
presentment_amount?: string | null;
|
|
161
|
+
exchange_rate?: string | null;
|
|
109
162
|
installments: number;
|
|
110
163
|
status: TransactionStatus;
|
|
111
164
|
pix_qr_code?: string;
|
|
@@ -496,4 +549,4 @@ declare class Vitrin {
|
|
|
496
549
|
request<T = unknown>(path: string, options?: Parameters<VitrinClient['request']>[1]): Promise<T>;
|
|
497
550
|
}
|
|
498
551
|
|
|
499
|
-
export { type Balance, type ConstructEventOptions, type Customer, 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 };
|
|
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 };
|
package/dist/index.js
CHANGED
|
@@ -75,7 +75,7 @@ var VitrinClient = class {
|
|
|
75
75
|
lastError = new VitrinNetworkError(
|
|
76
76
|
netErr.name === "AbortError" ? `Timeout ap\xF3s ${this.timeout}ms` : netErr.message || "Falha de rede"
|
|
77
77
|
);
|
|
78
|
-
if (attempt < this.maxRetries) {
|
|
78
|
+
if (attempt < this.maxRetries && canRetryAfterNetworkError(method, idempotencyKey)) {
|
|
79
79
|
await sleep(backoffMs(attempt));
|
|
80
80
|
continue;
|
|
81
81
|
}
|
|
@@ -157,6 +157,11 @@ function parseRetryAfter(header) {
|
|
|
157
157
|
if (!Number.isNaN(seconds)) return seconds * 1e3;
|
|
158
158
|
return null;
|
|
159
159
|
}
|
|
160
|
+
var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
|
|
161
|
+
function canRetryAfterNetworkError(method, idempotencyKey) {
|
|
162
|
+
if (IDEMPOTENT_METHODS.has(method.toUpperCase())) return true;
|
|
163
|
+
return Boolean(idempotencyKey);
|
|
164
|
+
}
|
|
160
165
|
function backoffMs(attempt) {
|
|
161
166
|
const base = 250 * Math.pow(2, attempt);
|
|
162
167
|
return base + Math.floor(Math.random() * base * 0.5);
|