API
Create pay-to-open links, pay for them with USDC over x402 v2, and manage everything the web app can do, over REST or MCP.
Overview
Every URLGate link has a price in USDC. Opening it answers HTTP 402 Payment Required with x402 v2 payment requirements; the buyer signs a USDC transfer authorization (EIP-3009, no gas for the buyer), retries, and receives the destination. Creators receive the link price minus the platform fee, on-chain, on every paid open.
- Base URL
https://urlgate.xyz- Protocol
- x402 v2 (
PAYMENT-REQUIRED/PAYMENT-SIGNATURE/PAYMENT-RESPONSEheaders), schemeexact. Legacy x402 v1 bodies are still sent for older clients. - Default network
- Base (CAIP-2
eip155:8453, chain ID 8453) - Currency
- USDC
0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913, 6 decimals. Amounts in JSON bodies are decimal strings ("0.050000"); amounts in x402 requirements are base units ("50000"). - Identity
- SIWE session (cookie or Bearer token): required for every account change. A per-request
SIGN-IN-WITH-Xheader only re-opens links you paid for (or created) and reads low-sensitivity account data (whoami, points, membership, preferences). Nothing else proves a wallet:X-Wallet-Addressand?wallet=are ignored. - Machine-readable
- openapi.json (OpenAPI 3.1 with
x-payment-info), llms.txt, SKILL.md, MCP athttps://urlgate.xyz/mcp. - Timestamps
- ISO 8601 in UTC (
2026-10-14T12:00:00.000Z).
Short codes are case-insensitive: /AbC123 and /abc123 open the same link (if old links differ only in case, the oldest one wins). Responses always use the link's canonical code.
Networks
This deployment's default network is Base (eip155:8453, chain ID 8453, x402 v1 name base), paying in USDC at 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913.
A deployment may accept more than one network. Each 402 lists one accepts[] entry per network the link sells on (the link's networks ∩ the networks enabled right now); pick the one you hold USDC on. A creator can restrict a link to a subset (networks option, at least one).
Production accepts mainnets only and preview testnets only (Base Sepolia); this is enforced in code from the deployment's environment. URLGate can switch a network off: it then disappears from /api/v2/networks, link options and checkout, and a payment signed for it is refused (402 requirement_mismatch). A link whose only chosen network is off sells on the enabled ones instead and says so in options.networksFallback / options.networksNotice.
| Method | Path | Returns |
|---|---|---|
GET | /api/v2/networks | { mode, networks: [{ id, label, chainId, v1Name, asset, name, version, explorer, testnet, default }] }: every enabled network and its USDC contract (name / version are the token's EIP-712 domain). mode is mainnet (production) or testnet (preview); default: true marks the default network (first). |
Sign-in
Paying never needs an account. Signing in is needed to create links, manage them, see your unlocks and re-open a link you already paid for. A request's wallet is taken from, in order: Authorization: Bearer <token>, then SIGN-IN-WITH-X (only where it is allowed, see below), then the ug_session cookie. Banned wallets are treated as signed out everywhere.
SIWE session (EIP-4361)
GET /api/v2/auth/nonce?address=0x…(optional&chainId=, default: the first enabled network) →{ nonce, domain, uri, chainId, expiresInSeconds: 600, message }.messageis a ready-to-sign SIWE message (only whenaddressis given).- Sign
messagewithpersonal_sign(EIP-191). Smart wallets (EIP-1271 / EIP-6492) are supported. POST /api/v2/auth/verifywith{ "message", "signature", "kind": "agent" | "human" }→{ success, wallet, kind, token, expiresAt }.
Agent tokens last 24 hours, human sessions 7 days; humans also get an HttpOnly, SameSite=Lax ug_session cookie. The nonce is single-use and valid for 10 minutes; the message's domain and URI must be this site. Failures: 400 (missing or malformed message), 401 (wrong domain, expired, bad signature, nonce already used), 403 wallet_banned.
SIGN-IN-WITH-X (per request: re-open and low-sensitivity reads)
SIGN-IN-WITH-X proves wallet control for one request on one resource. It is honoured only to re-open a link the wallet paid for or created (GET /<code>, GET /api/urlgate/<code>, MCP open_link) and on a few low-sensitivity GET routes (whoami, points, leaderboard rank, membership status, preferences). Anything that changes an account (agent keys, free link creation, link edits, price and destination changes, pause / remove, grants, preferences, membership, sessions), and every read that returns destinations, payments or account security data (my links, owner link views, analytics, payments, audit, grants, my unlocks, history / profile destinations, creator stats, sessions, agent keys), needs the Bearer token or session from SIWE sign-in above: with SIWX alone it answers 401 { "code": "siwx_not_allowed" }, and link creation treats you as anonymous (agent fee; the link belongs to the paying wallet). The admin console and moderator API never accept it.
- Get a server challenge: the 402's
extensions["sign-in-with-x"].info, orGET /api/v2/auth/siwx/challenge?resource=<absolute URL on this site>→{ info: { domain, uri, statement, version, nonce, issuedAt, expirationTime, resources }, supportedChains, expiresAt }(rate-limited per IP). A short link gets the statement Sign in to URLGate to re-open a link you already paid for, any other URL Sign in to URLGate to read your account (read-only). - Sign
infoas an EIP-4361 message with achainIdfromsupportedChains(@x402/extensions>= 2.23.0createSIWxPayloaddoes this). - Send
SIGN-IN-WITH-X: base64(JSON)on exactly that URL within 5 minutes:
{
"domain": "<host of https://urlgate.xyz>",
"address": "0xYourWallet",
"uri": "https://urlgate.xyz/abc123",
"statement": "Sign in to URLGate to re-open a link you already paid for",
"version": "1",
"chainId": "eip155:8453",
"type": "eip191",
"nonce": "<from the challenge>",
"issuedAt": "<from the challenge>",
"expirationTime": "<from the challenge>",
"resources": ["https://urlgate.xyz/abc123"],
"signature": "0x…"
}
Checked: domain and URI are this site; uri is the requested resource (a signature for /abc does not open /xyz) and resources holds only it; statement matches; expirationTime is present, in the future and at most 5 minutes after issuedAt; chainId is an enabled network; the nonce was issued by this server for this resource and is used once (checked after the signature). Transition: nonces the client made up itself still work once until the cutoff in /llms.txt (default 2026-11-06T00:00:00Z), with Deprecation: true, Sunset and X-URLGate-SIWX-Warning response headers; after that only server-issued nonces verify. SIWX verification is rate-limited per IP.
Session endpoints
| Method | Path | Notes |
|---|---|---|
GET | /api/v2/auth/me | { signedIn: false }, or { signedIn: true, wallet, kind, via, jti, tier, membership, gating }. Cookie sessions also get csrfToken (the create form's X-CSRF-Token); Bearer and SIGN-IN-WITH-X callers never do. |
GET | /api/v2/auth/sessions | Live sessions and tokens: { wallet, sessions: [{ jti, kind, current, createdAt, expiresAt }] }. |
POST | /api/v2/auth/revoke | Body { "scope": "current" } (default), { "scope": "all" } or { "jti": "…" } → { success, scope, revoked }. Bearer or session only: SIGN-IN-WITH-X answers 401 siwx_not_allowed. |
POST | /api/v2/auth/logout | Revokes the presented token and clears the cookie → { success, revoked }. |
Revocation takes effect immediately: every token is checked against its server-side session row.
Preferences (colour scheme)
| Method | Path | Notes |
|---|---|---|
GET | /api/v2/me/preferences | Signed in. { wallet, preferences: { theme }, updatedAt, allowed: { theme: ["green", "blue", "system"] }, defaults: { theme: "blue" } }; theme is null until chosen. MCP: my_preferences. |
PATCH | /api/v2/me/preferences | Signed in, own wallet only (there is no wallet parameter). Body { "theme": "green" | "blue" | "system" }, or null to reset. Unknown fields 400 unknown_field, other values 400 invalid_theme. Cookie sessions must send a same-origin Origin (403 bad_origin). Same response as GET. |
Which scheme a page uses: ?theme=green|blue|system on any page URL (this view only, never saved) > the signed-in wallet's saved choice > this browser's last choice > blue (the default; green is an explicit choice). system keeps the default blue palette and follows the device for light / dark.
Create links
| Method | Path | Who |
|---|---|---|
POST | /api/urlgate/create | The website's create form: free. Only a real form submission counts: a signed-in human's session cookie, a same-origin Origin (or Referer), X-URLGate-Form: create and X-CSRF-Token (the csrfToken from GET /api/v2/auth/me, handed to cookie sessions only). The body's wallet is ignored: the link belongs to the signed-in wallet. Every other caller (API, MCP, scripts) gets exactly the agent route's rules below. A session cookie alone is not an API credential, so another site can't spend your free quota. |
POST | /api/urlgate/agent/create | API, scripts and agents (and the MCP create_link tool). Signed in (Authorization: Bearer from /api/v2/auth/verify; SIGN-IN-WITH-X does not count) or with an agent key: free within the daily quota. Anonymous or over quota: creation fee 0.01 USDC per link via x402. Response adds agentCreated: true, creationMode (free_quota | paid) and, when free, freeQuota. |
Request body (JSON)
| Field | Type | Notes |
|---|---|---|
url | string | Required. http / https, no credentials, at most 2048 characters. |
price | string | Required. Plain decimal USDC, minimum 0.01, below 1,000,000, at most 6 decimals ("0.25"). No exponents or signs. Stored as 6 decimals. |
wallet | string | Paid creation only (agent route, or /api/urlgate/create outside the create form), optional. Payout wallet; defaults to the signed-in wallet, else the wallet that paid the creation fee. Naming any other address is refused (403 Creator Mismatch). |
shortcode | string | Optional custom code, 3-20 of A-Z a-z 0-9 _ - (premium custom_slug). Unique case-insensitively and may not look like an existing code (0/O, 1/l/I, 5/S, _/-, rn/m, vv/w). Generated codes are 6+ letters and digits. |
title | string | Optional, up to 120 characters. |
description | string | Optional, up to 500 characters. |
afterPay | string | receipt (default: show the receipt page) or redirect (go straight to the destination). |
networks | string[] | CAIP-2 ids to sell on, at least one, all enabled (see networks). Omit for all enabled networks. []: 400 networks_required; an id that is not enabled: 400 network_unavailable (checked before any creation fee settles). |
Creation fee
Pricing on this deployment: links created from the website's create form are free. Over the API and MCP, a signed-in wallet (or an agent key) creates 10 links a day free (100 with Premium; 3 a day while a wallet is new to URLGate); anonymous callers and anyone over quota pay 0.01 USDC per link. Quotas reset at 00:00 UTC; a global daily ceiling and an admin kill switch apply to everyone. Your live numbers: GET /api/v2/agents/get-started (MCP get_started). Every fee, price, quota, period and limit in force (no sign-in, cached 60 s): GET /api/v2/config (MCP site_config); every number in these docs is rendered from it. While creation is paused by an administrator, both create routes answer 503 with code: "creation_paused" before any fee is asked for. When the fee applies, the first request returns 402 with the exact amount (x402 v2 PAYMENT-REQUIRED header; the body is the same v2 PaymentRequired, whose extensions.bazaar holds the request and response schemas, plus code (why: anonymous, free_quota_exhausted, new_wallet_quota_exhausted, agent_key_cap_reached, free_global_ceiling, free_creation_paused, paid_only), freeQuota and nextSteps); retry with PAYMENT-SIGNATURE as described under Open paid links, but with a single leg (there is no platform-fee leg on creation). The body is validated before the fee is settled, so a bad request never costs anything.
Limits and next steps
Every quota or limit error carries nextSteps: a list of { action, description, how?, url? } with action one of sign_in, use_agent_key, pay_0.01, upgrade, wait. Creation is limited per minute per wallet, per agent key and per IP (IPv6 per /64): 429 rate_limited with Retry-After. The same destination from the same wallet within a few minutes answers 409 duplicate_link with the existing link; blocked domains 403 domain_blocked. New links may be checked against a reputation service in the background; that never delays creation, and a bad result only holds the link for review.
Agent keys
For a bot without a wallet: a signed-in human creates a key in the dashboard (Settings → Agent keys) or with POST /api/v2/me/agent-keys {"name","dailyCap"?,"expiresInDays"?,"networks"?} (MCP agent_keys). The key (ugk_…) is returned once; only a hash is stored. The bot sends Authorization: Bearer ugk_… (or X-URLGate-Agent-Key) to /api/urlgate/agent/create; the links belong to the human's wallet and use the key's daily cap (and the owner's quota). A key can only create links. Revoke with DELETE /api/v2/me/agent-keys/{id}; invalid, revoked or expired keys answer 401 (invalid_agent_key, agent_key_revoked, agent_key_expired). Plain-language guide: /agents/guide.
A legacy transaction hash (Authorization: x402 <txhash>) is also accepted for the creation fee, only when signed in as the wallet that sent it, and only for recent transfers. Creations paid with x402 v2 return a PAYMENT-RESPONSE header; paid agent creations also return a legacy X-PAYMENT-RESPONSE receipt. If the agent fee is zero, the agent route needs a signed-in wallet instead.
Response (200)
{
"success": true,
"shortcode": "abc123",
"shortUrl": "https://urlgate.xyz/abc123",
"destinationUrl": "https://example.com/report.pdf",
"price": "0.050000",
"creatorWallet": "0xyourwallet…",
"feeBreakdown": {
"appliesTo": "each paid open",
"buyerPays": "0.050000",
"serviceFee": "0.000150",
"serviceFeePercentage": 0.3,
"creatorReceives": "0.049850",
"creatorPercentage": 99.7
},
"createdAt": "2026-10-14T12:00:00.000Z",
"title": "Q3 report",
"afterPay": "receipt",
"agentCreated": true
}
feeBreakdown uses the live platform-fee setting. title, description, afterPay and networks appear only when set; agentCreated only on the agent route. Errors: 400 Invalid URL / Invalid Price (code invalid_price or below_min_price) / Invalid Wallet / Invalid Shortcode; 401; 402; 403 premium_required, wallet_banned or Creator Mismatch; 409 Shortcode Taken (reserved, taken, or shortcode_lookalike) or Payment Already Used.
Open paid links (x402 v2)
GET /{code} and GET /api/urlgate/{code} are the same handler. Send Accept: application/json: with Accept: text/html you get the browser paywall page (still 402, with the same PAYMENT-REQUIRED header), and access is a 302 to the destination instead of JSON. A successful open that carried PAYMENT-SIGNATURE or an Authorization: x402 proof answers JSON whatever the Accept header.
The handler checks, in order: (1) a signed-in creator or earlier buyer gets in without paying; (2) an allowlisted wallet or a free-pass promo code gets in free; (3) an x402 v2 PAYMENT-SIGNATURE is verified and settled; (4) a legacy v1 transaction hash; (5) otherwise 402.
Preview: ?preview=1 on a browser page load (Accept: text/html, no payment headers) never forwards to the destination. A signed-in earlier buyer is sent to their receipt (302 /r/{id}); everyone else, the link's creator included, gets the paywall exactly as an unpaid visitor sees it. A preview redeems no allowlist entry or free pass on page load and is not counted: no 402 view, no click, no audit row, so it can't be used to inflate a link's numbers. It never reveals the destination to someone who hasn't paid. JSON requests (agents, the checkout's own calls) ignore it; paying from a preview page works normally and ends on the receipt rather than auto-redirecting.
1. Ask: 402 Payment Required
GET /abc123 HTTP/1.1
Host: <host of https://urlgate.xyz>
Accept: application/json
HTTP/1.1 402 Payment Required
PAYMENT-REQUIRED: eyJ4NDAyVmVyc2lvbiI6Mi… base64 JSON (x402 v2), below
X-Payment-Required: true
The body is the legacy x402 v1 challenge (x402Version: 1, accepts[0] with network: "base", asset: "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", maxAmountRequired = the full price in base units, payTo = the creator), plus a promo object when a promo code was sent. Use the header. Decoded PAYMENT-REQUIRED for a link priced 1 USDC with a 0.3% platform fee:
{
"x402Version": 2,
"error": "Payment required",
"resource": {
"url": "https://urlgate.xyz/abc123",
"description": "Access to shortened URL abc123 (1.000000 USDC: 0.997000 to creator + 0.003000 platform fee)",
"mimeType": "text/html"
},
"accepts": [{
"scheme": "exact",
"network": "eip155:8453",
"amount": "997000",
"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"payTo": "0xCreatorWallet…",
"maxTimeoutSeconds": 60,
"extra": { "name": "<USDC EIP-712 name>", "version": "<USDC EIP-712 version>" }
}],
"extensions": {
"sign-in-with-x": {
"info": { "domain": "…", "uri": "https://urlgate.xyz/abc123", "statement": "Sign in to URLGate to re-open a link you already paid for", "version": "1",
"nonce": "…(server-issued, single use)", "issuedAt": "…", "expirationTime": "…(+5 min)", "resources": ["https://urlgate.xyz/abc123"] },
"supportedChains": [{ "chainId": "eip155:8453", "type": "eip191" }],
"schema": { … }
},
"platform-fee": {
"info": {
"percent": 0.3, "amount": "0.003000", "listPrice": "1.000000", "creatorAmount": "0.997000",
"payTo": "0xServiceWallet…", "header": "PAYMENT-SIGNATURE-FEE",
"description": "Platform fee (0.3% of list price)"
},
"accepts": [{ "scheme": "exact", "network": "eip155:8453", "amount": "3000",
"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "payTo": "0xServiceWallet…",
"maxTimeoutSeconds": 60, "extra": { … } }]
}
}
}
2. Pay: two legs, one request
An x402 exact authorization has a single recipient, so the price is split into two EIP-3009 TransferWithAuthorization signatures, both from the same wallet and both sent on the same retry:
| Header | Leg | Sign against |
|---|---|---|
PAYMENT-SIGNATURE | Creator share (leg: "creator") | One entry of accepts[] |
PAYMENT-SIGNATURE-FEE | Platform fee (leg: "platform-fee") | The entry of extensions["platform-fee"].accepts[] on the same network |
Each header is base64(JSON) of an x402 v2 payment payload:
{
"x402Version": 2,
"resource": { … }, optional: copy of the 402's resource
"accepted": { …the accepts[] entry, unchanged… },
"payload": {
"signature": "0x…", EIP-712 signature, domain = extra.name / extra.version / chainId / asset
"authorization": {
"from": "0xBuyer…", "to": "<accepted.payTo>", "value": "<accepted.amount>",
"validAfter": "1791979195", "validBefore": "1791979255", "nonce": "0x<32 random bytes>"
}
}
}
acceptedmust match one offered entry exactly (scheme, network, asset, payTo, amount), otherwiserequirement_mismatch.- The authorization must already be valid and may not outlive the offer:
validBeforeat mostmaxTimeoutSeconds(60 s) from now, with 30 s of clock-skew tolerance. - Both legs are verified (signature, balance, on-chain simulation) before either is settled, and the payer's USDC balance must cover both (else
402insufficient_funds,charged: false, withneededandbalance; nothing settled). The fee leg settles first, then the creator leg. - Partial payments. Two EIP-3009 transfers can't settle atomically (only a batching contract could), so one leg can still settle while the other fails. Then that wallet has an open partial payment for the link, and every later request for it from that wallet (payment header payer, session cookie, Bearer or
SIGN-IN-WITH-X) gets a402withcode: "partial_payment"andpartial: { paid: { leg, amount, tx, txUrl, network }, owed: { leg, amount }, total, feePercent, expiresAt }in the body and inPAYMENT-REQUIRED, whoseaccepts[]holds only the owed leg (to the creator, or to URLGate when the fee is owed; noplatform-feeextension). Send that one signature alone:PAYMENT-SIGNATUREwhen the creator leg is owed;PAYMENT-SIGNATURE-FEE(orPAYMENT-SIGNATURE) when the fee is owed. The settled leg is never charged again; a second copy of it in the request is ignored. The owed amount is locked when the first leg settles: a promo code sent later is echoed (promo.appliesToPartial: false) but changes nothing.409partial_in_progress: an earlier owed-leg payment may still land; wait until the time given and retry. - Missing fee leg:
402withcode: "fee_leg_missing",missing: ["platform-fee"],charged: falseandhowToFixsteps. It is refused before either leg is verified, reserved or settled, so nothing is charged and the same main-leg signature can be resent with the fee leg. Legs from different wallets:402payer_mismatch. - When the fee rounds to zero (only possible on old links priced below the 0.01 minimum), there is no
platform-feeextension and a singlePAYMENT-SIGNATUREsuffices. - A v2 payload is also accepted in
X-PAYMENTinstead ofPAYMENT-SIGNATURE.
Worked example: two signatures, one request
A 0.05 USDC link at the 0.3% fee: the main leg is 49850 units to the creator, the fee leg 150 units to URLGate. Sign each with the same wallet (two nonces), then send both at once.
- Read
accepts[i](main) and theextensions["platform-fee"].accepts[]entry with the samenetwork(fee) from the 402. - Sign EIP-3009
TransferWithAuthorizationfor each:to= that entry'spayTo,value= itsamount. - HTTP: retry with
PAYMENT-SIGNATURE: base64(main payload)andPAYMENT-SIGNATURE-FEE: base64(fee payload). MCP: put the two payload objects in_meta, as below. - Only one leg sent? You get
fee_leg_missingand are not charged; add the fee leg and retry.
{ "jsonrpc": "2.0", "id": 7, "method": "tools/call",
"params": { "name": "open_link", "arguments": { "code": "Gp1qJx" },
"_meta": {
"x402/payment": { "x402Version": 2, "accepted": { …accepts[i]… }, "payload": { "signature": "0x…", "authorization": { "to": "0xCreator…", "value": "49850", "nonce": "0xN1…", … } } },
"x402/payment-fee": { "x402Version": 2, "accepted": { …extensions["platform-fee"].accepts[i]… }, "payload": { "signature": "0x…", "authorization": { "to": "0xURLGate…", "value": "150", "nonce": "0xN2…", … } } }
} } }
→ result: { structuredContent: { status: 200, data: { destination, … } }, _meta: { "x402/payment-response": { success, transaction, network, payer } } }
3. Receive: 200 + PAYMENT-RESPONSE
HTTP/1.1 200 OK
PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVl… base64 JSON: success, transaction, network, payer, paidAt, receiptUrl
Cache-Control: private, no-store
{
"success": true,
"message": "Payment settled",
"destination": "https://example.com/report.pdf",
"transaction": "0x…",
"txUrl": "https://…/tx/0x…",
"network": "eip155:8453",
"fee": { "amount": "0.003000", "payTo": "0xServiceWallet…", "percent": 0.3, "transaction": "0x…", "txUrl": "…" },
"creatorAmount": "0.997000",
"paidAt": "2026-10-14T12:00:05.000Z",
"receipt": { "id": "…", "url": "https://urlgate.xyz/r/…" },
"afterPay": "receipt",
"accessExpiresAt": null,
"receiptMessage": null,
"title": "Q3 report"
}
fee.reused: true marks a fee carried over from an earlier failed attempt. accessExpiresAt is set when the link sells time-limited passes.
Payment failures
A rejected payment returns a fresh PAYMENT-REQUIRED header and:
{ "error": "Invalid Payment", "code": "insufficient_funds", "leg": "creator", "message": "Your wallet doesn't have enough USDC on …" }
Status is 402, 409 (already_redeemed) or 502 (facilitator_unavailable). When the failure was upstream (URLGate's settler, the RPC or the network) rather than the buyer's, the body adds retryable: true and retryMessage: the failed leg moved nothing, so sign that leg again. If only the creator leg failed after the fee settled, feeCharged describes the fee that moved (amount, transaction, txUrl, reusedOnRetry: true). On settlement_unconfirmed do not pay again: re-open the link signed in a minute later. All codes are listed under Errors.
Promo codes and allowlists
Add ?promo=CODE or X-Promo-Code: CODE. A discount lowers the amounts in the 402; a 100% free pass needs a signed-in wallet (it owns the unlock). Signed-in wallets on a link's allowlist open it free. Free unlocks answer 200 with via: "promo" | "allowlist", amount: "0.000000" and a receipt. In a browser they follow the link's afterPay like a paid unlock: receipt (default) is a 302 to the receipt page /r/{id}, whose Continue button opens the link; redirect goes straight to the destination.
Legacy v1 transaction hash
Older clients may pay with an on-chain USDC transfer to the creator and send its hash as Authorization: x402 <txhash> (or in X-PAYMENT, ?paymentProof=, ?proof=). This is accepted only when:
- the link charges no platform fee: a single transfer cannot pay two recipients, so with a fee configured the answer is
402asking forPAYMENT-SIGNATURE+PAYMENT-SIGNATURE-FEE; - the request is signed in (Bearer or cookie) as the wallet that sent the transfer, otherwise
401sign_in_requiredor403payer_mismatch; - the transfer is on Base, recent (about one hour of blocks by default), pays at least the price to the creator, and has not been used before (
403).
Receipts and re-opening
Re-open without paying again: request the link signed in as the buying wallet (Bearer, cookie, or a SIGN-IN-WITH-X header signed over this link's challenge). You get 200 { success, message, destination, alreadyPaid: true, isCreator: false }; the creator gets isCreator: true. Time-limited passes stop re-opening once accessExpiresAt passes. Paused, expired and sold-out links still re-open for earlier buyers; removed links do not.
| Method | Path | Notes |
|---|---|---|
GET | /api/v2/receipts/{id} | Public to anyone holding the id, never shows the destination. Link receipts: { receiptId, kind: "link_access", url, paidAt, currency, amount, listPrice, fee, creatorAmount, network, networkLabel, tx, txUrl, feeTx, feeTxUrl, payer, seller, via, x402Version, access, accessExpiresAt, link, continueUrl, afterPay, receiptMessage }. Membership receipts: kind: "membership" with periodStart / periodEnd. 404 if unknown. |
GET | /r/{id} | Human receipt page (HTML, noindex). |
GET | /api/v2/me/unlocks | Signed in. Links you paid for, newest first: { wallet, count, unlocks: [{ shortcode, title, url, access: "open" | "expired" | "unavailable", available, openUrl, linkStatus, reason, reasonLabel, note, message, paidAt, amount, listPrice, fee, network, networkLabel, tx, txUrl, feeTx, feeTxUrl, via, receipt, accessExpiresAt, destinationChangedAfterPurchase, purchases }] }. Filter ?access=open; ?format=csv for CSV. |
My links, analytics and CSV
All of these need a signed-in wallet; the /links/{code}/… routes also need it to be the link's creator (401 / 403 / 404 otherwise).
| Method | Path | Notes |
|---|---|---|
GET | /api/v2/me/links | { wallet, tier, links: [{ shortcode, shortUrl, destinationUrl, price, title, description, active, status, linkStatus, reasonLabel, statusReason, statusChangedAt, clicks, views402, sales, freeUnlocks, uniquePayers, gross, platformFees, earned, conversion, failedPayments, payerKinds: { agent, human, unknown }, lastSaleAt, abuseReports, createdVia, createdAt, updatedAt, options }] }. Sales, gross, unique payers, last sale and the agent / human split count paid (x402) unlocks; free unlocks are separate; abuseReports is a count only. ?format=csv (premium) columns: shortcode, shortUrl, destinationUrl, title, description, price, status, statusReason, statusChangedAt, afterPay, expiresAt, maxUses, accessTtlSeconds, networks (space-separated, all = every enabled network), clicks, views402, sales, freeUnlocks, uniquePayers, gross, platformFees, earned, conversion, failedPayments, agentSales, humanSales, unknownSales, lastSaleAt, abuseReports, createdVia, createdAt, updatedAt. Cells that start with =, +, -, @, tab or CR are prefixed with ' so spreadsheets don't run them as formulas (every CSV export does this). |
GET | /api/v2/me/analytics | Totals and daily series across your links: { wallet, range, totals, series, tier }. |
GET | /api/v2/links/{code} | Owner view: { link: { shortcode, shortUrl, destinationUrl, price, title, description, status, options, createdVia, createdAt, updatedAt, destinationChangedAt, qrUrl }, entitlements: { tier, features } }. |
GET | /api/v2/links/{code}/analytics | { link, range, totals, series, advanced, tier }: 402 views, sales, conversion, earnings and the agent / human split (totals.payerKinds). advanced (referrers, countries, buyers) is premium (null without it; free wallets never receive breakdown data). Rate-limited. |
GET | /api/v2/links/{code}/payments | { shortcode, count, payments: [{ paidAt, buyer, amount, listPrice, fee, earned, network, tx, txUrl, feeTx, via, accessExpiresAt, receiptId, payerKind }] } (latest 200). ?payerKind=agent|human|unknown; ?format=csv (premium, all rows). |
GET | /api/v2/links/{code}/audit | Audit trail with truncated IPs: { shortcode, entries, nextCursor }. ?type=, ?from=, ?to=, ?cursor=, ?limit= (max 1000); ?format=csv (premium). |
GET | /api/v2/links/{code}/qr.svg | Public. QR code of the short URL (SVG). Rate-limited. |
range is 24h, 7d or 30d (default); 90d and all are premium. Analytics days are America/Los_Angeles calendar days. CSV responses are text/csv attachments; without premium, CSV requests answer 403 premium_required (except My unlocks).
Manage links
Edit: PATCH /api/v2/links/{code}
Send only the fields to change; null clears an option. Response: { success, changed, link }.
| Field | Notes |
|---|---|
price | Same rules as creation (minimum 0.01). A link already priced below the minimum may re-send its current price. |
title, description | Up to 120 / 500 characters. |
afterPay | receipt or redirect. |
networks | Array (or comma list) of enabled CAIP-2 ids, at least one; null = all enabled networks. []: 400 networks_required; an id that is not enabled: 400 network_unavailable. |
receiptMessage | Premium (receipt_branding). Up to 280 characters, shown on the receipt. |
expiresAt | Premium (link_expiry). Future ISO date; sales stop afterwards. |
maxUses | Premium (max_uses). Whole number ≥ 1; sales stop when reached. |
accessTtlSeconds | Premium (timed_pass). 3600 to 31622400 (366 days); null or 0 = forever. |
destinationUrl | Free until the first sale. After it: 409 destination_locked, unless you have a real Premium membership (edit_after_sale); buyers then see "destination changed after your purchase". |
Pause, resume, remove, restore
| Method | Path | Effect |
|---|---|---|
POST | /api/v2/links/{code}/pause | Stops new sales; earlier buyers keep access. Optional body { "note": "…" } shown to buyers. |
POST | /api/v2/links/{code}/resume | Back to active. |
POST | /api/v2/links/{code}/remove | Removed by seller: nobody can buy or re-open. Optional { "note" }. |
POST | /api/v2/links/{code}/restore | Undo a seller removal. |
Responses: { success, …status } (the status object below). An impossible transition is 409; a link removed by URLGate cannot be edited or restored by its owner (403).
Allowlist and promo codes (premium)
| Method | Path | Notes |
|---|---|---|
GET | /api/v2/links/{code}/grants | { shortcode, grants }. |
POST | /api/v2/links/{code}/grants | { "kind": "wallet", "wallet": "0x…" } (allowlist) or { "kind": "promo", "code": "SPRING", "discountPct": 100 } (promo_codes; code 3-32 of letters, digits, _ or -; discountPct 1-100, default 100). Optional maxRedemptions, expiresAt, note. → 201 { success, grant }, promo grants add shareUrl. |
DELETE | /api/v2/links/{code}/grants/{id} | Revoke a grant. |
Report a link
No sign-in needed. Humans can use /report.html; MCP: report_link.
| Method | Path | Body / result |
|---|---|---|
POST | /api/v2/links/{code}/report | { "reason": "scam_phishing" | "malware" | "illegal" | "dmca" | "spam" | "child_sexual_exploitation" | "other", "details": "…" }, optional email, wallet (0x…). details at most 2000 characters. → 202 { success, reportId, message }. child_sexual_exploitation takes the link offline at once pending review (per-reporter limits apply), preserves the records and queues the case for a report to NCMEC; it is accepted for a link URLGate already removed. The older reasons phishing_malware, legal, tos_violation are still accepted. |
POST | /api/v2/reports | Same, with "link": the short code or the full URL (https://urlgate.xyz/abc123). |
GET | /api/v2/reports/form-token | Browsers only: { token, minFillMs, expiresInMs }, same-origin (no CORS). A report sent from a browser (any Origin header) must include it as formToken, at least 3 seconds after it was issued. |
Errors: 400 (invalid_reason, invalid_field, invalid_link, form_too_fast, form_token_invalid, form_expired, form_rejected), 403 cross_origin, 404, 409 already_reported (one report per reporter per link while it is open, and at least 24 h apart; includes reportId) or 409 link_removed, 429 (10 reports per minute per IP). Your IP address, email and contact wallet are deleted after 30 days; see Privacy.
Link status and 410 Gone
| Method | Path | Notes |
|---|---|---|
GET | /api/v2/links/{code}/status | Public. The status object plus price. Check this before paying. |
GET | /api/urlgate/{code}/info | Public metadata, never the destination: { shortcode, price, totalClicks, active, createdAt, title, description, options: { afterPay, accessTtlSeconds, access, expiresAt, maxUses, networks, activeNetworks, networksFallback, networksNotice }, status }. networks is the creator's choice (null = all), activeNetworks where it sells right now. |
status | New sales | Earlier buyers |
|---|---|---|
| active | yes | re-open |
| paused | no | re-open |
| expired | no (expiresAt passed) | re-open |
| sold_out | no (maxUses reached) | re-open |
| removed_by_seller | no | no |
| removed_by_admin | no | no |
When a link cannot be opened by the caller, GET /{code} answers 410 (an HTML status page for browsers):
{
"error": "Link Disabled",
"message": "URLGate removed this link. It can no longer be opened or bought.",
"shortcode": "abc123",
"title": "Q3 report",
"status": "removed_by_admin",
"linkStatus": "removed_by_admin",
"available": false,
"reopenable": false,
"reason": "phishing_malware",
"reasonLabel": "Phishing or malware",
"note": null,
"changedAt": "2026-10-14T12:00:00.000Z",
"expiresAt": null,
"retryable": false
}
status is the buyer-facing state (including expired / sold_out), linkStatus the stored one. reason is seller_removed for seller removals and one of dmca, legal, phishing_malware, tos_violation, other for URLGate takedowns. retryable is true only for paused. Unknown codes answer 404 { "error": "Not Found", "message": "Short link not found" }.
Errors
Errors are JSON: { "error": "<short title>", "message": "<sentence>" }, plus a machine-readable code where one applies. Branch on the status and code, not on the message text.
| Status | error / code | When |
|---|---|---|
| 400 | Invalid URL, Invalid Price (invalid_price, below_min_price), Invalid Wallet, Invalid Shortcode, Bad Request | Validation failed. |
| 401 | Unauthorized (sign_in_required) | No valid session / Bearer / SIWX, or a SIWE verify failure. siwx_not_allowed: a SIGN-IN-WITH-X header on a route that changes an account (sign in with SIWE and send the Bearer token). siwx_invalid: the header was rejected (the message says why). |
| 402 | Payment Required (fee_leg_missing) | Pay first; see the PAYMENT-REQUIRED header. |
| 402 / 403 / 409 / 502 | Invalid Payment + payment code below | The payment was refused; leg names the failed leg. |
| 403 | Forbidden (wallet_banned), Premium Required (premium_required), Creator Mismatch | Not your link, suspended wallet, premium-only option, or a wallet you have not proven. |
| 404 | Not Found | Unknown link, receipt or grant. |
| 409 | Shortcode Taken (shortcode_lookalike), Conflict (destination_locked), Payment Already Used, Link Unavailable | Code in use, destination locked after a sale, proof replayed, status change not allowed, or a stored price that cannot be paid. |
| 410 | Link Disabled | Paused / expired / sold out (for new buyers) or removed. |
| 429 | Too Many Requests | Rate limit. |
| 500 | Internal Server Error | Unexpected failure. |
| 503 | Service Unavailable | The platform-fee or membership recipient is not configured. |
Payment codes
code | Meaning | Retry? |
|---|---|---|
insufficient_funds | Not enough USDC on the chosen network. Before settling, the balance must cover both legs together: then charged: false, needed: { total, creator, fee }, balance, nothing settled. | After funding |
partial_payment | One leg of your earlier payment settled; partial says what was paid and what is owed, and accepts[] offers only the owed leg (partial payments). | Pay the owed leg only |
partial_in_progress | (409) An earlier payment of the owed leg may still land. | Later, not twice |
authorization_expired, authorization_not_yet_valid, authorization_too_long, authorization_malformed | EIP-3009 validity window wrong (check your clock; at most 60 s). | Sign again |
authorization_used | That authorization nonce was already used. | New signature |
invalid_signature | Signature does not verify. | Sign again |
wrong_amount, wrong_recipient, wrong_network, requirement_mismatch | The signed payment differs from the offer (re-read the 402). | Sign again |
payer_mismatch | Legs signed by different wallets, or a tx hash not sent by your signed-in wallet. | No |
fee_leg_missing | Only the main leg was sent: PAYMENT-SIGNATURE-FEE (MCP _meta["x402/payment-fee"] / paymentSignatureFee) is missing. Refused before anything was verified or settled; nothing was charged. The body has missing and howToFix. | Add the fee leg (same main leg is fine) |
compat_signature | The authorization was first sent to payment_compat_check; such signatures can never pay for anything. | New signature |
already_redeemed | Payment already used (409). Sign in as the payer to re-open. | No |
settlement_unconfirmed | May have gone through; not confirmed yet. | Do not pay again |
facilitator_unavailable, payment_failed | Upstream failure; nothing was charged for the failed leg (retryable: true). | Yes |
tx_not_found, tx_failed, no_matching_transfer, proof_too_old, invalid_proof, rpc_unavailable | Legacy tx-hash proofs only. | Depends |
Rate limits
Limits are per client IP and per bucket, enforced at each Cloudflare location (by default 100 requests per minute). Exceeding one returns 429 { "error": "Too Many Requests", "message": "…" }; back off and retry.
- Link creation:
/api/urlgate/createand/api/urlgate/agent/createshare one bucket. - SIGN-IN-WITH-X verification.
- Per-link analytics and QR codes.
- Payment compatibility check (
/api/v2/payments/compat-check, MCPpayment_compat_check): 10 per minute per IP, no Premium allowance. - Reports (
POST /api/v2/links/{code}/report,POST /api/v2/reports): a stricter 10 per minute per IP with no Premium allowance, plus one report per reporter per link (while it is open, and 24 h apart).
Premium members get a larger per-wallet allowance (by default 1000 per minute) once the per-IP budget is spent, on every bucket except SIWX verification; send your Bearer token or SIWX header so it applies.
Payment compatibility check (free, verify-only)
Check that your x402 client can sign URLGate's two-leg payment before you spend anything: POST https://urlgate.xyz/api/v2/payments/compat-check (also GET) or the MCP tool payment_compat_check. Nothing is ever settled or broadcast.
- Call it without payment:
402with a two-legPAYMENT-REQUIREDon this deployment's networks (testnet on preview, mainnet on production), tiny amounts (0.001 USDC split like a paid open) and a 30 svalidBefore. - Sign both legs with the same wallet and call again with
PAYMENT-SIGNATURE+PAYMENT-SIGNATURE-FEE(MCP:_meta["x402/payment"]+_meta["x402/payment-fee"]). - Both legs are verified (never settled) and you get
200 { verdict, ok, legs: { main, fee }, nextSteps }. Verdicts:ok,fee_leg_missing,main_leg_missing,wrong_network,bad_signature,amount_mismatch, plusrequirement_mismatch,payer_mismatch,expired,insufficient_funds,facilitator_unavailable.
Signatures sent to the check are recorded and can never pay for anything (a real paid route answers compat_signature); sign new ones for the real call. Rate limit: a few calls a minute per IP (429).
The preview testnet test link REQUIRES a wallet with Base Sepolia testnet + test USDC. If your wallet can't use testnet, follow the production path: run payment_compat_check on production (verify-only, no funds move) and, if you meet the two-signature requirements, proceed with the real paid tools.
Testnet path
- Use a wallet on Base Sepolia (eip155:84532) holding test USDC (e.g. faucet.circle.com). Only signatures are needed, no gas.
- Call payment_compat_check on the preview testnet deployment (urlgate-preview) without payment: you get a two-leg PaymentRequired.
- Sign BOTH legs (an accepts[] entry + the extensions["platform-fee"].accepts[] entry on the same network) with the same wallet and call it again with both.
- verdict "ok" = your client can pay URLGate. Nothing is ever settled.
Production path
- Call payment_compat_check on production (https://urlgate.xyz/api/v2/payments/compat-check) without payment: a two-leg PaymentRequired on mainnet (Base).
- Sign BOTH legs and call it again with both signatures. Verify-only: no funds move (the wallet only needs to hold the 0.001 USDC test amount for verification).
- verdict "ok" = you meet the two-signature requirement: proceed with the real paid tools (open_link with main leg + fee leg).
- Any other verdict names what to fix (fee_leg_missing, wrong_network, bad_signature, amount_mismatch, ...); fix it and re-run the check before paying.
MCP and agent discovery
Start with the free get_started tool (alias pricing_and_limits) or /agents (?format=json): the three ways to create links, your quota and next steps.
MCP server
POST https://urlgate.xyz/mcp: MCP Streamable HTTP, stateless JSON-RPC (initialize, ping, tools/list, tools/call; batches of up to 20). No SSE (GET /mcp is 405). Every web-app feature is a tool that runs the same REST route in-process.
- Auth:
Authorization: Beareron the MCP request, or atokenargument on each tool call (SIGN-IN-WITH-Xon the MCP request, signed forhttps://urlgate.xyz/mcpor the link URL, only servesopen_linkand the low-sensitivity read tools (whoami, my_points, points_leaderboard_me, membership_status, my_preferences), once per request). Cookies are never used. Get a token with thesign_intool. - Paid tools (
open_link,create_link,buy_membership) follow the x402 MCP transport: the first call returns a tool result withisError: truewhosestructuredContentis the x402 v2PaymentRequired(the same object as JSON incontent[0].text;content[1].texthas the next steps). Retry with the signedPaymentPayloadinparams._meta["x402/payment"](fallback: thepaymentSignatureargument, base64). The settlement comes back inresult._meta["x402/payment-response"]. Payment errors are the sameisErrorresult witherror: "<code>: <message>"and the details inresult._meta["urlgate/payment-error"]. open_linkneeds TWO signatures (see Two legs): the main leg in_meta["x402/payment"]and the platform-fee leg in_meta["x402/payment-fee"](or the argumentspaymentSignature+paymentSignatureFee).create_linkandbuy_membershiptake one.- Before paying: run the free, verify-only
payment_compat_checktool to confirm your client signs both legs correctly. The preview testnet test link REQUIRES a wallet with Base Sepolia testnet + test USDC. - Tools:
open_link,get_link_info,link_status,report_link,my_unlocks,get_receipt,create_link,my_links,get_my_link,update_link,set_link_status,link_analytics,my_analytics,link_payments,link_audit,link_grants,link_qr,membership_status,buy_membership,redeem_premium_code,dismiss_renewal_reminder,my_points,set_points_prefs,points_leaderboard,points_leaderboard_me,points_rules,verify_ledger,sign_in,whoami,sessions,my_preferences,list_networks,open_link_instructions. Schemas:tools/listor /mcp/server-card.
Discovery documents
| Path | What |
|---|---|
/openapi.json | OpenAPI 3.1, every endpoint with x-payment-info and its x-mcp-tool. |
/llms.txt | Short agent-oriented summary. |
/skills/urlgate/SKILL.md | Agent skill: step-by-step pay, create, sign in. |
/.well-known/agent-skills/index.json | Agent Skills index with the SKILL.md digest. |
/.well-known/x402 | x402 resources (agent create, membership purchase). |
/.well-known/api-catalog | RFC 9727 linkset (service-desc, service-doc, status). |
/.well-known/mcp/catalog.json | MCP catalog pointing at /mcp and its server card. |
/mcp/server-card | MCP server info, transport and tools. |
/api/urlgate | Legacy x402 v1 service descriptor (x402scan). |
/health | { status: "ok", service, runtime, timestamp }. |
The homepage also sends RFC 8288 Link headers to the api-catalog, openapi.json and llms.txt. Sales are tagged payerKind agent / human / unknown for creators; to be counted as a verified agent, include an ERC-8004 identity in the payment payload's extensions["8004-reputation"] (details in SKILL.md).
Examples
curl
# Public metadata and status (never the destination)
curl -s https://urlgate.xyz/api/urlgate/abc123/info
curl -s https://urlgate.xyz/api/v2/links/abc123/status
# The 402 challenge: decode the PAYMENT-REQUIRED header
curl -s -o /dev/null -D - -H 'Accept: application/json' https://urlgate.xyz/abc123 \
| grep -i '^payment-required:' | cut -d' ' -f2 | tr -d '\r' | base64 -d | jq
# Sign in (SIWE): get a message, sign it with your wallet, exchange it for a token
curl -s 'https://urlgate.xyz/api/v2/auth/nonce?address=0xYourWallet' | jq -r .message > siwe.txt
# …sign siwe.txt (EIP-191 personal_sign) → $SIG
TOKEN=$(jq -n --rawfile m siwe.txt --arg s "$SIG" '{message:$m, signature:$s, kind:"agent"}' \
| curl -s -X POST https://urlgate.xyz/api/v2/auth/verify -H 'Content-Type: application/json' -d @- | jq -r .token)
# Create a link as the signed-in wallet: free within your daily quota (10/day);
# over quota it answers 402 with the creation fee (0.01 USDC) and nextSteps.
# (https://urlgate.xyz/api/urlgate/create follows the same rules for API callers.)
curl -s -i -X POST https://urlgate.xyz/api/urlgate/agent/create \
-H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-d '{"url":"https://example.com/report.pdf","price":"0.05","title":"Q3 report"}'
# Anonymous: the first call answers 402 with the creation fee (0.01 USDC)
curl -s -i -X POST https://urlgate.xyz/api/urlgate/agent/create \
-H 'Content-Type: application/json' -d '{"url":"https://example.com/report.pdf","price":"0.05"}'
# With an agent key from a human's dashboard (links belong to the key owner)
curl -s -X POST https://urlgate.xyz/api/urlgate/agent/create -H "Authorization: Bearer $UGK" \
-H 'Content-Type: application/json' -d '{"url":"https://example.com/report.pdf","price":"0.05"}'
# Your quota, tier and next steps
curl -s -H "Authorization: Bearer $TOKEN" https://urlgate.xyz/api/v2/agents/get-started
# Re-open a link you already bought (no payment)
curl -s -H 'Accept: application/json' -H "Authorization: Bearer $TOKEN" https://urlgate.xyz/abc123
# Manage: my links, edit, pause, sales CSV (premium)
curl -s -H "Authorization: Bearer $TOKEN" https://urlgate.xyz/api/v2/me/links
curl -s -X PATCH https://urlgate.xyz/api/v2/links/abc123 -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"price":"0.10","afterPay":"redirect"}'
curl -s -X POST https://urlgate.xyz/api/v2/links/abc123/pause -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"note":"Back next week"}'
curl -s -H "Authorization: Bearer $TOKEN" 'https://urlgate.xyz/api/v2/links/abc123/payments?format=csv' -o sales.csv
# Sign out everywhere
curl -s -X POST https://urlgate.xyz/api/v2/auth/revoke -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"scope":"all"}'
JavaScript (fetch + viem): pay for and open a link
import { privateKeyToAccount } from 'viem/accounts';
const BASE = 'https://urlgate.xyz';
const account = privateKeyToAccount(process.env.PRIVATE_KEY);
const b64 = (o) => btoa(JSON.stringify(o));
const unb64 = (s) => JSON.parse(atob(s));
const nonce32 = () => '0x' + [...crypto.getRandomValues(new Uint8Array(32))].map((b) => b.toString(16).padStart(2, '0')).join('');
// One x402 v2 "exact" payment: an EIP-3009 TransferWithAuthorization for one accepts[] entry.
async function signLeg(req, resource) {
const now = Math.floor(Date.now() / 1000);
const authorization = {
from: account.address,
to: req.payTo,
value: req.amount,
validAfter: String(now - 5),
validBefore: String(now + 55), // must not outlive maxTimeoutSeconds (60)
nonce: nonce32(),
};
const signature = await account.signTypedData({
domain: { name: req.extra.name, version: req.extra.version, chainId: Number(req.network.split(':')[1]), verifyingContract: req.asset },
types: {
TransferWithAuthorization: [
{ name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'value', type: 'uint256' },
{ name: 'validAfter', type: 'uint256' }, { name: 'validBefore', type: 'uint256' }, { name: 'nonce', type: 'bytes32' },
],
},
primaryType: 'TransferWithAuthorization',
message: { ...authorization, value: BigInt(authorization.value), validAfter: BigInt(authorization.validAfter), validBefore: BigInt(authorization.validBefore) },
});
return b64({ x402Version: 2, resource, accepted: req, payload: { signature, authorization } });
}
export async function openLink(code) {
const url = `${BASE}/${code}`;
const first = await fetch(url, { headers: { Accept: 'application/json' } });
if (first.status !== 402) return first.json(); // 200 (already paid), 404, 410 …
const pr = unb64(first.headers.get('PAYMENT-REQUIRED'));
const req = pr.accepts.find((a) => a.network === 'eip155:8453') ?? pr.accepts[0];
const headers = { Accept: 'application/json', 'PAYMENT-SIGNATURE': await signLeg(req, pr.resource) };
const fee = pr.extensions?.['platform-fee'];
if (fee) {
const feeReq = fee.accepts.find((a) => a.network === req.network);
headers['PAYMENT-SIGNATURE-FEE'] = await signLeg(feeReq, pr.resource);
}
const res = await fetch(url, { headers });
const body = await res.json();
if (!res.ok) throw new Error(`${res.status} ${body.code ?? ''} ${body.leg ?? ''}: ${body.message}`);
return { destination: body.destination, receipt: body.receipt?.url, settlement: unb64(res.headers.get('PAYMENT-RESPONSE')) };
}
JavaScript: sign in, then use the token
export async function signIn() {
const n = await (await fetch(`${BASE}/api/v2/auth/nonce?address=${account.address}`)).json();
const signature = await account.signMessage({ message: n.message });
const res = await fetch(`${BASE}/api/v2/auth/verify`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: n.message, signature, kind: 'agent' }),
});
const { token } = await res.json(); // valid 24 h
return token;
}
const token = await signIn();
const auth = { Authorization: `Bearer ${token}` };
const created = await (await fetch(`${BASE}/api/urlgate/create`, {
method: 'POST',
headers: { ...auth, 'Content-Type': 'application/json' },
body: JSON.stringify({ url: 'https://example.com/report.pdf', price: '0.05', title: 'Q3 report' }),
})).json();
const { links } = await (await fetch(`${BASE}/api/v2/me/links`, { headers: auth })).json();
JavaScript: SIGN-IN-WITH-X to re-open a link
import { createSiweMessage } from 'viem/siwe';
// A server challenge for exactly the URL you will request (or read it from the 402's extensions["sign-in-with-x"].info).
async function siwxHeader(resource) {
const { info } = await (await fetch(`${BASE}/api/v2/auth/siwx/challenge?resource=${encodeURIComponent(resource)}`)).json();
const p = { ...info, address: account.address, chainId: 'eip155:8453', type: 'eip191' };
const message = createSiweMessage({
address: p.address, chainId: 8453, domain: p.domain, nonce: p.nonce, uri: p.uri, version: p.version,
statement: p.statement, issuedAt: new Date(p.issuedAt), expirationTime: new Date(p.expirationTime), resources: p.resources,
});
return b64({ ...p, signature: await account.signMessage({ message }) });
}
// One header per request, for that URL only (each nonce works once): re-open a link you bought.
const again = await fetch(`${BASE}/abc123`, { headers: { Accept: 'application/json', 'SIGN-IN-WITH-X': await siwxHeader(`${BASE}/abc123`) } });
// Changing anything (agent keys, links, prices) needs the Bearer token from /api/v2/auth/verify instead.
Legacy v1 endpoints
Kept for existing integrations; new code should use the /api/v2 routes above. Wallet-scoped routes need the same sign-in (Bearer or cookie; never SIWX); the old X-Wallet-* signature headers are refused with 401.
| Method | Path | Notes |
|---|---|---|
GET | /api/urlgate/{code} | Same as GET /{code}. |
PUT | /api/urlgate/{code}/destination | { "newDestination": "https://…" }, creator only; locked after the first sale (409 destination_locked) unless premium. |
POST | /api/urlgate/{code}/update-price | { "price": "0.10" }, creator only. |
POST | /api/urlgate/{code}/deactivate, …/reactivate | Pause / resume, creator only. |
GET | /api/urlgate/{code}/payments, …/changelog | Creator only. |
GET | /api/urlgate/creator/{wallet}/stats, …/links | Only for the signed-in wallet itself. |
GET | /api/urlgate/history/{wallet} | Payments by a wallet (?page, ?limit ≤ 100, ?search). Destinations and proofs only for the signed-in owner; everyone else gets redacted: true. |
GET | /api/urlgate/profile/{wallet} | Creator stats and links, redacted the same way. |