@ar-agents/mercadopago 0.7.0 → 0.9.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/CHANGELOG.md +125 -0
- package/README.md +162 -2
- package/cookbook/01-checkout-pro-basic.ts +99 -0
- package/cookbook/02-saas-subscription.ts +137 -0
- package/cookbook/03-webhook-handler.ts +162 -0
- package/cookbook/04-marketplace-split.ts +194 -0
- package/cookbook/05-qr-in-store.ts +142 -0
- package/cookbook/06-3ds-challenge.ts +139 -0
- package/cookbook/07-auth-only-order.ts +127 -0
- package/cookbook/08-recovery-patterns.ts +191 -0
- package/cookbook/README.md +36 -0
- package/dist/index.cjs +407 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +278 -50
- package/dist/index.d.ts +278 -50
- package/dist/index.js +404 -35
- package/dist/index.js.map +1 -1
- package/dist/state-C6Wzb_XX.d.cts +106 -0
- package/dist/state-C6Wzb_XX.d.ts +106 -0
- package/dist/vercel-kv.cjs +92 -0
- package/dist/vercel-kv.cjs.map +1 -0
- package/dist/vercel-kv.d.cts +107 -0
- package/dist/vercel-kv.d.ts +107 -0
- package/dist/vercel-kv.js +88 -0
- package/dist/vercel-kv.js.map +1 -0
- package/package.json +32 -3
- package/tools.manifest.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,172 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { ToolSet } from 'ai';
|
|
3
|
+
import { S as SubscriptionStateAdapter } from './state-C6Wzb_XX.cjs';
|
|
4
|
+
export { I as IdempotencyCache, a as InMemoryIdempotencyCache, b as InMemoryOAuthTokenStore, c as InMemoryStateAdapter, O as OAuthTokenRecord, d as OAuthTokenStore, e as SubscriptionStateRecord } from './state-C6Wzb_XX.cjs';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Circuit breaker — protects your app from cascading failures when MP
|
|
8
|
+
* (or any upstream) is degraded.
|
|
9
|
+
*
|
|
10
|
+
* # Why
|
|
11
|
+
*
|
|
12
|
+
* When MP's API has an outage, naive retry-with-backoff still pounds the
|
|
13
|
+
* dead service N times per request × every concurrent request. That makes
|
|
14
|
+
* MP's outage worse AND your app's error rate worse (each request burns
|
|
15
|
+
* `requestTimeoutMs × maxRetries` ms of CPU/event-loop time before failing).
|
|
16
|
+
*
|
|
17
|
+
* A circuit breaker observes failures over a rolling window. After enough
|
|
18
|
+
* failures it OPENS — subsequent calls fail fast (no network round-trip)
|
|
19
|
+
* with a `CircuitOpenError`. After a cooldown it HALF-OPENs — lets one
|
|
20
|
+
* trial through. If that succeeds, it CLOSES (back to normal). If it
|
|
21
|
+
* fails, it RE-OPENs for another cooldown.
|
|
22
|
+
*
|
|
23
|
+
* # State machine
|
|
24
|
+
*
|
|
25
|
+
* CLOSED ──(failures ≥ threshold)──▶ OPEN
|
|
26
|
+
* ▲ │
|
|
27
|
+
* │ │ (cooldown elapsed)
|
|
28
|
+
* │ ▼
|
|
29
|
+
* │ HALF_OPEN
|
|
30
|
+
* │ │
|
|
31
|
+
* └──(trial succeeds)────────────────┤
|
|
32
|
+
* │ (trial fails)
|
|
33
|
+
* ▼
|
|
34
|
+
* OPEN
|
|
35
|
+
*
|
|
36
|
+
* # When to use
|
|
37
|
+
*
|
|
38
|
+
* - **Protects YOUR app** from being slow/dead when MP is slow/dead.
|
|
39
|
+
* - **Protects MP** from your app pummeling it during incidents.
|
|
40
|
+
* - **Surfaces a clear signal to ops**: `circuit_open` event tells you
|
|
41
|
+
* "MP is broken, my app is intentionally short-circuiting" — different
|
|
42
|
+
* from "MP timed out 30s × 3 retries × 1000 concurrent users".
|
|
43
|
+
*
|
|
44
|
+
* # When NOT to use
|
|
45
|
+
*
|
|
46
|
+
* - For idempotent reads where stale-cached data is acceptable, prefer
|
|
47
|
+
* a cache-aside pattern instead.
|
|
48
|
+
* - For fire-and-forget webhooks where the backpressure should propagate
|
|
49
|
+
* to MP itself (return 5xx, MP retries with backoff).
|
|
50
|
+
*
|
|
51
|
+
* # Configuration
|
|
52
|
+
*
|
|
53
|
+
* Defaults are tuned for typical MP traffic patterns:
|
|
54
|
+
* - `failureThreshold: 5` — open after 5 consecutive failures
|
|
55
|
+
* - `successThreshold: 2` — close after 2 trial successes (half-open)
|
|
56
|
+
* - `resetTimeoutMs: 30_000` — 30s cooldown before half-open trial
|
|
57
|
+
* - `monitoringWindowMs: 60_000` — count failures within a 60s window
|
|
58
|
+
*
|
|
59
|
+
* # Per-host vs global
|
|
60
|
+
*
|
|
61
|
+
* The default `MercadoPagoClient` uses ONE breaker per client instance
|
|
62
|
+
* (which means one per upstream host: `api.mercadopago.com` for prod,
|
|
63
|
+
* `api.mercadopago.com` sandbox for TEST). For multi-host setups (e.g.,
|
|
64
|
+
* marketplace flows with per-seller clients), instantiate a SHARED breaker
|
|
65
|
+
* and pass it to all clients — they all benefit from the same backpressure
|
|
66
|
+
* signal.
|
|
67
|
+
*/
|
|
68
|
+
type CircuitState = "CLOSED" | "OPEN" | "HALF_OPEN";
|
|
69
|
+
interface CircuitBreakerOptions {
|
|
70
|
+
/** Open the breaker after this many consecutive failures. Default 5. */
|
|
71
|
+
failureThreshold?: number;
|
|
72
|
+
/** Close the breaker after this many successive successes in HALF_OPEN. Default 2. */
|
|
73
|
+
successThreshold?: number;
|
|
74
|
+
/** Time to stay OPEN before allowing a HALF_OPEN trial. Default 30s. */
|
|
75
|
+
resetTimeoutMs?: number;
|
|
76
|
+
/** Rolling window for counting failures. Failures older than this don't count. Default 60s. */
|
|
77
|
+
monitoringWindowMs?: number;
|
|
78
|
+
/**
|
|
79
|
+
* Called on EVERY state transition. Useful for emitting metrics/logs.
|
|
80
|
+
* `cause` is the error that triggered the transition (when applicable).
|
|
81
|
+
*/
|
|
82
|
+
onStateChange?: (event: {
|
|
83
|
+
from: CircuitState;
|
|
84
|
+
to: CircuitState;
|
|
85
|
+
cause?: unknown;
|
|
86
|
+
consecutiveFailures: number;
|
|
87
|
+
}) => void;
|
|
88
|
+
/**
|
|
89
|
+
* Predicate to decide whether an error should count as a circuit failure.
|
|
90
|
+
* By default, all errors count. Override to ignore expected business
|
|
91
|
+
* errors (e.g., 404s, validation errors) — they shouldn't open the breaker.
|
|
92
|
+
*/
|
|
93
|
+
isFailure?: (error: unknown) => boolean;
|
|
94
|
+
/** Time provider (for tests). Defaults to `Date.now`. */
|
|
95
|
+
now?: () => number;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Thrown when a circuit breaker is OPEN and rejects a call without trying.
|
|
99
|
+
* Catch this separately from MercadoPagoError to differentiate "MP said no"
|
|
100
|
+
* from "we didn't even ask MP".
|
|
101
|
+
*/
|
|
102
|
+
declare class CircuitOpenError extends Error {
|
|
103
|
+
readonly retryAfterMs: number;
|
|
104
|
+
readonly consecutiveFailures: number;
|
|
105
|
+
constructor(retryAfterMs: number, consecutiveFailures: number);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Thread-safe circuit breaker. Single-instance per upstream (typically per
|
|
109
|
+
* `MercadoPagoClient`). Pass to multiple clients to share state.
|
|
110
|
+
*
|
|
111
|
+
* @example
|
|
112
|
+
* ```ts
|
|
113
|
+
* import { CircuitBreaker, MercadoPagoClient } from "@ar-agents/mercadopago";
|
|
114
|
+
*
|
|
115
|
+
* const breaker = new CircuitBreaker({
|
|
116
|
+
* failureThreshold: 5,
|
|
117
|
+
* resetTimeoutMs: 30_000,
|
|
118
|
+
* onStateChange: (e) => metrics.increment(`circuit.${e.to}`),
|
|
119
|
+
* });
|
|
120
|
+
*
|
|
121
|
+
* const client = new MercadoPagoClient({
|
|
122
|
+
* accessToken: process.env.MP_ACCESS_TOKEN!,
|
|
123
|
+
* circuitBreaker: breaker,
|
|
124
|
+
* });
|
|
125
|
+
* ```
|
|
126
|
+
*/
|
|
127
|
+
declare class CircuitBreaker {
|
|
128
|
+
private state;
|
|
129
|
+
private consecutiveFailures;
|
|
130
|
+
private halfOpenSuccesses;
|
|
131
|
+
private openedAt;
|
|
132
|
+
/** Timestamps of failures within the monitoring window. */
|
|
133
|
+
private failureWindow;
|
|
134
|
+
private readonly failureThreshold;
|
|
135
|
+
private readonly successThreshold;
|
|
136
|
+
private readonly resetTimeoutMs;
|
|
137
|
+
private readonly monitoringWindowMs;
|
|
138
|
+
private readonly onStateChange;
|
|
139
|
+
private readonly isFailureFn;
|
|
140
|
+
private readonly now;
|
|
141
|
+
constructor(opts?: CircuitBreakerOptions);
|
|
142
|
+
/** Read the current state. Useful for health checks + metrics. */
|
|
143
|
+
getState(): CircuitState;
|
|
144
|
+
/** Read diagnostic state for health checks + dashboards. */
|
|
145
|
+
getStats(): {
|
|
146
|
+
state: CircuitState;
|
|
147
|
+
consecutiveFailures: number;
|
|
148
|
+
failuresInWindow: number;
|
|
149
|
+
msSinceOpened: number | null;
|
|
150
|
+
msUntilHalfOpen: number | null;
|
|
151
|
+
};
|
|
152
|
+
/**
|
|
153
|
+
* Execute `fn` under the breaker's protection.
|
|
154
|
+
* - If the breaker is OPEN, throws `CircuitOpenError` immediately.
|
|
155
|
+
* - If `fn` succeeds, may transition HALF_OPEN → CLOSED.
|
|
156
|
+
* - If `fn` fails (and the error counts as a failure), records the
|
|
157
|
+
* failure; may transition CLOSED → OPEN or HALF_OPEN → OPEN.
|
|
158
|
+
*/
|
|
159
|
+
execute<T>(fn: () => Promise<T>): Promise<T>;
|
|
160
|
+
/** Manually force the breaker open. Useful for runbook / manual ops. */
|
|
161
|
+
trip(reason?: unknown): void;
|
|
162
|
+
/** Manually reset the breaker to CLOSED. */
|
|
163
|
+
reset(): void;
|
|
164
|
+
private recordSuccess;
|
|
165
|
+
private recordFailure;
|
|
166
|
+
private transitionTo;
|
|
167
|
+
private pruneWindow;
|
|
168
|
+
private failuresInCurrentWindow;
|
|
169
|
+
}
|
|
3
170
|
|
|
4
171
|
/**
|
|
5
172
|
* Base class for any error originating from the Mercado Pago integration. All
|
|
@@ -1118,6 +1285,10 @@ interface MercadoPagoClientOptions {
|
|
|
1118
1285
|
/**
|
|
1119
1286
|
* Observability hook fired AFTER every request (success or failure).
|
|
1120
1287
|
* Useful for logging, metrics, tracing. Synchronous, fire-and-forget.
|
|
1288
|
+
*
|
|
1289
|
+
* The `traceContext` field follows the W3C Trace Context spec — pass
|
|
1290
|
+
* an OpenTelemetry-compatible context propagator and you get full
|
|
1291
|
+
* distributed tracing for free. See `traceContext` option below.
|
|
1121
1292
|
*/
|
|
1122
1293
|
onCall?: (event: {
|
|
1123
1294
|
method: string;
|
|
@@ -1126,7 +1297,52 @@ interface MercadoPagoClientOptions {
|
|
|
1126
1297
|
httpStatus: number | null;
|
|
1127
1298
|
retried: number;
|
|
1128
1299
|
success: boolean;
|
|
1300
|
+
/** v0.9: MP's `x-request-id` echo. Useful for support tickets. */
|
|
1301
|
+
requestId?: string | null;
|
|
1302
|
+
/** v0.9: MP's rate-limit headers when present. */
|
|
1303
|
+
rateLimit?: {
|
|
1304
|
+
remaining: number | null;
|
|
1305
|
+
resetSeconds: number | null;
|
|
1306
|
+
};
|
|
1307
|
+
/** v0.9: Circuit breaker state at the time of the call. */
|
|
1308
|
+
circuitState?: "CLOSED" | "OPEN" | "HALF_OPEN";
|
|
1309
|
+
/** v0.9: Trace context for OpenTelemetry-style propagation. */
|
|
1310
|
+
traceContext?: {
|
|
1311
|
+
traceId?: string;
|
|
1312
|
+
spanId?: string;
|
|
1313
|
+
};
|
|
1129
1314
|
}) => void;
|
|
1315
|
+
/**
|
|
1316
|
+
* v0.9 — Opt-in circuit breaker. When MP is failing, fail fast instead of
|
|
1317
|
+
* piling up retries against a dead service. Pass a configured instance
|
|
1318
|
+
* (or share one across multiple clients to give them shared backpressure
|
|
1319
|
+
* signal).
|
|
1320
|
+
*
|
|
1321
|
+
* @example
|
|
1322
|
+
* ```ts
|
|
1323
|
+
* const breaker = new CircuitBreaker({
|
|
1324
|
+
* failureThreshold: 5,
|
|
1325
|
+
* resetTimeoutMs: 30_000,
|
|
1326
|
+
* onStateChange: (e) => metrics.gauge("circuit.state", e.to),
|
|
1327
|
+
* });
|
|
1328
|
+
* const client = new MercadoPagoClient({ accessToken: "...", circuitBreaker: breaker });
|
|
1329
|
+
* ```
|
|
1330
|
+
*/
|
|
1331
|
+
circuitBreaker?: CircuitBreaker;
|
|
1332
|
+
/**
|
|
1333
|
+
* v0.9 — Optional W3C Trace Context propagator. If provided, the client
|
|
1334
|
+
* extracts traceId/spanId on each request, injects `traceparent` /
|
|
1335
|
+
* `tracestate` headers (MP echoes them back via x-request-id), and surfaces
|
|
1336
|
+
* them in `onCall` events. Compatible with OpenTelemetry without adding
|
|
1337
|
+
* `@opentelemetry/api` as a peer dep.
|
|
1338
|
+
*
|
|
1339
|
+
* If you have OTEL set up, just pass `() => trace.getActiveSpan()?.spanContext()`.
|
|
1340
|
+
*/
|
|
1341
|
+
traceContext?: () => {
|
|
1342
|
+
traceId?: string;
|
|
1343
|
+
spanId?: string;
|
|
1344
|
+
traceFlags?: number;
|
|
1345
|
+
} | undefined;
|
|
1130
1346
|
}
|
|
1131
1347
|
interface RequestOptions {
|
|
1132
1348
|
/** Idempotency key. Required for POST/PUT to dedupe retries safely. */
|
|
@@ -1141,6 +1357,13 @@ interface RequestOptions {
|
|
|
1141
1357
|
payerEmail?: string;
|
|
1142
1358
|
sellerEmail?: string;
|
|
1143
1359
|
};
|
|
1360
|
+
/**
|
|
1361
|
+
* v0.9 — Parent AbortSignal for deadline propagation. When the agent
|
|
1362
|
+
* has a fixed budget (e.g., 5s for the whole tool call), pass it here.
|
|
1363
|
+
* The client merges it with its own per-request timeout — whichever
|
|
1364
|
+
* fires first wins.
|
|
1365
|
+
*/
|
|
1366
|
+
signal?: AbortSignal;
|
|
1144
1367
|
}
|
|
1145
1368
|
/**
|
|
1146
1369
|
* Thin, typed wrapper around Mercado Pago's REST API. Exposes the surface
|
|
@@ -1156,8 +1379,16 @@ declare class MercadoPagoClient {
|
|
|
1156
1379
|
private readonly requestTimeoutMs;
|
|
1157
1380
|
private readonly maxRetries;
|
|
1158
1381
|
private readonly onCall;
|
|
1382
|
+
private readonly circuitBreaker;
|
|
1383
|
+
private readonly traceContext;
|
|
1159
1384
|
constructor(options: MercadoPagoClientOptions);
|
|
1385
|
+
/**
|
|
1386
|
+
* v0.9 — Inspect the circuit breaker state (when configured). Returns
|
|
1387
|
+
* `null` when no circuit breaker is wired. Useful for health checks.
|
|
1388
|
+
*/
|
|
1389
|
+
getCircuitState(): ReturnType<CircuitBreaker["getStats"]> | null;
|
|
1160
1390
|
private request;
|
|
1391
|
+
private requestUnprotected;
|
|
1161
1392
|
/**
|
|
1162
1393
|
* Create a recurring subscription (preapproval). The returned `init_point`
|
|
1163
1394
|
* URL is where the buyer must complete the FIRST payment with their card +
|
|
@@ -1623,52 +1854,26 @@ declare class MercadoPagoClient {
|
|
|
1623
1854
|
id: string;
|
|
1624
1855
|
canceled: true;
|
|
1625
1856
|
}>;
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
lastWebhookAt?: string;
|
|
1647
|
-
metadata?: Record<string, unknown>;
|
|
1648
|
-
}
|
|
1649
|
-
/**
|
|
1650
|
-
* Persistence surface for subscription state. Implementations may back this
|
|
1651
|
-
* with Upstash Redis, Vercel KV, Postgres, in-memory, or anything that
|
|
1652
|
-
* supports the three operations. The default `InMemoryStateAdapter` is
|
|
1653
|
-
* provided for tests and trivial single-process deployments; production
|
|
1654
|
-
* setups should plug in a durable store.
|
|
1655
|
-
*/
|
|
1656
|
-
interface SubscriptionStateAdapter {
|
|
1657
|
-
set(id: string, state: Partial<SubscriptionStateRecord>): Promise<void>;
|
|
1658
|
-
get(id: string): Promise<SubscriptionStateRecord | null>;
|
|
1659
|
-
list?(): Promise<string[]>;
|
|
1660
|
-
}
|
|
1661
|
-
/**
|
|
1662
|
-
* Volatile, single-process state adapter. Useful for tests and demos. Do not
|
|
1663
|
-
* use in production: state is lost on restart and is not safe across tenants.
|
|
1664
|
-
*/
|
|
1665
|
-
declare class InMemoryStateAdapter implements SubscriptionStateAdapter {
|
|
1666
|
-
private readonly store;
|
|
1667
|
-
set(id: string, state: Partial<SubscriptionStateRecord>): Promise<void>;
|
|
1668
|
-
get(id: string): Promise<SubscriptionStateRecord | null>;
|
|
1669
|
-
list(): Promise<string[]>;
|
|
1670
|
-
/** Test helper: drop everything. Not part of the adapter interface. */
|
|
1671
|
-
reset(): void;
|
|
1857
|
+
/**
|
|
1858
|
+
* Liveness probe against MP. Returns latency + circuit-breaker state.
|
|
1859
|
+
* Use as a /health endpoint for k8s, Vercel cron, or status-page checks.
|
|
1860
|
+
*
|
|
1861
|
+
* Returns `{ ok: false, ... }` instead of throwing — designed for
|
|
1862
|
+
* monitoring loops that want to keep running.
|
|
1863
|
+
*
|
|
1864
|
+
* @param signal Optional AbortSignal to cap wait time (e.g., 2s for
|
|
1865
|
+
* status-page polling).
|
|
1866
|
+
*/
|
|
1867
|
+
healthCheck(signal?: AbortSignal): Promise<{
|
|
1868
|
+
ok: boolean;
|
|
1869
|
+
latencyMs: number;
|
|
1870
|
+
/** MP user_id when reachable. */
|
|
1871
|
+
userId: string | null;
|
|
1872
|
+
/** Last error message when not OK. */
|
|
1873
|
+
error: string | null;
|
|
1874
|
+
/** Circuit breaker state when configured. */
|
|
1875
|
+
circuit: ReturnType<CircuitBreaker["getStats"]> | null;
|
|
1876
|
+
}>;
|
|
1672
1877
|
}
|
|
1673
1878
|
|
|
1674
1879
|
interface MercadoPagoToolsOptions {
|
|
@@ -1709,7 +1914,7 @@ interface MercadoPagoToolsOptions {
|
|
|
1709
1914
|
clientSecret: string;
|
|
1710
1915
|
};
|
|
1711
1916
|
}
|
|
1712
|
-
type ToolName = "create_subscription" | "get_subscription_status" | "cancel_subscription" | "pause_subscription" | "resume_subscription" | "create_payment" | "get_payment" | "search_payments" | "cancel_payment" | "capture_payment" | "refund_payment" | "list_refunds" | "create_payment_preference" | "get_payment_preference" | "create_customer" | "find_customer_by_email" | "list_customer_cards" | "delete_customer_card" | "list_payment_methods" | "calculate_installments" | "get_account_info" | "charge_saved_card" | "create_qr_payment" | "cancel_qr_payment" | "create_subscription_plan" | "list_subscription_plans" | "update_subscription_plan" | "subscribe_to_plan" | "list_subscription_payments" | "create_store" | "list_stores" | "create_pos" | "list_pos" | "list_payment_disputes" | "get_dispute" | "list_identification_types" | "list_issuers" | "list_webhooks" | "create_webhook" | "update_webhook" | "delete_webhook" | "handle_webhook" | "oauth_authorize_url" | "oauth_exchange_code" | "oauth_refresh_token" | "create_order" | "get_order" | "update_order" | "capture_order" | "cancel_order" | "get_account_balance" | "list_account_movements" | "list_settlements" | "get_settlement" | "analyze_payment_3ds" | "get_test_cards" | "get_customer" | "update_customer" | "create_customer_card" | "get_customer_card" | "get_subscription_plan" | "update_subscription" | "search_subscriptions" | "get_refund" | "update_payment_preference" | "get_merchant_order" | "search_merchant_orders" | "update_merchant_order" | "get_store" | "update_store" | "delete_store" | "get_pos" | "update_pos" | "delete_pos" | "list_bank_accounts" | "register_bank_account" | "list_point_devices" | "update_point_device_mode" | "create_point_payment_intent" | "get_point_payment_intent" | "cancel_point_payment_intent" | "compute_marketplace_fee" | "explain_payment_status";
|
|
1917
|
+
type ToolName = "create_subscription" | "get_subscription_status" | "cancel_subscription" | "pause_subscription" | "resume_subscription" | "create_payment" | "get_payment" | "search_payments" | "cancel_payment" | "capture_payment" | "refund_payment" | "list_refunds" | "create_payment_preference" | "get_payment_preference" | "create_customer" | "find_customer_by_email" | "list_customer_cards" | "delete_customer_card" | "list_payment_methods" | "calculate_installments" | "get_account_info" | "charge_saved_card" | "create_qr_payment" | "cancel_qr_payment" | "create_subscription_plan" | "list_subscription_plans" | "update_subscription_plan" | "subscribe_to_plan" | "list_subscription_payments" | "create_store" | "list_stores" | "create_pos" | "list_pos" | "list_payment_disputes" | "get_dispute" | "list_identification_types" | "list_issuers" | "list_webhooks" | "create_webhook" | "update_webhook" | "delete_webhook" | "handle_webhook" | "oauth_authorize_url" | "oauth_exchange_code" | "oauth_refresh_token" | "create_order" | "get_order" | "update_order" | "capture_order" | "cancel_order" | "get_account_balance" | "list_account_movements" | "list_settlements" | "get_settlement" | "analyze_payment_3ds" | "get_test_cards" | "get_customer" | "update_customer" | "create_customer_card" | "get_customer_card" | "get_subscription_plan" | "update_subscription" | "search_subscriptions" | "get_refund" | "update_payment_preference" | "get_merchant_order" | "search_merchant_orders" | "update_merchant_order" | "get_store" | "update_store" | "delete_store" | "get_pos" | "update_pos" | "delete_pos" | "list_bank_accounts" | "register_bank_account" | "list_point_devices" | "update_point_device_mode" | "create_point_payment_intent" | "get_point_payment_intent" | "cancel_point_payment_intent" | "compute_marketplace_fee" | "explain_payment_status" | "mp_health_check";
|
|
1713
1918
|
/**
|
|
1714
1919
|
* Build a tool set for the Vercel AI SDK that exposes Mercado Pago to an
|
|
1715
1920
|
* agent. Pass directly to `Experimental_Agent`'s `tools` option, or merge with
|
|
@@ -1733,12 +1938,26 @@ type ToolName = "create_subscription" | "get_subscription_status" | "cancel_subs
|
|
|
1733
1938
|
*/
|
|
1734
1939
|
declare function mercadoPagoTools(client: MercadoPagoClient, options: MercadoPagoToolsOptions): ToolSet;
|
|
1735
1940
|
|
|
1941
|
+
/**
|
|
1942
|
+
* Webhook helpers — parse incoming MP notifications and verify the
|
|
1943
|
+
* HMAC-SHA256 signature MP sends in the `x-signature` header.
|
|
1944
|
+
*
|
|
1945
|
+
* # Edge Runtime
|
|
1946
|
+
*
|
|
1947
|
+
* Both `verifyWebhookSignature` and `parseWebhookEvent` work in Vercel
|
|
1948
|
+
* Edge Runtime, Cloudflare Workers, Deno, browsers, and Node 18+. The
|
|
1949
|
+
* HMAC verification uses Web Crypto under the hood (see `./crypto.ts`)
|
|
1950
|
+
* and is **async** — make sure to `await` the call.
|
|
1951
|
+
*/
|
|
1952
|
+
|
|
1736
1953
|
/**
|
|
1737
1954
|
* Parse a Mercado Pago webhook from the raw request body and URL search params.
|
|
1738
1955
|
* MP sends the topic and resource id in EITHER the URL query string OR the
|
|
1739
1956
|
* body, depending on integration version — this normalizes both shapes into a
|
|
1740
1957
|
* single structure.
|
|
1741
1958
|
*
|
|
1959
|
+
* **Pure function — synchronous, no I/O.**
|
|
1960
|
+
*
|
|
1742
1961
|
* @example
|
|
1743
1962
|
* ```ts
|
|
1744
1963
|
* export async function POST(req: Request) {
|
|
@@ -1755,25 +1974,34 @@ declare function parseWebhookEvent(body: unknown, searchParams?: URLSearchParams
|
|
|
1755
1974
|
/**
|
|
1756
1975
|
* Verify the HMAC-SHA256 signature MP sends in the `x-signature` header for
|
|
1757
1976
|
* webhook authenticity. Returns true if the signature matches the expected
|
|
1758
|
-
* value derived from the integration's secret key
|
|
1977
|
+
* value derived from the integration's secret key AND the timestamp is
|
|
1978
|
+
* within the replay-tolerance window.
|
|
1979
|
+
*
|
|
1980
|
+
* **Async** — runs on Web Crypto under the hood, works in Edge Runtime.
|
|
1759
1981
|
*
|
|
1760
1982
|
* @param requestId The value of the `x-request-id` request header.
|
|
1761
1983
|
* @param dataId The id of the resource the webhook is about (from query or body).
|
|
1762
1984
|
* @param signatureHeader The full `x-signature` header value MP sent.
|
|
1763
1985
|
* @param secret Your integration's webhook secret (configured in MP dev panel).
|
|
1986
|
+
* @param replayToleranceSeconds Optional override. Default 300s (5 min).
|
|
1764
1987
|
*
|
|
1765
1988
|
* @remarks
|
|
1766
1989
|
* MP's `x-signature` header has the form: `ts=NNNNNNNN,v1=HEXSIGNATURE`. We
|
|
1767
1990
|
* extract the timestamp and the v1 signature, then compute
|
|
1768
1991
|
* `HMAC-SHA256(secret, "id:${dataId};request-id:${requestId};ts:${ts};")`
|
|
1769
1992
|
* and compare with constant-time equality.
|
|
1993
|
+
*
|
|
1994
|
+
* **Replay protection**: rejects signatures whose `ts` is older than
|
|
1995
|
+
* `replayToleranceSeconds` (default 5min) — prevents an attacker who
|
|
1996
|
+
* captured a valid webhook from replaying it later.
|
|
1770
1997
|
*/
|
|
1771
1998
|
declare function verifyWebhookSignature(params: {
|
|
1772
1999
|
requestId: string | null;
|
|
1773
2000
|
dataId: string;
|
|
1774
2001
|
signatureHeader: string | null;
|
|
1775
2002
|
secret: string;
|
|
1776
|
-
|
|
2003
|
+
replayToleranceSeconds?: number;
|
|
2004
|
+
}): Promise<boolean>;
|
|
1777
2005
|
|
|
1778
2006
|
/**
|
|
1779
2007
|
* Mercado Pago OAuth flow — for marketplace integrations where YOUR app
|
|
@@ -2079,4 +2307,4 @@ interface PaymentStatusExplanation {
|
|
|
2079
2307
|
*/
|
|
2080
2308
|
declare function explainPaymentStatus(payment: Payment): PaymentStatusExplanation;
|
|
2081
2309
|
|
|
2082
|
-
export { type AccountBalance, type AccountInfo, type AccountMovement, type AutoRecurring, type BankAccount, type CardToken, type CreateCardTokenParams, type CreateCustomerParams, type CreateOrderParams, type CreatePaymentParams, type CreatePointPaymentIntentParams, type CreatePosParams, type CreatePreapprovalParams, type CreatePreferenceParams, type CreateQrPaymentParams, type CreateRefundParams, type CreateStoreParams, type CreateSubscriptionPlanParams, type CreateWebhookParams, type CurrencyId, type Customer, type CustomerCard, type Dispute, type FrequencyType, type IdentificationType,
|
|
2310
|
+
export { type AccountBalance, type AccountInfo, type AccountMovement, type AutoRecurring, type BankAccount, type CardToken, CircuitBreaker, type CircuitBreakerOptions, CircuitOpenError, type CircuitState, type CreateCardTokenParams, type CreateCustomerParams, type CreateOrderParams, type CreatePaymentParams, type CreatePointPaymentIntentParams, type CreatePosParams, type CreatePreapprovalParams, type CreatePreferenceParams, type CreateQrPaymentParams, type CreateRefundParams, type CreateStoreParams, type CreateSubscriptionPlanParams, type CreateWebhookParams, type CurrencyId, type Customer, type CustomerCard, type Dispute, type FrequencyType, type IdentificationType, type InstallmentOffer, type Issuer, type MarketplaceFeeRule, type MarketplaceParams, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, type MercadoPagoClientOptions, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, type MercadoPagoToolsOptions, type MerchantOrder, type OAuthToken, type Order, type OrderItem, type OrderStatus, type ParsedWebhookEvent, type Payment, type PaymentMethod, type PaymentStatus, type PaymentStatusExplanation, type PaymentsSearchResult, type PointDevice, type PointPaymentIntent, type PointPaymentIntentState, type Pos, type Preapproval, type PreapprovalStatus, type Preference, type PreferenceItem, type QrOrder, type Refund, type SearchPaymentsParams, type Settlement, type SiteId, type Store, type SubscriptionPayment, type SubscriptionPlan, SubscriptionStateAdapter, TEST_CARDS_AR, TEST_PAYERS_AR, type TestCard, type ThreeDSInfo, type ThreeDSStatus, type WebhookBody, type WebhookConfig, type WebhookTopic, analyze3DS, buildAuthorizeUrl, buildTestCardScenario, classifyError, computeMarketplaceFee, exchangeCodeForToken, expirationTimeMs, explainPaymentStatus, isExpiringSoon, mercadoPagoTools, parseWebhookEvent, refreshAccessToken, verifyWebhookSignature };
|