@paymos/mcp 1.5.1 → 1.6.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/dist/index.js CHANGED
@@ -1,10 +1,41 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { realpathSync } from "fs";
4
+ import { realpathSync as realpathSync3 } from "fs";
5
5
  import { pathToFileURL } from "url";
6
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
7
 
8
+ // src/auth.ts
9
+ import { spawn } from "child_process";
10
+ import { accessSync, constants as constants3, lstatSync as lstatSync4, realpathSync } from "fs";
11
+ import { homedir as homedir2 } from "os";
12
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join2, parse, relative, resolve as resolve2, sep } from "path";
13
+
14
+ // src/setup.ts
15
+ import {
16
+ chmodSync,
17
+ closeSync as closeSync3,
18
+ constants as constants2,
19
+ existsSync,
20
+ fstatSync as fstatSync3,
21
+ linkSync,
22
+ lstatSync as lstatSync3,
23
+ mkdirSync as mkdirSync2,
24
+ openSync as openSync3,
25
+ readFileSync as readFileSync2,
26
+ renameSync,
27
+ unlinkSync as unlinkSync2,
28
+ writeFileSync
29
+ } from "fs";
30
+ import { randomUUID } from "crypto";
31
+ import { homedir } from "os";
32
+ import { dirname as dirname2, isAbsolute, join, resolve } from "path";
33
+ import { createInterface } from "readline";
34
+ import { Writable } from "stream";
35
+ import { isDeepStrictEqual } from "util";
36
+ import { applyEdits, modify, parse as parseJson, parseTree } from "jsonc-parser";
37
+ import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
38
+
8
39
  // src/credential-file.ts
9
40
  import { constants, closeSync, fstatSync, lstatSync, openSync, readFileSync } from "fs";
10
41
 
@@ -62,6 +93,20 @@ Restart or reconnect your MCP client after setup.`,
62
93
  write: "Setup could not save the files. Check the target paths and write permissions, then retry."
63
94
  }
64
95
  };
96
+ var AUTH_COPY = {
97
+ help: "Usage: paymos auth [--client codex|claude-code]\n\nConnect your merchant account in the client's browser sign-in.",
98
+ chooseClient: "Choose your MCP client (codex or claude-code)",
99
+ errors: {
100
+ client_required: "Choose your client with --client codex or --client claude-code.",
101
+ configuration_conflict: "A Paymos entry conflicts with this connection or changed during setup. Review your MCP settings and try again.",
102
+ configuration_scope_unknown: "The effective MCP configuration could not be verified. Use Authenticate in your client's MCP settings.",
103
+ client_installation_unknown: "A supported client installation could not be verified. Use Authenticate in your client's MCP settings or run its native mcp login command.",
104
+ auth_cancelled: "Sign-in was cancelled.",
105
+ auth_failed: "The client could not complete sign-in. Check its output for details.",
106
+ configuration_restore_skipped: "Could not restore the previous MCP settings. Review your client's configuration before retrying.",
107
+ configuration_write_failed: "Could not save the MCP settings. Check the file and its permissions."
108
+ }
109
+ };
65
110
 
66
111
  // src/credential-file.ts
67
112
  function readCredentialFile(path) {
@@ -70,9 +115,9 @@ function readCredentialFile(path) {
70
115
  const link = lstatSync(path);
71
116
  if (!link.isFile() || link.isSymbolicLink()) throw new Error();
72
117
  fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
73
- const stat = fstatSync(fd);
74
- if (!stat.isFile() || stat.size > 16384 || stat.ino !== link.ino) throw new Error();
75
- if (process.platform !== "win32" && ((stat.mode & 63) !== 0 || process.getuid !== void 0 && stat.uid !== process.getuid())) throw new Error();
118
+ const stat2 = fstatSync(fd);
119
+ if (!stat2.isFile() || stat2.size > 16384 || stat2.ino !== link.ino) throw new Error();
120
+ if (process.platform !== "win32" && ((stat2.mode & 63) !== 0 || process.getuid !== void 0 && stat2.uid !== process.getuid())) throw new Error();
76
121
  const value = JSON.parse(readFileSync(fd, "utf8"));
77
122
  if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error();
78
123
  const record = value;
@@ -89,38 +134,6 @@ function readCredentialFile(path) {
89
134
  }
90
135
  }
91
136
 
92
- // src/config.ts
93
- var FLAG_NAMES = /* @__PURE__ */ new Map([
94
- ["--api-key-id", "apiKeyId"],
95
- ["--api-secret", "apiSecret"]
96
- ]);
97
- function parseFlags(argv) {
98
- const flags = {};
99
- for (let index = 0; index < argv.length; index += 1) {
100
- const token = argv[index];
101
- if (token === void 0 || token === "--") break;
102
- const equals = token.indexOf("=");
103
- const head = equals < 0 ? token : token.slice(0, equals);
104
- const field = FLAG_NAMES.get(head);
105
- if (!field) continue;
106
- const value = equals < 0 ? argv[index + 1] : token.slice(equals + 1);
107
- if (value === void 0) break;
108
- flags[field] = value;
109
- if (equals < 0) index += 1;
110
- }
111
- return flags;
112
- }
113
- function loadCredentials(env, flags) {
114
- const file = env.PAYMOS_CREDENTIALS_FILE === void 0 ? void 0 : readCredentialFile(env.PAYMOS_CREDENTIALS_FILE);
115
- const apiKeyId = (env.PAYMOS_API_KEY_ID ?? flags.apiKeyId ?? file?.apiKeyId ?? "").trim();
116
- const apiSecret = (env.PAYMOS_API_SECRET ?? flags.apiSecret ?? file?.apiSecret ?? "").trim();
117
- const webhookSecret = (env.PAYMOS_WEBHOOK_SECRET ?? file?.webhookSecret ?? "").trim();
118
- return webhookSecret === "" ? { apiKeyId, apiSecret } : { apiKeyId, apiSecret, webhookSecret };
119
- }
120
-
121
- // src/gateway.ts
122
- import { Paymos } from "@paymos/sdk";
123
-
124
137
  // src/gate.ts
125
138
  var SANDBOX_ONLY_CODE = "paymos/sandbox-only";
126
139
  var SANDBOX_ONLY_MESSAGE = "Live keys arrive in phase 2. Create a test key pair in Dashboard \u2192 Developers \u2192 API keys.";
@@ -148,419 +161,1853 @@ function checkCredentials(credentials) {
148
161
  function startupLine(check, apiKeyId) {
149
162
  return check.ok ? `[paymos-mcp] sandbox session ready (${apiKeyId.slice(0, TEST_KEY_PREFIX.length + 4)}\u2026)` : `[paymos-mcp] ${check.code}: ${check.message}`;
150
163
  }
151
-
152
- // src/errors.ts
153
- import { ApiError } from "@paymos/sdk";
154
- var ToolError = class extends Error {
155
- code;
156
- constructor(code, message) {
157
- super(message);
158
- this.name = "ToolError";
164
+ var deliveryMessages = {
165
+ delivery_arguments: "Check the required --prepare or --token, --request-id, and file options.",
166
+ delivery_unsafe_path: "Choose a regular file inside the current directory, without links or traversal.",
167
+ delivery_state_unavailable: "The local delivery preparation is missing, expired, or already used.",
168
+ delivery_context_mismatch: "The delivery does not match its prepared operation or file.",
169
+ delivery_unavailable: "The delivery is unavailable from its original connection.",
170
+ delivery_request_failed: "Paymos could not complete the delivery request.",
171
+ delivery_invalid_response: "Paymos returned an unexpected delivery response.",
172
+ delivery_file_too_large: "The delivery exceeds the file size limit.",
173
+ delivery_local_io_failed: "The delivery could not be saved locally."
174
+ };
175
+ var MerchantDeliveryError = class extends Error {
176
+ constructor(code) {
177
+ super(code + ": " + deliveryMessages[code]);
159
178
  this.code = code;
160
179
  }
161
180
  };
162
- function toolErrorFrom(error2) {
163
- if (error2 instanceof ToolError) return error2;
164
- if (error2 instanceof ApiError) {
165
- const code = error2.code === "" ? "api_error" : error2.code;
166
- return new ToolError(`paymos/${code}`, error2.message);
167
- }
168
- const message = error2 instanceof Error ? error2.message : String(error2);
169
- return new ToolError("paymos/sdk_error", message);
170
- }
171
181
 
172
- // src/gateway.ts
173
- var PaymosGateway = class {
174
- credentials;
175
- overrides;
176
- constructor(credentials, overrides = {}) {
177
- this.credentials = credentials;
178
- this.overrides = overrides;
179
- }
180
- check() {
181
- return checkCredentials(this.credentials);
182
- }
183
- /** Webhook signing secret for the local `verify_webhook_signature` tool. */
184
- webhookSecret() {
185
- return this.credentials.webhookSecret;
186
- }
187
- client() {
188
- const check = this.check();
189
- if (!check.ok) throw new ToolError(check.code, check.message);
190
- return new Paymos({
191
- apiKey: this.credentials.apiKeyId,
192
- apiSecret: this.credentials.apiSecret,
193
- ...this.overrides.fetch ? { fetch: this.overrides.fetch } : {}
194
- });
182
+ // src/setup-lock.ts
183
+ import { closeSync as closeSync2, fstatSync as fstatSync2, lstatSync as lstatSync2, mkdirSync, openSync as openSync2, unlinkSync } from "fs";
184
+ import { dirname } from "path";
185
+ var LOCK_SUFFIX = ".paymos-setup.lock";
186
+ var STALE_LOCK_MS = 3e4;
187
+ var DestinationBusyError = class extends Error {
188
+ constructor() {
189
+ super("Another setup is publishing to this destination.");
190
+ this.name = "DestinationBusyError";
195
191
  }
196
- invoices() {
197
- return this.client().invoices;
192
+ };
193
+ function sameIdentity(first, second) {
194
+ return first.ino === second.ino && first.dev === second.dev && first.birthtimeNs === second.birthtimeNs;
195
+ }
196
+ function acquire(lock, now) {
197
+ for (let attempt = 0; ; attempt++) {
198
+ let fd;
199
+ try {
200
+ fd = openSync2(lock, "wx", 384);
201
+ } catch (cause) {
202
+ if (cause.code !== "EEXIST") throw cause;
203
+ if (attempt > 0 || !removeIfStale(lock, now)) throw new DestinationBusyError();
204
+ continue;
205
+ }
206
+ try {
207
+ const opened = fstatSync2(fd, { bigint: true });
208
+ const pathStat2 = lstatSync2(lock, { bigint: true });
209
+ if (!opened.isFile() || !pathStat2.isFile() || opened.ino !== pathStat2.ino || opened.birthtimeNs !== pathStat2.birthtimeNs || opened.dev !== 0n && pathStat2.dev !== 0n && opened.dev !== pathStat2.dev) {
210
+ throw new DestinationBusyError();
211
+ }
212
+ return pathStat2;
213
+ } finally {
214
+ closeSync2(fd);
215
+ }
198
216
  }
199
- paymentChannels() {
200
- return this.client().paymentChannels;
217
+ }
218
+ function removeIfStale(lock, now) {
219
+ try {
220
+ const stale = lstatSync2(lock, { bigint: true });
221
+ if (!stale.isFile() || now() - Number(stale.mtimeMs) < STALE_LOCK_MS) return false;
222
+ const current = lstatSync2(lock, { bigint: true });
223
+ if (!current.isFile() || !sameIdentity(stale, current) || stale.mtimeNs !== current.mtimeNs) return false;
224
+ unlinkSync(lock);
225
+ return true;
226
+ } catch (cause) {
227
+ return cause.code === "ENOENT";
201
228
  }
202
- paymentChannelDeposits() {
203
- return this.client().paymentChannelDeposits;
229
+ }
230
+ function release(lock, mine) {
231
+ try {
232
+ const stat2 = lstatSync2(lock, { bigint: true });
233
+ if (stat2.isFile() && sameIdentity(stat2, mine)) unlinkSync(lock);
234
+ } catch {
204
235
  }
205
- };
206
-
207
- // src/server.ts
208
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
209
-
210
- // src/tools.ts
211
- import { z } from "zod";
212
- import { TimestampSkewError, WebhookVerifier } from "@paymos/sdk";
213
-
214
- // src/wire-shape.ts
215
- function toWireShape(value) {
216
- if (Array.isArray(value)) return value.map(toWireShape);
217
- if (value === null || typeof value !== "object") return value;
218
- const out = {};
219
- for (const [key, item] of Object.entries(value)) {
220
- out[key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)] = toWireShape(item);
236
+ }
237
+ function withDestinationLock(destination, action, now = Date.now) {
238
+ const lock = destination + LOCK_SUFFIX;
239
+ mkdirSync(dirname(lock), { recursive: true, mode: 448 });
240
+ const mine = acquire(lock, now);
241
+ try {
242
+ return action();
243
+ } finally {
244
+ release(lock, mine);
221
245
  }
222
- return out;
223
246
  }
224
247
 
225
- // src/tools.ts
226
- var NETWORKS = "TRC20, ERC20, BEP20, POLYGON, ARBITRUM, OPTIMISM, BASE, TON, AVAX, SOL, NEAR, SUI, PLASMA";
227
- var INVOICE_STATUSES = [
228
- "awaiting_client",
229
- "awaiting_payment",
230
- "confirming",
231
- "underpaid_waiting",
232
- "paid",
233
- "paid_over",
234
- "underpaid",
235
- "expired",
236
- "cancelled"
248
+ // src/setup.ts
249
+ var SETUP_CLIENTS = [
250
+ "codex",
251
+ "claude-code",
252
+ "claude-desktop",
253
+ "kimi",
254
+ "cursor",
255
+ "windsurf",
256
+ "opencode",
257
+ "vscode",
258
+ "generic"
237
259
  ];
238
- var INVOICE_RESULT_HINT = "Returns the invoice in wire form: invoice_id, status, payment_url, order, payment (expected, address, transfers), expires_at. status: awaiting_client | awaiting_payment | confirming | underpaid_waiting | paid | paid_over | underpaid | expired | cancelled.";
239
- function textJson(value) {
240
- return {
241
- content: [{ type: "text", text: JSON.stringify(value, null, 2) }]
242
- };
260
+ function error(kind) {
261
+ throw new Error(SETUP_COPY.errors[kind]);
243
262
  }
244
- function failure(error2) {
245
- const toolError = toolErrorFrom(error2);
246
- return {
247
- isError: true,
248
- content: [{ type: "text", text: JSON.stringify({ code: toolError.code, message: toolError.message }, null, 2) }]
249
- };
263
+ function sameIdentity2(a, b) {
264
+ return a.ino === b.ino && a.dev === b.dev && a.birthtimeNs === b.birthtimeNs;
250
265
  }
251
- async function guarded(run) {
252
- try {
253
- return await run();
254
- } catch (error2) {
255
- return failure(error2);
266
+ function options(argv) {
267
+ const result = { dryRun: false, help: false };
268
+ const seen = /* @__PURE__ */ new Set();
269
+ const flags = /* @__PURE__ */ new Map([
270
+ ["--client", "client"],
271
+ ["--config", "config"],
272
+ ["--credentials-file", "credentialsFile"]
273
+ ]);
274
+ for (let i = 0; i < argv.length; i++) {
275
+ const arg = argv[i];
276
+ const split = arg.indexOf("=");
277
+ const flag = split < 0 ? arg : arg.slice(0, split);
278
+ const normalized = flag === "-h" ? "--help" : flag;
279
+ if (seen.has(normalized)) error("arguments");
280
+ seen.add(normalized);
281
+ if (normalized === "--help" || normalized === "--dry-run") {
282
+ if (split >= 0) error("arguments");
283
+ if (normalized === "--help") result.help = true;
284
+ else result.dryRun = true;
285
+ continue;
286
+ }
287
+ const field = flags.get(flag);
288
+ if (!field) error("arguments");
289
+ const value = split < 0 ? argv[++i] : arg.slice(split + 1);
290
+ if (value === void 0 || value.trim() === "" || value.startsWith("--")) error("arguments");
291
+ result[field] = value;
256
292
  }
293
+ return result;
257
294
  }
258
- function registerTools(server, gateway) {
259
- server.registerTool(
260
- "create_payment_channel",
261
- {
262
- title: "Create payment channel",
263
- description: "Create a Sandbox payment channel using project_id and external_id. Repeating the same pair returns the existing channel.",
264
- inputSchema: {
265
- project_id: z.string().min(1).describe("Project ID."),
266
- external_id: z.string().min(1).max(128).describe("Your identifier for the payer; channel creation is idempotent within the project.")
267
- }
268
- },
269
- async ({ project_id, external_id }) => guarded(async () => {
270
- const channel = await gateway.paymentChannels().create({ projectId: project_id, externalId: external_id });
271
- return textJson(toWireShape(channel));
272
- })
273
- );
274
- server.registerTool(
275
- "get_payment_channel",
276
- {
277
- title: "Get payment channel",
278
- description: "Read a Sandbox payment channel by ID, including its current status and available deposit addresses.",
279
- inputSchema: { payment_channel_id: z.string().min(1).describe("Payment channel ID.") }
280
- },
281
- async ({ payment_channel_id }) => guarded(async () => textJson(toWireShape(await gateway.paymentChannels().get(payment_channel_id))))
282
- );
283
- server.registerTool(
284
- "list_payment_channels",
285
- {
286
- title: "List payment channels",
287
- description: "List Sandbox payment channels with optional project_id, external_id, and status filters. Use limit and cursor to request one page at a time.",
288
- inputSchema: {
289
- project_id: z.string().min(1).optional().describe("Project ID."),
290
- external_id: z.string().min(1).max(128).optional().describe("Your identifier for the payer; channel creation is idempotent within the project."),
291
- status: z.array(z.enum(["active", "blocked", "provisioning"])).optional().describe("Array of channel statuses to include: active, blocked, or provisioning."),
292
- limit: z.number().int().min(1).max(100).optional().describe("Maximum number of items to return in this page."),
293
- cursor: z.string().optional().describe("Pagination cursor from the previous channel-list response.")
294
- }
295
- },
296
- async ({ project_id, external_id, status, limit, cursor }) => guarded(async () => {
297
- const page = await gateway.paymentChannels().list({
298
- ...project_id !== void 0 ? { projectId: project_id } : {},
299
- ...external_id !== void 0 ? { externalId: external_id } : {},
300
- ...status !== void 0 ? { status } : {},
301
- ...limit !== void 0 ? { limit } : {},
302
- ...cursor !== void 0 ? { cursor } : {}
303
- });
304
- return textJson(toWireShape(page));
305
- })
306
- );
307
- server.registerTool(
308
- "block_payment_channel",
309
- {
310
- title: "Block payment channel",
311
- description: "Set a Sandbox payment channel's status to blocked.",
312
- inputSchema: { payment_channel_id: z.string().min(1).describe("Payment channel ID.") }
313
- },
314
- async ({ payment_channel_id }) => guarded(async () => textJson(toWireShape(await gateway.paymentChannels().block(payment_channel_id))))
315
- );
316
- server.registerTool(
317
- "unblock_payment_channel",
318
- {
319
- title: "Unblock payment channel",
320
- description: "Clear a Sandbox payment channel's blocked status.",
321
- inputSchema: { payment_channel_id: z.string().min(1).describe("Payment channel ID.") }
322
- },
323
- async ({ payment_channel_id }) => guarded(async () => textJson(toWireShape(await gateway.paymentChannels().unblock(payment_channel_id))))
324
- );
325
- server.registerTool(
326
- "simulate_payment_channel_deposit",
327
- {
328
- title: "Simulate payment channel deposit",
329
- description: "Create a new Sandbox deposit on every call using a channel ID, decimal-string amount, currency, and network. The optional stage accepts confirming, reorged, or confirmed and defaults to confirmed. No real blockchain is called, and no real funds move.",
330
- inputSchema: {
331
- payment_channel_id: z.string().min(1).describe("Payment channel ID."),
332
- amount: z.string().min(1).describe("Deposit amount as a decimal string."),
333
- currency: z.string().min(1).describe("Currency symbol for the simulated deposit."),
334
- network: z.string().min(1).describe("Network for the simulated deposit."),
335
- stage: z.enum(["confirming", "reorged", "confirmed"]).optional().describe("Simulated deposit stage: confirming, reorged, or confirmed. Defaults to confirmed when omitted.")
336
- }
337
- },
338
- async ({ payment_channel_id, amount, currency, network, stage }) => guarded(async () => {
339
- const deposit = await gateway.paymentChannels().simulateDeposit(payment_channel_id, {
340
- amount,
341
- currency,
342
- network,
343
- ...stage !== void 0 ? { stage } : {}
295
+ function object(value) {
296
+ return value !== null && typeof value === "object" && !Array.isArray(value);
297
+ }
298
+ function equalData(left, right) {
299
+ if (isDeepStrictEqual(left, right)) return true;
300
+ if (!object(left) || !object(right)) return false;
301
+ const plain = (value) => Object.getPrototypeOf(value) === null || Object.getPrototypeOf(value) === Object.prototype;
302
+ if (!plain(left) || !plain(right)) return false;
303
+ const keys = Object.keys(left);
304
+ return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && equalData(left[key], right[key]));
305
+ }
306
+ function absolute(path, context) {
307
+ if (path === "~") return context.home;
308
+ if (path.startsWith("~/") || path.startsWith("~\\")) return resolve(context.home, path.slice(2));
309
+ return resolve(context.cwd, path);
310
+ }
311
+ function defaultConfigPath(client, env, context) {
312
+ const configHome = env.XDG_CONFIG_HOME || join(context.home, ".config");
313
+ switch (client) {
314
+ case "codex":
315
+ return join(env.CODEX_HOME || join(context.home, ".codex"), "config.toml");
316
+ case "claude-code":
317
+ return join(context.home, ".claude.json");
318
+ case "kimi":
319
+ return join(env.KIMI_CODE_HOME || join(context.home, ".kimi-code"), "mcp.json");
320
+ case "cursor":
321
+ return join(context.home, ".cursor", "mcp.json");
322
+ case "windsurf":
323
+ return join(context.home, ".codeium", "windsurf", "mcp_config.json");
324
+ case "vscode":
325
+ return join(context.cwd, ".vscode", "mcp.json");
326
+ case "opencode": {
327
+ if (env.OPENCODE_CONFIG) return env.OPENCODE_CONFIG;
328
+ const jsonc = join(configHome, "opencode", "opencode.jsonc");
329
+ return existsSync(jsonc) ? jsonc : join(configHome, "opencode", "opencode.json");
330
+ }
331
+ case "claude-desktop":
332
+ if (context.platform === "win32" && env.APPDATA)
333
+ return join(env.APPDATA, "Claude", "claude_desktop_config.json");
334
+ if (context.platform === "darwin")
335
+ return join(context.home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
336
+ return error("configRequired");
337
+ case "generic":
338
+ return error("configRequired");
339
+ }
340
+ }
341
+ function snapshot(path) {
342
+ let fd;
343
+ try {
344
+ const stat2 = lstatSync3(path, { bigint: true });
345
+ if (stat2.isSymbolicLink()) error("symlink");
346
+ if (!stat2.isFile() || stat2.size > 4194304n) error("configFile");
347
+ fd = openSync3(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
348
+ const opened = fstatSync3(fd, { bigint: true });
349
+ if (opened.ino !== stat2.ino || opened.birthtimeNs !== stat2.birthtimeNs || stat2.dev !== 0n && opened.dev !== stat2.dev) error("changed");
350
+ return { path, content: readFileSync2(fd, "utf8"), identity: stat2 };
351
+ } catch (cause) {
352
+ if (cause.code === "ENOENT") return { path, content: null };
353
+ if (cause instanceof Error && Object.values(SETUP_COPY.errors).includes(cause.message)) throw cause;
354
+ return error("configFile");
355
+ } finally {
356
+ if (fd !== void 0) closeSync3(fd);
357
+ }
358
+ }
359
+ function assertUnchanged(before) {
360
+ const current = snapshot(before.path);
361
+ if (current.content !== before.content || current.content !== null && before.content !== null && !sameIdentity2(current.identity, before.identity)) error("changed");
362
+ }
363
+ function assertUniqueKeys(node) {
364
+ if (node.type === "object") {
365
+ const keys = /* @__PURE__ */ new Set();
366
+ for (const property of node.children ?? []) {
367
+ const key = property.children?.[0]?.value;
368
+ if (keys.has(key)) error("configFile");
369
+ keys.add(key);
370
+ }
371
+ }
372
+ for (const child of node.children ?? []) assertUniqueKeys(child);
373
+ }
374
+ function jsonConfig(text) {
375
+ const errors = [];
376
+ const value = parseJson(text, errors, { allowTrailingComma: true, allowEmptyContent: false });
377
+ const tree = parseTree(text, [], { allowTrailingComma: true });
378
+ if (errors.length !== 0 || !object(value) || !tree) error("configFile");
379
+ assertUniqueKeys(tree);
380
+ return value;
381
+ }
382
+ function parseConfig(format, original) {
383
+ if (format === "jsonc") return jsonConfig(original ?? "{}\n");
384
+ try {
385
+ return parseToml(original ?? "");
386
+ } catch {
387
+ return error("configFile");
388
+ }
389
+ }
390
+ function configEntries(root, group) {
391
+ const entries = root[group];
392
+ if (entries === void 0) return {};
393
+ if (!object(entries)) return error("configFile");
394
+ return entries;
395
+ }
396
+ function planConfigEntry(format, original, group, name, entry) {
397
+ const root = parseConfig(format, original);
398
+ const entries = configEntries(root, group);
399
+ if (Object.hasOwn(entries, name)) {
400
+ if (!equalData(entries[name], entry)) error("conflict");
401
+ return original;
402
+ }
403
+ const text = original ?? (format === "toml" ? "" : "{}\n");
404
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
405
+ const next = format === "toml" ? text + eol + stringifyToml({ [group]: { [name]: entry } }).replace(/\r?\n/g, eol) : applyEdits(text, modify(text, [group, name], entry, {
406
+ formattingOptions: { insertSpaces: true, tabSize: 2, eol }
407
+ }));
408
+ const expected = { ...root, [group]: { ...entries, [name]: entry } };
409
+ if (!equalData(parseConfig(format, next), expected)) error("configFile");
410
+ return next;
411
+ }
412
+ function planClientConfig(client, original, credentialsPath, platform) {
413
+ const command = platform === "win32" ? "cmd" : "npx";
414
+ const args = platform === "win32" ? ["/d", "/c", "npx", "-y", "@paymos/mcp"] : ["-y", "@paymos/mcp"];
415
+ const env = { PAYMOS_CREDENTIALS_FILE: credentialsPath };
416
+ const entry = client === "opencode" ? { type: "local", command: [command, ...args], environment: env, enabled: true } : { ...client === "vscode" ? { type: "stdio" } : {}, command, args, env };
417
+ if (client === "codex") return planConfigEntry("toml", original, "mcp_servers", "paymos", entry);
418
+ const group = client === "opencode" ? "mcp" : client === "vscode" ? "servers" : "mcpServers";
419
+ return planConfigEntry("jsonc", original, group, "paymos", entry);
420
+ }
421
+ function writeConfig(before, content) {
422
+ mkdirSync2(dirname2(before.path), { recursive: true, mode: 448 });
423
+ const temp = join(dirname2(before.path), `.paymos-${randomUUID()}.tmp`);
424
+ let created = false;
425
+ try {
426
+ writeFileSync(temp, content, { encoding: "utf8", mode: 384, flag: "wx" });
427
+ created = true;
428
+ if (process.platform !== "win32") chmodSync(temp, 384);
429
+ const identity = lstatSync3(temp, { bigint: true });
430
+ assertUnchanged(before);
431
+ if (before.content === null) linkSync(temp, before.path);
432
+ else renameSync(temp, before.path);
433
+ return identity;
434
+ } finally {
435
+ if (created && existsSync(temp)) unlinkSync2(temp);
436
+ }
437
+ }
438
+ function restoreConfig(before, content, identity) {
439
+ const current = snapshot(before.path);
440
+ if (current.content === null || current.content !== content || !sameIdentity2(current.identity, identity)) return false;
441
+ if (before.content === null) unlinkSync2(before.path);
442
+ else writeConfig(current, before.content);
443
+ return true;
444
+ }
445
+ async function ask(io, label, secret = false) {
446
+ if (!io.interactive) error("nonInteractive");
447
+ return (await io.ask(label, secret)).trim();
448
+ }
449
+ function terminalIO() {
450
+ return {
451
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
452
+ log: (message) => console.log(message),
453
+ ask: (label, secret) => new Promise((accept, reject) => {
454
+ let muted = false;
455
+ const output = new Writable({ write(chunk, _encoding, done) {
456
+ if (!muted) process.stdout.write(chunk);
457
+ done();
458
+ } });
459
+ const reader = createInterface({ input: process.stdin, output, terminal: true });
460
+ let settled = false;
461
+ const cancel = () => {
462
+ if (settled) return;
463
+ settled = true;
464
+ muted = false;
465
+ process.stdout.write("\n");
466
+ reader.close();
467
+ reject(new Error(SETUP_COPY.errors.cancelled));
468
+ };
469
+ reader.once("SIGINT", cancel);
470
+ reader.once("close", () => {
471
+ if (!settled) cancel();
344
472
  });
345
- return textJson(toWireShape(deposit));
346
- })
347
- );
348
- server.registerTool(
349
- "get_payment_channel_deposit",
350
- {
351
- title: "Get payment channel deposit",
352
- description: "Read a Sandbox payment channel deposit by ID at any stage, including confirming, reorged, and confirmed.",
353
- inputSchema: { payment_channel_deposit_id: z.string().min(1).describe("Payment channel deposit ID.") }
354
- },
355
- async ({ payment_channel_deposit_id }) => guarded(async () => textJson(toWireShape(await gateway.paymentChannelDeposits().get(payment_channel_deposit_id))))
356
- );
357
- server.registerTool(
358
- "list_payment_channel_deposits",
359
- {
360
- title: "List confirmed channel deposits",
361
- description: "Poll confirmed Sandbox deposits, oldest first. Every response includes next_cursor, even on an empty page; save it for the next poll. If the feed stops advancing, the optional blocked field identifies the deposit and explains why.",
362
- inputSchema: {
363
- limit: z.number().int().min(1).max(100).optional().describe("Maximum number of items to return in this page."),
364
- cursor: z.string().optional().describe("Cursor from the previous response. For the deposit feed, keep it even after an empty page."),
365
- project_id: z.string().min(1).optional().describe("Project ID."),
366
- payment_channel_id: z.string().min(1).optional().describe("Payment channel ID."),
367
- confirmed_from: z.number().int().optional().describe("Inclusive lower bound in Unix seconds for the initial poll. Keep the same value when continuing with a cursor.")
368
- }
369
- },
370
- async ({ limit, cursor, project_id, payment_channel_id, confirmed_from }) => guarded(async () => {
371
- const page = await gateway.paymentChannelDeposits().read({
372
- ...limit !== void 0 ? { limit } : {},
373
- ...cursor !== void 0 ? { cursor } : {},
374
- ...project_id !== void 0 ? { projectId: project_id } : {},
375
- ...payment_channel_id !== void 0 ? { paymentChannelId: payment_channel_id } : {},
376
- ...confirmed_from !== void 0 ? { confirmedFrom: confirmed_from } : {}
473
+ process.stdout.write(`${label}: `);
474
+ muted = secret;
475
+ reader.question("", (answer) => {
476
+ settled = true;
477
+ muted = false;
478
+ if (secret) process.stdout.write("\n");
479
+ reader.close();
480
+ accept(answer);
377
481
  });
378
- return textJson(toWireShape(page));
379
482
  })
380
- );
381
- server.registerTool(
382
- "create_invoice",
383
- {
384
- title: "Create a sandbox invoice",
385
- description: "Create a Paymos invoice and get a hosted payment_url the customer opens. Idempotent per project: reuse the same external_order_id and you get the existing invoice back instead of a duplicate. " + INVOICE_RESULT_HINT,
386
- inputSchema: {
387
- project_id: z.string().min(1).describe("Project receiving the invoice (prj_\u2026)"),
388
- amount: z.string().min(1).describe('Decimal string, e.g. "50.00" \u2014 amounts are strings, never floats'),
389
- currency: z.string().min(2).describe("Fiat code (USD, EUR\u2026) or stablecoin symbol (USDT, USDC\u2026)"),
390
- network: z.string().optional().describe(
391
- `Locks the crypto invoice to one network: ${NETWORKS}. Omit to let the customer choose on the payment page`
392
- ),
393
- external_order_id: z.string().min(1).max(128).describe("Your order identifier (\u2264128 chars); idempotency key per project"),
394
- customer_fee_percent: z.number().int().min(0).max(100).optional().describe("0\u2013100 service fee percent charged to the customer; overrides the project setting"),
395
- client_id: z.string().max(200).optional().describe("Your customer reference (\u2264200 chars)")
483
+ };
484
+ }
485
+ async function runSetup(argv, env = process.env, io = terminalIO(), context = { home: homedir(), cwd: process.cwd(), platform: process.platform }) {
486
+ const flags = options(argv);
487
+ if (flags.help) {
488
+ io.log(SETUP_COPY.help);
489
+ return;
490
+ }
491
+ io.log(SETUP_COPY.title);
492
+ const requested = flags.client ?? await ask(io, `${SETUP_COPY.chooseClient} (${SETUP_CLIENTS.join(", ")})`);
493
+ if (!SETUP_CLIENTS.includes(requested)) error("client");
494
+ const client = requested;
495
+ const configPath = absolute(flags.config ?? defaultConfigPath(client, env, context), context);
496
+ const credentialsPath = absolute(flags.credentialsFile ?? env.PAYMOS_CREDENTIALS_FILE ?? join(env.XDG_CONFIG_HOME || join(context.home, ".config"), "paymos", "mcp", "credentials.json"), context);
497
+ const samePath3 = context.platform === "win32" ? configPath.toLowerCase() === credentialsPath.toLowerCase() : configPath === credentialsPath;
498
+ if (samePath3 || !isAbsolute(configPath) || !isAbsolute(credentialsPath)) error("conflict");
499
+ const before = snapshot(configPath);
500
+ const beforeKeys = snapshot(credentialsPath);
501
+ const stored = beforeKeys.content === null ? void 0 : readCredentialFile(credentialsPath);
502
+ const apiKeyId = (env.PAYMOS_API_KEY_ID ?? stored?.apiKeyId ?? await ask(io, SETUP_COPY.apiKey)).trim();
503
+ const apiSecret = (env.PAYMOS_API_SECRET ?? stored?.apiSecret ?? await ask(io, SETUP_COPY.apiSecret, true)).trim();
504
+ const webhookSecret = (env.PAYMOS_WEBHOOK_SECRET ?? stored?.webhookSecret ?? (io.interactive ? await ask(io, SETUP_COPY.webhookSecret, true) : "")).trim();
505
+ const credentials = {
506
+ apiKeyId,
507
+ apiSecret,
508
+ ...webhookSecret === "" ? {} : { webhookSecret }
509
+ };
510
+ if (!checkCredentials(credentials).ok) error("credentials");
511
+ if (stored !== void 0 && !isDeepStrictEqual(stored, credentials)) error("conflict");
512
+ const next = planClientConfig(client, before.content, credentialsPath, context.platform);
513
+ if (flags.dryRun) {
514
+ io.log(SETUP_COPY.preview(configPath));
515
+ io.log(SETUP_COPY.preview(credentialsPath));
516
+ return;
517
+ }
518
+ if (before.content === next && stored !== void 0) {
519
+ io.log(SETUP_COPY.unchanged(configPath));
520
+ return;
521
+ }
522
+ let createdKeys;
523
+ try {
524
+ withDestinationLock(configPath, () => {
525
+ assertUnchanged(before);
526
+ assertUnchanged(beforeKeys);
527
+ if (stored === void 0) {
528
+ createdKeys = writeConfig(beforeKeys, JSON.stringify(credentials, null, 2) + "\n");
396
529
  }
397
- },
398
- async ({
399
- project_id,
400
- amount,
401
- currency,
402
- network,
403
- external_order_id,
404
- customer_fee_percent,
405
- client_id
406
- }) => guarded(async () => {
407
- const invoice = await gateway.invoices().create({
408
- projectId: project_id,
409
- amount,
410
- currency,
411
- externalOrderId: external_order_id,
412
- ...network !== void 0 ? { network } : {},
413
- ...customer_fee_percent !== void 0 ? { customerFeePercent: customer_fee_percent } : {},
414
- ...client_id !== void 0 ? { clientId: client_id } : {}
415
- });
416
- return textJson(toWireShape(invoice));
417
- })
418
- );
419
- server.registerTool(
420
- "get_invoice",
421
- {
422
- title: "Read an invoice",
423
- description: "Fetch the current state of one Paymos invoice by invoice_id. " + INVOICE_RESULT_HINT,
424
- inputSchema: {
425
- invoice_id: z.string().min(1).describe("Invoice identifier (inv_\u2026)")
530
+ if (before.content !== next) writeConfig(before, next);
531
+ });
532
+ } catch (cause) {
533
+ if (cause instanceof DestinationBusyError) error("changed");
534
+ if (createdKeys !== void 0) {
535
+ try {
536
+ const stat2 = lstatSync3(credentialsPath, { bigint: true });
537
+ if (!stat2.isSymbolicLink() && sameIdentity2(stat2, createdKeys) && isDeepStrictEqual(readCredentialFile(credentialsPath), credentials)) unlinkSync2(credentialsPath);
538
+ } catch {
426
539
  }
427
- },
428
- async ({ invoice_id }) => guarded(async () => {
429
- const invoice = await gateway.invoices().get(invoice_id);
430
- return textJson(toWireShape(invoice));
431
- })
432
- );
433
- server.registerTool(
434
- "list_invoices",
435
- {
436
- title: "List invoices",
437
- description: "Read one cursor-paginated page of invoices for a project. Filters: status (repeatable), external_order_id, created_from/created_to (Unix seconds). The result carries items[] and next_cursor \u2014 next_cursor is absent on the last page. Poll with the returned cursor; do not guess offsets.",
438
- inputSchema: {
439
- project_id: z.string().min(1).describe("Project whose invoices to list (prj_\u2026)"),
440
- limit: z.number().int().positive().optional().describe("Page size; the server default and maximum apply"),
441
- cursor: z.string().optional().describe("Cursor from a previous list_invoices response"),
442
- status: z.array(z.enum(INVOICE_STATUSES)).optional().describe(
443
- "Repeatable status filter: awaiting_client | awaiting_payment | confirming | underpaid_waiting | paid | paid_over | underpaid | expired | cancelled"
444
- ),
445
- external_order_id: z.string().optional().describe("Filter by your order identifier"),
446
- created_from: z.number().int().optional().describe("Unix seconds, inclusive lower bound"),
447
- created_to: z.number().int().optional().describe("Unix seconds, inclusive upper bound")
540
+ }
541
+ if (cause instanceof Error && Object.values(SETUP_COPY.errors).includes(cause.message)) throw cause;
542
+ error("write");
543
+ }
544
+ io.log(SETUP_COPY.configured(configPath));
545
+ io.log(SETUP_COPY.restart);
546
+ }
547
+
548
+ // src/auth.ts
549
+ var remoteUrl = "https://app.paymos.io/connect/merchant-mcp";
550
+ var remoteEntries = {
551
+ codex: {
552
+ url: remoteUrl,
553
+ scopes: ["merchant:mcp", "offline_access"],
554
+ oauth: {
555
+ client_id: "paymos-merchant-codex",
556
+ callback_port: 33419,
557
+ callback_url: "http://127.0.0.1:33419/callback"
558
+ }
559
+ },
560
+ "claude-code": {
561
+ type: "http",
562
+ url: remoteUrl,
563
+ oauth: { clientId: "paymos-merchant-claude-code", callbackPort: 33420, scopes: "merchant:mcp offline_access" }
564
+ }
565
+ };
566
+ var AuthError = class extends Error {
567
+ constructor(code) {
568
+ super(code + ": " + AUTH_COPY.errors[code]);
569
+ this.code = code;
570
+ }
571
+ };
572
+ function fail(code) {
573
+ throw new AuthError(code);
574
+ }
575
+ async function chooseClient(argv, io) {
576
+ let input;
577
+ if (argv.length === 2 && argv[0] === "--client") input = argv[1];
578
+ else if (argv.length === 1 && argv[0]?.startsWith("--client=")) input = argv[0].slice(9);
579
+ else if (argv.length === 0 && io.interactive) {
580
+ try {
581
+ input = (await io.ask(AUTH_COPY.chooseClient, false)).trim();
582
+ } catch {
583
+ return fail("auth_cancelled");
584
+ }
585
+ }
586
+ if (input === "codex" || input === "claude-code") return input;
587
+ return fail("client_required");
588
+ }
589
+ function samePath(left, right, platform) {
590
+ if (platform === "win32") return resolve2(left).toLowerCase() === resolve2(right).toLowerCase();
591
+ return resolve2(left) === resolve2(right);
592
+ }
593
+ function inside(root, path) {
594
+ const tail = relative(root, path);
595
+ return tail === "" || tail !== ".." && !tail.startsWith(".." + sep) && !isAbsolute2(tail);
596
+ }
597
+ function stat(path) {
598
+ return lstatSync4(path, { throwIfNoEntry: false });
599
+ }
600
+ function projectDirectories(context) {
601
+ const dirs = [];
602
+ for (let dir = context.cwd; ; dir = dirname3(dir)) {
603
+ dirs.push(dir);
604
+ if (stat(join2(dir, ".git"))) return { dirs, repository: dir };
605
+ if (dir === dirname3(dir) || samePath(dir, context.home, context.platform)) return { dirs };
606
+ }
607
+ }
608
+ function systemRoot(value, fallback) {
609
+ if (value && !isAbsolute2(value)) return fail("configuration_scope_unknown");
610
+ return resolve2(value || fallback);
611
+ }
612
+ function windowsPaths(env, home) {
613
+ return {
614
+ programFiles: systemRoot(env.ProgramFiles, join2(parse(home).root, "Program Files")),
615
+ programData: systemRoot(env.ProgramData, join2(parse(home).root, "ProgramData")),
616
+ appData: systemRoot(env.APPDATA, join2(home, "AppData", "Roaming")),
617
+ localAppData: systemRoot(env.LOCALAPPDATA, join2(home, "AppData", "Local"))
618
+ };
619
+ }
620
+ function fixedFile(path, platform, allowedRoot = dirname3(path)) {
621
+ const info = stat(path);
622
+ if (!info) return void 0;
623
+ const real = realpathSync(path);
624
+ if (!inside(allowedRoot, real) || !stat(real)?.isFile() || platform === "win32" && (info.isSymbolicLink() || !samePath(path, real, platform))) {
625
+ return fail("client_installation_unknown");
626
+ }
627
+ if (platform !== "win32") accessSync(real, constants3.X_OK);
628
+ return real;
629
+ }
630
+ function packageLauncher(modules, client, platform) {
631
+ const name = client === "codex" ? "@openai/codex" : "@anthropic-ai/claude-code";
632
+ const command = client === "codex" ? "codex" : "claude";
633
+ const root = join2(modules, name);
634
+ const info = stat(root);
635
+ if (!info) return void 0;
636
+ if (!info.isDirectory() || !samePath(realpathSync(root), root, platform)) return fail("client_installation_unknown");
637
+ const manifest = parseConfig("jsonc", snapshot(join2(root, "package.json")).content);
638
+ const bin = object(manifest.bin) ? manifest.bin[command] : void 0;
639
+ const nativeBin = platform === "win32" ? "bin/claude.exe" : "bin/claude";
640
+ const fixedBins = client === "codex" ? ["bin/codex.js"] : ["cli.js", nativeBin];
641
+ if (manifest.name !== name || typeof bin !== "string" || !fixedBins.includes(bin)) {
642
+ return fail("client_installation_unknown");
643
+ }
644
+ const binary = fixedFile(join2(root, bin), platform, root);
645
+ if (!binary) return fail("client_installation_unknown");
646
+ if (bin === nativeBin) return { executable: binary };
647
+ const node = isAbsolute2(process.execPath) ? realpathSync(process.execPath) : void 0;
648
+ if (!node || !stat(node)?.isFile()) return fail("client_installation_unknown");
649
+ return { executable: node, jsBin: binary };
650
+ }
651
+ function resolveLaunch(client, context, env, repository) {
652
+ const { home, platform } = context;
653
+ const command = client === "codex" ? "codex" : "claude";
654
+ const candidates = /* @__PURE__ */ new Map();
655
+ const outsideRepository = (path) => !repository || !inside(repository, path);
656
+ const add = (launch) => {
657
+ if (!launch) return;
658
+ const bin = launch.jsBin ?? launch.executable;
659
+ if (!outsideRepository(bin) || !outsideRepository(launch.executable)) return fail("client_installation_unknown");
660
+ candidates.set(platform === "win32" ? bin.toLowerCase() : bin, launch);
661
+ };
662
+ try {
663
+ if (platform === "win32") {
664
+ const paths = windowsPaths(env, home);
665
+ for (const prefix of [join2(paths.appData, "npm"), join2(paths.programFiles, "nodejs")]) {
666
+ if (!outsideRepository(prefix)) return fail("client_installation_unknown");
667
+ add(packageLauncher(join2(prefix, "node_modules"), client, platform));
448
668
  }
449
- },
450
- async ({ project_id, limit, cursor, status, external_order_id, created_from, created_to }) => guarded(async () => {
451
- const page = await gateway.invoices().list({
452
- projectId: project_id,
453
- ...limit !== void 0 ? { limit } : {},
454
- ...cursor !== void 0 ? { cursor } : {},
455
- ...status !== void 0 ? { status } : {},
456
- ...external_order_id !== void 0 ? { externalOrderId: external_order_id } : {},
457
- ...created_from !== void 0 ? { createdFrom: created_from } : {},
458
- ...created_to !== void 0 ? { createdTo: created_to } : {}
459
- });
460
- return textJson(toWireShape(page));
461
- })
462
- );
463
- server.registerTool(
464
- "cancel_invoice",
465
- {
466
- title: "Cancel an invoice",
467
- description: "Cancel an invoice that has not been paid yet; the reason is stored on the record. Invoices in a final status (paid, paid_over, underpaid, expired, cancelled) cannot be cancelled. " + INVOICE_RESULT_HINT,
468
- inputSchema: {
469
- invoice_id: z.string().min(1).describe("Invoice identifier (inv_\u2026)"),
470
- reason: z.string().min(1).max(500).describe("Why the invoice is cancelled (1\u2013500 chars, stored)")
669
+ const exe = command + ".exe";
670
+ const installed = client === "codex" ? join2(paths.localAppData, "Programs", "OpenAI", "Codex", "bin", exe) : join2(home, ".local", "bin", exe);
671
+ if (stat(installed)) {
672
+ const resolved = realpathSync(installed);
673
+ const releases = join2(home, ".codex", "packages", "standalone", "releases");
674
+ if (client === "codex" && !samePath(installed, resolved, platform)) {
675
+ const target = relative(releases, resolved).split(sep).join("/");
676
+ if (!/^[\d][\w.-]*-(?:x86_64|aarch64)-pc-windows-msvc\/(?:bin\/)?codex\.exe$/i.test(target)) {
677
+ return fail("client_installation_unknown");
678
+ }
679
+ add({ executable: fixedFile(resolved, platform, releases) });
680
+ } else {
681
+ add({ executable: fixedFile(installed, platform) });
682
+ }
471
683
  }
472
- },
473
- async ({ invoice_id, reason }) => guarded(async () => {
474
- const invoice = await gateway.invoices().cancel(invoice_id, reason);
475
- return textJson(toWireShape(invoice));
476
- })
477
- );
478
- server.registerTool(
479
- "simulate_invoice_payment",
480
- {
481
- title: "Simulate a sandbox payment",
482
- description: "Sandbox only: drive a test invoice through a payment outcome without touching a blockchain. The server derives the amounts \u2014 never compute money client-side. stage=paid marks it fully paid; overpaid pays more than expected; underpay pays less (invoice lands in underpaid waiting for a top-up); cancel voids it; paid_late pays the full amount after the deadline \u2014 the invoice keeps its terminal decision and gains the late-payment mark. " + INVOICE_RESULT_HINT,
483
- inputSchema: {
484
- invoice_id: z.string().min(1).describe("Test invoice identifier (is_test=true)"),
485
- stage: z.enum(["paid", "overpaid", "underpay", "cancel", "paid_late"]).describe("Outcome to simulate: paid | overpaid | underpay | cancel | paid_late")
684
+ const wingetRoot = client === "codex" ? "OpenAI.Codex" : "Anthropic.ClaudeCode";
685
+ const wingetName = client === "codex" ? "codex-" + (process.arch === "arm64" ? "aarch64" : "x86_64") + "-pc-windows-msvc.exe" : exe;
686
+ for (const base of [join2(paths.localAppData, "Microsoft"), paths.programFiles]) {
687
+ const packageDir = join2(base, "WinGet", "Packages", wingetRoot + "_Microsoft.Winget.Source_8wekyb3d8bbwe");
688
+ const absolute2 = fixedFile(join2(packageDir, wingetName), platform);
689
+ if (absolute2) add({ executable: absolute2 });
486
690
  }
487
- },
488
- async ({ invoice_id, stage }) => guarded(async () => {
489
- const invoice = await gateway.invoices().simulatePayment(invoice_id, stage);
490
- return textJson(toWireShape(invoice));
491
- })
492
- );
493
- server.registerTool(
494
- "verify_webhook_signature",
495
- {
496
- title: "Verify a webhook signature",
497
- description: 'Verify the X-Webhook-Signature header of a Paymos webhook against its raw body, locally (no API call). Header format: t={unix},v1={hmac_hex("{unix}.{payload}")}; during secret rotation two v1= values are present and either may match. Use the raw request body byte-for-byte \u2014 re-serialized JSON breaks the signature.',
498
- inputSchema: {
499
- payload: z.string().min(1).describe("The raw webhook body exactly as received"),
500
- signature_header: z.string().describe("The X-Webhook-Signature header value, e.g. t=1760000000,v1=9f2c\u2026"),
501
- secret: z.string().optional().describe("Webhook secret (whsec_\u2026); defaults to PAYMOS_WEBHOOK_SECRET"),
502
- tolerance_seconds: z.number().int().min(0).optional().describe("Max age of the t= timestamp (default 300); older headers are rejected as expired")
691
+ } else {
692
+ const userBin = join2(home, ".local", "bin", command);
693
+ if (stat(userBin)) {
694
+ const releases = client === "codex" ? join2(home, ".codex", "packages", "standalone", "releases") : join2(home, ".local", "share", "claude", "versions");
695
+ const userRoot = stat(userBin)?.isSymbolicLink() ? releases : dirname3(userBin);
696
+ const executable = fixedFile(userBin, platform, userRoot);
697
+ if (executable) add({ executable });
503
698
  }
504
- },
505
- async ({ payload, signature_header, secret, tolerance_seconds }) => {
506
- const effectiveSecret = secret ?? gateway.webhookSecret();
507
- if (effectiveSecret === void 0) {
508
- return textJson({ valid: false, reason: "missing_secret" });
699
+ for (const prefix of /* @__PURE__ */ new Set(["/usr", "/usr/local", "/opt/homebrew", dirname3(dirname3(process.execPath))])) {
700
+ if (!isAbsolute2(prefix) || !outsideRepository(prefix)) continue;
701
+ add(packageLauncher(join2(prefix, "lib", "node_modules"), client, platform));
509
702
  }
510
- const verifier = new WebhookVerifier(
511
- effectiveSecret,
512
- tolerance_seconds === void 0 ? 300 : tolerance_seconds
513
- );
514
- try {
515
- verifier.assertValid(signature_header, payload);
516
- return textJson({ valid: true });
517
- } catch (error2) {
518
- if (error2 instanceof TimestampSkewError) return textJson({ valid: false, reason: "expired" });
519
- return textJson({ valid: false, reason: "bad_signature" });
703
+ for (const prefix of ["/usr", "/usr/local", "/opt/homebrew"]) {
704
+ const executable = fixedFile(join2(prefix, "bin", command), platform, prefix);
705
+ if (executable && !executable.endsWith(".js")) add({ executable });
520
706
  }
521
707
  }
522
- );
708
+ } catch {
709
+ return fail("client_installation_unknown");
710
+ }
711
+ if (candidates.size !== 1) return fail("client_installation_unknown");
712
+ return candidates.values().next().value;
523
713
  }
524
-
525
- // src/generated/resources.ts
526
- var DOC_RESOURCES = [
527
- {
528
- "name": "quick-start",
529
- "slug": "quick-start",
530
- "uri": "paymos://docs/quick-start",
531
- "description": "Paymos quick start: create a test key pair, issue the first invoice, take the first payment.",
532
- "mimeType": "text/html",
533
- "text": `<h2 id="create-an-account">Create an account</h2>
534
- <p>Sign in at <a href="/">paymos.io</a> with an email magic link (or Google / passkey) \u2014 no password to set.</p>
535
- <h2 id="create-a-project">Create a project</h2>
536
- <p>Open <a href="/projects/create"><strong>Dashboard \u2192 Projects \u2192 New project</strong></a>, name the project, and enable the asset and network pairs your customers will use.</p>
537
- <h2 id="get-your-test-api-keys">Get your test API keys</h2>
538
- <p>Navigate to <a href="/developers/api"><strong>Dashboard \u2192 Developer \u2192 API Keys</strong></a> and generate a test key pair:</p>
539
- <ul class="list-none p-0 m-0 flex flex-col gap-3"><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><strong>Payment Key</strong> (<code>pk_test_\u2026</code>) \u2014 used to create test invoices and read invoice status</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><strong>API Secret</strong> (<code>sk_test_\u2026</code>) \u2014 used to compute the HMAC-SHA256 request signature (see the warning below)</span></li></ul>
540
- <div class="callout callout--warning"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 3 1.7 17h16.6L10 3Zm0 5v4m0 3h.01"></path></svg><div class="callout__body"><p>API Secret never leaves your server. Never send it in headers, query strings, or client code. Never commit it to git \u2014 rotate immediately if it leaks.</p></div></div>
541
- <h2 id="register-a-test-webhook-endpoint">Register a test webhook endpoint</h2>
542
- <p>Expose your server's webhook handler at an HTTPS URL, then open <a href="/developers/webhooks"><strong>Dashboard \u2192 Developer \u2192 Webhooks</strong></a> in Sandbox and create an endpoint. Enter the HTTPS callback URL, select the <code>Invoice</code> category and your project, then create the endpoint. Copy the one-time <code>whsec_test_\u2026</code> secret to your server; it is separate from the API key pair and signs test webhook deliveries.</p>
543
- <h2 id="create-a-test-invoice">Create a test invoice</h2>
544
- <p>Use an official server SDK below. It serializes the request, creates the exact
545
- HMAC signature, sets the timestamp headers, applies safe retries, and returns a
546
- typed response. Manual signing is documented separately in <a href="/docs/authentication">Authentication</a>.</p>
547
- <div class="code-tab-group"><div class="code-tab-bar"><button type="button" class="code-tab-btn active" data-tab-idx="0" data-code-lang="curl">cURL</button><button type="button" class="code-tab-btn" data-tab-idx="1" data-code-lang="mcp">MCP</button><button type="button" class="code-tab-btn" data-tab-idx="2" data-code-lang="javascript"><i class="devicon-javascript-plain colored"></i> JavaScript</button><button type="button" class="code-tab-btn" data-tab-idx="3" data-code-lang="python"><i class="devicon-python-plain colored"></i> Python</button><button type="button" class="code-tab-btn" data-tab-idx="4" data-code-lang="php"><i class="devicon-php-plain colored"></i> PHP</button><button type="button" class="code-tab-btn" data-tab-idx="5" data-code-lang="go"><i class="devicon-go-plain colored"></i> Go</button><button type="button" class="code-tab-btn" data-tab-idx="6" data-code-lang="csharp"><i class="devicon-csharp-plain colored"></i> C#</button><button type="button" class="code-tab-btn" data-tab-idx="7" data-code-lang="java"><i class="devicon-java-plain colored"></i> Java</button><button type="button" class="code-tab-btn" data-tab-idx="8" data-code-lang="ruby"><i class="devicon-ruby-plain colored"></i> Ruby</button><button type="button" class="code-tab-btn" data-tab-idx="9" data-code-lang="rust"><i class="devicon-rust-original colored"></i> Rust</button></div><div class="code-tab-panel active" data-code-lang="curl"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="curl"><code><span class="line"><span style="color:#E06C75">API_KEY_ID</span><span style="color:#56B6C2">=</span><span style="color:#98C379">"pk_live_xxxxxxxxxxxx"</span></span>
548
- <span class="line"><span style="color:#E06C75">API_SECRET</span><span style="color:#56B6C2">=</span><span style="color:#98C379">"sk_live_xxxxxxxxxxxx"</span></span>
549
- <span class="line"><span style="color:#E06C75">BODY</span><span style="color:#56B6C2">=</span><span style="color:#98C379">'{"project_id":"prj_xxxxxxxxxxxx","amount":"100.00","currency":"USD","external_order_id":"order-123","client_id":"customer-456"}'</span></span>
550
- <span class="line"></span>
551
- <span class="line"><span style="color:#E06C75">TS</span><span style="color:#56B6C2">=</span><span style="color:#ABB2BF">$(</span><span style="color:#61AFEF">date</span><span style="color:#98C379"> +%s</span><span style="color:#ABB2BF">)</span></span>
552
- <span class="line"><span style="color:#E06C75">BODY_HASH</span><span style="color:#56B6C2">=</span><span style="color:#ABB2BF">$(</span><span style="color:#56B6C2">printf</span><span style="color:#98C379"> '%s'</span><span style="color:#98C379"> "</span><span style="color:#E06C75">$BODY</span><span style="color:#98C379">"</span><span style="color:#ABB2BF"> | </span><span style="color:#61AFEF">openssl</span><span style="color:#98C379"> dgst</span><span style="color:#D19A66"> -sha256</span><span style="color:#D19A66"> -hex</span><span style="color:#ABB2BF"> | </span><span style="color:#61AFEF">sed</span><span style="color:#98C379"> 's/^.* //'</span><span style="color:#ABB2BF">)</span></span>
553
- <span class="line"><span style="color:#E06C75">SIGNATURE</span><span style="color:#56B6C2">=</span><span style="color:#ABB2BF">$(</span><span style="color:#56B6C2">printf</span><span style="color:#98C379"> '%s\\n%s\\n%s\\n%s\\n%s'</span><span style="color:#98C379"> "</span><span style="color:#E06C75">$TS</span><span style="color:#98C379">"</span><span style="color:#98C379"> POST</span><span style="color:#98C379"> /v1/invoices</span><span style="color:#98C379"> ''</span><span style="color:#98C379"> "</span><span style="color:#E06C75">$BODY_HASH</span><span style="color:#98C379">"</span><span style="color:#56B6C2"> \\</span></span>
554
- <span class="line"><span style="color:#ABB2BF"> | </span><span style="color:#61AFEF">openssl</span><span style="color:#98C379"> dgst</span><span style="color:#D19A66"> -sha256</span><span style="color:#D19A66"> -hmac</span><span style="color:#98C379"> "</span><span style="color:#E06C75">$API_SECRET</span><span style="color:#98C379">"</span><span style="color:#D19A66"> -binary</span><span style="color:#ABB2BF"> | </span><span style="color:#61AFEF">base64</span><span style="color:#ABB2BF">)</span></span>
555
- <span class="line"></span>
556
- <span class="line"><span style="color:#61AFEF">curl</span><span style="color:#D19A66"> -sS</span><span style="color:#98C379"> https://api.paymos.io/v1/invoices</span><span style="color:#56B6C2"> \\</span></span>
557
- <span class="line"><span style="color:#D19A66"> -H</span><span style="color:#98C379"> "Authorization: HMAC-SHA256 </span><span style="color:#E06C75">$API_KEY_ID</span><span style="color:#98C379">:</span><span style="color:#E06C75">$SIGNATURE</span><span style="color:#98C379">"</span><span style="color:#56B6C2"> \\</span></span>
558
- <span class="line"><span style="color:#D19A66"> -H</span><span style="color:#98C379"> "X-Request-Timestamp: </span><span style="color:#E06C75">$TS</span><span style="color:#98C379">"</span><span style="color:#56B6C2"> \\</span></span>
559
- <span class="line"><span style="color:#D19A66"> -H</span><span style="color:#98C379"> "Content-Type: application/json"</span><span style="color:#56B6C2"> \\</span></span>
560
- <span class="line"><span style="color:#D19A66"> -d</span><span style="color:#98C379"> "</span><span style="color:#E06C75">$BODY</span><span style="color:#98C379">"</span></span>
561
- <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="mcp"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="mcp"><code><span class="line"><span style="color:#ABB2BF">Setup once in terminal: </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">npx -y @paymos/mcp setup</span><span style="color:#E5C07B">\`</span></span>
562
- <span class="line"></span>
563
- <span class="line"><span style="color:#ABB2BF">Prompt:</span></span>
714
+ function sandboxEntry(value) {
715
+ if (!object(value) || Object.hasOwn(value, "url") || Object.hasOwn(value, "oauth") || value.type !== void 0 && value.type !== "stdio") return false;
716
+ return value.command === "npx" && equalData(value.args, ["-y", "@paymos/mcp"]) || value.command === "cmd" && equalData(value.args, ["/d", "/c", "npx", "-y", "@paymos/mcp"]) || value.command === "paymos-mcp" && (value.args === void 0 || equalData(value.args, []));
717
+ }
718
+ function assertConfigLocation(path, platform) {
719
+ if (!isAbsolute2(path)) fail("configuration_scope_unknown");
720
+ for (let parent = dirname3(path); ; parent = dirname3(parent)) {
721
+ const info = stat(parent);
722
+ if (info) {
723
+ if (!info.isDirectory() || !samePath(parent, realpathSync(parent), platform)) fail("configuration_scope_unknown");
724
+ return;
725
+ }
726
+ if (parent === dirname3(parent)) fail("configuration_scope_unknown");
727
+ }
728
+ }
729
+ function preflight(client, context, env, dirs) {
730
+ const { home, platform } = context;
731
+ const windows = platform === "win32" ? windowsPaths(env, home) : void 0;
732
+ const format = client === "codex" ? "toml" : "jsonc";
733
+ const group = client === "codex" ? "mcp_servers" : "mcpServers";
734
+ const target = defaultConfigPath(client, env, context);
735
+ const watched = /* @__PURE__ */ new Map();
736
+ const layers = [];
737
+ const disabled = /* @__PURE__ */ new Set();
738
+ const read = (path, type = format) => {
739
+ assertConfigLocation(path, platform);
740
+ let before = watched.get(path);
741
+ if (!before) {
742
+ before = snapshot(path);
743
+ watched.set(path, before);
744
+ }
745
+ return parseConfig(type, before.content);
746
+ };
747
+ const rejectManagedFiles = (paths) => {
748
+ for (const path of paths) {
749
+ if (stat(path)) fail("configuration_scope_unknown");
750
+ watched.set(path, { path, content: null });
751
+ }
752
+ };
753
+ try {
754
+ const user = read(target);
755
+ if (client === "codex") {
756
+ const system = windows ? join2(windows.programData, "OpenAI", "Codex") : resolve2("/etc/codex");
757
+ rejectManagedFiles([
758
+ join2(system, "managed_config.toml"),
759
+ join2(system, "requirements.toml"),
760
+ join2(dirname3(target), "managed_config.toml"),
761
+ join2(dirname3(target), "requirements.toml")
762
+ ]);
763
+ if (env.CODEX_PROFILE || user.profile !== void 0) fail("configuration_scope_unknown");
764
+ const projects = [join2(context.cwd, "config.toml"), ...dirs.map((dir) => join2(dir, ".codex", "config.toml"))];
765
+ const roots = [
766
+ ...projects.filter((path) => !samePath(path, target, platform)).map((path) => read(path)),
767
+ user,
768
+ read(join2(system, "config.toml"))
769
+ ];
770
+ for (const root of roots) {
771
+ if (root.project_root_markers !== void 0 && !equalData(root.project_root_markers, [".git"])) {
772
+ fail("configuration_scope_unknown");
773
+ }
774
+ layers.push(configEntries(root, group));
775
+ }
776
+ } else {
777
+ const userConfig = join2(home, ".claude");
778
+ if (env.CLAUDE_CONFIG_DIR && !samePath(env.CLAUDE_CONFIG_DIR, userConfig, platform)) fail("configuration_scope_unknown");
779
+ const systems = windows ? [join2(windows.programFiles, "ClaudeCode"), join2(windows.programData, "ClaudeCode")] : [resolve2(platform === "darwin" ? "/Library/Application Support/ClaudeCode" : "/etc/claude-code")];
780
+ rejectManagedFiles([...systems, userConfig].flatMap((dir) => ["managed-mcp.json", "managed-settings.json", "managed-settings.d"].map((name2) => join2(dir, name2))));
781
+ const noteDisabled = (root) => {
782
+ for (const key of ["disabledMcpServers", "disabledMcpjsonServers"]) {
783
+ const entries2 = root[key];
784
+ if (entries2 === void 0) continue;
785
+ if (!Array.isArray(entries2)) return fail("configuration_scope_unknown");
786
+ for (const name2 of entries2) disabled.add(name2);
787
+ }
788
+ };
789
+ const localProjects = configEntries(user, "projects");
790
+ for (const dir of dirs) {
791
+ for (const [path, settings] of Object.entries(localProjects)) {
792
+ if (!isAbsolute2(path) || !samePath(path, dir, platform)) continue;
793
+ if (!object(settings)) return fail("configuration_scope_unknown");
794
+ layers.push(configEntries(settings, group));
795
+ noteDisabled(settings);
796
+ }
797
+ }
798
+ for (const dir of dirs) layers.push(configEntries(read(join2(dir, ".mcp.json")), group));
799
+ layers.push(configEntries(user, group));
800
+ noteDisabled(user);
801
+ const settingsPaths = [join2(userConfig, "settings.json"), ...dirs.flatMap((dir) => ["settings.json", "settings.local.json"].map((name2) => join2(dir, ".claude", name2)))];
802
+ for (const path of settingsPaths) {
803
+ const settings = read(path);
804
+ if (["allowManagedMcpServersOnly", "allowedMcpServers", "deniedMcpServers"].some((key) => settings[key] !== void 0)) fail("configuration_scope_unknown");
805
+ noteDisabled(settings);
806
+ }
807
+ }
808
+ const profile = remoteEntries[client];
809
+ const entries = (name2) => layers.filter((layer) => Object.hasOwn(layer, name2)).map((layer) => layer[name2]);
810
+ const primary = entries("paymos");
811
+ const alternate = entries("paymos-merchant");
812
+ if (primary.some((value) => !equalData(value, profile) && !sandboxEntry(value))) fail("configuration_conflict");
813
+ const name = primary.some(sandboxEntry) || primary.length === 0 && alternate.some((value) => equalData(value, profile)) ? "paymos-merchant" : "paymos";
814
+ const chosen = entries(name);
815
+ if (disabled.has(name) || chosen.some((value) => !equalData(value, profile))) fail("configuration_conflict");
816
+ const before = watched.get(target);
817
+ const next = chosen.length === 0 ? planConfigEntry(format, before.content, group, name, profile) : before.content;
818
+ return { name, before, next, watched: [...watched.values()] };
819
+ } catch (cause) {
820
+ if (cause instanceof AuthError) throw cause;
821
+ return fail("configuration_scope_unknown");
822
+ }
823
+ }
824
+ function nativeLogin(launch, name, cwd, env) {
825
+ const args = [...launch.jsBin ? [launch.jsBin] : [], "mcp", "login", name];
826
+ const childEnv = { ...env };
827
+ if (launch.jsBin) {
828
+ for (const key of Object.keys(childEnv)) {
829
+ if (["NODE_OPTIONS", "NODE_PATH"].includes(key.toUpperCase())) delete childEnv[key];
830
+ }
831
+ }
832
+ return new Promise((accept, reject) => {
833
+ let child;
834
+ let signal;
835
+ const interrupt = (reason) => {
836
+ signal ??= reason;
837
+ if (child && child.exitCode === null && child.signalCode === null) child.kill(reason);
838
+ };
839
+ const onInt = () => interrupt("SIGINT");
840
+ const onTerm = () => interrupt("SIGTERM");
841
+ const cleanup = () => {
842
+ process.removeListener("SIGINT", onInt);
843
+ process.removeListener("SIGTERM", onTerm);
844
+ };
845
+ process.on("SIGINT", onInt);
846
+ process.on("SIGTERM", onTerm);
847
+ try {
848
+ child = spawn(launch.executable, args, { cwd, env: childEnv, shell: false, stdio: "inherit" });
849
+ child.once("error", () => {
850
+ cleanup();
851
+ reject(new AuthError("auth_failed"));
852
+ });
853
+ child.once("close", (code, childSignal) => {
854
+ cleanup();
855
+ const reason = signal ?? childSignal;
856
+ accept(reason === "SIGINT" ? 130 : reason === "SIGTERM" ? 143 : code ?? 1);
857
+ });
858
+ } catch {
859
+ cleanup();
860
+ reject(new AuthError("auth_failed"));
861
+ }
862
+ });
863
+ }
864
+ async function runAuth(argv, env = process.env, io = terminalIO(), input = { home: homedir2(), cwd: process.cwd(), platform: process.platform }) {
865
+ if (argv.length === 1 && (argv[0] === "--help" || argv[0] === "-h")) {
866
+ io.log(AUTH_COPY.help);
867
+ return 0;
868
+ }
869
+ let client;
870
+ try {
871
+ client = await chooseClient(argv, io);
872
+ } catch (cause) {
873
+ if (!(cause instanceof AuthError) || cause.code !== "auth_cancelled") throw cause;
874
+ io.log(cause.message);
875
+ return 130;
876
+ }
877
+ let context;
878
+ let project;
879
+ try {
880
+ if (env.GIT_DIR || env.GIT_WORK_TREE) return fail("configuration_scope_unknown");
881
+ context = { ...input, cwd: realpathSync(input.cwd), home: realpathSync(input.home) };
882
+ project = projectDirectories(context);
883
+ } catch {
884
+ return fail("configuration_scope_unknown");
885
+ }
886
+ const launch = resolveLaunch(client, context, env, project.repository);
887
+ const plan = preflight(client, context, env, project.dirs);
888
+ const next = plan.next;
889
+ const assertPlanUnchanged = () => {
890
+ for (const before of plan.watched) {
891
+ assertConfigLocation(before.path, context.platform);
892
+ assertUnchanged(before);
893
+ }
894
+ };
895
+ let published;
896
+ try {
897
+ if (next !== null && next !== plan.before.content) {
898
+ published = withDestinationLock(plan.before.path, () => {
899
+ assertPlanUnchanged();
900
+ return writeConfig(plan.before, next);
901
+ });
902
+ } else {
903
+ assertPlanUnchanged();
904
+ }
905
+ } catch (cause) {
906
+ if (cause instanceof AuthError) throw cause;
907
+ if (cause instanceof DestinationBusyError || cause instanceof Error && cause.message === SETUP_COPY.errors.changed) {
908
+ return fail("configuration_conflict");
909
+ }
910
+ return fail("configuration_write_failed");
911
+ }
912
+ const restore = () => {
913
+ if (published === void 0 || next === null) return;
914
+ let restored = false;
915
+ try {
916
+ assertConfigLocation(plan.before.path, context.platform);
917
+ restored = withDestinationLock(plan.before.path, () => {
918
+ assertConfigLocation(plan.before.path, context.platform);
919
+ return restoreConfig(plan.before, next, published);
920
+ });
921
+ } catch {
922
+ }
923
+ if (!restored) io.log("configuration_restore_skipped: " + AUTH_COPY.errors.configuration_restore_skipped);
924
+ };
925
+ let code;
926
+ try {
927
+ code = await nativeLogin(launch, plan.name, context.cwd, env);
928
+ } catch (cause) {
929
+ restore();
930
+ throw cause;
931
+ }
932
+ if (code === 0) return code;
933
+ restore();
934
+ const error2 = code === 130 || code === 143 ? "auth_cancelled" : "auth_failed";
935
+ io.log(error2 + ": " + AUTH_COPY.errors[error2]);
936
+ return code;
937
+ }
938
+
939
+ // src/config.ts
940
+ var FLAG_NAMES = /* @__PURE__ */ new Map([
941
+ ["--api-key-id", "apiKeyId"],
942
+ ["--api-secret", "apiSecret"]
943
+ ]);
944
+ function parseFlags(argv) {
945
+ const flags = {};
946
+ for (let index = 0; index < argv.length; index += 1) {
947
+ const token = argv[index];
948
+ if (token === void 0 || token === "--") break;
949
+ const equals = token.indexOf("=");
950
+ const head = equals < 0 ? token : token.slice(0, equals);
951
+ const field = FLAG_NAMES.get(head);
952
+ if (!field) continue;
953
+ const value = equals < 0 ? argv[index + 1] : token.slice(equals + 1);
954
+ if (value === void 0) break;
955
+ flags[field] = value;
956
+ if (equals < 0) index += 1;
957
+ }
958
+ return flags;
959
+ }
960
+ function loadCredentials(env, flags) {
961
+ const file = env.PAYMOS_CREDENTIALS_FILE === void 0 ? void 0 : readCredentialFile(env.PAYMOS_CREDENTIALS_FILE);
962
+ const apiKeyId = (env.PAYMOS_API_KEY_ID ?? flags.apiKeyId ?? file?.apiKeyId ?? "").trim();
963
+ const apiSecret = (env.PAYMOS_API_SECRET ?? flags.apiSecret ?? file?.apiSecret ?? "").trim();
964
+ const webhookSecret = (env.PAYMOS_WEBHOOK_SECRET ?? file?.webhookSecret ?? "").trim();
965
+ return webhookSecret === "" ? { apiKeyId, apiSecret } : { apiKeyId, apiSecret, webhookSecret };
966
+ }
967
+
968
+ // src/files.ts
969
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
970
+ import { closeSync as closeSync4, constants as constants4, fstatSync as fstatSync4, linkSync as linkSync2, lstatSync as lstatSync6, openSync as openSync4, readSync, unlinkSync as unlinkSync4 } from "fs";
971
+ import { open } from "fs/promises";
972
+ import { dirname as dirname4, join as join4 } from "path";
973
+
974
+ // src/install-secret.ts
975
+ import { spawnSync } from "child_process";
976
+ import { createHash, randomBytes } from "crypto";
977
+ import { lstatSync as lstatSync5, mkdirSync as mkdirSync3, readdirSync, realpathSync as realpathSync2, unlinkSync as unlinkSync3 } from "fs";
978
+ import { userInfo } from "os";
979
+ import { isAbsolute as isAbsolute3, join as join3, parse as parse2, relative as relative2, resolve as resolve3, sep as sep2 } from "path";
980
+ import { parseEnv } from "util";
981
+ var origin = "https://app.paymos.io";
982
+ var resource = "/connect/merchant-mcp";
983
+ var lifetimeMs = 5 * 6e4;
984
+ var requestTimeoutMs = 6e4;
985
+ var stateFolder = ".paymos-mcp-delivery";
986
+ var uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;
987
+ var windowsStateScript = String.raw`
988
+ using namespace System.IO
989
+ using namespace System.Security.AccessControl
990
+ using namespace System.Security.Principal
991
+
992
+ $ErrorActionPreference = 'Stop'
993
+ try {
994
+ $path = [Environment]::GetEnvironmentVariable('PAYMOS_DELIVERY_STATE_PATH')
995
+ $action = [Environment]::GetEnvironmentVariable('PAYMOS_DELIVERY_STATE_ACTION')
996
+ $sid = [WindowsIdentity]::GetCurrent().User
997
+ $rights = [FileSystemRights]::FullControl
998
+ $sections = [AccessControlSections]'Access, Owner'
999
+
1000
+ function New-PrivateAcl([bool] $directory) {
1001
+ if ($directory) {
1002
+ $acl = [DirectorySecurity]::new()
1003
+ $inheritance = [InheritanceFlags]'ContainerInherit, ObjectInherit'
1004
+ } else {
1005
+ $acl = [FileSecurity]::new()
1006
+ $inheritance = [InheritanceFlags]::None
1007
+ }
1008
+ $acl.SetOwner($sid)
1009
+ $acl.SetAccessRuleProtection($true, $false)
1010
+ $acl.AddAccessRule([FileSystemAccessRule]::new($sid, $rights, $inheritance,
1011
+ [PropagationFlags]::None, [AccessControlType]::Allow))
1012
+ return $acl
1013
+ }
1014
+
1015
+ function Assert-OrdinaryPath([string] $item, [bool] $directory) {
1016
+ $attributes = [File]::GetAttributes($item)
1017
+ if (($attributes -band [FileAttributes]::ReparsePoint) -or
1018
+ ([bool]($attributes -band [FileAttributes]::Directory) -ne $directory)) {
1019
+ throw 'Unexpected filesystem object'
1020
+ }
1021
+ }
1022
+
1023
+ function Assert-PrivateAcl([FileSystemSecurity] $acl, [AceFlags] $flags) {
1024
+ $descriptor = [RawSecurityDescriptor]::new($acl.GetSecurityDescriptorBinaryForm(), 0)
1025
+ if (!$acl.AreAccessRulesProtected -or $descriptor.Owner.Value -ne $sid.Value -or
1026
+ $descriptor.DiscretionaryAcl.Count -ne 1) { throw 'Unexpected state ACL' }
1027
+ $rule = $descriptor.DiscretionaryAcl[0]
1028
+ if ($rule.AceType -ne [AceType]::AccessAllowed -or $rule.AceFlags -ne $flags -or
1029
+ $rule.AccessMask -ne [int]$rights -or $rule.SecurityIdentifier.Value -ne $sid.Value) {
1030
+ throw 'Unexpected state access rule'
1031
+ }
1032
+ }
1033
+
1034
+ function Assert-PrivateDirectory([string] $directory) {
1035
+ Assert-OrdinaryPath $directory $true
1036
+ Assert-PrivateAcl ([Directory]::GetAccessControl($directory, $sections)) ([AceFlags]'ContainerInherit, ObjectInherit')
1037
+ }
1038
+
1039
+ switch ($action) {
1040
+ 'write-file' {
1041
+ $directory = [Path]::GetDirectoryName($path)
1042
+ Assert-OrdinaryPath ([Path]::GetDirectoryName($directory)) $true
1043
+ [void][Directory]::CreateDirectory($directory, (New-PrivateAcl $true))
1044
+ Assert-PrivateDirectory $directory
1045
+ $staged = [Path]::Combine($directory, '.paymos-' + [Guid]::NewGuid().ToString('N') + '.tmp')
1046
+ $file = [FileStream]::new($staged, [FileMode]::CreateNew, $rights,
1047
+ [FileShare]::None, 4096, [FileOptions]::None, (New-PrivateAcl $false))
1048
+ try {
1049
+ try {
1050
+ Assert-PrivateAcl ($file.GetAccessControl()) ([AceFlags]::None)
1051
+ [Console]::OpenStandardInput().CopyTo($file)
1052
+ $file.Flush($true)
1053
+ } finally { $file.Dispose() }
1054
+ # Same-directory move keeps the protected ACL and refuses to replace an existing file.
1055
+ [File]::Move($staged, $path)
1056
+ } catch {
1057
+ [File]::Delete($staged)
1058
+ throw
1059
+ }
1060
+ }
1061
+ 'check-file' {
1062
+ Assert-PrivateDirectory ([Path]::GetDirectoryName($path))
1063
+ Assert-OrdinaryPath $path $false
1064
+ Assert-PrivateAcl ([File]::GetAccessControl($path, $sections)) ([AceFlags]::None)
1065
+ }
1066
+ default { throw 'Unexpected action' }
1067
+ }
1068
+ } catch { exit 1 }
1069
+ `;
1070
+ function defaultDeliveryRuntime() {
1071
+ return {
1072
+ cwd: process.cwd(),
1073
+ home: userInfo().homedir,
1074
+ platform: process.platform,
1075
+ now: Date.now,
1076
+ fetch: globalThis.fetch,
1077
+ stdout: (line) => console.log(line)
1078
+ };
1079
+ }
1080
+ function failDelivery(code) {
1081
+ throw new MerchantDeliveryError(code);
1082
+ }
1083
+ async function safeDelivery(action) {
1084
+ try {
1085
+ await action();
1086
+ } catch (error2) {
1087
+ if (error2 instanceof MerchantDeliveryError) throw error2;
1088
+ failDelivery("delivery_local_io_failed");
1089
+ }
1090
+ }
1091
+ function isBase64Url(value, length) {
1092
+ if (typeof value !== "string" || value.length !== Math.ceil(length * 4 / 3) || !/^[A-Za-z0-9_-]+$/.test(value)) return false;
1093
+ const bytes = Buffer.from(value, "base64url");
1094
+ return bytes.length === length && bytes.toString("base64url") === value;
1095
+ }
1096
+ function validUuid(value) {
1097
+ return typeof value === "string" && uuid.test(value) && value !== "00000000-0000-0000-0000-000000000000";
1098
+ }
1099
+ function deliveryArguments(argv, kind) {
1100
+ const fileOption = kind === "install-secret" ? "--env-file" : "--file";
1101
+ const common = [fileOption, "--merchant-id", "--environment", "--operation-id", "--request-id", "--token"];
1102
+ const flags = /* @__PURE__ */ new Map();
1103
+ for (let i = 0; i < argv.length; i++) {
1104
+ const flag = argv[i];
1105
+ if (flags.has(flag)) failDelivery("delivery_arguments");
1106
+ if (flag === "--prepare") {
1107
+ flags.set(flag, "");
1108
+ continue;
1109
+ }
1110
+ if (!common.includes(flag)) failDelivery("delivery_arguments");
1111
+ const value = argv[++i];
1112
+ if (!value || value.startsWith("--")) failDelivery("delivery_arguments");
1113
+ flags.set(flag, value);
1114
+ }
1115
+ const file = flags.get(fileOption);
1116
+ if (!file) return failDelivery("delivery_arguments");
1117
+ if (flags.has("--prepare")) {
1118
+ const merchantId = flags.get("--merchant-id")?.toLowerCase();
1119
+ const operationId = flags.get("--operation-id")?.toLowerCase();
1120
+ const environment = flags.get("--environment")?.toLowerCase();
1121
+ if (flags.size !== 5 || !validUuid(merchantId) || !validUuid(operationId) || environment !== "sandbox" && environment !== "production") return failDelivery("delivery_arguments");
1122
+ return { prepare: true, file, scope: { merchantId, environment, operationId } };
1123
+ }
1124
+ const requestId = flags.get("--request-id");
1125
+ const ticket = flags.get("--token");
1126
+ const prefix = kind === "install-secret" ? "otk_" : "ftk_";
1127
+ if (flags.size !== 3 || !isBase64Url(requestId, 32) || !ticket?.startsWith(prefix) || !isBase64Url(ticket.slice(prefix.length), kind === "upload-file" ? 48 : 32)) {
1128
+ return failDelivery("delivery_arguments");
1129
+ }
1130
+ return { prepare: false, file, requestId, ticket };
1131
+ }
1132
+ function pathStat(path) {
1133
+ return lstatSync5(path, { bigint: true, throwIfNoEntry: false });
1134
+ }
1135
+ function sameOpenFile(path, opened) {
1136
+ return path.isFile() && opened.isFile() && path.ino === opened.ino && path.birthtimeNs === opened.birthtimeNs && (path.dev === 0n || opened.dev === 0n || path.dev === opened.dev);
1137
+ }
1138
+ function samePath2(left, right, platform) {
1139
+ return platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
1140
+ }
1141
+ function inside2(directory, path) {
1142
+ const child = relative2(directory, path);
1143
+ return child !== ".." && !child.startsWith(".." + sep2) && !isAbsolute3(child);
1144
+ }
1145
+ function ordinaryDirectory(path, platform) {
1146
+ return !!pathStat(path)?.isDirectory() && samePath2(realpathSync2(path), path, platform);
1147
+ }
1148
+ function windowsStateAcl(action, path, input) {
1149
+ const systemRoot2 = process.env.SystemRoot;
1150
+ if (process.platform !== "win32" || !systemRoot2 || !/^[A-Za-z]:[\\/]/.test(systemRoot2)) {
1151
+ return failDelivery("delivery_state_unavailable");
1152
+ }
1153
+ const windows = resolve3(systemRoot2);
1154
+ const executable = join3(windows, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
1155
+ if (!pathStat(executable)?.isFile() || !samePath2(realpathSync2(executable), executable, "win32")) {
1156
+ return failDelivery("delivery_state_unavailable");
1157
+ }
1158
+ const result = spawnSync(executable, [
1159
+ "-NoLogo",
1160
+ "-NoProfile",
1161
+ "-NonInteractive",
1162
+ "-EncodedCommand",
1163
+ Buffer.from(windowsStateScript, "utf16le").toString("base64")
1164
+ ], {
1165
+ cwd: windows,
1166
+ shell: false,
1167
+ stdio: [input === void 0 ? "ignore" : "pipe", "ignore", "ignore"],
1168
+ input,
1169
+ timeout: 1e4,
1170
+ windowsHide: true,
1171
+ env: { SystemRoot: windows, PAYMOS_DELIVERY_STATE_ACTION: action, PAYMOS_DELIVERY_STATE_PATH: path }
1172
+ });
1173
+ if (result.error || result.status !== 0) return failDelivery("delivery_state_unavailable");
1174
+ }
1175
+ function assertDeliveryTarget(target) {
1176
+ try {
1177
+ const segments = relative2(target.directory, target.path).split(sep2);
1178
+ let folder = target.directory;
1179
+ if (!ordinaryDirectory(folder, target.platform)) failDelivery("delivery_unsafe_path");
1180
+ for (const segment of segments.slice(0, -1)) {
1181
+ folder = join3(folder, segment);
1182
+ if (!ordinaryDirectory(folder, target.platform)) failDelivery("delivery_unsafe_path");
1183
+ }
1184
+ const stat2 = pathStat(target.path);
1185
+ if (stat2 && (!stat2.isFile() || stat2.nlink !== 1n || !samePath2(realpathSync2(target.path), target.path, target.platform))) {
1186
+ failDelivery("delivery_unsafe_path");
1187
+ }
1188
+ return stat2;
1189
+ } catch {
1190
+ return failDelivery("delivery_unsafe_path");
1191
+ }
1192
+ }
1193
+ function deliveryTarget(file, runtime) {
1194
+ const tail = file.slice(parse2(file).root.length);
1195
+ const segments = tail.split(/[\\/]/);
1196
+ if (/\p{Cc}/u.test(file) || /^[\\/]{2}/.test(file) || segments.some((segment) => segment === ".." || segment.toLowerCase() === ".git") || runtime.platform === "win32" && /^[a-z]:/i.test(file) && !isAbsolute3(file) || runtime.platform === "win32" && segments.some((segment) => /[:*?"<>|]/.test(segment) || segment !== "." && /[. ]$/.test(segment) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(segment)) || runtime.platform !== "win32" && file.includes("\\")) return failDelivery("delivery_unsafe_path");
1197
+ const directory = realpathSync2(runtime.cwd);
1198
+ const path = resolve3(directory, file);
1199
+ if (path === directory || !inside2(directory, path)) return failDelivery("delivery_unsafe_path");
1200
+ const target = { directory, path, platform: runtime.platform };
1201
+ assertDeliveryTarget(target);
1202
+ return target;
1203
+ }
1204
+ function stateDirectory(runtime, target, create) {
1205
+ try {
1206
+ const home = resolve3(runtime.home);
1207
+ if (!isAbsolute3(runtime.home) || !ordinaryDirectory(home, runtime.platform)) failDelivery("delivery_state_unavailable");
1208
+ const base = runtime.platform === "win32" ? join3(home, "AppData", "Local") : home;
1209
+ if (!ordinaryDirectory(base, runtime.platform)) return failDelivery("delivery_state_unavailable");
1210
+ const directory = join3(base, stateFolder);
1211
+ if (inside2(target.directory, directory) || inside2(directory, target.path)) failDelivery("delivery_unsafe_path");
1212
+ let stat2 = pathStat(directory);
1213
+ if (!stat2 && create) {
1214
+ if (runtime.platform === "win32") return directory;
1215
+ try {
1216
+ mkdirSync3(directory, { mode: 448 });
1217
+ } catch (cause) {
1218
+ if (cause.code !== "EEXIST") throw cause;
1219
+ }
1220
+ stat2 = pathStat(directory);
1221
+ }
1222
+ if (!stat2?.isDirectory() || !ordinaryDirectory(directory, runtime.platform) || runtime.platform !== "win32" && !privateMode(stat2)) {
1223
+ return failDelivery("delivery_state_unavailable");
1224
+ }
1225
+ return directory;
1226
+ } catch (cause) {
1227
+ if (cause instanceof MerchantDeliveryError) throw cause;
1228
+ return failDelivery("delivery_state_unavailable");
1229
+ }
1230
+ }
1231
+ function privateMode(stat2) {
1232
+ return (stat2.mode & 0o077n) === 0n && (process.geteuid === void 0 || stat2.uid === BigInt(process.geteuid()));
1233
+ }
1234
+ function removeExpiredState(directory, runtime, justWritten) {
1235
+ const cutoff = runtime.now() - lifetimeMs;
1236
+ for (const file of readdirSync(directory, { withFileTypes: true })) {
1237
+ if (file.name === justWritten || !file.isFile() || !/^[A-Za-z0-9_-]{43}\.json$/.test(file.name)) continue;
1238
+ const path = join3(directory, file.name);
1239
+ const stat2 = pathStat(path);
1240
+ if (stat2?.isFile() && stat2.nlink === 1n && Number(stat2.mtimeMs) <= cutoff) {
1241
+ try {
1242
+ if (runtime.platform === "win32") windowsStateAcl("check-file", path);
1243
+ unlinkSync3(path);
1244
+ } catch {
1245
+ }
1246
+ }
1247
+ }
1248
+ }
1249
+ function prepareDelivery(kind, scope, target, runtime, upload) {
1250
+ const directory = stateDirectory(runtime, target, true);
1251
+ const requestId = randomBytes(32).toString("base64url");
1252
+ const verifier = randomBytes(32).toString("base64url");
1253
+ const now = runtime.now();
1254
+ const filename = requestId + ".json";
1255
+ const path = join3(directory, filename);
1256
+ const state = JSON.stringify({
1257
+ origin,
1258
+ kind,
1259
+ ...scope,
1260
+ requestId,
1261
+ verifier,
1262
+ createdAt: now,
1263
+ expiresAt: now + lifetimeMs,
1264
+ target: target.path,
1265
+ directory: target.directory,
1266
+ upload
1267
+ });
1268
+ if (runtime.platform === "win32") {
1269
+ windowsStateAcl("write-file", path, state);
1270
+ removeExpiredState(directory, runtime, filename);
1271
+ } else {
1272
+ removeExpiredState(directory, runtime);
1273
+ writeConfig({ path, content: null }, state);
1274
+ }
1275
+ const challenge = createHash("sha256").update(verifier, "ascii").digest("base64url");
1276
+ runtime.stdout(JSON.stringify({ request_id: requestId, challenge, ...upload }));
1277
+ }
1278
+ function claimDelivery(kind, input, target, runtime, upload) {
1279
+ const directory = stateDirectory(runtime, target, false);
1280
+ const path = join3(directory, input.requestId + ".json");
1281
+ try {
1282
+ const checked = runtime.platform === "win32" ? pathStat(path) : void 0;
1283
+ if (runtime.platform === "win32") {
1284
+ if (!checked?.isFile() || checked.nlink !== 1n || checked.size > 4096n) {
1285
+ return failDelivery("delivery_state_unavailable");
1286
+ }
1287
+ windowsStateAcl("check-file", path);
1288
+ }
1289
+ return withDestinationLock(path, () => {
1290
+ const stat2 = pathStat(path);
1291
+ if (!stat2?.isFile() || stat2.nlink !== 1n || stat2.size > 4096n || (checked ? !sameOpenFile(checked, stat2) : !privateMode(stat2))) {
1292
+ return failDelivery("delivery_state_unavailable");
1293
+ }
1294
+ const before = snapshot(path);
1295
+ if (before.content === null || stat2.ino !== before.identity.ino || stat2.dev !== before.identity.dev || stat2.birthtimeNs !== before.identity.birthtimeNs) return failDelivery("delivery_state_unavailable");
1296
+ const state = parseConfig("jsonc", before.content);
1297
+ const now = runtime.now();
1298
+ if (state.origin !== origin || state.requestId !== input.requestId || !isBase64Url(state.verifier, 32) || !validUuid(state.merchantId) || !validUuid(state.operationId) || state.environment !== "sandbox" && state.environment !== "production" || typeof state.createdAt !== "number" || typeof state.expiresAt !== "number" || !Number.isSafeInteger(state.createdAt) || !Number.isSafeInteger(state.expiresAt) || state.createdAt > now || state.expiresAt <= state.createdAt || state.expiresAt - state.createdAt > lifetimeMs) {
1299
+ return failDelivery("delivery_state_unavailable");
1300
+ }
1301
+ const consume = () => {
1302
+ if (checked) {
1303
+ const current = pathStat(path);
1304
+ if (!current || !sameOpenFile(stat2, current) || current.nlink !== 1n || current.size !== stat2.size || current.mtimeNs !== stat2.mtimeNs || current.ctimeNs !== stat2.ctimeNs) {
1305
+ return failDelivery("delivery_state_unavailable");
1306
+ }
1307
+ } else assertUnchanged(before);
1308
+ unlinkSync3(path);
1309
+ };
1310
+ if (state.expiresAt <= now) {
1311
+ consume();
1312
+ return failDelivery("delivery_state_unavailable");
1313
+ }
1314
+ if (state.kind !== kind || state.directory !== target.directory || state.target !== target.path || upload && (!object(state.upload) || upload.byte_length !== state.upload.byte_length || upload.content_sha256 !== state.upload.content_sha256 || upload.content_type !== state.upload.content_type) || !upload && state.upload !== void 0) return failDelivery("delivery_context_mismatch");
1315
+ consume();
1316
+ return {
1317
+ requestId: input.requestId,
1318
+ verifier: state.verifier,
1319
+ expiresAt: state.expiresAt,
1320
+ merchantId: state.merchantId,
1321
+ environment: state.environment,
1322
+ operationId: state.operationId
1323
+ };
1324
+ });
1325
+ } catch (cause) {
1326
+ if (cause instanceof MerchantDeliveryError) throw cause;
1327
+ return failDelivery("delivery_state_unavailable");
1328
+ }
1329
+ }
1330
+ function checkDeliveryExpiry(proof, runtime) {
1331
+ if (runtime.now() >= proof.expiresAt) failDelivery("delivery_state_unavailable");
1332
+ }
1333
+ async function redeemDelivery(kind, input, proof, runtime, upload) {
1334
+ checkDeliveryExpiry(proof, runtime);
1335
+ const install = kind === "install-secret";
1336
+ const url = origin + resource + (install ? "/tickets/secret/redeem" : "/files/" + input.ticket);
1337
+ const headers = new Headers({ "Accept-Encoding": "identity", "Cache-Control": "no-store" });
1338
+ let body;
1339
+ if (install) {
1340
+ headers.set("Content-Type", "application/json");
1341
+ body = JSON.stringify({ ticket: input.ticket, request_id: proof.requestId, verifier: proof.verifier });
1342
+ } else {
1343
+ headers.set("Paymos-Delivery-Request", proof.requestId);
1344
+ headers.set("Paymos-Delivery-Verifier", proof.verifier);
1345
+ if (upload) {
1346
+ headers.set("Content-Type", upload.descriptor.content_type);
1347
+ body = upload.bytes;
1348
+ }
1349
+ }
1350
+ let response;
1351
+ try {
1352
+ response = await runtime.fetch(url, {
1353
+ method: kind === "download-file" ? "GET" : "POST",
1354
+ headers,
1355
+ ...body === void 0 ? {} : { body },
1356
+ credentials: "omit",
1357
+ redirect: "error",
1358
+ referrerPolicy: "no-referrer",
1359
+ signal: AbortSignal.timeout(Math.max(1, Math.min(requestTimeoutMs, proof.expiresAt - runtime.now())))
1360
+ });
1361
+ } catch {
1362
+ return failDelivery("delivery_request_failed");
1363
+ }
1364
+ if (response.redirected || response.url && response.url !== url || response.status !== (kind === "upload-file" ? 204 : 200)) {
1365
+ void response.body?.cancel().catch(() => {
1366
+ });
1367
+ if (response.status === 413) return failDelivery("delivery_file_too_large");
1368
+ if (response.status === 404 || response.status === 410) return failDelivery("delivery_unavailable");
1369
+ return failDelivery("delivery_request_failed");
1370
+ }
1371
+ return response;
1372
+ }
1373
+ function responseType(response) {
1374
+ return response.headers.get("Content-Type")?.split(";")[0]?.trim().toLowerCase();
1375
+ }
1376
+ async function streamDelivery(response, limit, write) {
1377
+ const rawLength = response.headers.get("Content-Length");
1378
+ const encoding = response.headers.get("Content-Encoding");
1379
+ const advertised = rawLength === null || encoding && encoding !== "identity" ? void 0 : Number(rawLength);
1380
+ if (advertised !== void 0 && (!/^\d+$/.test(rawLength) || !Number.isSafeInteger(advertised) || advertised > limit)) return failDelivery("delivery_file_too_large");
1381
+ if (!response.body) return failDelivery("delivery_invalid_response");
1382
+ const reader = response.body.getReader();
1383
+ let bytes = 0;
1384
+ let completed = false;
1385
+ try {
1386
+ while (true) {
1387
+ let next;
1388
+ try {
1389
+ next = await reader.read();
1390
+ } catch {
1391
+ return failDelivery("delivery_request_failed");
1392
+ }
1393
+ if (next.done) break;
1394
+ bytes += next.value.byteLength;
1395
+ if (bytes > limit) failDelivery("delivery_file_too_large");
1396
+ if (advertised !== void 0 && bytes > advertised) failDelivery("delivery_invalid_response");
1397
+ await write(next.value);
1398
+ }
1399
+ if (advertised !== void 0 && bytes !== advertised) failDelivery("delivery_invalid_response");
1400
+ completed = true;
1401
+ return bytes;
1402
+ } finally {
1403
+ if (!completed) void reader.cancel().catch(() => {
1404
+ });
1405
+ reader.releaseLock();
1406
+ }
1407
+ }
1408
+ var secretKeys = {
1409
+ payment: ["PAYMOS_API_KEY", "PAYMOS_API_SECRET"],
1410
+ payout: ["PAYMOS_PAYOUT_API_KEY", "PAYMOS_PAYOUT_API_SECRET"],
1411
+ webhook: ["PAYMOS_WEBHOOK_SECRET"],
1412
+ invite: ["PAYMOS_INVITE_LINK"]
1413
+ };
1414
+ async function redeemedFields(response, proof) {
1415
+ if (responseType(response) !== "application/json") return failDelivery("delivery_invalid_response");
1416
+ const chunks = [];
1417
+ await streamDelivery(response, 16384, (chunk) => {
1418
+ chunks.push(chunk);
1419
+ });
1420
+ let body;
1421
+ try {
1422
+ body = parseConfig("jsonc", new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
1423
+ } catch {
1424
+ return failDelivery("delivery_invalid_response");
1425
+ }
1426
+ if (body.request_id !== proof.requestId || body.merchant_id !== proof.merchantId || body.environment !== proof.environment || body.operation_id !== proof.operationId) {
1427
+ return failDelivery("delivery_context_mismatch");
1428
+ }
1429
+ const kind = body.kind;
1430
+ if (typeof kind !== "string" || !Object.hasOwn(secretKeys, kind) || !object(body.fields)) {
1431
+ return failDelivery("delivery_invalid_response");
1432
+ }
1433
+ const keys = secretKeys[kind];
1434
+ if (Object.keys(body).length !== 7 || body.suggested_env_key !== keys[0] || Object.keys(body.fields).length !== keys.length) {
1435
+ return failDelivery("delivery_invalid_response");
1436
+ }
1437
+ const fields = {};
1438
+ for (const key of keys) {
1439
+ const value = body.fields[key];
1440
+ if (typeof value !== "string" || value.length === 0 || Buffer.byteLength(value, "utf8") > 4096 || /['\p{Cc}]/u.test(value)) return failDelivery("delivery_invalid_response");
1441
+ fields[key] = value;
1442
+ }
1443
+ return fields;
1444
+ }
1445
+ function mergeEnv(original, fields) {
1446
+ if (original.includes("\uFFFD")) return failDelivery("delivery_local_io_failed");
1447
+ const bom = original.startsWith("\uFEFF") ? "\uFEFF" : "";
1448
+ const text = original.slice(bom.length);
1449
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
1450
+ const before = parseEnv(text);
1451
+ const kept = text.split(/(?<=\n)/).filter((line) => {
1452
+ const assignment = /^[ \t]*(?:export[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*=/.exec(line);
1453
+ if (!assignment || !Object.hasOwn(fields, assignment[1])) return true;
1454
+ const value = line.slice(assignment[0].length).trim();
1455
+ const quote = value[0];
1456
+ if ((quote === "'" || quote === '"' || quote === "`") && value.indexOf(quote, 1) < 0) {
1457
+ failDelivery("delivery_local_io_failed");
1458
+ }
1459
+ return false;
1460
+ }).join("");
1461
+ const lines = Object.entries(fields).map(([key, value]) => key + "='" + value + "'" + eol).join("");
1462
+ const next = kept + (kept === "" || kept.endsWith("\n") ? "" : eol) + lines;
1463
+ const parsed = parseEnv(next);
1464
+ const expected = { ...before, ...fields };
1465
+ if (Object.keys(parsed).length !== Object.keys(expected).length || Object.entries(expected).some(([key, value]) => parsed[key] !== value)) return failDelivery("delivery_local_io_failed");
1466
+ return bom + next;
1467
+ }
1468
+ async function runInstallSecret(argv, runtime) {
1469
+ return safeDelivery(async () => {
1470
+ const input = deliveryArguments(argv, "install-secret");
1471
+ const io = runtime ?? defaultDeliveryRuntime();
1472
+ const target = deliveryTarget(input.file, io);
1473
+ const before = snapshot(target.path);
1474
+ if (input.prepare) {
1475
+ prepareDelivery("install-secret", input.scope, target, io);
1476
+ return;
1477
+ }
1478
+ const proof = claimDelivery("install-secret", input, target, io);
1479
+ const response = await redeemDelivery("install-secret", input, proof, io);
1480
+ const fields = await redeemedFields(response, proof);
1481
+ withDestinationLock(target.path, () => {
1482
+ checkDeliveryExpiry(proof, io);
1483
+ assertDeliveryTarget(target);
1484
+ assertUnchanged(before);
1485
+ writeConfig(before, mergeEnv(before.content ?? "", fields));
1486
+ });
1487
+ io.stdout(JSON.stringify({ status: "installed" }));
1488
+ });
1489
+ }
1490
+
1491
+ // src/files.ts
1492
+ var maxUploadBytes = 2 * 1024 * 1024;
1493
+ var maxDownloadBytes = 128 * 1024 * 1024;
1494
+ var exportTypes = /* @__PURE__ */ new Set([
1495
+ "text/csv",
1496
+ "application/zip",
1497
+ "application/x-zip-compressed",
1498
+ "application/octet-stream",
1499
+ "image/png",
1500
+ "image/svg+xml"
1501
+ ]);
1502
+ function imageType(bytes) {
1503
+ if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return "image/png";
1504
+ if (bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255]))) return "image/jpeg";
1505
+ if (bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WEBP") return "image/webp";
1506
+ return failDelivery("delivery_context_mismatch");
1507
+ }
1508
+ function readUpload(target) {
1509
+ const stat2 = assertDeliveryTarget(target);
1510
+ if (!stat2 || stat2.size <= 0n) return failDelivery("delivery_unsafe_path");
1511
+ if (stat2.size > BigInt(maxUploadBytes)) return failDelivery("delivery_file_too_large");
1512
+ const fd = openSync4(target.path, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
1513
+ try {
1514
+ const opened = fstatSync4(fd, { bigint: true });
1515
+ if (!sameOpenFile(stat2, opened) || opened.size !== stat2.size) return failDelivery("delivery_context_mismatch");
1516
+ const bytes = Buffer.alloc(Number(stat2.size));
1517
+ let offset = 0;
1518
+ while (offset < bytes.length) {
1519
+ const count = readSync(fd, bytes, offset, bytes.length - offset, null);
1520
+ if (!count) return failDelivery("delivery_context_mismatch");
1521
+ offset += count;
1522
+ }
1523
+ const after = assertDeliveryTarget(target);
1524
+ if (readSync(fd, Buffer.alloc(1), 0, 1, null) !== 0 || !after || !sameOpenFile(after, opened) || after.mtimeNs !== stat2.mtimeNs || after.size !== stat2.size) return failDelivery("delivery_context_mismatch");
1525
+ return { bytes, descriptor: {
1526
+ byte_length: bytes.length,
1527
+ content_sha256: createHash2("sha256").update(bytes).digest("hex"),
1528
+ content_type: imageType(bytes)
1529
+ } };
1530
+ } finally {
1531
+ closeSync4(fd);
1532
+ }
1533
+ }
1534
+ async function runUploadFile(argv, runtime) {
1535
+ return safeDelivery(async () => {
1536
+ const input = deliveryArguments(argv, "upload-file");
1537
+ const io = runtime ?? defaultDeliveryRuntime();
1538
+ const target = deliveryTarget(input.file, io);
1539
+ const upload = readUpload(target);
1540
+ if (input.prepare) {
1541
+ prepareDelivery("upload-file", input.scope, target, io, upload.descriptor);
1542
+ return;
1543
+ }
1544
+ const proof = claimDelivery("upload-file", input, target, io, upload.descriptor);
1545
+ await redeemDelivery("upload-file", input, proof, io, upload);
1546
+ io.stdout(JSON.stringify({ status: "staged" }));
1547
+ });
1548
+ }
1549
+ async function runDownloadFile(argv, runtime) {
1550
+ return safeDelivery(async () => {
1551
+ const input = deliveryArguments(argv, "download-file");
1552
+ const io = runtime ?? defaultDeliveryRuntime();
1553
+ const target = deliveryTarget(input.file, io);
1554
+ if (assertDeliveryTarget(target)) failDelivery("delivery_unsafe_path");
1555
+ if (input.prepare) {
1556
+ prepareDelivery("download-file", input.scope, target, io);
1557
+ return;
1558
+ }
1559
+ const proof = claimDelivery("download-file", input, target, io);
1560
+ const temp = join4(dirname4(target.path), ".paymos-download-" + randomUUID2() + ".tmp");
1561
+ const file = await open(temp, "wx", 384);
1562
+ let identity;
1563
+ let closed = false;
1564
+ try {
1565
+ identity = await file.stat({ bigint: true });
1566
+ if (process.platform !== "win32") await file.chmod(384);
1567
+ const response = await redeemDelivery("download-file", input, proof, io);
1568
+ if (!exportTypes.has(responseType(response) ?? "")) {
1569
+ void response.body?.cancel().catch(() => {
1570
+ });
1571
+ failDelivery("delivery_invalid_response");
1572
+ }
1573
+ const bytes = await streamDelivery(response, maxDownloadBytes, (chunk) => file.writeFile(chunk));
1574
+ await file.sync();
1575
+ await file.close();
1576
+ closed = true;
1577
+ withDestinationLock(target.path, () => {
1578
+ checkDeliveryExpiry(proof, io);
1579
+ if (assertDeliveryTarget(target)) failDelivery("delivery_unsafe_path");
1580
+ const staged = lstatSync6(temp, { bigint: true });
1581
+ if (!sameOpenFile(staged, identity) || staged.size !== BigInt(bytes)) failDelivery("delivery_context_mismatch");
1582
+ linkSync2(temp, target.path);
1583
+ });
1584
+ io.stdout(JSON.stringify({ status: "downloaded", byte_length: bytes }));
1585
+ } finally {
1586
+ if (!closed) await file.close().catch(() => {
1587
+ });
1588
+ try {
1589
+ if (identity && sameOpenFile(lstatSync6(temp, { bigint: true }), identity)) unlinkSync4(temp);
1590
+ } catch {
1591
+ }
1592
+ }
1593
+ });
1594
+ }
1595
+
1596
+ // src/gateway.ts
1597
+ import { Paymos } from "@paymos/sdk";
1598
+
1599
+ // src/errors.ts
1600
+ import { ApiError } from "@paymos/sdk";
1601
+ var ToolError = class extends Error {
1602
+ code;
1603
+ constructor(code, message) {
1604
+ super(message);
1605
+ this.name = "ToolError";
1606
+ this.code = code;
1607
+ }
1608
+ };
1609
+ function toolErrorFrom(error2) {
1610
+ if (error2 instanceof ToolError) return error2;
1611
+ if (error2 instanceof ApiError) {
1612
+ const code = error2.code === "" ? "api_error" : error2.code;
1613
+ return new ToolError(`paymos/${code}`, error2.message);
1614
+ }
1615
+ const message = error2 instanceof Error ? error2.message : String(error2);
1616
+ return new ToolError("paymos/sdk_error", message);
1617
+ }
1618
+
1619
+ // src/gateway.ts
1620
+ var PaymosGateway = class {
1621
+ credentials;
1622
+ overrides;
1623
+ constructor(credentials, overrides = {}) {
1624
+ this.credentials = credentials;
1625
+ this.overrides = overrides;
1626
+ }
1627
+ check() {
1628
+ return checkCredentials(this.credentials);
1629
+ }
1630
+ /** Webhook signing secret for the local `verify_webhook_signature` tool. */
1631
+ webhookSecret() {
1632
+ return this.credentials.webhookSecret;
1633
+ }
1634
+ client() {
1635
+ const check = this.check();
1636
+ if (!check.ok) throw new ToolError(check.code, check.message);
1637
+ return new Paymos({
1638
+ apiKey: this.credentials.apiKeyId,
1639
+ apiSecret: this.credentials.apiSecret,
1640
+ ...this.overrides.fetch ? { fetch: this.overrides.fetch } : {}
1641
+ });
1642
+ }
1643
+ invoices() {
1644
+ return this.client().invoices;
1645
+ }
1646
+ paymentChannels() {
1647
+ return this.client().paymentChannels;
1648
+ }
1649
+ paymentChannelDeposits() {
1650
+ return this.client().paymentChannelDeposits;
1651
+ }
1652
+ };
1653
+
1654
+ // src/server.ts
1655
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1656
+
1657
+ // src/tools.ts
1658
+ import { z } from "zod";
1659
+ import { TimestampSkewError, WebhookVerifier } from "@paymos/sdk";
1660
+
1661
+ // src/wire-shape.ts
1662
+ function toWireShape(value) {
1663
+ if (Array.isArray(value)) return value.map(toWireShape);
1664
+ if (value === null || typeof value !== "object") return value;
1665
+ const out = {};
1666
+ for (const [key, item] of Object.entries(value)) {
1667
+ out[key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)] = toWireShape(item);
1668
+ }
1669
+ return out;
1670
+ }
1671
+
1672
+ // src/tools.ts
1673
+ var NETWORKS = "TRC20, ERC20, BEP20, POLYGON, ARBITRUM, OPTIMISM, BASE, TON, AVAX, SOL, NEAR, SUI, PLASMA";
1674
+ var INVOICE_STATUSES = [
1675
+ "awaiting_client",
1676
+ "awaiting_payment",
1677
+ "confirming",
1678
+ "underpaid_waiting",
1679
+ "paid",
1680
+ "paid_over",
1681
+ "underpaid",
1682
+ "expired",
1683
+ "cancelled"
1684
+ ];
1685
+ var INVOICE_RESULT_HINT = "Returns the invoice in wire form: invoice_id, status, payment_url, order, payment (expected, address, transfers), expires_at. status: awaiting_client | awaiting_payment | confirming | underpaid_waiting | paid | paid_over | underpaid | expired | cancelled.";
1686
+ function textJson(value) {
1687
+ return {
1688
+ content: [{ type: "text", text: JSON.stringify(value, null, 2) }]
1689
+ };
1690
+ }
1691
+ function failure(error2) {
1692
+ const toolError = toolErrorFrom(error2);
1693
+ return {
1694
+ isError: true,
1695
+ content: [{ type: "text", text: JSON.stringify({ code: toolError.code, message: toolError.message }, null, 2) }]
1696
+ };
1697
+ }
1698
+ async function guarded(run) {
1699
+ try {
1700
+ return await run();
1701
+ } catch (error2) {
1702
+ return failure(error2);
1703
+ }
1704
+ }
1705
+ function registerTools(server, gateway) {
1706
+ server.registerTool(
1707
+ "create_payment_channel",
1708
+ {
1709
+ title: "Create payment channel",
1710
+ description: "Create a Sandbox payment channel using project_id and external_id. Repeating the same pair returns the existing channel.",
1711
+ inputSchema: {
1712
+ project_id: z.string().min(1).describe("Project ID."),
1713
+ external_id: z.string().min(1).max(128).describe("Your identifier for the payer; channel creation is idempotent within the project.")
1714
+ }
1715
+ },
1716
+ async ({ project_id, external_id }) => guarded(async () => {
1717
+ const channel = await gateway.paymentChannels().create({ projectId: project_id, externalId: external_id });
1718
+ return textJson(toWireShape(channel));
1719
+ })
1720
+ );
1721
+ server.registerTool(
1722
+ "get_payment_channel",
1723
+ {
1724
+ title: "Get payment channel",
1725
+ description: "Read a Sandbox payment channel by ID, including its current status and available deposit addresses.",
1726
+ inputSchema: { payment_channel_id: z.string().min(1).describe("Payment channel ID.") }
1727
+ },
1728
+ async ({ payment_channel_id }) => guarded(async () => textJson(toWireShape(await gateway.paymentChannels().get(payment_channel_id))))
1729
+ );
1730
+ server.registerTool(
1731
+ "list_payment_channels",
1732
+ {
1733
+ title: "List payment channels",
1734
+ description: "List Sandbox payment channels with optional project_id, external_id, and status filters. Use limit and cursor to request one page at a time.",
1735
+ inputSchema: {
1736
+ project_id: z.string().min(1).optional().describe("Project ID."),
1737
+ external_id: z.string().min(1).max(128).optional().describe("Your identifier for the payer; channel creation is idempotent within the project."),
1738
+ status: z.array(z.enum(["active", "blocked", "provisioning"])).optional().describe("Array of channel statuses to include: active, blocked, or provisioning."),
1739
+ limit: z.number().int().min(1).max(100).optional().describe("Maximum number of items to return in this page."),
1740
+ cursor: z.string().optional().describe("Pagination cursor from the previous channel-list response.")
1741
+ }
1742
+ },
1743
+ async ({ project_id, external_id, status, limit, cursor }) => guarded(async () => {
1744
+ const page = await gateway.paymentChannels().list({
1745
+ ...project_id !== void 0 ? { projectId: project_id } : {},
1746
+ ...external_id !== void 0 ? { externalId: external_id } : {},
1747
+ ...status !== void 0 ? { status } : {},
1748
+ ...limit !== void 0 ? { limit } : {},
1749
+ ...cursor !== void 0 ? { cursor } : {}
1750
+ });
1751
+ return textJson(toWireShape(page));
1752
+ })
1753
+ );
1754
+ server.registerTool(
1755
+ "block_payment_channel",
1756
+ {
1757
+ title: "Block payment channel",
1758
+ description: "Set a Sandbox payment channel's status to blocked.",
1759
+ inputSchema: { payment_channel_id: z.string().min(1).describe("Payment channel ID.") }
1760
+ },
1761
+ async ({ payment_channel_id }) => guarded(async () => textJson(toWireShape(await gateway.paymentChannels().block(payment_channel_id))))
1762
+ );
1763
+ server.registerTool(
1764
+ "unblock_payment_channel",
1765
+ {
1766
+ title: "Unblock payment channel",
1767
+ description: "Clear a Sandbox payment channel's blocked status.",
1768
+ inputSchema: { payment_channel_id: z.string().min(1).describe("Payment channel ID.") }
1769
+ },
1770
+ async ({ payment_channel_id }) => guarded(async () => textJson(toWireShape(await gateway.paymentChannels().unblock(payment_channel_id))))
1771
+ );
1772
+ server.registerTool(
1773
+ "simulate_payment_channel_deposit",
1774
+ {
1775
+ title: "Simulate payment channel deposit",
1776
+ description: "Create a new Sandbox deposit on every call using a channel ID, decimal-string amount, currency, and network. The optional stage accepts confirming, reorged, or confirmed and defaults to confirmed. No real blockchain is called, and no real funds move.",
1777
+ inputSchema: {
1778
+ payment_channel_id: z.string().min(1).describe("Payment channel ID."),
1779
+ amount: z.string().min(1).describe("Deposit amount as a decimal string."),
1780
+ currency: z.string().min(1).describe("Currency symbol for the simulated deposit."),
1781
+ network: z.string().min(1).describe("Network for the simulated deposit."),
1782
+ stage: z.enum(["confirming", "reorged", "confirmed"]).optional().describe("Simulated deposit stage: confirming, reorged, or confirmed. Defaults to confirmed when omitted.")
1783
+ }
1784
+ },
1785
+ async ({ payment_channel_id, amount, currency, network, stage }) => guarded(async () => {
1786
+ const deposit = await gateway.paymentChannels().simulateDeposit(payment_channel_id, {
1787
+ amount,
1788
+ currency,
1789
+ network,
1790
+ ...stage !== void 0 ? { stage } : {}
1791
+ });
1792
+ return textJson(toWireShape(deposit));
1793
+ })
1794
+ );
1795
+ server.registerTool(
1796
+ "get_payment_channel_deposit",
1797
+ {
1798
+ title: "Get payment channel deposit",
1799
+ description: "Read a Sandbox payment channel deposit by ID at any stage, including confirming, reorged, and confirmed.",
1800
+ inputSchema: { payment_channel_deposit_id: z.string().min(1).describe("Payment channel deposit ID.") }
1801
+ },
1802
+ async ({ payment_channel_deposit_id }) => guarded(async () => textJson(toWireShape(await gateway.paymentChannelDeposits().get(payment_channel_deposit_id))))
1803
+ );
1804
+ server.registerTool(
1805
+ "list_payment_channel_deposits",
1806
+ {
1807
+ title: "List confirmed channel deposits",
1808
+ description: "Poll confirmed Sandbox deposits, oldest first. Every response includes next_cursor, even on an empty page; save it for the next poll. If the feed stops advancing, the optional blocked field identifies the deposit and explains why.",
1809
+ inputSchema: {
1810
+ limit: z.number().int().min(1).max(100).optional().describe("Maximum number of items to return in this page."),
1811
+ cursor: z.string().optional().describe("Cursor from the previous response. For the deposit feed, keep it even after an empty page."),
1812
+ project_id: z.string().min(1).optional().describe("Project ID."),
1813
+ payment_channel_id: z.string().min(1).optional().describe("Payment channel ID."),
1814
+ confirmed_from: z.number().int().optional().describe("Inclusive lower bound in Unix seconds for the initial poll. Keep the same value when continuing with a cursor.")
1815
+ }
1816
+ },
1817
+ async ({ limit, cursor, project_id, payment_channel_id, confirmed_from }) => guarded(async () => {
1818
+ const page = await gateway.paymentChannelDeposits().read({
1819
+ ...limit !== void 0 ? { limit } : {},
1820
+ ...cursor !== void 0 ? { cursor } : {},
1821
+ ...project_id !== void 0 ? { projectId: project_id } : {},
1822
+ ...payment_channel_id !== void 0 ? { paymentChannelId: payment_channel_id } : {},
1823
+ ...confirmed_from !== void 0 ? { confirmedFrom: confirmed_from } : {}
1824
+ });
1825
+ return textJson(toWireShape(page));
1826
+ })
1827
+ );
1828
+ server.registerTool(
1829
+ "create_invoice",
1830
+ {
1831
+ title: "Create a sandbox invoice",
1832
+ description: "Create a Paymos invoice and get a hosted payment_url the customer opens. Idempotent per project: reuse the same external_order_id and you get the existing invoice back instead of a duplicate. " + INVOICE_RESULT_HINT,
1833
+ inputSchema: {
1834
+ project_id: z.string().min(1).describe("Project receiving the invoice (prj_\u2026)"),
1835
+ amount: z.string().min(1).describe('Decimal string, e.g. "50.00" \u2014 amounts are strings, never floats'),
1836
+ currency: z.string().min(2).describe("Fiat code (USD, EUR\u2026) or stablecoin symbol (USDT, USDC\u2026)"),
1837
+ network: z.string().optional().describe(
1838
+ `Locks the crypto invoice to one network: ${NETWORKS}. Omit to let the customer choose on the payment page`
1839
+ ),
1840
+ external_order_id: z.string().min(1).max(128).describe("Your order identifier (\u2264128 chars); idempotency key per project"),
1841
+ customer_fee_percent: z.number().int().min(0).max(100).optional().describe("0\u2013100 service fee percent charged to the customer; overrides the project setting"),
1842
+ client_id: z.string().max(200).optional().describe("Your customer reference (\u2264200 chars)")
1843
+ }
1844
+ },
1845
+ async ({
1846
+ project_id,
1847
+ amount,
1848
+ currency,
1849
+ network,
1850
+ external_order_id,
1851
+ customer_fee_percent,
1852
+ client_id
1853
+ }) => guarded(async () => {
1854
+ const invoice = await gateway.invoices().create({
1855
+ projectId: project_id,
1856
+ amount,
1857
+ currency,
1858
+ externalOrderId: external_order_id,
1859
+ ...network !== void 0 ? { network } : {},
1860
+ ...customer_fee_percent !== void 0 ? { customerFeePercent: customer_fee_percent } : {},
1861
+ ...client_id !== void 0 ? { clientId: client_id } : {}
1862
+ });
1863
+ return textJson(toWireShape(invoice));
1864
+ })
1865
+ );
1866
+ server.registerTool(
1867
+ "get_invoice",
1868
+ {
1869
+ title: "Read an invoice",
1870
+ description: "Fetch the current state of one Paymos invoice by invoice_id. " + INVOICE_RESULT_HINT,
1871
+ inputSchema: {
1872
+ invoice_id: z.string().min(1).describe("Invoice identifier (inv_\u2026)")
1873
+ }
1874
+ },
1875
+ async ({ invoice_id }) => guarded(async () => {
1876
+ const invoice = await gateway.invoices().get(invoice_id);
1877
+ return textJson(toWireShape(invoice));
1878
+ })
1879
+ );
1880
+ server.registerTool(
1881
+ "list_invoices",
1882
+ {
1883
+ title: "List invoices",
1884
+ description: "Read one cursor-paginated page of invoices for a project. Filters: status (repeatable), external_order_id, created_from/created_to (Unix seconds). The result carries items[] and next_cursor \u2014 next_cursor is absent on the last page. Poll with the returned cursor; do not guess offsets.",
1885
+ inputSchema: {
1886
+ project_id: z.string().min(1).describe("Project whose invoices to list (prj_\u2026)"),
1887
+ limit: z.number().int().positive().optional().describe("Page size; the server default and maximum apply"),
1888
+ cursor: z.string().optional().describe("Cursor from a previous list_invoices response"),
1889
+ status: z.array(z.enum(INVOICE_STATUSES)).optional().describe(
1890
+ "Repeatable status filter: awaiting_client | awaiting_payment | confirming | underpaid_waiting | paid | paid_over | underpaid | expired | cancelled"
1891
+ ),
1892
+ external_order_id: z.string().optional().describe("Filter by your order identifier"),
1893
+ created_from: z.number().int().optional().describe("Unix seconds, inclusive lower bound"),
1894
+ created_to: z.number().int().optional().describe("Unix seconds, inclusive upper bound")
1895
+ }
1896
+ },
1897
+ async ({ project_id, limit, cursor, status, external_order_id, created_from, created_to }) => guarded(async () => {
1898
+ const page = await gateway.invoices().list({
1899
+ projectId: project_id,
1900
+ ...limit !== void 0 ? { limit } : {},
1901
+ ...cursor !== void 0 ? { cursor } : {},
1902
+ ...status !== void 0 ? { status } : {},
1903
+ ...external_order_id !== void 0 ? { externalOrderId: external_order_id } : {},
1904
+ ...created_from !== void 0 ? { createdFrom: created_from } : {},
1905
+ ...created_to !== void 0 ? { createdTo: created_to } : {}
1906
+ });
1907
+ return textJson(toWireShape(page));
1908
+ })
1909
+ );
1910
+ server.registerTool(
1911
+ "cancel_invoice",
1912
+ {
1913
+ title: "Cancel an invoice",
1914
+ description: "Cancel an invoice that has not been paid yet; the reason is stored on the record. Invoices in a final status (paid, paid_over, underpaid, expired, cancelled) cannot be cancelled. " + INVOICE_RESULT_HINT,
1915
+ inputSchema: {
1916
+ invoice_id: z.string().min(1).describe("Invoice identifier (inv_\u2026)"),
1917
+ reason: z.string().min(1).max(500).describe("Why the invoice is cancelled (1\u2013500 chars, stored)")
1918
+ }
1919
+ },
1920
+ async ({ invoice_id, reason }) => guarded(async () => {
1921
+ const invoice = await gateway.invoices().cancel(invoice_id, reason);
1922
+ return textJson(toWireShape(invoice));
1923
+ })
1924
+ );
1925
+ server.registerTool(
1926
+ "simulate_invoice_payment",
1927
+ {
1928
+ title: "Simulate a sandbox payment",
1929
+ description: "Sandbox only: drive a test invoice through a payment outcome without touching a blockchain. The server derives the amounts \u2014 never compute money client-side. stage=paid marks it fully paid; overpaid pays more than expected; underpay pays less (invoice lands in underpaid waiting for a top-up); cancel voids it; paid_late pays the full amount after the deadline \u2014 the invoice keeps its terminal decision and gains the late-payment mark. " + INVOICE_RESULT_HINT,
1930
+ inputSchema: {
1931
+ invoice_id: z.string().min(1).describe("Test invoice identifier (is_test=true)"),
1932
+ stage: z.enum(["paid", "overpaid", "underpay", "cancel", "paid_late"]).describe("Outcome to simulate: paid | overpaid | underpay | cancel | paid_late")
1933
+ }
1934
+ },
1935
+ async ({ invoice_id, stage }) => guarded(async () => {
1936
+ const invoice = await gateway.invoices().simulatePayment(invoice_id, stage);
1937
+ return textJson(toWireShape(invoice));
1938
+ })
1939
+ );
1940
+ server.registerTool(
1941
+ "verify_webhook_signature",
1942
+ {
1943
+ title: "Verify a webhook signature",
1944
+ description: 'Verify the X-Webhook-Signature header of a Paymos webhook against its raw body, locally (no API call). Header format: t={unix},v1={hmac_hex("{unix}.{payload}")}; during secret rotation two v1= values are present and either may match. Use the raw request body byte-for-byte \u2014 re-serialized JSON breaks the signature.',
1945
+ inputSchema: {
1946
+ payload: z.string().min(1).describe("The raw webhook body exactly as received"),
1947
+ signature_header: z.string().describe("The X-Webhook-Signature header value, e.g. t=1760000000,v1=9f2c\u2026"),
1948
+ secret: z.string().optional().describe("Webhook secret (whsec_\u2026); defaults to PAYMOS_WEBHOOK_SECRET"),
1949
+ tolerance_seconds: z.number().int().min(0).optional().describe("Max age of the t= timestamp (default 300); older headers are rejected as expired")
1950
+ }
1951
+ },
1952
+ async ({ payload, signature_header, secret, tolerance_seconds }) => {
1953
+ const effectiveSecret = secret ?? gateway.webhookSecret();
1954
+ if (effectiveSecret === void 0) {
1955
+ return textJson({ valid: false, reason: "missing_secret" });
1956
+ }
1957
+ const verifier = new WebhookVerifier(
1958
+ effectiveSecret,
1959
+ tolerance_seconds === void 0 ? 300 : tolerance_seconds
1960
+ );
1961
+ try {
1962
+ verifier.assertValid(signature_header, payload);
1963
+ return textJson({ valid: true });
1964
+ } catch (error2) {
1965
+ if (error2 instanceof TimestampSkewError) return textJson({ valid: false, reason: "expired" });
1966
+ return textJson({ valid: false, reason: "bad_signature" });
1967
+ }
1968
+ }
1969
+ );
1970
+ }
1971
+
1972
+ // src/generated/resources.ts
1973
+ var DOC_RESOURCES = [
1974
+ {
1975
+ "name": "quick-start",
1976
+ "slug": "quick-start",
1977
+ "uri": "paymos://docs/quick-start",
1978
+ "description": "Paymos quick start: create a test key pair, issue the first invoice, take the first payment.",
1979
+ "mimeType": "text/html",
1980
+ "text": `<h2 id="create-an-account">Create an account</h2>
1981
+ <p>Sign in at <a href="/">paymos.io</a> with an email magic link (or Google / passkey) \u2014 no password to set.</p>
1982
+ <h2 id="create-a-project">Create a project</h2>
1983
+ <p>Open <a href="/projects/create"><strong>Dashboard \u2192 Projects \u2192 New project</strong></a>, name the project, and enable the asset and network pairs your customers will use.</p>
1984
+ <h2 id="get-your-test-api-keys">Get your test API keys</h2>
1985
+ <p>Navigate to <a href="/developers/api"><strong>Dashboard \u2192 Developer \u2192 API Keys</strong></a> and generate a test key pair:</p>
1986
+ <ul class="list-none p-0 m-0 flex flex-col gap-3"><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><strong>Payment Key</strong> (<code>pk_test_\u2026</code>) \u2014 used to create test invoices and read invoice status</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><strong>API Secret</strong> (<code>sk_test_\u2026</code>) \u2014 used to compute the HMAC-SHA256 request signature (see the warning below)</span></li></ul>
1987
+ <div class="callout callout--warning"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 3 1.7 17h16.6L10 3Zm0 5v4m0 3h.01"></path></svg><div class="callout__body"><p>API Secret never leaves your server. Never send it in headers, query strings, or client code. Never commit it to git \u2014 rotate immediately if it leaks.</p></div></div>
1988
+ <h2 id="register-a-test-webhook-endpoint">Register a test webhook endpoint</h2>
1989
+ <p>Expose your server's webhook handler at an HTTPS URL, then open <a href="/developers/webhooks"><strong>Dashboard \u2192 Developer \u2192 Webhooks</strong></a> in Sandbox and create an endpoint. Enter the HTTPS callback URL, select the <code>Invoice</code> category and your project, then create the endpoint. Copy the one-time <code>whsec_test_\u2026</code> secret to your server; it is separate from the API key pair and signs test webhook deliveries.</p>
1990
+ <h2 id="create-a-test-invoice">Create a test invoice</h2>
1991
+ <p>Use an official server SDK below. It serializes the request, creates the exact
1992
+ HMAC signature, sets the timestamp headers, applies safe retries, and returns a
1993
+ typed response. Manual signing is documented separately in <a href="/docs/authentication">Authentication</a>.</p>
1994
+ <div class="code-tab-group"><div class="code-tab-bar"><button type="button" class="code-tab-btn active" data-tab-idx="0" data-code-lang="curl">cURL</button><button type="button" class="code-tab-btn" data-tab-idx="1" data-code-lang="mcp">MCP</button><button type="button" class="code-tab-btn" data-tab-idx="2" data-code-lang="javascript"><i class="devicon-javascript-plain colored"></i> JavaScript</button><button type="button" class="code-tab-btn" data-tab-idx="3" data-code-lang="python"><i class="devicon-python-plain colored"></i> Python</button><button type="button" class="code-tab-btn" data-tab-idx="4" data-code-lang="php"><i class="devicon-php-plain colored"></i> PHP</button><button type="button" class="code-tab-btn" data-tab-idx="5" data-code-lang="go"><i class="devicon-go-plain colored"></i> Go</button><button type="button" class="code-tab-btn" data-tab-idx="6" data-code-lang="csharp"><i class="devicon-csharp-plain colored"></i> C#</button><button type="button" class="code-tab-btn" data-tab-idx="7" data-code-lang="java"><i class="devicon-java-plain colored"></i> Java</button><button type="button" class="code-tab-btn" data-tab-idx="8" data-code-lang="ruby"><i class="devicon-ruby-plain colored"></i> Ruby</button><button type="button" class="code-tab-btn" data-tab-idx="9" data-code-lang="rust"><i class="devicon-rust-original colored"></i> Rust</button></div><div class="code-tab-panel active" data-code-lang="curl"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="curl"><code><span class="line"><span style="color:#E06C75">API_KEY_ID</span><span style="color:#56B6C2">=</span><span style="color:#98C379">"pk_live_xxxxxxxxxxxx"</span></span>
1995
+ <span class="line"><span style="color:#E06C75">API_SECRET</span><span style="color:#56B6C2">=</span><span style="color:#98C379">"sk_live_xxxxxxxxxxxx"</span></span>
1996
+ <span class="line"><span style="color:#E06C75">BODY</span><span style="color:#56B6C2">=</span><span style="color:#98C379">'{"project_id":"prj_xxxxxxxxxxxx","amount":"100.00","currency":"USD","external_order_id":"order-123","client_id":"customer-456"}'</span></span>
1997
+ <span class="line"></span>
1998
+ <span class="line"><span style="color:#E06C75">TS</span><span style="color:#56B6C2">=</span><span style="color:#ABB2BF">$(</span><span style="color:#61AFEF">date</span><span style="color:#98C379"> +%s</span><span style="color:#ABB2BF">)</span></span>
1999
+ <span class="line"><span style="color:#E06C75">BODY_HASH</span><span style="color:#56B6C2">=</span><span style="color:#ABB2BF">$(</span><span style="color:#56B6C2">printf</span><span style="color:#98C379"> '%s'</span><span style="color:#98C379"> "</span><span style="color:#E06C75">$BODY</span><span style="color:#98C379">"</span><span style="color:#ABB2BF"> | </span><span style="color:#61AFEF">openssl</span><span style="color:#98C379"> dgst</span><span style="color:#D19A66"> -sha256</span><span style="color:#D19A66"> -hex</span><span style="color:#ABB2BF"> | </span><span style="color:#61AFEF">sed</span><span style="color:#98C379"> 's/^.* //'</span><span style="color:#ABB2BF">)</span></span>
2000
+ <span class="line"><span style="color:#E06C75">SIGNATURE</span><span style="color:#56B6C2">=</span><span style="color:#ABB2BF">$(</span><span style="color:#56B6C2">printf</span><span style="color:#98C379"> '%s\\n%s\\n%s\\n%s\\n%s'</span><span style="color:#98C379"> "</span><span style="color:#E06C75">$TS</span><span style="color:#98C379">"</span><span style="color:#98C379"> POST</span><span style="color:#98C379"> /v1/invoices</span><span style="color:#98C379"> ''</span><span style="color:#98C379"> "</span><span style="color:#E06C75">$BODY_HASH</span><span style="color:#98C379">"</span><span style="color:#56B6C2"> \\</span></span>
2001
+ <span class="line"><span style="color:#ABB2BF"> | </span><span style="color:#61AFEF">openssl</span><span style="color:#98C379"> dgst</span><span style="color:#D19A66"> -sha256</span><span style="color:#D19A66"> -hmac</span><span style="color:#98C379"> "</span><span style="color:#E06C75">$API_SECRET</span><span style="color:#98C379">"</span><span style="color:#D19A66"> -binary</span><span style="color:#ABB2BF"> | </span><span style="color:#61AFEF">base64</span><span style="color:#ABB2BF">)</span></span>
2002
+ <span class="line"></span>
2003
+ <span class="line"><span style="color:#61AFEF">curl</span><span style="color:#D19A66"> -sS</span><span style="color:#98C379"> https://api.paymos.io/v1/invoices</span><span style="color:#56B6C2"> \\</span></span>
2004
+ <span class="line"><span style="color:#D19A66"> -H</span><span style="color:#98C379"> "Authorization: HMAC-SHA256 </span><span style="color:#E06C75">$API_KEY_ID</span><span style="color:#98C379">:</span><span style="color:#E06C75">$SIGNATURE</span><span style="color:#98C379">"</span><span style="color:#56B6C2"> \\</span></span>
2005
+ <span class="line"><span style="color:#D19A66"> -H</span><span style="color:#98C379"> "X-Request-Timestamp: </span><span style="color:#E06C75">$TS</span><span style="color:#98C379">"</span><span style="color:#56B6C2"> \\</span></span>
2006
+ <span class="line"><span style="color:#D19A66"> -H</span><span style="color:#98C379"> "Content-Type: application/json"</span><span style="color:#56B6C2"> \\</span></span>
2007
+ <span class="line"><span style="color:#D19A66"> -d</span><span style="color:#98C379"> "</span><span style="color:#E06C75">$BODY</span><span style="color:#98C379">"</span></span>
2008
+ <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="mcp"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="mcp"><code><span class="line"><span style="color:#ABB2BF">Setup once in terminal: </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">npx -y @paymos/mcp setup</span><span style="color:#E5C07B">\`</span></span>
2009
+ <span class="line"></span>
2010
+ <span class="line"><span style="color:#ABB2BF">Prompt:</span></span>
564
2011
  <span class="line"><span style="color:#ABB2BF">Read </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">paymos://docs/hosted-checkout</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF"> and integrate Paymos invoice</span></span>
565
2012
  <span class="line"><span style="color:#ABB2BF">creation into my backend using the official SDK for this project's</span></span>
566
2013
  <span class="line"><span style="color:#ABB2BF">stack. Then use </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">@paymos/mcp</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF"> in sandbox to call </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">create_invoice</span><span style="color:#E5C07B">\`</span></span>
@@ -677,981 +2124,621 @@ typed response. Manual signing is documented separately in <a href="/docs/authen
677
2124
  <span class="line"><span style="color:#ABB2BF"> .</span><span style="color:#61AFEF">externalOrderId</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"order-123"</span><span style="color:#ABB2BF">)</span></span>
678
2125
  <span class="line"><span style="color:#ABB2BF"> .</span><span style="color:#61AFEF">clientId</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"customer-456"</span><span style="color:#ABB2BF">)</span></span>
679
2126
  <span class="line"><span style="color:#ABB2BF"> .</span><span style="color:#61AFEF">build</span><span style="color:#ABB2BF">());</span></span>
680
- <span class="line"></span>
681
- <span class="line"><span style="color:#E5C07B">System</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">out</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">println</span><span style="color:#ABB2BF">(</span><span style="color:#E5C07B">invoice</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">invoiceId</span><span style="color:#ABB2BF">() </span><span style="color:#56B6C2">+</span><span style="color:#98C379"> " "</span><span style="color:#56B6C2"> +</span><span style="color:#E5C07B"> invoice</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">paymentUrl</span><span style="color:#ABB2BF">());</span></span>
682
- <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="ruby"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="ruby"><code><span class="line"><span style="color:#61AFEF">require </span><span style="color:#98C379">'paymos'</span></span>
683
- <span class="line"></span>
684
- <span class="line"><span style="color:#E06C75">paymos</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> Paymos</span><span style="color:#ABB2BF">::</span><span style="color:#E5C07B">Client</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">new</span><span style="color:#ABB2BF">(</span></span>
685
- <span class="line"><span style="color:#56B6C2"> api_key</span><span style="color:#D19A66">:</span><span style="color:#E5C07B"> ENV</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">fetch</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'PAYMOS_API_KEY'</span><span style="color:#ABB2BF">),</span></span>
686
- <span class="line"><span style="color:#56B6C2"> api_secret</span><span style="color:#D19A66">:</span><span style="color:#E5C07B"> ENV</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">fetch</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'PAYMOS_API_SECRET'</span><span style="color:#ABB2BF">)</span></span>
687
- <span class="line"><span style="color:#ABB2BF">)</span></span>
688
- <span class="line"><span style="color:#E06C75">invoice</span><span style="color:#56B6C2"> =</span><span style="color:#ABB2BF"> paymos.</span><span style="color:#61AFEF">invoices</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">create</span><span style="color:#ABB2BF">(</span></span>
689
- <span class="line"><span style="color:#56B6C2"> project_id</span><span style="color:#D19A66">:</span><span style="color:#98C379"> 'prj_xxxxxxxxxxxx'</span><span style="color:#ABB2BF">,</span></span>
690
- <span class="line"><span style="color:#56B6C2"> amount</span><span style="color:#D19A66">:</span><span style="color:#98C379"> '100.00'</span><span style="color:#ABB2BF">,</span></span>
691
- <span class="line"><span style="color:#56B6C2"> currency</span><span style="color:#D19A66">:</span><span style="color:#98C379"> 'USD'</span><span style="color:#ABB2BF">,</span></span>
692
- <span class="line"><span style="color:#56B6C2"> external_order_id</span><span style="color:#D19A66">:</span><span style="color:#98C379"> 'order-123'</span><span style="color:#ABB2BF">,</span></span>
693
- <span class="line"><span style="color:#56B6C2"> client_id</span><span style="color:#D19A66">:</span><span style="color:#98C379"> 'customer-456'</span></span>
694
- <span class="line"><span style="color:#ABB2BF">)</span></span>
695
- <span class="line"></span>
696
- <span class="line"><span style="color:#56B6C2">puts</span><span style="color:#98C379"> "</span><span style="color:#C678DD">#{</span><span style="color:#ABB2BF">invoice.</span><span style="color:#61AFEF">invoice_id</span><span style="color:#C678DD">}</span><span style="color:#C678DD"> #{</span><span style="color:#ABB2BF">invoice.</span><span style="color:#61AFEF">payment_url</span><span style="color:#C678DD">}</span><span style="color:#98C379">"</span></span>
697
- <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="rust"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="rust"><code><span class="line"><span style="color:#C678DD">use</span><span style="color:#E5C07B"> paymos</span><span style="color:#ABB2BF">::{</span><span style="color:#E5C07B">CreateInvoiceRequest</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">PaymosClient</span><span style="color:#ABB2BF">};</span></span>
698
- <span class="line"></span>
699
- <span class="line"><span style="color:#C678DD">let</span><span style="color:#E06C75"> paymos</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> PaymosClient</span><span style="color:#ABB2BF">::</span><span style="color:#61AFEF">new</span><span style="color:#ABB2BF">(</span></span>
700
- <span class="line"><span style="color:#E5C07B"> std</span><span style="color:#ABB2BF">::</span><span style="color:#E5C07B">env</span><span style="color:#ABB2BF">::</span><span style="color:#61AFEF">var</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"PAYMOS_API_KEY"</span><span style="color:#ABB2BF">)?,</span></span>
701
- <span class="line"><span style="color:#E5C07B"> std</span><span style="color:#ABB2BF">::</span><span style="color:#E5C07B">env</span><span style="color:#ABB2BF">::</span><span style="color:#61AFEF">var</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"PAYMOS_API_SECRET"</span><span style="color:#ABB2BF">)?,</span></span>
702
- <span class="line"><span style="color:#ABB2BF">)?;</span></span>
703
- <span class="line"><span style="color:#C678DD">let</span><span style="color:#E06C75"> invoice</span><span style="color:#56B6C2"> =</span><span style="color:#E06C75"> paymos</span></span>
704
- <span class="line"><span style="color:#ABB2BF"> .</span><span style="color:#61AFEF">invoices</span><span style="color:#ABB2BF">()</span></span>
705
- <span class="line"><span style="color:#ABB2BF"> .</span><span style="color:#61AFEF">create</span><span style="color:#ABB2BF">(&#x26;</span><span style="color:#E5C07B">CreateInvoiceRequest</span><span style="color:#ABB2BF"> {</span></span>
706
- <span class="line"><span style="color:#E06C75"> project_id</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"prj_xxxxxxxxxxxx"</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">to_owned</span><span style="color:#ABB2BF">(),</span></span>
707
- <span class="line"><span style="color:#E06C75"> amount</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"100.00"</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">to_owned</span><span style="color:#ABB2BF">(),</span></span>
708
- <span class="line"><span style="color:#E06C75"> currency</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"USD"</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">to_owned</span><span style="color:#ABB2BF">(),</span></span>
709
- <span class="line"><span style="color:#E06C75"> external_order_id</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"order-123"</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">to_owned</span><span style="color:#ABB2BF">(),</span></span>
710
- <span class="line"><span style="color:#E06C75"> network</span><span style="color:#ABB2BF">: </span><span style="color:#E5C07B">None</span><span style="color:#ABB2BF">,</span></span>
711
- <span class="line"><span style="color:#E06C75"> customer_fee_percent</span><span style="color:#ABB2BF">: </span><span style="color:#E5C07B">None</span><span style="color:#ABB2BF">,</span></span>
712
- <span class="line"><span style="color:#E06C75"> client_id</span><span style="color:#ABB2BF">: </span><span style="color:#E5C07B">Some</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"customer-456"</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">to_owned</span><span style="color:#ABB2BF">()),</span></span>
713
- <span class="line"><span style="color:#ABB2BF"> })</span></span>
714
- <span class="line"><span style="color:#ABB2BF"> .</span><span style="color:#C678DD">await</span><span style="color:#ABB2BF">?;</span></span>
715
- <span class="line"></span>
716
- <span class="line"><span style="color:#61AFEF">println!</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"{} {}"</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">invoice</span><span style="color:#ABB2BF">.invoice_id, </span><span style="color:#E06C75">invoice</span><span style="color:#ABB2BF">.payment_url);</span></span>
717
- <span class="line"></span></code></pre></div></div>
718
- <h2 id="open-checkout">Open checkout</h2>
719
- <p>The response includes a <code>payment_url</code>. Redirect your customer there or embed the same URL with <code>?embed=true</code>:</p>
720
- <pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="json"><code><span class="line"><span style="color:#ABB2BF">{</span></span>
721
- <span class="line"><span style="color:#E06C75"> "invoice_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"inv_5CcyDYmMUGtzYL10q0Iimr"</span><span style="color:#ABB2BF">,</span></span>
722
- <span class="line"><span style="color:#E06C75"> "project_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"prj_xFukZuAJZR06pLVBh3uwzv"</span><span style="color:#ABB2BF">,</span></span>
723
- <span class="line"><span style="color:#E06C75"> "status"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"awaiting_client"</span><span style="color:#ABB2BF">,</span></span>
724
- <span class="line"><span style="color:#E06C75"> "is_final"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">false</span><span style="color:#ABB2BF">,</span></span>
725
- <span class="line"><span style="color:#E06C75"> "is_test"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">true</span><span style="color:#ABB2BF">,</span></span>
726
- <span class="line"><span style="color:#E06C75"> "payment_url"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"https://checkout.paymos.io/invoice/inv_5CcyDYmMUGtzYL10q0Iimr"</span><span style="color:#ABB2BF">,</span></span>
727
- <span class="line"><span style="color:#E06C75"> "order"</span><span style="color:#ABB2BF">: {</span></span>
728
- <span class="line"><span style="color:#E06C75"> "external_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"order-123"</span><span style="color:#ABB2BF">,</span></span>
729
- <span class="line"><span style="color:#E06C75"> "client_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"customer-456"</span><span style="color:#ABB2BF">,</span></span>
730
- <span class="line"><span style="color:#E06C75"> "amount"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"100.00"</span><span style="color:#ABB2BF">,</span></span>
731
- <span class="line"><span style="color:#E06C75"> "currency"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"USD"</span></span>
732
- <span class="line"><span style="color:#ABB2BF"> },</span></span>
733
- <span class="line"><span style="color:#E06C75"> "created_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1743594000</span><span style="color:#ABB2BF">,</span></span>
734
- <span class="line"><span style="color:#E06C75"> "updated_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1743594000</span><span style="color:#ABB2BF">,</span></span>
735
- <span class="line"><span style="color:#E06C75"> "expires_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1743597600</span></span>
736
- <span class="line"><span style="color:#ABB2BF">}</span></span>
737
- <span class="line"></span></code></pre>
738
- <p>The customer sees a payment page with the wallet address, QR code, and countdown timer. They can pay with any asset + network enabled on the project \u2014 see <a href="/docs/supported-currencies">Supported Currencies</a>.</p>
739
- <p>On a Telegram-bot project that same <code>payment_url</code> opens the Paymos bot instead. The payer picks the asset and network there, gets the address and QR code, and follows the status without leaving Telegram \u2014 and without a Paymos account.</p>
740
- <p>See <a href="/docs/hosted-checkout">Hosted Checkout</a> for redirect mode, iframe embed mode, and browser event handling.</p>
741
- <h2 id="handle-the-webhook">Handle the webhook</h2>
742
- <p>When the payment is confirmed, Paymos sends a POST to your registered webhook URL:</p>
743
- <pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="json"><code><span class="line"><span style="color:#ABB2BF">{</span></span>
744
- <span class="line"><span style="color:#E06C75"> "event_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"evt_J7EEYeL9pZJukfj2c5OQ44"</span><span style="color:#ABB2BF">,</span></span>
745
- <span class="line"><span style="color:#E06C75"> "event_type"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"invoice.paid"</span><span style="color:#ABB2BF">,</span></span>
746
- <span class="line"><span style="color:#E06C75"> "version"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1</span><span style="color:#ABB2BF">,</span></span>
747
- <span class="line"><span style="color:#E06C75"> "occurred_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739281200</span><span style="color:#ABB2BF">,</span></span>
748
- <span class="line"><span style="color:#E06C75"> "data"</span><span style="color:#ABB2BF">: {</span></span>
749
- <span class="line"><span style="color:#E06C75"> "invoice_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"inv_5CcyDYmMUGtzYL10q0Iimr"</span><span style="color:#ABB2BF">,</span></span>
750
- <span class="line"><span style="color:#E06C75"> "project_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"prj_xFukZuAJZR06pLVBh3uwzv"</span><span style="color:#ABB2BF">,</span></span>
751
- <span class="line"><span style="color:#E06C75"> "status"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"paid"</span><span style="color:#ABB2BF">,</span></span>
752
- <span class="line"><span style="color:#E06C75"> "is_final"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">true</span><span style="color:#ABB2BF">,</span></span>
753
- <span class="line"><span style="color:#E06C75"> "is_test"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">false</span><span style="color:#ABB2BF">,</span></span>
754
- <span class="line"><span style="color:#E06C75"> "payment_url"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"https://checkout.paymos.io/invoice/inv_5CcyDYmMUGtzYL10q0Iimr"</span><span style="color:#ABB2BF">,</span></span>
755
- <span class="line"><span style="color:#E06C75"> "order"</span><span style="color:#ABB2BF">: {</span></span>
756
- <span class="line"><span style="color:#E06C75"> "external_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"order-12345"</span><span style="color:#ABB2BF">,</span></span>
757
- <span class="line"><span style="color:#E06C75"> "client_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"customer-67890"</span><span style="color:#ABB2BF">,</span></span>
758
- <span class="line"><span style="color:#E06C75"> "amount"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"100.00"</span><span style="color:#ABB2BF">,</span></span>
759
- <span class="line"><span style="color:#E06C75"> "currency"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"USD"</span></span>
760
- <span class="line"><span style="color:#ABB2BF"> },</span></span>
761
- <span class="line"><span style="color:#E06C75"> "payment"</span><span style="color:#ABB2BF">: {</span></span>
762
- <span class="line"><span style="color:#E06C75"> "currency"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"USDT"</span><span style="color:#ABB2BF">,</span></span>
763
- <span class="line"><span style="color:#E06C75"> "network"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"TRC20"</span><span style="color:#ABB2BF">,</span></span>
764
- <span class="line"><span style="color:#E06C75"> "chain_id"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">728126428</span><span style="color:#ABB2BF">,</span></span>
765
- <span class="line"><span style="color:#E06C75"> "contract_address"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"</span><span style="color:#ABB2BF">,</span></span>
766
- <span class="line"><span style="color:#E06C75"> "expected"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"50.00"</span><span style="color:#ABB2BF">,</span></span>
767
- <span class="line"><span style="color:#E06C75"> "address"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9"</span><span style="color:#ABB2BF">,</span></span>
768
- <span class="line"><span style="color:#E06C75"> "exchange_rate"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"2.00"</span><span style="color:#ABB2BF">,</span></span>
769
- <span class="line"><span style="color:#E06C75"> "paid"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"50.00"</span><span style="color:#ABB2BF">,</span></span>
770
- <span class="line"><span style="color:#E06C75"> "remaining"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"0"</span><span style="color:#ABB2BF">,</span></span>
771
- <span class="line"><span style="color:#E06C75"> "fee"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"0.50"</span><span style="color:#ABB2BF">,</span></span>
772
- <span class="line"><span style="color:#E06C75"> "net"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"49.50"</span><span style="color:#ABB2BF">,</span></span>
773
- <span class="line"><span style="color:#E06C75"> "transfers"</span><span style="color:#ABB2BF">: [</span></span>
774
- <span class="line"><span style="color:#ABB2BF"> {</span></span>
775
- <span class="line"><span style="color:#E06C75"> "tx_hash"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890"</span><span style="color:#ABB2BF">,</span></span>
776
- <span class="line"><span style="color:#E06C75"> "amount"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"50.00"</span><span style="color:#ABB2BF">,</span></span>
777
- <span class="line"><span style="color:#E06C75"> "status"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"confirmed"</span><span style="color:#ABB2BF">,</span></span>
778
- <span class="line"><span style="color:#E06C75"> "created_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739281020</span><span style="color:#ABB2BF">,</span></span>
779
- <span class="line"><span style="color:#E06C75"> "confirmed_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739281200</span><span style="color:#ABB2BF">,</span></span>
780
- <span class="line"><span style="color:#E06C75"> "required_confirmations"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">19</span><span style="color:#ABB2BF">,</span></span>
781
- <span class="line"><span style="color:#E06C75"> "estimated_confirmation_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739281080</span><span style="color:#ABB2BF">,</span></span>
782
- <span class="line"><span style="color:#E06C75"> "explorer_url"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"https://tronscan.org/#/transaction/abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890"</span></span>
783
- <span class="line"><span style="color:#ABB2BF"> }</span></span>
784
- <span class="line"><span style="color:#ABB2BF"> ]</span></span>
785
- <span class="line"><span style="color:#ABB2BF"> },</span></span>
786
- <span class="line"><span style="color:#E06C75"> "expires_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739284200</span><span style="color:#ABB2BF">,</span></span>
787
- <span class="line"><span style="color:#E06C75"> "completed_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739281200</span><span style="color:#ABB2BF">,</span></span>
788
- <span class="line"><span style="color:#E06C75"> "created_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739277600</span><span style="color:#ABB2BF">,</span></span>
789
- <span class="line"><span style="color:#E06C75"> "updated_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739281200</span></span>
790
- <span class="line"><span style="color:#ABB2BF"> }</span></span>
791
- <span class="line"><span style="color:#ABB2BF">}</span></span>
792
- <span class="line"></span></code></pre>
793
- <p>Verify the <code>X-Webhook-Signature</code> header and fulfill the order.</p>
794
- <div class="callout callout--danger"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 2.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15ZM7 7l6 6m0-6-6 6"></path></svg><div class="callout__body"><p>Never fulfill an order from a browser event (<code>paymos:succeeded</code> or iframe <code>postMessage</code>). Only the signed server-side webhook is authoritative \u2014 browser signals can be spoofed.</p></div></div>
795
- <div class="code-tab-group"><div class="code-tab-bar"><button type="button" class="code-tab-btn active" data-tab-idx="0" data-code-lang="javascript"><i class="devicon-javascript-plain colored"></i> JavaScript</button><button type="button" class="code-tab-btn" data-tab-idx="1" data-code-lang="mcp">MCP</button><button type="button" class="code-tab-btn" data-tab-idx="2" data-code-lang="python"><i class="devicon-python-plain colored"></i> Python</button><button type="button" class="code-tab-btn" data-tab-idx="3" data-code-lang="php"><i class="devicon-php-plain colored"></i> PHP</button><button type="button" class="code-tab-btn" data-tab-idx="4" data-code-lang="go"><i class="devicon-go-plain colored"></i> Go</button><button type="button" class="code-tab-btn" data-tab-idx="5" data-code-lang="csharp"><i class="devicon-csharp-plain colored"></i> C#</button><button type="button" class="code-tab-btn" data-tab-idx="6" data-code-lang="java"><i class="devicon-java-plain colored"></i> Java</button><button type="button" class="code-tab-btn" data-tab-idx="7" data-code-lang="ruby"><i class="devicon-ruby-plain colored"></i> Ruby</button><button type="button" class="code-tab-btn" data-tab-idx="8" data-code-lang="rust"><i class="devicon-rust-original colored"></i> Rust</button></div><div class="code-tab-panel active" data-code-lang="javascript"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="javascript"><code><span class="line"><span style="color:#C678DD">import</span><span style="color:#ABB2BF"> { </span><span style="color:#E06C75">WebhookVerifier</span><span style="color:#ABB2BF"> } </span><span style="color:#C678DD">from</span><span style="color:#98C379"> '@paymos/sdk'</span><span style="color:#ABB2BF">;</span></span>
796
- <span class="line"></span>
797
- <span class="line"><span style="color:#C678DD">const</span><span style="color:#E5C07B"> verifier</span><span style="color:#56B6C2"> =</span><span style="color:#C678DD"> new</span><span style="color:#61AFEF"> WebhookVerifier</span><span style="color:#ABB2BF">(</span><span style="color:#E5C07B">process</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">env</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">PAYMOS_WEBHOOK_SECRET</span><span style="color:#ABB2BF">);</span></span>
798
- <span class="line"></span>
799
- <span class="line"><span style="color:#7F848E;font-style:italic">// Keep the body as a Buffer until verification succeeds.</span></span>
800
- <span class="line"><span style="color:#C678DD">const</span><span style="color:#E5C07B"> event</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> verifier</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">constructEvent</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">signatureHeader</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">rawBody</span><span style="color:#ABB2BF">);</span></span>
801
- <span class="line"><span style="color:#E5C07B">console</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">log</span><span style="color:#ABB2BF">(</span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">eventId</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">eventType</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">data</span><span style="color:#ABB2BF">);</span></span>
802
- <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="mcp"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="mcp"><code><span class="line"><span style="color:#ABB2BF">Setup once in terminal: </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">npx -y @paymos/mcp setup</span><span style="color:#E5C07B">\`</span></span>
803
- <span class="line"></span>
804
- <span class="line"><span style="color:#ABB2BF">Prompt:</span></span>
805
- <span class="line"><span style="color:#ABB2BF">Read </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">paymos://docs/webhooks</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF"> and add a Paymos webhook endpoint to my</span></span>
806
- <span class="line"><span style="color:#ABB2BF">backend that verifies </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">X-Webhook-Signature</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF"> over the unparsed raw</span></span>
807
- <span class="line"><span style="color:#ABB2BF">request body using </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">WebhookVerifier</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF"> from the official SDK and</span></span>
808
- <span class="line"><span style="color:#ABB2BF">deduplicates deliveries by </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">event_id</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF">. Use </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">@paymos/mcp</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF"> tool</span></span>
809
- <span class="line"><span style="color:#E5C07B">\`</span><span style="color:#98C379">verify_webhook_signature</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF"> to test valid and tampered signatures.</span></span>
810
- <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="python"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="python"><code><span class="line"><span style="color:#C678DD">import</span><span style="color:#ABB2BF"> os</span></span>
811
- <span class="line"></span>
812
- <span class="line"><span style="color:#C678DD">from</span><span style="color:#ABB2BF"> paymos </span><span style="color:#C678DD">import</span><span style="color:#ABB2BF"> WebhookVerifier</span></span>
813
- <span class="line"></span>
814
- <span class="line"><span style="color:#ABB2BF">verifier </span><span style="color:#56B6C2">=</span><span style="color:#61AFEF"> WebhookVerifier</span><span style="color:#ABB2BF">(os.environ[</span><span style="color:#98C379">"PAYMOS_WEBHOOK_SECRET"</span><span style="color:#ABB2BF">])</span></span>
815
- <span class="line"></span>
816
- <span class="line"><span style="color:#7F848E;font-style:italic"># Keep raw_body as bytes until verification succeeds.</span></span>
817
- <span class="line"><span style="color:#ABB2BF">event </span><span style="color:#56B6C2">=</span><span style="color:#ABB2BF"> verifier.</span><span style="color:#61AFEF">construct_event</span><span style="color:#ABB2BF">(signature_header, raw_body)</span></span>
818
- <span class="line"><span style="color:#56B6C2">print</span><span style="color:#ABB2BF">(event[</span><span style="color:#98C379">"event_id"</span><span style="color:#ABB2BF">], event[</span><span style="color:#98C379">"event_type"</span><span style="color:#ABB2BF">], event[</span><span style="color:#98C379">"data"</span><span style="color:#ABB2BF">])</span></span>
819
- <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="php"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="php"><code><span class="line"><span style="color:#56B6C2">&#x3C;</span><span style="color:#C678DD">?</span><span style="color:#ABB2BF">php</span></span>
820
- <span class="line"><span style="color:#C678DD">use</span><span style="color:#ABB2BF"> Paymos\\Webhook\\</span><span style="color:#E5C07B">WebhookEvent</span><span style="color:#ABB2BF">;</span></span>
821
- <span class="line"><span style="color:#C678DD">use</span><span style="color:#ABB2BF"> Paymos\\Webhook\\</span><span style="color:#E5C07B">WebhookVerifier</span><span style="color:#ABB2BF">;</span></span>
822
- <span class="line"></span>
823
- <span class="line"><span style="color:#E06C75">$verifier</span><span style="color:#56B6C2"> =</span><span style="color:#C678DD"> new</span><span style="color:#E5C07B"> WebhookVerifier</span><span style="color:#ABB2BF">(</span><span style="color:#56B6C2">getenv</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'PAYMOS_WEBHOOK_SECRET'</span><span style="color:#ABB2BF">));</span></span>
824
- <span class="line"></span>
825
- <span class="line"><span style="color:#7F848E;font-style:italic">// Keep $rawBody unchanged until verification succeeds.</span></span>
826
- <span class="line"><span style="color:#E06C75">$payload</span><span style="color:#56B6C2"> =</span><span style="color:#E06C75"> $verifier</span><span style="color:#ABB2BF">-></span><span style="color:#61AFEF">decodeVerifiedPayload</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">$signatureHeader</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">$rawBody</span><span style="color:#ABB2BF">);</span></span>
827
- <span class="line"><span style="color:#E06C75">$event</span><span style="color:#56B6C2"> =</span><span style="color:#C678DD"> new</span><span style="color:#E5C07B"> WebhookEvent</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">$payload</span><span style="color:#ABB2BF">);</span></span>
828
- <span class="line"><span style="color:#56B6C2">echo</span><span style="color:#E06C75"> $event</span><span style="color:#ABB2BF">-></span><span style="color:#61AFEF">id</span><span style="color:#ABB2BF">() </span><span style="color:#ABB2BF">.</span><span style="color:#98C379"> ' '</span><span style="color:#ABB2BF"> .</span><span style="color:#E06C75"> $event</span><span style="color:#ABB2BF">-></span><span style="color:#61AFEF">type</span><span style="color:#ABB2BF">();</span></span>
829
- <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="go"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="go"><code><span class="line"><span style="color:#C678DD">package</span><span style="color:#E5C07B"> main</span></span>
830
- <span class="line"></span>
831
- <span class="line"><span style="color:#C678DD">import</span><span style="color:#ABB2BF"> (</span></span>
832
- <span class="line"><span style="color:#98C379"> "fmt"</span></span>
833
- <span class="line"><span style="color:#98C379"> "os"</span></span>
834
- <span class="line"><span style="color:#98C379"> "time"</span></span>
835
- <span class="line"></span>
836
- <span class="line"><span style="color:#E06C75"> paymos</span><span style="color:#98C379"> "github.com/Paymos-labs/go-sdk/v2"</span></span>
837
- <span class="line"><span style="color:#ABB2BF">)</span></span>
838
- <span class="line"></span>
839
- <span class="line"><span style="color:#C678DD">type</span><span style="color:#E5C07B"> invoiceEventData</span><span style="color:#C678DD"> struct</span><span style="color:#ABB2BF"> {</span></span>
840
- <span class="line"><span style="color:#E06C75"> InvoiceID</span><span style="color:#C678DD"> string</span><span style="color:#98C379"> \`json:"invoice_id"\`</span></span>
841
- <span class="line"><span style="color:#ABB2BF">}</span></span>
842
- <span class="line"></span>
843
- <span class="line"><span style="color:#C678DD">func</span><span style="color:#61AFEF"> handleWebhook</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75;font-style:italic">signatureHeader</span><span style="color:#C678DD"> string</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75;font-style:italic">rawBody</span><span style="color:#ABB2BF"> []</span><span style="color:#C678DD">byte</span><span style="color:#ABB2BF">) </span><span style="color:#C678DD">error</span><span style="color:#ABB2BF"> {</span></span>
844
- <span class="line"><span style="color:#E06C75"> verifier</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">err</span><span style="color:#E5C07B"> :=</span><span style="color:#E06C75"> paymos</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">NewWebhookVerifier</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">os</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">Getenv</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"PAYMOS_WEBHOOK_SECRET"</span><span style="color:#ABB2BF">), </span><span style="color:#D19A66">5</span><span style="color:#C678DD">*</span><span style="color:#E06C75">time</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">Minute</span><span style="color:#ABB2BF">)</span></span>
845
- <span class="line"><span style="color:#C678DD"> if</span><span style="color:#E06C75"> err</span><span style="color:#56B6C2"> !=</span><span style="color:#D19A66"> nil</span><span style="color:#ABB2BF"> {</span></span>
846
- <span class="line"><span style="color:#C678DD"> return</span><span style="color:#E06C75"> err</span></span>
847
- <span class="line"><span style="color:#ABB2BF"> }</span></span>
848
- <span class="line"><span style="color:#C678DD"> var</span><span style="color:#E06C75"> event</span><span style="color:#E5C07B"> paymos</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">WebhookEvent</span><span style="color:#ABB2BF">[</span><span style="color:#E5C07B">invoiceEventData</span><span style="color:#ABB2BF">]</span></span>
849
- <span class="line"><span style="color:#C678DD"> if</span><span style="color:#E06C75"> err</span><span style="color:#E5C07B"> :=</span><span style="color:#E06C75"> verifier</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">ConstructEvent</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">signatureHeader</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">rawBody</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">time</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">Now</span><span style="color:#ABB2BF">(), </span><span style="color:#C678DD">&#x26;</span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">); </span><span style="color:#E06C75">err</span><span style="color:#56B6C2"> !=</span><span style="color:#D19A66"> nil</span><span style="color:#ABB2BF"> {</span></span>
850
- <span class="line"><span style="color:#C678DD"> return</span><span style="color:#E06C75"> err</span></span>
851
- <span class="line"><span style="color:#ABB2BF"> }</span></span>
852
- <span class="line"><span style="color:#E06C75"> fmt</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">Println</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">EventID</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">EventType</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">Data</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">InvoiceID</span><span style="color:#ABB2BF">)</span></span>
853
- <span class="line"><span style="color:#C678DD"> return</span><span style="color:#D19A66"> nil</span></span>
854
- <span class="line"><span style="color:#ABB2BF">}</span></span>
855
- <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="csharp"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="csharp"><code><span class="line"><span style="color:#C678DD">using</span><span style="color:#E5C07B"> Paymos</span><span style="color:#ABB2BF">;</span></span>
856
- <span class="line"></span>
857
- <span class="line"><span style="color:#C678DD">var</span><span style="color:#E06C75"> verifier</span><span style="color:#56B6C2"> =</span><span style="color:#ABB2BF"> new </span><span style="color:#E5C07B">WebhookVerifier</span><span style="color:#ABB2BF">(</span></span>
858
- <span class="line"><span style="color:#E5C07B"> Environment</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">GetEnvironmentVariable</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"PAYMOS_WEBHOOK_SECRET"</span><span style="color:#ABB2BF">)</span><span style="color:#56B6C2">!</span><span style="color:#ABB2BF">);</span></span>
859
- <span class="line"></span>
860
- <span class="line"><span style="color:#7F848E;font-style:italic">// Keep rawBody as ReadOnlySpan&#x3C;byte> until verification succeeds.</span></span>
861
- <span class="line"><span style="color:#C678DD">var</span><span style="color:#E06C75"> webhook</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> verifier</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">ConstructEvent</span><span style="color:#ABB2BF">&#x3C;</span><span style="color:#E5C07B">InvoiceEventData</span><span style="color:#ABB2BF">>(</span><span style="color:#E06C75">signatureHeader</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">rawBody</span><span style="color:#ABB2BF">);</span></span>
862
- <span class="line"><span style="color:#E5C07B">Console</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">WriteLine</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">$"</span><span style="color:#ABB2BF">{</span><span style="color:#E5C07B">webhook</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">EventId</span><span style="color:#ABB2BF">}</span><span style="color:#ABB2BF"> {</span><span style="color:#E5C07B">webhook</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">EventType</span><span style="color:#ABB2BF">}</span><span style="color:#ABB2BF"> {</span><span style="color:#E5C07B">webhook</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">Data</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">InvoiceId</span><span style="color:#ABB2BF">}</span><span style="color:#98C379">"</span><span style="color:#ABB2BF">);</span></span>
863
- <span class="line"></span>
864
- <span class="line"><span style="color:#C678DD">public</span><span style="color:#C678DD"> sealed</span><span style="color:#C678DD"> record</span><span style="color:#E5C07B"> InvoiceEventData</span><span style="color:#ABB2BF">(</span><span style="color:#C678DD">string</span><span style="color:#E5C07B"> InvoiceId</span><span style="color:#ABB2BF">);</span></span>
865
- <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="java"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="java"><code><span class="line"><span style="color:#C678DD">import</span><span style="color:#E5C07B"> com.fasterxml.jackson.databind.JsonNode</span><span style="color:#ABB2BF">;</span></span>
866
- <span class="line"><span style="color:#C678DD">import</span><span style="color:#E5C07B"> io.paymos.WebhookEvent</span><span style="color:#ABB2BF">;</span></span>
867
- <span class="line"><span style="color:#C678DD">import</span><span style="color:#E5C07B"> io.paymos.WebhookVerifier</span><span style="color:#ABB2BF">;</span></span>
868
- <span class="line"><span style="color:#C678DD">import</span><span style="color:#E5C07B"> java.time.Instant</span><span style="color:#ABB2BF">;</span></span>
869
- <span class="line"></span>
870
- <span class="line"><span style="color:#E5C07B">WebhookVerifier</span><span style="color:#E06C75"> verifier </span><span style="color:#56B6C2">=</span><span style="color:#C678DD"> new</span><span style="color:#61AFEF"> WebhookVerifier</span><span style="color:#E06C75">(</span><span style="color:#E5C07B">System</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">getenv</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"PAYMOS_WEBHOOK_SECRET"</span><span style="color:#ABB2BF">)</span><span style="color:#E06C75">)</span><span style="color:#ABB2BF">;</span></span>
871
- <span class="line"></span>
872
- <span class="line"><span style="color:#7F848E;font-style:italic">// Keep rawBody as byte[] until verification succeeds.</span></span>
873
- <span class="line"><span style="color:#E5C07B">WebhookEvent</span><span style="color:#ABB2BF">&#x3C;</span><span style="color:#E5C07B">JsonNode</span><span style="color:#ABB2BF">></span><span style="color:#E06C75"> event </span><span style="color:#56B6C2">=</span></span>
874
- <span class="line"><span style="color:#E5C07B"> verifier</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">constructEvent</span><span style="color:#ABB2BF">(signatureHeader, rawBody, </span><span style="color:#E5C07B">Instant</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">now</span><span style="color:#ABB2BF">());</span></span>
875
- <span class="line"><span style="color:#E5C07B">System</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">out</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">println</span><span style="color:#ABB2BF">(</span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">eventId</span><span style="color:#ABB2BF">() </span><span style="color:#56B6C2">+</span><span style="color:#98C379"> " "</span><span style="color:#56B6C2"> +</span><span style="color:#E5C07B"> event</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">eventType</span><span style="color:#ABB2BF">() </span><span style="color:#56B6C2">+</span><span style="color:#98C379"> " "</span><span style="color:#56B6C2"> +</span><span style="color:#E5C07B"> event</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">data</span><span style="color:#ABB2BF">());</span></span>
2127
+ <span class="line"></span>
2128
+ <span class="line"><span style="color:#E5C07B">System</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">out</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">println</span><span style="color:#ABB2BF">(</span><span style="color:#E5C07B">invoice</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">invoiceId</span><span style="color:#ABB2BF">() </span><span style="color:#56B6C2">+</span><span style="color:#98C379"> " "</span><span style="color:#56B6C2"> +</span><span style="color:#E5C07B"> invoice</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">paymentUrl</span><span style="color:#ABB2BF">());</span></span>
876
2129
  <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="ruby"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="ruby"><code><span class="line"><span style="color:#61AFEF">require </span><span style="color:#98C379">'paymos'</span></span>
877
2130
  <span class="line"></span>
878
- <span class="line"><span style="color:#E06C75">verifier</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> Paymos</span><span style="color:#ABB2BF">::</span><span style="color:#E5C07B">WebhookVerifier</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">new</span><span style="color:#ABB2BF">(</span><span style="color:#E5C07B">ENV</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">fetch</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'PAYMOS_WEBHOOK_SECRET'</span><span style="color:#ABB2BF">))</span></span>
2131
+ <span class="line"><span style="color:#E06C75">paymos</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> Paymos</span><span style="color:#ABB2BF">::</span><span style="color:#E5C07B">Client</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">new</span><span style="color:#ABB2BF">(</span></span>
2132
+ <span class="line"><span style="color:#56B6C2"> api_key</span><span style="color:#D19A66">:</span><span style="color:#E5C07B"> ENV</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">fetch</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'PAYMOS_API_KEY'</span><span style="color:#ABB2BF">),</span></span>
2133
+ <span class="line"><span style="color:#56B6C2"> api_secret</span><span style="color:#D19A66">:</span><span style="color:#E5C07B"> ENV</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">fetch</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'PAYMOS_API_SECRET'</span><span style="color:#ABB2BF">)</span></span>
2134
+ <span class="line"><span style="color:#ABB2BF">)</span></span>
2135
+ <span class="line"><span style="color:#E06C75">invoice</span><span style="color:#56B6C2"> =</span><span style="color:#ABB2BF"> paymos.</span><span style="color:#61AFEF">invoices</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">create</span><span style="color:#ABB2BF">(</span></span>
2136
+ <span class="line"><span style="color:#56B6C2"> project_id</span><span style="color:#D19A66">:</span><span style="color:#98C379"> 'prj_xxxxxxxxxxxx'</span><span style="color:#ABB2BF">,</span></span>
2137
+ <span class="line"><span style="color:#56B6C2"> amount</span><span style="color:#D19A66">:</span><span style="color:#98C379"> '100.00'</span><span style="color:#ABB2BF">,</span></span>
2138
+ <span class="line"><span style="color:#56B6C2"> currency</span><span style="color:#D19A66">:</span><span style="color:#98C379"> 'USD'</span><span style="color:#ABB2BF">,</span></span>
2139
+ <span class="line"><span style="color:#56B6C2"> external_order_id</span><span style="color:#D19A66">:</span><span style="color:#98C379"> 'order-123'</span><span style="color:#ABB2BF">,</span></span>
2140
+ <span class="line"><span style="color:#56B6C2"> client_id</span><span style="color:#D19A66">:</span><span style="color:#98C379"> 'customer-456'</span></span>
2141
+ <span class="line"><span style="color:#ABB2BF">)</span></span>
879
2142
  <span class="line"></span>
880
- <span class="line"><span style="color:#7F848E;font-style:italic"># Keep raw_body as the original String until verification succeeds.</span></span>
881
- <span class="line"><span style="color:#E06C75">event</span><span style="color:#56B6C2"> =</span><span style="color:#ABB2BF"> verifier.</span><span style="color:#61AFEF">construct_event</span><span style="color:#ABB2BF">(signature_header, raw_body)</span></span>
882
- <span class="line"><span style="color:#56B6C2">puts</span><span style="color:#98C379"> "</span><span style="color:#C678DD">#{</span><span style="color:#ABB2BF">event.</span><span style="color:#61AFEF">event_id</span><span style="color:#C678DD">}</span><span style="color:#C678DD"> #{</span><span style="color:#ABB2BF">event.</span><span style="color:#61AFEF">event_type</span><span style="color:#C678DD">}</span><span style="color:#C678DD"> #{</span><span style="color:#ABB2BF">event.</span><span style="color:#61AFEF">data</span><span style="color:#C678DD">}</span><span style="color:#98C379">"</span></span>
883
- <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="rust"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="rust"><code><span class="line"><span style="color:#C678DD">use</span><span style="color:#E5C07B"> paymos</span><span style="color:#ABB2BF">::{</span><span style="color:#E5C07B">Invoice</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">WebhookEvent</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">WebhookVerifier</span><span style="color:#ABB2BF">};</span></span>
2143
+ <span class="line"><span style="color:#56B6C2">puts</span><span style="color:#98C379"> "</span><span style="color:#C678DD">#{</span><span style="color:#ABB2BF">invoice.</span><span style="color:#61AFEF">invoice_id</span><span style="color:#C678DD">}</span><span style="color:#C678DD"> #{</span><span style="color:#ABB2BF">invoice.</span><span style="color:#61AFEF">payment_url</span><span style="color:#C678DD">}</span><span style="color:#98C379">"</span></span>
2144
+ <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="rust"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="rust"><code><span class="line"><span style="color:#C678DD">use</span><span style="color:#E5C07B"> paymos</span><span style="color:#ABB2BF">::{</span><span style="color:#E5C07B">CreateInvoiceRequest</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">PaymosClient</span><span style="color:#ABB2BF">};</span></span>
884
2145
  <span class="line"></span>
885
- <span class="line"><span style="color:#C678DD">let</span><span style="color:#E06C75"> verifier</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> WebhookVerifier</span><span style="color:#ABB2BF">::</span><span style="color:#61AFEF">new</span><span style="color:#ABB2BF">(</span><span style="color:#E5C07B">std</span><span style="color:#ABB2BF">::</span><span style="color:#E5C07B">env</span><span style="color:#ABB2BF">::</span><span style="color:#61AFEF">var</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"PAYMOS_WEBHOOK_SECRET"</span><span style="color:#ABB2BF">)?)?;</span></span>
2146
+ <span class="line"><span style="color:#C678DD">let</span><span style="color:#E06C75"> paymos</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> PaymosClient</span><span style="color:#ABB2BF">::</span><span style="color:#61AFEF">new</span><span style="color:#ABB2BF">(</span></span>
2147
+ <span class="line"><span style="color:#E5C07B"> std</span><span style="color:#ABB2BF">::</span><span style="color:#E5C07B">env</span><span style="color:#ABB2BF">::</span><span style="color:#61AFEF">var</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"PAYMOS_API_KEY"</span><span style="color:#ABB2BF">)?,</span></span>
2148
+ <span class="line"><span style="color:#E5C07B"> std</span><span style="color:#ABB2BF">::</span><span style="color:#E5C07B">env</span><span style="color:#ABB2BF">::</span><span style="color:#61AFEF">var</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"PAYMOS_API_SECRET"</span><span style="color:#ABB2BF">)?,</span></span>
2149
+ <span class="line"><span style="color:#ABB2BF">)?;</span></span>
2150
+ <span class="line"><span style="color:#C678DD">let</span><span style="color:#E06C75"> invoice</span><span style="color:#56B6C2"> =</span><span style="color:#E06C75"> paymos</span></span>
2151
+ <span class="line"><span style="color:#ABB2BF"> .</span><span style="color:#61AFEF">invoices</span><span style="color:#ABB2BF">()</span></span>
2152
+ <span class="line"><span style="color:#ABB2BF"> .</span><span style="color:#61AFEF">create</span><span style="color:#ABB2BF">(&#x26;</span><span style="color:#E5C07B">CreateInvoiceRequest</span><span style="color:#ABB2BF"> {</span></span>
2153
+ <span class="line"><span style="color:#E06C75"> project_id</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"prj_xxxxxxxxxxxx"</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">to_owned</span><span style="color:#ABB2BF">(),</span></span>
2154
+ <span class="line"><span style="color:#E06C75"> amount</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"100.00"</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">to_owned</span><span style="color:#ABB2BF">(),</span></span>
2155
+ <span class="line"><span style="color:#E06C75"> currency</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"USD"</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">to_owned</span><span style="color:#ABB2BF">(),</span></span>
2156
+ <span class="line"><span style="color:#E06C75"> external_order_id</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"order-123"</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">to_owned</span><span style="color:#ABB2BF">(),</span></span>
2157
+ <span class="line"><span style="color:#E06C75"> network</span><span style="color:#ABB2BF">: </span><span style="color:#E5C07B">None</span><span style="color:#ABB2BF">,</span></span>
2158
+ <span class="line"><span style="color:#E06C75"> customer_fee_percent</span><span style="color:#ABB2BF">: </span><span style="color:#E5C07B">None</span><span style="color:#ABB2BF">,</span></span>
2159
+ <span class="line"><span style="color:#E06C75"> client_id</span><span style="color:#ABB2BF">: </span><span style="color:#E5C07B">Some</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"customer-456"</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">to_owned</span><span style="color:#ABB2BF">()),</span></span>
2160
+ <span class="line"><span style="color:#ABB2BF"> })</span></span>
2161
+ <span class="line"><span style="color:#ABB2BF"> .</span><span style="color:#C678DD">await</span><span style="color:#ABB2BF">?;</span></span>
886
2162
  <span class="line"></span>
887
- <span class="line"><span style="color:#7F848E;font-style:italic">// Keep raw_body as &#x26;[u8] until verification succeeds.</span></span>
888
- <span class="line"><span style="color:#C678DD">let</span><span style="color:#E06C75"> event</span><span style="color:#ABB2BF">: </span><span style="color:#E5C07B">WebhookEvent</span><span style="color:#ABB2BF">&#x3C;</span><span style="color:#E5C07B">Invoice</span><span style="color:#ABB2BF">> </span><span style="color:#56B6C2">=</span><span style="color:#E06C75"> verifier</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">construct_event</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">signature_header</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">raw_body</span><span style="color:#ABB2BF">)?;</span></span>
889
- <span class="line"><span style="color:#61AFEF">println!</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"{} {} {}"</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">.event_id, </span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">.event_type, </span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">.data.invoice_id);</span></span>
2163
+ <span class="line"><span style="color:#61AFEF">println!</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"{} {}"</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">invoice</span><span style="color:#ABB2BF">.invoice_id, </span><span style="color:#E06C75">invoice</span><span style="color:#ABB2BF">.payment_url);</span></span>
890
2164
  <span class="line"></span></code></pre></div></div>
891
- <h2 id="simulate-the-test-payment">Simulate the test payment</h2>
892
- <p>Use the <a href="/docs/invoices/simulate-payment">payment simulator</a> to mark the test invoice paid. Do not send real assets to a test invoice. Confirm that your registered endpoint receives the signed event and that your server verifies it with <code>whsec_test_\u2026</code> before fulfilling the order.</p>
893
- <h2 id="move-to-production">Move to Production</h2>
894
- <p>Once the Sandbox request and signed webhook work, switch to Production in the dashboard. There is no manual approval step. Switching the environment does not create keys: open <strong>Dashboard \u2192 Developer \u2192 API Keys</strong> and create separate live credentials (<code>pk_live_\u2026</code> and <code>sk_live_\u2026</code>). Register the live webhook endpoint separately and store its <code>whsec_live_\u2026</code> secret apart from the test secret.</p>
895
- <h2 id="accept-your-first-real-mainnet-payment">Accept your first real mainnet payment</h2>
896
- <p>Repeat the invoice request with the live credentials, open the returned <code>payment_url</code> \u2014 the checkout page, or the Paymos bot on a Telegram-bot project \u2014 and send a supported asset on an enabled mainnet network. Paymos detects the transfer and sends the signed live webhook after the required confirmations.</p>
897
- <p>The normal self-serve flow from sign-up to a first real mainnet payment takes about 10 minutes. This is an onboarding benchmark, not an SLA: confirmation time still depends on the network, amount, and current blockchain conditions.</p>
898
- <h2 id="next-steps">Next steps</h2>
899
- <ul class="list-none p-0 m-0 flex flex-col gap-3"><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><a href="/docs/api-keys">API Keys</a> \u2014 credential types, scope, lifecycle</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><a href="/docs/server-sdks">Server SDKs</a> \u2014 official clients for eight language ecosystems</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><a href="/docs/hosted-checkout">Hosted Checkout</a> \u2014 redirect and iframe embed options</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><a href="/docs/testing">Testing</a> \u2014 how to test in sandbox</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><a href="/docs/webhooks">Webhooks</a> \u2014 signature verification and retry policy</span></li></ul>`
900
- },
901
- {
902
- "name": "hosted-checkout",
903
- "slug": "hosted-checkout",
904
- "uri": "paymos://docs/hosted-checkout",
905
- "description": "Hosted checkout: the payment_url flow, invoice lifecycle and redirect handling.",
906
- "mimeType": "text/html",
907
- "text": `<p>Use the <code>payment_url</code> returned by <code>POST /v1/invoices</code> as the canonical checkout URL. The same URL supports two presentation modes \u2014 full-page redirect and embedded iframe.</p>
908
- <p>Both modes work on any project except a Telegram-bot one. There the same <code>payment_url</code> is a deep link into the Paymos bot \u2014 no hosted page to redirect to or embed.</p>
909
- <h2 id="redirect-mode">Redirect mode</h2>
910
- <p>Redirect mode is the simplest integration. Send the customer to <code>payment_url</code> after your server creates the invoice:</p>
911
- <pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="html"><code><span class="line"><span style="color:#ABB2BF">&#x3C;</span><span style="color:#E06C75">a</span><span style="color:#D19A66"> href</span><span style="color:#ABB2BF">=</span><span style="color:#98C379">"https://checkout.paymos.io/invoice/inv_xxx"</span><span style="color:#ABB2BF">>Pay invoice&#x3C;/</span><span style="color:#E06C75">a</span><span style="color:#ABB2BF">></span></span>
912
- <span class="line"></span></code></pre>
913
- <p>The customer completes the payment on the Paymos-hosted page. Your server fulfills the order only after receiving and verifying the signed webhook event.</p>
914
- <h2 id="embed-mode">Embed mode</h2>
915
- <p>Embed mode uses the same <code>payment_url</code> with <code>?embed=true</code>. Use this when your server already creates invoices and you only want the hosted checkout UI inside your own page:</p>
916
- <pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="html"><code><span class="line"><span style="color:#ABB2BF">&#x3C;</span><span style="color:#E06C75">iframe</span></span>
917
- <span class="line"><span style="color:#D19A66"> src</span><span style="color:#ABB2BF">=</span><span style="color:#98C379">"https://checkout.paymos.io/invoice/inv_xxx?embed=true"</span></span>
918
- <span class="line"><span style="color:#D19A66"> title</span><span style="color:#ABB2BF">=</span><span style="color:#98C379">"Paymos checkout"</span></span>
919
- <span class="line"><span style="color:#D19A66"> allow</span><span style="color:#ABB2BF">=</span><span style="color:#98C379">"clipboard-write"</span></span>
920
- <span class="line"><span style="color:#D19A66"> sandbox</span><span style="color:#ABB2BF">=</span><span style="color:#98C379">"allow-scripts allow-same-origin allow-forms allow-popups"</span></span>
921
- <span class="line"><span style="color:#D19A66"> style</span><span style="color:#ABB2BF">=</span><span style="color:#98C379">"display:block;width:100%;max-width:460px;height:min(90vh,900px);border:0;"</span></span>
922
- <span class="line"><span style="color:#ABB2BF">>&#x3C;/</span><span style="color:#E06C75">iframe</span><span style="color:#ABB2BF">></span></span>
923
- <span class="line"></span></code></pre>
924
- <h2 id="embed-events">Embed events</h2>
925
- <p>The checkout iframe sends <code>postMessage</code> transport events to the parent page:</p>
926
- <table>
927
- <thead>
928
- <tr>
929
- <th>Event</th>
930
- <th>Meaning</th>
931
- </tr>
932
- </thead>
933
- <tbody>
934
- <tr>
935
- <td><code>paymos:succeeded</code></td>
936
- <td>Checkout reached <code>paid</code> or <code>paid_over</code>.</td>
937
- </tr>
938
- <tr>
939
- <td><code>paymos:failed</code></td>
940
- <td>Checkout reached a terminal failure state such as <code>underpaid</code>, <code>expired</code>, or <code>cancelled</code>.</td>
941
- </tr>
942
- <tr>
943
- <td><code>paymos:close</code></td>
944
- <td>Customer clicked a close/back action inside the embedded checkout.</td>
945
- </tr>
946
- </tbody>
947
- </table>
948
- <p>Parent pages must validate both the sender origin and the iframe source:</p>
949
- <pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="javascript"><code><span class="line"><span style="color:#C678DD">const</span><span style="color:#E5C07B"> iframe</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> document</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">querySelector</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'#paymos-checkout'</span><span style="color:#ABB2BF">);</span></span>
950
- <span class="line"></span>
951
- <span class="line"><span style="color:#E5C07B">window</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">addEventListener</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'message'</span><span style="color:#ABB2BF">, (</span><span style="color:#E06C75;font-style:italic">event</span><span style="color:#ABB2BF">) </span><span style="color:#C678DD">=></span><span style="color:#ABB2BF"> {</span></span>
952
- <span class="line"><span style="color:#C678DD"> if</span><span style="color:#ABB2BF"> (</span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">origin</span><span style="color:#56B6C2"> !==</span><span style="color:#98C379"> 'https://checkout.paymos.io'</span><span style="color:#ABB2BF">) </span><span style="color:#C678DD">return</span><span style="color:#ABB2BF">;</span></span>
953
- <span class="line"><span style="color:#C678DD"> if</span><span style="color:#ABB2BF"> (</span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">source</span><span style="color:#56B6C2"> !==</span><span style="color:#E5C07B"> iframe</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">contentWindow</span><span style="color:#ABB2BF">) </span><span style="color:#C678DD">return</span><span style="color:#ABB2BF">;</span></span>
954
- <span class="line"><span style="color:#C678DD"> if</span><span style="color:#ABB2BF"> (</span><span style="color:#56B6C2">!</span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">data</span><span style="color:#56B6C2"> ||</span><span style="color:#C678DD"> typeof</span><span style="color:#E5C07B"> event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">data</span><span style="color:#56B6C2"> !==</span><span style="color:#98C379"> 'object'</span><span style="color:#ABB2BF">) </span><span style="color:#C678DD">return</span><span style="color:#ABB2BF">;</span></span>
955
- <span class="line"></span>
956
- <span class="line"><span style="color:#C678DD"> switch</span><span style="color:#ABB2BF"> (</span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">data</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">type</span><span style="color:#ABB2BF">) {</span></span>
957
- <span class="line"><span style="color:#C678DD"> case</span><span style="color:#98C379"> 'paymos:succeeded'</span><span style="color:#ABB2BF">:</span></span>
958
- <span class="line"><span style="color:#E5C07B"> console</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">log</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'Payment UI succeeded:'</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">data</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">invoice_id</span><span style="color:#ABB2BF">);</span></span>
959
- <span class="line"><span style="color:#C678DD"> break</span><span style="color:#ABB2BF">;</span></span>
960
- <span class="line"><span style="color:#C678DD"> case</span><span style="color:#98C379"> 'paymos:failed'</span><span style="color:#ABB2BF">:</span></span>
961
- <span class="line"><span style="color:#E5C07B"> console</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">warn</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'Payment UI failed:'</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">data</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">reason</span><span style="color:#ABB2BF">);</span></span>
962
- <span class="line"><span style="color:#C678DD"> break</span><span style="color:#ABB2BF">;</span></span>
963
- <span class="line"><span style="color:#C678DD"> case</span><span style="color:#98C379"> 'paymos:close'</span><span style="color:#ABB2BF">:</span></span>
964
- <span class="line"><span style="color:#E5C07B"> iframe</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">remove</span><span style="color:#ABB2BF">();</span></span>
965
- <span class="line"><span style="color:#C678DD"> break</span><span style="color:#ABB2BF">;</span></span>
966
- <span class="line"><span style="color:#ABB2BF"> }</span></span>
967
- <span class="line"><span style="color:#ABB2BF">});</span></span>
2165
+ <h2 id="open-checkout">Open checkout</h2>
2166
+ <p>The response includes a <code>payment_url</code>. Redirect your customer there or embed the same URL with <code>?embed=true</code>:</p>
2167
+ <pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="json"><code><span class="line"><span style="color:#ABB2BF">{</span></span>
2168
+ <span class="line"><span style="color:#E06C75"> "invoice_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"inv_5CcyDYmMUGtzYL10q0Iimr"</span><span style="color:#ABB2BF">,</span></span>
2169
+ <span class="line"><span style="color:#E06C75"> "project_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"prj_xFukZuAJZR06pLVBh3uwzv"</span><span style="color:#ABB2BF">,</span></span>
2170
+ <span class="line"><span style="color:#E06C75"> "status"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"awaiting_client"</span><span style="color:#ABB2BF">,</span></span>
2171
+ <span class="line"><span style="color:#E06C75"> "is_final"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">false</span><span style="color:#ABB2BF">,</span></span>
2172
+ <span class="line"><span style="color:#E06C75"> "is_test"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">true</span><span style="color:#ABB2BF">,</span></span>
2173
+ <span class="line"><span style="color:#E06C75"> "payment_url"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"https://checkout.paymos.io/invoice/inv_5CcyDYmMUGtzYL10q0Iimr"</span><span style="color:#ABB2BF">,</span></span>
2174
+ <span class="line"><span style="color:#E06C75"> "order"</span><span style="color:#ABB2BF">: {</span></span>
2175
+ <span class="line"><span style="color:#E06C75"> "external_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"order-123"</span><span style="color:#ABB2BF">,</span></span>
2176
+ <span class="line"><span style="color:#E06C75"> "client_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"customer-456"</span><span style="color:#ABB2BF">,</span></span>
2177
+ <span class="line"><span style="color:#E06C75"> "amount"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"100.00"</span><span style="color:#ABB2BF">,</span></span>
2178
+ <span class="line"><span style="color:#E06C75"> "currency"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"USD"</span></span>
2179
+ <span class="line"><span style="color:#ABB2BF"> },</span></span>
2180
+ <span class="line"><span style="color:#E06C75"> "created_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1743594000</span><span style="color:#ABB2BF">,</span></span>
2181
+ <span class="line"><span style="color:#E06C75"> "updated_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1743594000</span><span style="color:#ABB2BF">,</span></span>
2182
+ <span class="line"><span style="color:#E06C75"> "expires_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1743597600</span></span>
2183
+ <span class="line"><span style="color:#ABB2BF">}</span></span>
968
2184
  <span class="line"></span></code></pre>
969
- <div class="callout callout--danger"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 2.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15ZM7 7l6 6m0-6-6 6"></path></svg><div class="callout__body"><p>Treat these events as UX hints, not proof of payment. Drive spinners, redirects, and analytics from them \u2014 but never ship goods, credit balances, or mark an order paid based on a <code>postMessage</code>. A <code>postMessage</code> is trivial to spoof: any page sharing the customer's origin can post a fake <code>paymos:succeeded</code>. Settlement is confirmed only by the signed server-side webhook \u2014 the one source of truth for fulfillment.</p></div></div>
970
- <h2 id="security-model">Security model</h2>
971
- <p>The recommended iframe sandbox is deliberately small:</p>
972
- <ul class="list-none p-0 m-0 flex flex-col gap-3"><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>allow-scripts</code> is required for checkout interactivity, API calls, timers, copy buttons, and live status updates.</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>allow-same-origin</code> lets the Paymos-hosted checkout run with its own origin instead of an opaque sandbox origin.</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>allow-forms</code> allows normal form interactions inside checkout.</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>allow-top-navigation</code> is omitted so the iframe cannot navigate the merchant page.</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>allow-popups</code> lets the buyer open the terms and other checkout links in a new tab.</span></li></ul>
973
- <h2 id="when-to-use-low-code-sdk-instead">When to use Low-Code SDK instead</h2>
974
- <p>Use <a href="/docs/widget-sdk">Low-Code SDK</a> when you want Paymos to create invoices from browser-side config, render the payment button, manage the modal lifecycle, validate iframe messages, and dispatch <code>paymos:*</code> <code>CustomEvent</code>s for you.</p>
975
- <p>Use manual iframe embed when your backend already owns invoice creation and you only need to place the hosted checkout UI inside your page.</p>`
976
- },
977
- {
978
- "name": "webhooks",
979
- "slug": "webhooks",
980
- "uri": "paymos://docs/webhooks",
981
- "description": "Webhooks: event types, payloads, retries and signature verification.",
982
- "mimeType": "text/html",
983
- "text": '<p>Paymos sends an HTTPS <code>POST</code> when an invoice, a withdrawal, or a payment-channel deposit changes state. Webhooks are the authoritative asynchronous signal for your backend: API responses start an operation, while webhook events tell you what happened after blockchain processing.</p>\n<h2 id="integration-flow">Integration flow</h2>\n<ol>\n<li>Create a webhook endpoint in <strong>Dashboard \u2192 Developer \u2192 Webhooks</strong>.</li>\n<li>Choose one or more event categories: <code>Invoice</code>, <code>Withdrawal</code>, <code>Payment channel</code>.</li>\n<li>Optionally restrict invoice and payment-channel events to selected projects \u2014 one filter covers both. Withdrawal events are merchant-wide and ignore it.</li>\n<li>Store the displayed <code>whsec_\u2026</code> secret on your server.</li>\n<li>Verify every delivery against the unchanged raw request body.</li>\n<li>Persist <code>event_id</code>, acknowledge with <code>2xx</code>, and process the event asynchronously.</li>\n</ol>\n<p>Production and Sandbox have separate endpoints, secrets, and events. A sandbox event is never delivered to a production endpoint.</p>\n<h2 id="endpoint-rules">Endpoint rules</h2>\n<ul>\n<li>The URL must use HTTPS.</li>\n<li>The URL may name port 443 \u2014 what a URL without a port uses \u2014 or any port from 1024 up. Other ports are refused when you save, and an endpoint that already has one gets no deliveries.</li>\n<li>Up to 10 endpoints can be configured per merchant and environment.</li>\n<li>The same active URL cannot be registered twice in one environment.</li>\n<li>An endpoint must subscribe to at least one category.</li>\n<li>No project filter means every project is included.</li>\n<li>Suspending or deleting an endpoint stops new deliveries to it.</li>\n</ul>\n<h2 id="delivery-headers">Delivery headers</h2>\n<table>\n<thead>\n<tr>\n<th>Header</th>\n<th>Contract</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>Content-Type</code></td>\n<td><code>application/json; charset=utf-8</code></td>\n</tr>\n<tr>\n<td><code>X-Webhook-Id</code></td>\n<td>Same <code>evt_\u2026</code> value as <code>event_id</code> in the body; not covered by the signature</td>\n</tr>\n<tr>\n<td><code>X-Webhook-Timestamp</code></td>\n<td>Unix seconds for this delivery attempt</td>\n</tr>\n<tr>\n<td><code>X-Webhook-Signature</code></td>\n<td><code>t={timestamp},v1={hmac_hex}</code>; may contain two <code>v1</code> values during rotation</td>\n</tr>\n</tbody>\n</table>\n<p>Delivery is at-least-once and ordering is not guaranteed. Deduplicate on <code>event_id</code> from the verified body, then apply the resource state from <code>data</code> instead of counting events or assuming arrival order.</p>\n<p><code>X-Webhook-Id</code> is there for your logs, not for deduplication. The signature covers only the timestamp and the body, so a captured delivery can be resent with a different <code>X-Webhook-Id</code> and still verify while its timestamp passes your check \u2014 and a handler keyed on the header processes that copy a second time.</p>\n<h2 id="webhook-documentation">Webhook documentation</h2>\n<ul>\n<li><a href="/docs/webhooks/events">Event catalog</a> \u2014 every invoice, withdrawal, and payment-channel event type</li>\n<li><a href="/docs/webhooks/payloads">Payload contract</a> \u2014 envelope and resource snapshots</li>\n<li><a href="/docs/webhooks/verify">Verify signatures</a> \u2014 raw-body HMAC verification and secret rotation</li>\n<li><a href="/docs/webhooks/retry">Delivery and retries</a> \u2014 timeout, backoff, idempotency, and replay</li>\n<li><a href="/docs/webhooks/testing">Test webhooks</a> \u2014 sandbox prerequisites and the interactive playground</li>\n</ul>'
984
- },
985
- {
986
- "name": "testing-sandbox",
987
- "slug": "testing",
988
- "uri": "paymos://docs/testing-sandbox",
989
- "description": "Testing in the sandbox: simulate payments, test key pairs, the go-live checklist.",
990
- "mimeType": "text/html",
991
- "text": `<p>Test your integration end-to-end in sandbox. Same API surface as production, simulated blockchain, signed webhooks, no real money at risk.</p>
992
- <h2 id="sandbox-vs-production">Sandbox vs production</h2>
993
- <table>
994
- <thead>
995
- <tr>
996
- <th>Feature</th>
997
- <th>Sandbox</th>
998
- <th>Production</th>
999
- </tr>
1000
- </thead>
1001
- <tbody>
1002
- <tr>
1003
- <td>Base URL</td>
1004
- <td><code>api.paymos.io/v1</code></td>
1005
- <td><code>api.paymos.io/v1</code></td>
1006
- </tr>
1007
- <tr>
1008
- <td>API Keys</td>
1009
- <td><code>pk_test_</code> / <code>rk_test_</code> IDs with <code>sk_test_</code> secrets</td>
1010
- <td><code>pk_live_</code> / <code>rk_live_</code> IDs with <code>sk_live_</code> secrets</td>
1011
- </tr>
1012
- <tr>
1013
- <td>Transactions</td>
1014
- <td>Simulated</td>
1015
- <td>Real blockchain</td>
1016
- </tr>
1017
- <tr>
1018
- <td>Webhooks</td>
1019
- <td>Sent normally</td>
1020
- <td>Sent normally</td>
1021
- </tr>
1022
- <tr>
1023
- <td>Funds</td>
1024
- <td>No real value</td>
1025
- <td>Real crypto</td>
1026
- </tr>
1027
- </tbody>
1028
- </table>
1029
- <h2 id="simulating-payments">Simulating payments</h2>
1030
- <p>Sandbox payments are not auto-confirmed by a timer. Trigger them explicitly:</p>
1031
- <div class="api-endpoint-badge"><span class="api-method-badge api-method-post">POST</span><span class="api-endpoint-badge__path">/v1/sandbox/invoices/:invoice_id/simulate-payment</span></div>
1032
- <div class="callout callout--info"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 2.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15Zm0 6.5v5m0-7.5h.01"></path></svg><div class="callout__body"><p>Body: <code>{ "stage": "paid" }</code> \u2014 <code>stage</code> is one of <code>paid</code>, <code>overpaid</code>, <code>underpay</code>, or <code>cancel</code>. Authenticate it like any other signed <code>/v1</code> call; it acts on sandbox invoices only, so a production key is rejected with <code>403 not_sandbox</code>. It fires the same lifecycle and webhook events as a real on-chain payment, so your verification path stays identical between sandbox and production.</p></div></div>
1033
- <h2 id="simulating-withdrawals">Simulating withdrawals</h2>
1034
- <p>Sandbox withdrawals don't settle on a real chain. Mark a pending sandbox withdrawal as completed to exercise your full payout flow:</p>
1035
- <div class="api-endpoint-badge"><span class="api-method-badge api-method-post">POST</span><span class="api-endpoint-badge__path">/v1/sandbox/withdrawals/:withdrawal_id/simulate-completion</span></div>
1036
- <p>No request body. Authenticate it like any other <code>/v1</code> call with your Payout key; it acts on sandbox withdrawals only. It transitions the withdrawal to <code>completed</code> and emits the same <code>withdrawal.completed</code> webhook as a real on-chain payout, so your reconciliation path stays identical between sandbox and production.</p>
1037
- <h2 id="simulating-refunds">Simulating refunds</h2>
1038
- <p>Create a sandbox refund first with <a href="/docs/refunds/create"><code>POST /v1/refunds</code></a> using your sandbox Payment key (<code>pk_test_</code>), then drive it to a terminal status:</p>
1039
- <div class="api-endpoint-badge"><span class="api-method-badge api-method-post">POST</span><span class="api-endpoint-badge__path">/v1/sandbox/refunds/:withdrawal_id/simulate</span></div>
1040
- <div class="callout callout--info"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 2.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15Zm0 6.5v5m0-7.5h.01"></path></svg><div class="callout__body"><p>Body: <code>{ "status": "completed" }</code> \u2014 <code>status</code> is one of <code>completed</code>, <code>failed</code>, or <code>cancelled</code>. Sign it with your sandbox Payment key (<code>pk_test_</code>). It updates the sandbox ledger and emits the corresponding <code>withdrawal.completed</code>, <code>withdrawal.failed</code>, or <code>withdrawal.cancelled</code> webhook with the full refund payload. See <a href="/docs/refunds/simulate">Simulate Refund</a> for the full contract.</p></div></div>
1041
- <h2 id="simulating-channel-deposits">Simulating channel deposits</h2>
1042
- <p>Sandbox payment channels derive their addresses locally and watch no chain, so deposits are created explicitly:</p>
1043
- <div class="api-endpoint-badge"><span class="api-method-badge api-method-post">POST</span><span class="api-endpoint-badge__path">/v1/sandbox/payment-channels/:payment_channel_id/simulate-deposit</span></div>
1044
- <div class="callout callout--info"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 2.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15Zm0 6.5v5m0-7.5h.01"></path></svg><div class="callout__body"><p>Body: <code>{ "amount": "100", "currency": "USDT", "network": "TRC20", "stage": "confirmed" }</code> \u2014 <code>stage</code> is one of <code>confirming</code>, <code>reorged</code> or <code>confirmed</code> and defaults to <code>confirmed</code>. Sign it with your sandbox Payment key; a production key is rejected before anything is created. Every call emits <code>payment_channel.deposit.confirming</code> first, then the terminal event for the stage you asked for, so your webhook path is identical between sandbox and production. See <a href="/docs/payment-channels/simulate-deposit">Simulate Channel Deposit</a> for the full contract.</p></div></div>
1045
- <h2 id="testing-webhooks-locally">Testing webhooks locally</h2>
1046
- <p>Expose your local server through a tunnel:</p>
1047
- <pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="bash"><code><span class="line"><span style="color:#61AFEF">ngrok</span><span style="color:#98C379"> http</span><span style="color:#D19A66"> 3000</span></span>
2185
+ <p>The customer sees a payment page with the wallet address, QR code, and countdown timer. They can pay with any asset + network enabled on the project \u2014 see <a href="/docs/supported-currencies">Supported Currencies</a>.</p>
2186
+ <p>On a Telegram-bot project that same <code>payment_url</code> opens the Paymos bot instead. The payer picks the asset and network there, gets the address and QR code, and follows the status without leaving Telegram \u2014 and without a Paymos account.</p>
2187
+ <p>See <a href="/docs/hosted-checkout">Hosted Checkout</a> for redirect mode, iframe embed mode, and browser event handling.</p>
2188
+ <h2 id="handle-the-webhook">Handle the webhook</h2>
2189
+ <p>When the payment is confirmed, Paymos sends a POST to your registered webhook URL:</p>
2190
+ <pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="json"><code><span class="line"><span style="color:#ABB2BF">{</span></span>
2191
+ <span class="line"><span style="color:#E06C75"> "event_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"evt_J7EEYeL9pZJukfj2c5OQ44"</span><span style="color:#ABB2BF">,</span></span>
2192
+ <span class="line"><span style="color:#E06C75"> "event_type"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"invoice.paid"</span><span style="color:#ABB2BF">,</span></span>
2193
+ <span class="line"><span style="color:#E06C75"> "version"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1</span><span style="color:#ABB2BF">,</span></span>
2194
+ <span class="line"><span style="color:#E06C75"> "occurred_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739281200</span><span style="color:#ABB2BF">,</span></span>
2195
+ <span class="line"><span style="color:#E06C75"> "data"</span><span style="color:#ABB2BF">: {</span></span>
2196
+ <span class="line"><span style="color:#E06C75"> "invoice_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"inv_5CcyDYmMUGtzYL10q0Iimr"</span><span style="color:#ABB2BF">,</span></span>
2197
+ <span class="line"><span style="color:#E06C75"> "project_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"prj_xFukZuAJZR06pLVBh3uwzv"</span><span style="color:#ABB2BF">,</span></span>
2198
+ <span class="line"><span style="color:#E06C75"> "status"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"paid"</span><span style="color:#ABB2BF">,</span></span>
2199
+ <span class="line"><span style="color:#E06C75"> "is_final"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">true</span><span style="color:#ABB2BF">,</span></span>
2200
+ <span class="line"><span style="color:#E06C75"> "is_test"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">false</span><span style="color:#ABB2BF">,</span></span>
2201
+ <span class="line"><span style="color:#E06C75"> "payment_url"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"https://checkout.paymos.io/invoice/inv_5CcyDYmMUGtzYL10q0Iimr"</span><span style="color:#ABB2BF">,</span></span>
2202
+ <span class="line"><span style="color:#E06C75"> "order"</span><span style="color:#ABB2BF">: {</span></span>
2203
+ <span class="line"><span style="color:#E06C75"> "external_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"order-12345"</span><span style="color:#ABB2BF">,</span></span>
2204
+ <span class="line"><span style="color:#E06C75"> "client_id"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"customer-67890"</span><span style="color:#ABB2BF">,</span></span>
2205
+ <span class="line"><span style="color:#E06C75"> "amount"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"100.00"</span><span style="color:#ABB2BF">,</span></span>
2206
+ <span class="line"><span style="color:#E06C75"> "currency"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"USD"</span></span>
2207
+ <span class="line"><span style="color:#ABB2BF"> },</span></span>
2208
+ <span class="line"><span style="color:#E06C75"> "payment"</span><span style="color:#ABB2BF">: {</span></span>
2209
+ <span class="line"><span style="color:#E06C75"> "currency"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"USDT"</span><span style="color:#ABB2BF">,</span></span>
2210
+ <span class="line"><span style="color:#E06C75"> "network"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"TRC20"</span><span style="color:#ABB2BF">,</span></span>
2211
+ <span class="line"><span style="color:#E06C75"> "chain_id"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">728126428</span><span style="color:#ABB2BF">,</span></span>
2212
+ <span class="line"><span style="color:#E06C75"> "contract_address"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"</span><span style="color:#ABB2BF">,</span></span>
2213
+ <span class="line"><span style="color:#E06C75"> "expected"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"50.00"</span><span style="color:#ABB2BF">,</span></span>
2214
+ <span class="line"><span style="color:#E06C75"> "address"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9"</span><span style="color:#ABB2BF">,</span></span>
2215
+ <span class="line"><span style="color:#E06C75"> "exchange_rate"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"2.00"</span><span style="color:#ABB2BF">,</span></span>
2216
+ <span class="line"><span style="color:#E06C75"> "paid"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"50.00"</span><span style="color:#ABB2BF">,</span></span>
2217
+ <span class="line"><span style="color:#E06C75"> "remaining"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"0"</span><span style="color:#ABB2BF">,</span></span>
2218
+ <span class="line"><span style="color:#E06C75"> "fee"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"0.50"</span><span style="color:#ABB2BF">,</span></span>
2219
+ <span class="line"><span style="color:#E06C75"> "net"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"49.50"</span><span style="color:#ABB2BF">,</span></span>
2220
+ <span class="line"><span style="color:#E06C75"> "transfers"</span><span style="color:#ABB2BF">: [</span></span>
2221
+ <span class="line"><span style="color:#ABB2BF"> {</span></span>
2222
+ <span class="line"><span style="color:#E06C75"> "tx_hash"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890"</span><span style="color:#ABB2BF">,</span></span>
2223
+ <span class="line"><span style="color:#E06C75"> "amount"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"50.00"</span><span style="color:#ABB2BF">,</span></span>
2224
+ <span class="line"><span style="color:#E06C75"> "status"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"confirmed"</span><span style="color:#ABB2BF">,</span></span>
2225
+ <span class="line"><span style="color:#E06C75"> "created_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739281020</span><span style="color:#ABB2BF">,</span></span>
2226
+ <span class="line"><span style="color:#E06C75"> "confirmed_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739281200</span><span style="color:#ABB2BF">,</span></span>
2227
+ <span class="line"><span style="color:#E06C75"> "required_confirmations"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">19</span><span style="color:#ABB2BF">,</span></span>
2228
+ <span class="line"><span style="color:#E06C75"> "estimated_confirmation_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739281080</span><span style="color:#ABB2BF">,</span></span>
2229
+ <span class="line"><span style="color:#E06C75"> "explorer_url"</span><span style="color:#ABB2BF">: </span><span style="color:#98C379">"https://tronscan.org/#/transaction/abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890"</span></span>
2230
+ <span class="line"><span style="color:#ABB2BF"> }</span></span>
2231
+ <span class="line"><span style="color:#ABB2BF"> ]</span></span>
2232
+ <span class="line"><span style="color:#ABB2BF"> },</span></span>
2233
+ <span class="line"><span style="color:#E06C75"> "expires_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739284200</span><span style="color:#ABB2BF">,</span></span>
2234
+ <span class="line"><span style="color:#E06C75"> "completed_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739281200</span><span style="color:#ABB2BF">,</span></span>
2235
+ <span class="line"><span style="color:#E06C75"> "created_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739277600</span><span style="color:#ABB2BF">,</span></span>
2236
+ <span class="line"><span style="color:#E06C75"> "updated_at"</span><span style="color:#ABB2BF">: </span><span style="color:#D19A66">1739281200</span></span>
2237
+ <span class="line"><span style="color:#ABB2BF"> }</span></span>
2238
+ <span class="line"><span style="color:#ABB2BF">}</span></span>
1048
2239
  <span class="line"></span></code></pre>
1049
- <p>Set the webhook URL in <a href="/developers/webhooks"><strong>Dashboard \u2192 Developer \u2192 Webhooks</strong></a>:</p>
1050
- <p><code>https://abc123.ngrok.io/api/paymos-webhook</code></p>
1051
- <h2 id="webhook-playground">Webhook playground</h2>
1052
- <p>The documentation includes a sandbox-only <strong>Webhook Playground</strong> that runs the real delivery path: it creates a sandbox invoice, drives it to the outcome you picked, and lets the delivery worker call your registered endpoint. Nothing is posted straight to your URL, so signature handling is verified against the same signing and retry code production uses.</p>
1053
- <ul class="list-none p-0 m-0 flex flex-col gap-3"><li class="flex gap-3"><span class="font-mono text-primary shrink-0">01</span><span>Go to <strong>Dashboard \u2192 Developer \u2192 Documentation</strong> in the sandbox environment</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">02</span><span>Open <a href="/docs/webhooks/testing"><strong>Webhooks \u2192 Testing</strong></a>, then select <strong>Playground</strong></span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">03</span><span>Pick an event type (<code>invoice.paid</code>, <code>invoice.paid_over</code>, <code>invoice.underpaid</code>, or <code>invoice.cancelled</code>), set the amount and currency, then <strong>Simulate</strong></span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">04</span><span>Check your server logs for the received event and the <code>X-Webhook-Signature</code> header</span></li></ul>
1054
- <p>It needs an active sandbox webhook endpoint and a sandbox Payment key. Production sending is disabled there by design.</p>
1055
- <h2 id="checklist-before-going-live">Checklist before going live</h2>
1056
- <ul class="list-none p-0 m-0 flex flex-col gap-3"><li class="flex gap-3"><span class="text-gray-300 shrink-0">\u2610</span><span>Webhook signature verification works</span></li><li class="flex gap-3"><span class="text-gray-300 shrink-0">\u2610</span><span>Invoice creation returns correct data</span></li><li class="flex gap-3"><span class="text-gray-300 shrink-0">\u2610</span><span>Payment flow redirects properly</span></li><li class="flex gap-3"><span class="text-gray-300 shrink-0">\u2610</span><span>Error handling covers non-2xx responses (4xx validation, 409 conflicts)</span></li><li class="flex gap-3"><span class="text-gray-300 shrink-0">\u2610</span><span>Idempotency with <code>external_order_id</code> works</span></li><li class="flex gap-3"><span class="text-gray-300 shrink-0">\u2610</span><span>Switch API key IDs from <code>pk_test_</code> / <code>rk_test_</code> to <code>pk_live_</code> / <code>rk_live_</code>, and secrets from <code>sk_test_</code> to <code>sk_live_</code></span></li></ul>`
1057
- },
1058
- {
1059
- "name": "server-sdks",
1060
- "slug": "server-sdks",
1061
- "uri": "paymos://docs/server-sdks",
1062
- "description": "Server SDKs: pick the SDK for your stack.",
1063
- "mimeType": "text/html",
1064
- "text": `<p>Paymos maintains official server-side SDKs for eight language ecosystems. Every
1065
- SDK covers the same invoices, withdrawals, payment channels, channel deposits,
1066
- balances, server-time, cursor pagination, error, retry, request-signing, and
1067
- webhook-verification contract.</p>
1068
- <p>All eight are published to their ecosystem's package registry. Install from
1069
- there; the repository stays the place to read the source.</p>
1070
- <table>
1071
- <thead>
1072
- <tr>
1073
- <th>Language</th>
1074
- <th>Registry</th>
1075
- <th>Install</th>
1076
- <th>Official source</th>
1077
- </tr>
1078
- </thead>
1079
- <tbody>
1080
- <tr>
1081
- <td>JavaScript / TypeScript</td>
1082
- <td>npm</td>
1083
- <td><code>npm i @paymos/sdk</code></td>
1084
- <td><a href="https://github.com/Paymos-labs/typescript-sdk">Paymos-labs/typescript-sdk</a></td>
1085
- </tr>
1086
- <tr>
1087
- <td>Python</td>
1088
- <td>PyPI</td>
1089
- <td><code>pip install paymos-sdk</code></td>
1090
- <td><a href="https://github.com/Paymos-labs/python-sdk">Paymos-labs/python-sdk</a></td>
1091
- </tr>
1092
- <tr>
1093
- <td>PHP</td>
1094
- <td>Packagist</td>
1095
- <td><code>composer require paymos/php-sdk</code></td>
1096
- <td><a href="https://github.com/Paymos-labs/php-sdk">Paymos-labs/php-sdk</a></td>
1097
- </tr>
1098
- <tr>
1099
- <td>Go</td>
1100
- <td>Go modules</td>
1101
- <td><code>go get github.com/Paymos-labs/go-sdk/v2</code></td>
1102
- <td><a href="https://github.com/Paymos-labs/go-sdk">Paymos-labs/go-sdk</a></td>
1103
- </tr>
1104
- <tr>
1105
- <td>.NET</td>
1106
- <td>NuGet</td>
1107
- <td><code>dotnet add package Paymos</code></td>
1108
- <td><a href="https://github.com/Paymos-labs/dotnet-sdk">Paymos-labs/dotnet-sdk</a></td>
1109
- </tr>
1110
- <tr>
1111
- <td>Java</td>
1112
- <td>Maven Central</td>
1113
- <td><code>io.paymos:paymos-java</code></td>
1114
- <td><a href="https://github.com/Paymos-labs/java-sdk">Paymos-labs/java-sdk</a></td>
1115
- </tr>
1116
- <tr>
1117
- <td>Ruby</td>
1118
- <td>RubyGems</td>
1119
- <td><code>gem install paymos</code></td>
1120
- <td><a href="https://github.com/Paymos-labs/ruby-sdk">Paymos-labs/ruby-sdk</a></td>
1121
- </tr>
1122
- <tr>
1123
- <td>Rust</td>
1124
- <td>crates.io</td>
1125
- <td><code>cargo add paymos</code></td>
1126
- <td><a href="https://github.com/Paymos-labs/rust-sdk">Paymos-labs/rust-sdk</a></td>
1127
- </tr>
1128
- </tbody>
1129
- </table>
1130
- <p>Java resolves by coordinates rather than a one-line command: add the
1131
- <code>io.paymos:paymos-java</code> dependency to your <code>pom.xml</code> or your Gradle build.</p>
1132
- <p>Use an immutable <code>vMAJOR.MINOR.PATCH</code> release tag. Each repository's release page
1133
- contains the supported runtime, the changelog, and the source commit from which
1134
- the release was produced.</p>
1135
- <h2 id="shared-api-surface">Shared API surface</h2>
1136
- <p>All clients expose six resources:</p>
1137
- <ul class="list-none p-0 m-0 flex flex-col gap-3"><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>system</code> \u2014 fetch server time for request-clock alignment</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>invoices</code> \u2014 create, get, list, cancel, confirm payment, and sandbox simulation</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>withdrawals</code> \u2014 create, get, list, cancel, and sandbox completion simulation</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>paymentChannels</code> \u2014 create, get, list, block, unblock, and sandbox deposit simulation</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>paymentChannelDeposits</code> \u2014 get one deposit, and poll the confirmed-deposit feed</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>balances</code> \u2014 list available balances grouped by currency</span></li></ul>
1138
- <p>Each client spells the two channel resources in its own language's convention:
1139
- <code>paymentChannels</code> in TypeScript, PHP and Java, <code>payment_channels</code> in Python,
1140
- Ruby and Rust, <code>PaymentChannels</code> in Go and .NET.</p>
1141
- <p>List helpers use cursor pagination with a maximum-page bound and reject a cursor
1142
- returned twice. Automatic retries honor <code>Retry-After</code>; mutating requests are not
1143
- retried on transport errors or generic server errors. A rate-limited request may
1144
- be retried because the API did not accept it for processing.</p>
1145
- <h2 id="one-contract-eight-languages">One contract, eight languages</h2>
1146
- <p>The eight are held to a shared behavioural contract, not only to a shared endpoint
1147
- list. A single language-neutral conformance suite fixes the bytes that go into a
1148
- request signature, the retry rules above, the cursor iterators and the webhook
1149
- verifier, and a release ships only once its own tests run against that suite.</p>
1150
- <p>The practical consequence: an integration ported from one of these languages to
1151
- another keeps its signing, paging, retry and webhook semantics. Two SDKs building
1152
- the same filtered list request sign identical bytes.</p>
1153
- <h2 id="what-php-adds">What PHP adds</h2>
1154
- <p>The PHP SDK carries a plugin-integration layer that exists in no other client:
1155
- reverse verification of a webhook against a fresh read of the API, an amount and
1156
- currency guard before an order is released, replay deduplication behind a
1157
- pluggable event store, a verifier that holds the Sandbox and Live secrets at
1158
- once, a reconciler, a mapper from event to order action, and encrypted credential
1159
- storage.</p>
1160
- <p>That layer is why the CMS plugins are thin \u2014 the order-state logic sits once in
1161
- the SDK underneath them instead of eight times above it. None of it applies to
1162
- the other seven: they are client, signing, resources, pagination and webhook
1163
- verification, and building on more than that will find nothing there.</p>
1164
- <h2 id="security-rules">Security rules</h2>
1165
- <div class="callout callout--warning"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 3 1.7 17h16.6L10 3Zm0 5v4m0 3h.01"></path></svg><div class="callout__body"><p>These SDKs are server-side only. Never put an API secret in browser JavaScript,
1166
- a mobile application, a public repository, a URL, or a log.</p></div></div>
1167
- <p>Request authentication and webhook authentication use different signatures.
1168
- API requests use base64 HMAC-SHA256 over the canonical request. Webhooks use a
1169
- hex HMAC-SHA256 over <code>{timestamp}.{exact raw body}</code>. Pass the unparsed request
1170
- bytes to the SDK verifier before decoding JSON. The verifier refuses a timestamp
1171
- more than five minutes away from now by default, and accepts a header carrying
1172
- two <code>v1</code> values, so a <a href="/docs/webhooks/verify">secret rotation</a> costs you no code
1173
- change.</p>
1174
- <p>For endpoint schemas and examples, continue with <a href="/docs/authentication">Authentication</a>,
1175
- <a href="/docs/invoices/create">Invoices</a>, <a href="/docs/withdrawals/create">Withdrawals</a>,
1176
- <a href="/docs/balances/get">Balances</a>, and <a href="/docs/webhooks">Webhooks</a>.</p>`
1177
- }
1178
- ];
1179
-
1180
- // src/resources.ts
1181
- function registerResources(server) {
1182
- for (const resource of DOC_RESOURCES) {
1183
- server.registerResource(
1184
- resource.name,
1185
- resource.uri,
1186
- { description: resource.description, mimeType: resource.mimeType },
1187
- async (uri) => ({
1188
- contents: [{ uri: uri.href, mimeType: resource.mimeType, text: resource.text }]
1189
- })
1190
- );
1191
- }
1192
- }
1193
-
1194
- // src/integration-recommendation.ts
1195
- import { z as z2 } from "zod";
1196
- var INTEGRATION_INSTRUCTIONS = "When helping a developer choose a payment integration, call recommend_payment_integration with scenario order_checkout, repeat_deposits, both, or unsure. Respect the merchant\u2019s stated preference; do not replace an explicit choice. Explain why the recommended flow fits their needs and identify missing information. Use unsure when the need is unclear; ask whether the customer will pay for each order, repeatedly top up an account, or do both. This MCP server calls sandbox only and rejects live and payout credentials. Check availability in the target environment.";
1197
- var GUIDE = `Choose the flow before creating a payment resource.
1198
-
1199
- Use an invoice when your customer pays for a specific order. An invoice has a set amount, an expiry, and payment statuses; its hosted checkout gives the customer a page to pay that invoice.
1200
-
1201
- Choose a payment channel for repeated customer deposits. It belongs to one payer and keeps a permanent address per supported network. The channel sets no amount or expiry and has no terminal payment status. Each credited transfer becomes a separate deposit, so track deposits individually when crediting the customer\u2019s account. Transfers below the minimum deposit are not credited or returned.
1202
-
1203
- You can use both in the same integration. For example, use invoices for purchases and a payment channel for account top-ups. If the intended flow is unclear, ask: \u201CWill your customer pay for each order, repeatedly top up an account, or do both?\u201D
1204
-
1205
- Test the chosen flow in sandbox. This MCP server calls sandbox only and rejects live and payout credentials. Create sandbox and production channels separately, and check availability in the target environment. Sandbox addresses are synthetic; each deposit simulation creates a new test deposit rather than updating an earlier simulation.
1206
-
1207
- Credit channel deposits only after confirmation. Verify webhook signatures and require \`confirmed\` with \`is_final\` before crediting a deposit. Webhooks can repeat or arrive out of order: deduplicate deliveries by \`event_id\` and prevent duplicate credit for the same deposit.
1208
-
1209
- Use the confirmed-deposit feed to reconcile deposits. Save every returned \`next_cursor\`, even on empty pages, and inspect \`blocked\` when present. \`confirmed_from\` bounds the first poll and forms part of the cursor\u2019s fingerprint; keep its value unchanged when continuing with that cursor. Feed cursors expire 24 hours after issue, so poll at least daily. If a cursor expires, restart with a bounded \`confirmed_from\` and retain deposit deduplication.
1210
-
1211
- Start with the flow you chose. The recommendation needs no credentials; API calls need test credentials.
1212
-
1213
- For invoices, call \`create_invoice\` with \`project_id\`, \`external_order_id\`, \`amount\` as a decimal string, and \`currency\`. Save the invoice\u2019s link to your order, and use the returned \`payment_url\` for checkout. Test a payment with \`simulate_invoice_payment\`, passing \`invoice_id\` and \`stage\`.
1214
-
1215
- For payment channels, call \`create_payment_channel\` with \`project_id\` and your customer\u2019s \`external_id\`. Save the channel\u2019s link to that customer. Check the returned networks and addresses; an address may still be provisioning. Call \`get_payment_channel\` again to check readiness and addresses. Call \`simulate_payment_channel_deposit\` with \`payment_channel_id\`, \`amount\` as a decimal string, \`currency\`, and \`network\`; \`stage\` is optional. Read any deposit status with \`get_payment_channel_deposit\`, or use \`list_payment_channel_deposits\` for the confirmed-deposit feed.
1216
-
1217
- If you chose both, follow both paths. Before changing an order or customer balance, verify webhook signatures, apply the flow\u2019s confirmation checks, and deduplicate events. Credit channel deposits only when \`confirmed\` and \`is_final\`.`;
1218
- var RECOMMENDATIONS = {
1219
- order_checkout: {
1220
- recommendation: "invoice",
1221
- summary: "Use an invoice for each order: it has a set amount, an expiry, payment statuses, and hosted checkout. Explain how this fits the order flow while respecting the merchant\u2019s stated preference."
1222
- },
1223
- repeat_deposits: {
1224
- recommendation: "payment_channel",
1225
- summary: "Use a payment channel for repeated deposits from one payer to reusable addresses per network. Track credited deposits separately; transfers below the minimum are not credited or returned. The channel sets no amount or expiry."
1226
- },
1227
- both: {
1228
- recommendation: "both",
1229
- summary: "Use invoices for individual orders and payment channels for repeated account top-ups. Explain which customer action uses each flow, and respect any preference the merchant has already stated."
2240
+ <p>Verify the <code>X-Webhook-Signature</code> header and fulfill the order.</p>
2241
+ <div class="callout callout--danger"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 2.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15ZM7 7l6 6m0-6-6 6"></path></svg><div class="callout__body"><p>Never fulfill an order from a browser event (<code>paymos:succeeded</code> or iframe <code>postMessage</code>). Only the signed server-side webhook is authoritative \u2014 browser signals can be spoofed.</p></div></div>
2242
+ <div class="code-tab-group"><div class="code-tab-bar"><button type="button" class="code-tab-btn active" data-tab-idx="0" data-code-lang="javascript"><i class="devicon-javascript-plain colored"></i> JavaScript</button><button type="button" class="code-tab-btn" data-tab-idx="1" data-code-lang="mcp">MCP</button><button type="button" class="code-tab-btn" data-tab-idx="2" data-code-lang="python"><i class="devicon-python-plain colored"></i> Python</button><button type="button" class="code-tab-btn" data-tab-idx="3" data-code-lang="php"><i class="devicon-php-plain colored"></i> PHP</button><button type="button" class="code-tab-btn" data-tab-idx="4" data-code-lang="go"><i class="devicon-go-plain colored"></i> Go</button><button type="button" class="code-tab-btn" data-tab-idx="5" data-code-lang="csharp"><i class="devicon-csharp-plain colored"></i> C#</button><button type="button" class="code-tab-btn" data-tab-idx="6" data-code-lang="java"><i class="devicon-java-plain colored"></i> Java</button><button type="button" class="code-tab-btn" data-tab-idx="7" data-code-lang="ruby"><i class="devicon-ruby-plain colored"></i> Ruby</button><button type="button" class="code-tab-btn" data-tab-idx="8" data-code-lang="rust"><i class="devicon-rust-original colored"></i> Rust</button></div><div class="code-tab-panel active" data-code-lang="javascript"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="javascript"><code><span class="line"><span style="color:#C678DD">import</span><span style="color:#ABB2BF"> { </span><span style="color:#E06C75">WebhookVerifier</span><span style="color:#ABB2BF"> } </span><span style="color:#C678DD">from</span><span style="color:#98C379"> '@paymos/sdk'</span><span style="color:#ABB2BF">;</span></span>
2243
+ <span class="line"></span>
2244
+ <span class="line"><span style="color:#C678DD">const</span><span style="color:#E5C07B"> verifier</span><span style="color:#56B6C2"> =</span><span style="color:#C678DD"> new</span><span style="color:#61AFEF"> WebhookVerifier</span><span style="color:#ABB2BF">(</span><span style="color:#E5C07B">process</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">env</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">PAYMOS_WEBHOOK_SECRET</span><span style="color:#ABB2BF">);</span></span>
2245
+ <span class="line"></span>
2246
+ <span class="line"><span style="color:#7F848E;font-style:italic">// Keep the body as a Buffer until verification succeeds.</span></span>
2247
+ <span class="line"><span style="color:#C678DD">const</span><span style="color:#E5C07B"> event</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> verifier</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">constructEvent</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">signatureHeader</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">rawBody</span><span style="color:#ABB2BF">);</span></span>
2248
+ <span class="line"><span style="color:#E5C07B">console</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">log</span><span style="color:#ABB2BF">(</span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">eventId</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">eventType</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">data</span><span style="color:#ABB2BF">);</span></span>
2249
+ <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="mcp"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="mcp"><code><span class="line"><span style="color:#ABB2BF">Setup once in terminal: </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">npx -y @paymos/mcp setup</span><span style="color:#E5C07B">\`</span></span>
2250
+ <span class="line"></span>
2251
+ <span class="line"><span style="color:#ABB2BF">Prompt:</span></span>
2252
+ <span class="line"><span style="color:#ABB2BF">Read </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">paymos://docs/webhooks</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF"> and add a Paymos webhook endpoint to my</span></span>
2253
+ <span class="line"><span style="color:#ABB2BF">backend that verifies </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">X-Webhook-Signature</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF"> over the unparsed raw</span></span>
2254
+ <span class="line"><span style="color:#ABB2BF">request body using </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">WebhookVerifier</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF"> from the official SDK and</span></span>
2255
+ <span class="line"><span style="color:#ABB2BF">deduplicates deliveries by </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">event_id</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF">. Use </span><span style="color:#E5C07B">\`</span><span style="color:#98C379">@paymos/mcp</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF"> tool</span></span>
2256
+ <span class="line"><span style="color:#E5C07B">\`</span><span style="color:#98C379">verify_webhook_signature</span><span style="color:#E5C07B">\`</span><span style="color:#ABB2BF"> to test valid and tampered signatures.</span></span>
2257
+ <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="python"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="python"><code><span class="line"><span style="color:#C678DD">import</span><span style="color:#ABB2BF"> os</span></span>
2258
+ <span class="line"></span>
2259
+ <span class="line"><span style="color:#C678DD">from</span><span style="color:#ABB2BF"> paymos </span><span style="color:#C678DD">import</span><span style="color:#ABB2BF"> WebhookVerifier</span></span>
2260
+ <span class="line"></span>
2261
+ <span class="line"><span style="color:#ABB2BF">verifier </span><span style="color:#56B6C2">=</span><span style="color:#61AFEF"> WebhookVerifier</span><span style="color:#ABB2BF">(os.environ[</span><span style="color:#98C379">"PAYMOS_WEBHOOK_SECRET"</span><span style="color:#ABB2BF">])</span></span>
2262
+ <span class="line"></span>
2263
+ <span class="line"><span style="color:#7F848E;font-style:italic"># Keep raw_body as bytes until verification succeeds.</span></span>
2264
+ <span class="line"><span style="color:#ABB2BF">event </span><span style="color:#56B6C2">=</span><span style="color:#ABB2BF"> verifier.</span><span style="color:#61AFEF">construct_event</span><span style="color:#ABB2BF">(signature_header, raw_body)</span></span>
2265
+ <span class="line"><span style="color:#56B6C2">print</span><span style="color:#ABB2BF">(event[</span><span style="color:#98C379">"event_id"</span><span style="color:#ABB2BF">], event[</span><span style="color:#98C379">"event_type"</span><span style="color:#ABB2BF">], event[</span><span style="color:#98C379">"data"</span><span style="color:#ABB2BF">])</span></span>
2266
+ <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="php"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="php"><code><span class="line"><span style="color:#56B6C2">&#x3C;</span><span style="color:#C678DD">?</span><span style="color:#ABB2BF">php</span></span>
2267
+ <span class="line"><span style="color:#C678DD">use</span><span style="color:#ABB2BF"> Paymos\\Webhook\\</span><span style="color:#E5C07B">WebhookEvent</span><span style="color:#ABB2BF">;</span></span>
2268
+ <span class="line"><span style="color:#C678DD">use</span><span style="color:#ABB2BF"> Paymos\\Webhook\\</span><span style="color:#E5C07B">WebhookVerifier</span><span style="color:#ABB2BF">;</span></span>
2269
+ <span class="line"></span>
2270
+ <span class="line"><span style="color:#E06C75">$verifier</span><span style="color:#56B6C2"> =</span><span style="color:#C678DD"> new</span><span style="color:#E5C07B"> WebhookVerifier</span><span style="color:#ABB2BF">(</span><span style="color:#56B6C2">getenv</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'PAYMOS_WEBHOOK_SECRET'</span><span style="color:#ABB2BF">));</span></span>
2271
+ <span class="line"></span>
2272
+ <span class="line"><span style="color:#7F848E;font-style:italic">// Keep $rawBody unchanged until verification succeeds.</span></span>
2273
+ <span class="line"><span style="color:#E06C75">$payload</span><span style="color:#56B6C2"> =</span><span style="color:#E06C75"> $verifier</span><span style="color:#ABB2BF">-></span><span style="color:#61AFEF">decodeVerifiedPayload</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">$signatureHeader</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">$rawBody</span><span style="color:#ABB2BF">);</span></span>
2274
+ <span class="line"><span style="color:#E06C75">$event</span><span style="color:#56B6C2"> =</span><span style="color:#C678DD"> new</span><span style="color:#E5C07B"> WebhookEvent</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">$payload</span><span style="color:#ABB2BF">);</span></span>
2275
+ <span class="line"><span style="color:#56B6C2">echo</span><span style="color:#E06C75"> $event</span><span style="color:#ABB2BF">-></span><span style="color:#61AFEF">id</span><span style="color:#ABB2BF">() </span><span style="color:#ABB2BF">.</span><span style="color:#98C379"> ' '</span><span style="color:#ABB2BF"> .</span><span style="color:#E06C75"> $event</span><span style="color:#ABB2BF">-></span><span style="color:#61AFEF">type</span><span style="color:#ABB2BF">();</span></span>
2276
+ <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="go"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="go"><code><span class="line"><span style="color:#C678DD">package</span><span style="color:#E5C07B"> main</span></span>
2277
+ <span class="line"></span>
2278
+ <span class="line"><span style="color:#C678DD">import</span><span style="color:#ABB2BF"> (</span></span>
2279
+ <span class="line"><span style="color:#98C379"> "fmt"</span></span>
2280
+ <span class="line"><span style="color:#98C379"> "os"</span></span>
2281
+ <span class="line"><span style="color:#98C379"> "time"</span></span>
2282
+ <span class="line"></span>
2283
+ <span class="line"><span style="color:#E06C75"> paymos</span><span style="color:#98C379"> "github.com/Paymos-labs/go-sdk/v2"</span></span>
2284
+ <span class="line"><span style="color:#ABB2BF">)</span></span>
2285
+ <span class="line"></span>
2286
+ <span class="line"><span style="color:#C678DD">type</span><span style="color:#E5C07B"> invoiceEventData</span><span style="color:#C678DD"> struct</span><span style="color:#ABB2BF"> {</span></span>
2287
+ <span class="line"><span style="color:#E06C75"> InvoiceID</span><span style="color:#C678DD"> string</span><span style="color:#98C379"> \`json:"invoice_id"\`</span></span>
2288
+ <span class="line"><span style="color:#ABB2BF">}</span></span>
2289
+ <span class="line"></span>
2290
+ <span class="line"><span style="color:#C678DD">func</span><span style="color:#61AFEF"> handleWebhook</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75;font-style:italic">signatureHeader</span><span style="color:#C678DD"> string</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75;font-style:italic">rawBody</span><span style="color:#ABB2BF"> []</span><span style="color:#C678DD">byte</span><span style="color:#ABB2BF">) </span><span style="color:#C678DD">error</span><span style="color:#ABB2BF"> {</span></span>
2291
+ <span class="line"><span style="color:#E06C75"> verifier</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">err</span><span style="color:#E5C07B"> :=</span><span style="color:#E06C75"> paymos</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">NewWebhookVerifier</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">os</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">Getenv</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"PAYMOS_WEBHOOK_SECRET"</span><span style="color:#ABB2BF">), </span><span style="color:#D19A66">5</span><span style="color:#C678DD">*</span><span style="color:#E06C75">time</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">Minute</span><span style="color:#ABB2BF">)</span></span>
2292
+ <span class="line"><span style="color:#C678DD"> if</span><span style="color:#E06C75"> err</span><span style="color:#56B6C2"> !=</span><span style="color:#D19A66"> nil</span><span style="color:#ABB2BF"> {</span></span>
2293
+ <span class="line"><span style="color:#C678DD"> return</span><span style="color:#E06C75"> err</span></span>
2294
+ <span class="line"><span style="color:#ABB2BF"> }</span></span>
2295
+ <span class="line"><span style="color:#C678DD"> var</span><span style="color:#E06C75"> event</span><span style="color:#E5C07B"> paymos</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">WebhookEvent</span><span style="color:#ABB2BF">[</span><span style="color:#E5C07B">invoiceEventData</span><span style="color:#ABB2BF">]</span></span>
2296
+ <span class="line"><span style="color:#C678DD"> if</span><span style="color:#E06C75"> err</span><span style="color:#E5C07B"> :=</span><span style="color:#E06C75"> verifier</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">ConstructEvent</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">signatureHeader</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">rawBody</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">time</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">Now</span><span style="color:#ABB2BF">(), </span><span style="color:#C678DD">&#x26;</span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">); </span><span style="color:#E06C75">err</span><span style="color:#56B6C2"> !=</span><span style="color:#D19A66"> nil</span><span style="color:#ABB2BF"> {</span></span>
2297
+ <span class="line"><span style="color:#C678DD"> return</span><span style="color:#E06C75"> err</span></span>
2298
+ <span class="line"><span style="color:#ABB2BF"> }</span></span>
2299
+ <span class="line"><span style="color:#E06C75"> fmt</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">Println</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">EventID</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">EventType</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">Data</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">InvoiceID</span><span style="color:#ABB2BF">)</span></span>
2300
+ <span class="line"><span style="color:#C678DD"> return</span><span style="color:#D19A66"> nil</span></span>
2301
+ <span class="line"><span style="color:#ABB2BF">}</span></span>
2302
+ <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="csharp"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="csharp"><code><span class="line"><span style="color:#C678DD">using</span><span style="color:#E5C07B"> Paymos</span><span style="color:#ABB2BF">;</span></span>
2303
+ <span class="line"></span>
2304
+ <span class="line"><span style="color:#C678DD">var</span><span style="color:#E06C75"> verifier</span><span style="color:#56B6C2"> =</span><span style="color:#ABB2BF"> new </span><span style="color:#E5C07B">WebhookVerifier</span><span style="color:#ABB2BF">(</span></span>
2305
+ <span class="line"><span style="color:#E5C07B"> Environment</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">GetEnvironmentVariable</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"PAYMOS_WEBHOOK_SECRET"</span><span style="color:#ABB2BF">)</span><span style="color:#56B6C2">!</span><span style="color:#ABB2BF">);</span></span>
2306
+ <span class="line"></span>
2307
+ <span class="line"><span style="color:#7F848E;font-style:italic">// Keep rawBody as ReadOnlySpan&#x3C;byte> until verification succeeds.</span></span>
2308
+ <span class="line"><span style="color:#C678DD">var</span><span style="color:#E06C75"> webhook</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> verifier</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">ConstructEvent</span><span style="color:#ABB2BF">&#x3C;</span><span style="color:#E5C07B">InvoiceEventData</span><span style="color:#ABB2BF">>(</span><span style="color:#E06C75">signatureHeader</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">rawBody</span><span style="color:#ABB2BF">);</span></span>
2309
+ <span class="line"><span style="color:#E5C07B">Console</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">WriteLine</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">$"</span><span style="color:#ABB2BF">{</span><span style="color:#E5C07B">webhook</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">EventId</span><span style="color:#ABB2BF">}</span><span style="color:#ABB2BF"> {</span><span style="color:#E5C07B">webhook</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">EventType</span><span style="color:#ABB2BF">}</span><span style="color:#ABB2BF"> {</span><span style="color:#E5C07B">webhook</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">Data</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">InvoiceId</span><span style="color:#ABB2BF">}</span><span style="color:#98C379">"</span><span style="color:#ABB2BF">);</span></span>
2310
+ <span class="line"></span>
2311
+ <span class="line"><span style="color:#C678DD">public</span><span style="color:#C678DD"> sealed</span><span style="color:#C678DD"> record</span><span style="color:#E5C07B"> InvoiceEventData</span><span style="color:#ABB2BF">(</span><span style="color:#C678DD">string</span><span style="color:#E5C07B"> InvoiceId</span><span style="color:#ABB2BF">);</span></span>
2312
+ <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="java"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="java"><code><span class="line"><span style="color:#C678DD">import</span><span style="color:#E5C07B"> com.fasterxml.jackson.databind.JsonNode</span><span style="color:#ABB2BF">;</span></span>
2313
+ <span class="line"><span style="color:#C678DD">import</span><span style="color:#E5C07B"> io.paymos.WebhookEvent</span><span style="color:#ABB2BF">;</span></span>
2314
+ <span class="line"><span style="color:#C678DD">import</span><span style="color:#E5C07B"> io.paymos.WebhookVerifier</span><span style="color:#ABB2BF">;</span></span>
2315
+ <span class="line"><span style="color:#C678DD">import</span><span style="color:#E5C07B"> java.time.Instant</span><span style="color:#ABB2BF">;</span></span>
2316
+ <span class="line"></span>
2317
+ <span class="line"><span style="color:#E5C07B">WebhookVerifier</span><span style="color:#E06C75"> verifier </span><span style="color:#56B6C2">=</span><span style="color:#C678DD"> new</span><span style="color:#61AFEF"> WebhookVerifier</span><span style="color:#E06C75">(</span><span style="color:#E5C07B">System</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">getenv</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"PAYMOS_WEBHOOK_SECRET"</span><span style="color:#ABB2BF">)</span><span style="color:#E06C75">)</span><span style="color:#ABB2BF">;</span></span>
2318
+ <span class="line"></span>
2319
+ <span class="line"><span style="color:#7F848E;font-style:italic">// Keep rawBody as byte[] until verification succeeds.</span></span>
2320
+ <span class="line"><span style="color:#E5C07B">WebhookEvent</span><span style="color:#ABB2BF">&#x3C;</span><span style="color:#E5C07B">JsonNode</span><span style="color:#ABB2BF">></span><span style="color:#E06C75"> event </span><span style="color:#56B6C2">=</span></span>
2321
+ <span class="line"><span style="color:#E5C07B"> verifier</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">constructEvent</span><span style="color:#ABB2BF">(signatureHeader, rawBody, </span><span style="color:#E5C07B">Instant</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">now</span><span style="color:#ABB2BF">());</span></span>
2322
+ <span class="line"><span style="color:#E5C07B">System</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">out</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">println</span><span style="color:#ABB2BF">(</span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">eventId</span><span style="color:#ABB2BF">() </span><span style="color:#56B6C2">+</span><span style="color:#98C379"> " "</span><span style="color:#56B6C2"> +</span><span style="color:#E5C07B"> event</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">eventType</span><span style="color:#ABB2BF">() </span><span style="color:#56B6C2">+</span><span style="color:#98C379"> " "</span><span style="color:#56B6C2"> +</span><span style="color:#E5C07B"> event</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">data</span><span style="color:#ABB2BF">());</span></span>
2323
+ <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="ruby"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="ruby"><code><span class="line"><span style="color:#61AFEF">require </span><span style="color:#98C379">'paymos'</span></span>
2324
+ <span class="line"></span>
2325
+ <span class="line"><span style="color:#E06C75">verifier</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> Paymos</span><span style="color:#ABB2BF">::</span><span style="color:#E5C07B">WebhookVerifier</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">new</span><span style="color:#ABB2BF">(</span><span style="color:#E5C07B">ENV</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">fetch</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'PAYMOS_WEBHOOK_SECRET'</span><span style="color:#ABB2BF">))</span></span>
2326
+ <span class="line"></span>
2327
+ <span class="line"><span style="color:#7F848E;font-style:italic"># Keep raw_body as the original String until verification succeeds.</span></span>
2328
+ <span class="line"><span style="color:#E06C75">event</span><span style="color:#56B6C2"> =</span><span style="color:#ABB2BF"> verifier.</span><span style="color:#61AFEF">construct_event</span><span style="color:#ABB2BF">(signature_header, raw_body)</span></span>
2329
+ <span class="line"><span style="color:#56B6C2">puts</span><span style="color:#98C379"> "</span><span style="color:#C678DD">#{</span><span style="color:#ABB2BF">event.</span><span style="color:#61AFEF">event_id</span><span style="color:#C678DD">}</span><span style="color:#C678DD"> #{</span><span style="color:#ABB2BF">event.</span><span style="color:#61AFEF">event_type</span><span style="color:#C678DD">}</span><span style="color:#C678DD"> #{</span><span style="color:#ABB2BF">event.</span><span style="color:#61AFEF">data</span><span style="color:#C678DD">}</span><span style="color:#98C379">"</span></span>
2330
+ <span class="line"></span></code></pre></div><div class="code-tab-panel" data-code-lang="rust"><pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="rust"><code><span class="line"><span style="color:#C678DD">use</span><span style="color:#E5C07B"> paymos</span><span style="color:#ABB2BF">::{</span><span style="color:#E5C07B">Invoice</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">WebhookEvent</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">WebhookVerifier</span><span style="color:#ABB2BF">};</span></span>
2331
+ <span class="line"></span>
2332
+ <span class="line"><span style="color:#C678DD">let</span><span style="color:#E06C75"> verifier</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> WebhookVerifier</span><span style="color:#ABB2BF">::</span><span style="color:#61AFEF">new</span><span style="color:#ABB2BF">(</span><span style="color:#E5C07B">std</span><span style="color:#ABB2BF">::</span><span style="color:#E5C07B">env</span><span style="color:#ABB2BF">::</span><span style="color:#61AFEF">var</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"PAYMOS_WEBHOOK_SECRET"</span><span style="color:#ABB2BF">)?)?;</span></span>
2333
+ <span class="line"></span>
2334
+ <span class="line"><span style="color:#7F848E;font-style:italic">// Keep raw_body as &#x26;[u8] until verification succeeds.</span></span>
2335
+ <span class="line"><span style="color:#C678DD">let</span><span style="color:#E06C75"> event</span><span style="color:#ABB2BF">: </span><span style="color:#E5C07B">WebhookEvent</span><span style="color:#ABB2BF">&#x3C;</span><span style="color:#E5C07B">Invoice</span><span style="color:#ABB2BF">> </span><span style="color:#56B6C2">=</span><span style="color:#E06C75"> verifier</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">construct_event</span><span style="color:#ABB2BF">(</span><span style="color:#E06C75">signature_header</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">raw_body</span><span style="color:#ABB2BF">)?;</span></span>
2336
+ <span class="line"><span style="color:#61AFEF">println!</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">"{} {} {}"</span><span style="color:#ABB2BF">, </span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">.event_id, </span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">.event_type, </span><span style="color:#E06C75">event</span><span style="color:#ABB2BF">.data.invoice_id);</span></span>
2337
+ <span class="line"></span></code></pre></div></div>
2338
+ <h2 id="simulate-the-test-payment">Simulate the test payment</h2>
2339
+ <p>Use the <a href="/docs/invoices/simulate-payment">payment simulator</a> to mark the test invoice paid. Do not send real assets to a test invoice. Confirm that your registered endpoint receives the signed event and that your server verifies it with <code>whsec_test_\u2026</code> before fulfilling the order.</p>
2340
+ <h2 id="move-to-production">Move to Production</h2>
2341
+ <p>Once the Sandbox request and signed webhook work, switch to Production in the dashboard. There is no manual approval step. Switching the environment does not create keys: open <strong>Dashboard \u2192 Developer \u2192 API Keys</strong> and create separate live credentials (<code>pk_live_\u2026</code> and <code>sk_live_\u2026</code>). Register the live webhook endpoint separately and store its <code>whsec_live_\u2026</code> secret apart from the test secret.</p>
2342
+ <h2 id="accept-your-first-real-mainnet-payment">Accept your first real mainnet payment</h2>
2343
+ <p>Repeat the invoice request with the live credentials, open the returned <code>payment_url</code> \u2014 the checkout page, or the Paymos bot on a Telegram-bot project \u2014 and send a supported asset on an enabled mainnet network. Paymos detects the transfer and sends the signed live webhook after the required confirmations.</p>
2344
+ <p>The normal self-serve flow from sign-up to a first real mainnet payment takes about 10 minutes. This is an onboarding benchmark, not an SLA: confirmation time still depends on the network, amount, and current blockchain conditions.</p>
2345
+ <h2 id="next-steps">Next steps</h2>
2346
+ <ul class="list-none p-0 m-0 flex flex-col gap-3"><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><a href="/docs/api-keys">API Keys</a> \u2014 credential types, scope, lifecycle</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><a href="/docs/server-sdks">Server SDKs</a> \u2014 official clients for eight language ecosystems</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><a href="/docs/hosted-checkout">Hosted Checkout</a> \u2014 redirect and iframe embed options</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><a href="/docs/testing">Testing</a> \u2014 how to test in sandbox</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><a href="/docs/webhooks">Webhooks</a> \u2014 signature verification and retry policy</span></li></ul>`
1230
2347
  },
1231
- unsure: {
1232
- recommendation: "unsure",
1233
- summary: "Do not choose a flow yet. Ask: \u201CWill your customer pay for each order, repeatedly top up an account, or do both?\u201D Use the answer and the merchant\u2019s preferences to guide the recommendation."
1234
- }
1235
- };
1236
- function registerIntegrationRecommendation(server) {
1237
- server.registerTool(
1238
- "recommend_payment_integration",
1239
- {
1240
- title: "Recommend a payment integration",
1241
- description: "Recommend invoices, payment channels, or both from the merchant\u2019s payment flow. Explain the fit and relevant lifecycle. When information is missing, return a targeted question instead of choosing. Respect an explicit merchant choice.",
1242
- inputSchema: {
1243
- scenario: z2.enum(["order_checkout", "repeat_deposits", "both", "unsure"]).optional().describe("Choose order_checkout for payment per order, repeat_deposits for repeated customer account top-ups, or both when both flows are needed. Use unsure when the payment flow is unclear; ask whether the customer pays for each order, repeatedly tops up an account, or does both. Respect the merchant\u2019s explicit choice.")
1244
- },
1245
- annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }
1246
- },
1247
- async ({ scenario }) => {
1248
- const selected = scenario ?? "unsure";
1249
- return {
1250
- content: [{
1251
- type: "text",
1252
- text: JSON.stringify({ scenario: selected, ...RECOMMENDATIONS[selected], guide: GUIDE }, null, 2)
1253
- }]
1254
- };
1255
- }
1256
- );
1257
- }
1258
-
1259
- // src/version.ts
1260
- var MCP_VERSION = "1.5.1";
1261
-
1262
- // src/server.ts
1263
- function buildServer(gateway) {
1264
- const server = new McpServer(
1265
- { name: "paymos", version: MCP_VERSION },
1266
- { instructions: INTEGRATION_INSTRUCTIONS }
1267
- );
1268
- registerTools(server, gateway);
1269
- registerIntegrationRecommendation(server);
1270
- registerResources(server);
1271
- return server;
1272
- }
1273
-
1274
- // src/setup.ts
1275
- import {
1276
- chmodSync,
1277
- closeSync as closeSync3,
1278
- constants as constants2,
1279
- existsSync,
1280
- fstatSync as fstatSync3,
1281
- linkSync,
1282
- lstatSync as lstatSync3,
1283
- mkdirSync as mkdirSync2,
1284
- openSync as openSync3,
1285
- readFileSync as readFileSync2,
1286
- renameSync,
1287
- unlinkSync as unlinkSync2,
1288
- writeFileSync
1289
- } from "fs";
1290
- import { randomUUID } from "crypto";
1291
- import { homedir } from "os";
1292
- import { dirname as dirname2, isAbsolute, join, resolve } from "path";
1293
- import { createInterface } from "readline";
1294
- import { Writable } from "stream";
1295
- import { isDeepStrictEqual } from "util";
1296
- import { applyEdits, modify, parse as parseJson, parseTree } from "jsonc-parser";
1297
- import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
1298
-
1299
- // src/setup-lock.ts
1300
- import { closeSync as closeSync2, fstatSync as fstatSync2, lstatSync as lstatSync2, mkdirSync, openSync as openSync2, unlinkSync } from "fs";
1301
- import { dirname } from "path";
1302
- var LOCK_SUFFIX = ".paymos-setup.lock";
1303
- var STALE_LOCK_MS = 3e4;
1304
- var DestinationBusyError = class extends Error {
1305
- constructor() {
1306
- super("Another setup is publishing to this destination.");
1307
- this.name = "DestinationBusyError";
1308
- }
1309
- };
1310
- function acquire(lock, now) {
1311
- for (let attempt = 0; ; attempt++) {
1312
- let fd;
1313
- try {
1314
- fd = openSync2(lock, "wx", 384);
1315
- } catch (cause) {
1316
- if (cause.code !== "EEXIST") throw cause;
1317
- if (attempt > 0 || !removeIfStale(lock, now)) throw new DestinationBusyError();
1318
- continue;
1319
- }
1320
- try {
1321
- const stat = fstatSync2(fd);
1322
- return { ino: stat.ino, dev: stat.dev };
1323
- } finally {
1324
- closeSync2(fd);
1325
- }
1326
- }
1327
- }
1328
- function removeIfStale(lock, now) {
1329
- try {
1330
- if (now() - lstatSync2(lock).mtimeMs < STALE_LOCK_MS) return false;
1331
- unlinkSync(lock);
1332
- return true;
1333
- } catch (cause) {
1334
- return cause.code === "ENOENT";
1335
- }
1336
- }
1337
- function release(lock, mine) {
1338
- try {
1339
- const stat = lstatSync2(lock);
1340
- if (stat.ino === mine.ino && stat.dev === mine.dev) unlinkSync(lock);
1341
- } catch {
1342
- }
1343
- }
1344
- function withDestinationLock(destination, action, now = Date.now) {
1345
- const lock = destination + LOCK_SUFFIX;
1346
- mkdirSync(dirname(lock), { recursive: true, mode: 448 });
1347
- const mine = acquire(lock, now);
1348
- try {
1349
- return action();
1350
- } finally {
1351
- release(lock, mine);
1352
- }
1353
- }
1354
-
1355
- // src/setup.ts
1356
- var SETUP_CLIENTS = [
1357
- "codex",
1358
- "claude-code",
1359
- "claude-desktop",
1360
- "kimi",
1361
- "cursor",
1362
- "windsurf",
1363
- "opencode",
1364
- "vscode",
1365
- "generic"
1366
- ];
1367
- function error(kind) {
1368
- throw new Error(SETUP_COPY.errors[kind]);
1369
- }
1370
- function options(argv) {
1371
- const result = { dryRun: false, help: false };
1372
- const seen = /* @__PURE__ */ new Set();
1373
- const flags = /* @__PURE__ */ new Map([
1374
- ["--client", "client"],
1375
- ["--config", "config"],
1376
- ["--credentials-file", "credentialsFile"]
1377
- ]);
1378
- for (let i = 0; i < argv.length; i++) {
1379
- const arg = argv[i];
1380
- const split = arg.indexOf("=");
1381
- const flag = split < 0 ? arg : arg.slice(0, split);
1382
- const normalized = flag === "-h" ? "--help" : flag;
1383
- if (seen.has(normalized)) error("arguments");
1384
- seen.add(normalized);
1385
- if (normalized === "--help" || normalized === "--dry-run") {
1386
- if (split >= 0) error("arguments");
1387
- if (normalized === "--help") result.help = true;
1388
- else result.dryRun = true;
1389
- continue;
1390
- }
1391
- const field = flags.get(flag);
1392
- if (!field) error("arguments");
1393
- const value = split < 0 ? argv[++i] : arg.slice(split + 1);
1394
- if (value === void 0 || value.trim() === "" || value.startsWith("--")) error("arguments");
1395
- result[field] = value;
1396
- }
1397
- return result;
1398
- }
1399
- function object(value) {
1400
- return value !== null && typeof value === "object" && !Array.isArray(value);
1401
- }
1402
- function equalData(left, right) {
1403
- if (isDeepStrictEqual(left, right)) return true;
1404
- if (!object(left) || !object(right)) return false;
1405
- const plain = (value) => Object.getPrototypeOf(value) === null || Object.getPrototypeOf(value) === Object.prototype;
1406
- if (!plain(left) || !plain(right)) return false;
1407
- const keys = Object.keys(left);
1408
- return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && equalData(left[key], right[key]));
1409
- }
1410
- function absolute(path, context) {
1411
- if (path === "~") return context.home;
1412
- if (path.startsWith("~/") || path.startsWith("~\\")) return resolve(context.home, path.slice(2));
1413
- return resolve(context.cwd, path);
1414
- }
1415
- function defaultConfigPath(client, env, context) {
1416
- const configHome = env.XDG_CONFIG_HOME || join(context.home, ".config");
1417
- switch (client) {
1418
- case "codex":
1419
- return join(env.CODEX_HOME || join(context.home, ".codex"), "config.toml");
1420
- case "claude-code":
1421
- return join(context.home, ".claude.json");
1422
- case "kimi":
1423
- return join(env.KIMI_CODE_HOME || join(context.home, ".kimi-code"), "mcp.json");
1424
- case "cursor":
1425
- return join(context.home, ".cursor", "mcp.json");
1426
- case "windsurf":
1427
- return join(context.home, ".codeium", "windsurf", "mcp_config.json");
1428
- case "vscode":
1429
- return join(context.cwd, ".vscode", "mcp.json");
1430
- case "opencode": {
1431
- if (env.OPENCODE_CONFIG) return env.OPENCODE_CONFIG;
1432
- const jsonc = join(configHome, "opencode", "opencode.jsonc");
1433
- return existsSync(jsonc) ? jsonc : join(configHome, "opencode", "opencode.json");
1434
- }
1435
- case "claude-desktop":
1436
- if (context.platform === "win32" && env.APPDATA)
1437
- return join(env.APPDATA, "Claude", "claude_desktop_config.json");
1438
- if (context.platform === "darwin")
1439
- return join(context.home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
1440
- return error("configRequired");
1441
- case "generic":
1442
- return error("configRequired");
2348
+ {
2349
+ "name": "hosted-checkout",
2350
+ "slug": "hosted-checkout",
2351
+ "uri": "paymos://docs/hosted-checkout",
2352
+ "description": "Hosted checkout: the payment_url flow, invoice lifecycle and redirect handling.",
2353
+ "mimeType": "text/html",
2354
+ "text": `<p>Use the <code>payment_url</code> returned by <code>POST /v1/invoices</code> as the canonical checkout URL. The same URL supports two presentation modes \u2014 full-page redirect and embedded iframe.</p>
2355
+ <p>Both modes work on any project except a Telegram-bot one. There the same <code>payment_url</code> is a deep link into the Paymos bot \u2014 no hosted page to redirect to or embed.</p>
2356
+ <h2 id="redirect-mode">Redirect mode</h2>
2357
+ <p>Redirect mode is the simplest integration. Send the customer to <code>payment_url</code> after your server creates the invoice:</p>
2358
+ <pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="html"><code><span class="line"><span style="color:#ABB2BF">&#x3C;</span><span style="color:#E06C75">a</span><span style="color:#D19A66"> href</span><span style="color:#ABB2BF">=</span><span style="color:#98C379">"https://checkout.paymos.io/invoice/inv_xxx"</span><span style="color:#ABB2BF">>Pay invoice&#x3C;/</span><span style="color:#E06C75">a</span><span style="color:#ABB2BF">></span></span>
2359
+ <span class="line"></span></code></pre>
2360
+ <p>The customer completes the payment on the Paymos-hosted page. Your server fulfills the order only after receiving and verifying the signed webhook event.</p>
2361
+ <h2 id="embed-mode">Embed mode</h2>
2362
+ <p>Embed mode uses the same <code>payment_url</code> with <code>?embed=true</code>. Use this when your server already creates invoices and you only want the hosted checkout UI inside your own page:</p>
2363
+ <pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="html"><code><span class="line"><span style="color:#ABB2BF">&#x3C;</span><span style="color:#E06C75">iframe</span></span>
2364
+ <span class="line"><span style="color:#D19A66"> src</span><span style="color:#ABB2BF">=</span><span style="color:#98C379">"https://checkout.paymos.io/invoice/inv_xxx?embed=true"</span></span>
2365
+ <span class="line"><span style="color:#D19A66"> title</span><span style="color:#ABB2BF">=</span><span style="color:#98C379">"Paymos checkout"</span></span>
2366
+ <span class="line"><span style="color:#D19A66"> allow</span><span style="color:#ABB2BF">=</span><span style="color:#98C379">"clipboard-write"</span></span>
2367
+ <span class="line"><span style="color:#D19A66"> sandbox</span><span style="color:#ABB2BF">=</span><span style="color:#98C379">"allow-scripts allow-same-origin allow-forms allow-popups"</span></span>
2368
+ <span class="line"><span style="color:#D19A66"> style</span><span style="color:#ABB2BF">=</span><span style="color:#98C379">"display:block;width:100%;max-width:460px;height:min(90vh,900px);border:0;"</span></span>
2369
+ <span class="line"><span style="color:#ABB2BF">>&#x3C;/</span><span style="color:#E06C75">iframe</span><span style="color:#ABB2BF">></span></span>
2370
+ <span class="line"></span></code></pre>
2371
+ <h2 id="embed-events">Embed events</h2>
2372
+ <p>The checkout iframe sends <code>postMessage</code> transport events to the parent page:</p>
2373
+ <table>
2374
+ <thead>
2375
+ <tr>
2376
+ <th>Event</th>
2377
+ <th>Meaning</th>
2378
+ </tr>
2379
+ </thead>
2380
+ <tbody>
2381
+ <tr>
2382
+ <td><code>paymos:succeeded</code></td>
2383
+ <td>Checkout reached <code>paid</code> or <code>paid_over</code>.</td>
2384
+ </tr>
2385
+ <tr>
2386
+ <td><code>paymos:failed</code></td>
2387
+ <td>Checkout reached a terminal failure state such as <code>underpaid</code>, <code>expired</code>, or <code>cancelled</code>.</td>
2388
+ </tr>
2389
+ <tr>
2390
+ <td><code>paymos:close</code></td>
2391
+ <td>Customer clicked a close/back action inside the embedded checkout.</td>
2392
+ </tr>
2393
+ </tbody>
2394
+ </table>
2395
+ <p>Parent pages must validate both the sender origin and the iframe source:</p>
2396
+ <pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="javascript"><code><span class="line"><span style="color:#C678DD">const</span><span style="color:#E5C07B"> iframe</span><span style="color:#56B6C2"> =</span><span style="color:#E5C07B"> document</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">querySelector</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'#paymos-checkout'</span><span style="color:#ABB2BF">);</span></span>
2397
+ <span class="line"></span>
2398
+ <span class="line"><span style="color:#E5C07B">window</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">addEventListener</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'message'</span><span style="color:#ABB2BF">, (</span><span style="color:#E06C75;font-style:italic">event</span><span style="color:#ABB2BF">) </span><span style="color:#C678DD">=></span><span style="color:#ABB2BF"> {</span></span>
2399
+ <span class="line"><span style="color:#C678DD"> if</span><span style="color:#ABB2BF"> (</span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">origin</span><span style="color:#56B6C2"> !==</span><span style="color:#98C379"> 'https://checkout.paymos.io'</span><span style="color:#ABB2BF">) </span><span style="color:#C678DD">return</span><span style="color:#ABB2BF">;</span></span>
2400
+ <span class="line"><span style="color:#C678DD"> if</span><span style="color:#ABB2BF"> (</span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">source</span><span style="color:#56B6C2"> !==</span><span style="color:#E5C07B"> iframe</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">contentWindow</span><span style="color:#ABB2BF">) </span><span style="color:#C678DD">return</span><span style="color:#ABB2BF">;</span></span>
2401
+ <span class="line"><span style="color:#C678DD"> if</span><span style="color:#ABB2BF"> (</span><span style="color:#56B6C2">!</span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">data</span><span style="color:#56B6C2"> ||</span><span style="color:#C678DD"> typeof</span><span style="color:#E5C07B"> event</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">data</span><span style="color:#56B6C2"> !==</span><span style="color:#98C379"> 'object'</span><span style="color:#ABB2BF">) </span><span style="color:#C678DD">return</span><span style="color:#ABB2BF">;</span></span>
2402
+ <span class="line"></span>
2403
+ <span class="line"><span style="color:#C678DD"> switch</span><span style="color:#ABB2BF"> (</span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">data</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">type</span><span style="color:#ABB2BF">) {</span></span>
2404
+ <span class="line"><span style="color:#C678DD"> case</span><span style="color:#98C379"> 'paymos:succeeded'</span><span style="color:#ABB2BF">:</span></span>
2405
+ <span class="line"><span style="color:#E5C07B"> console</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">log</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'Payment UI succeeded:'</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">data</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">invoice_id</span><span style="color:#ABB2BF">);</span></span>
2406
+ <span class="line"><span style="color:#C678DD"> break</span><span style="color:#ABB2BF">;</span></span>
2407
+ <span class="line"><span style="color:#C678DD"> case</span><span style="color:#98C379"> 'paymos:failed'</span><span style="color:#ABB2BF">:</span></span>
2408
+ <span class="line"><span style="color:#E5C07B"> console</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">warn</span><span style="color:#ABB2BF">(</span><span style="color:#98C379">'Payment UI failed:'</span><span style="color:#ABB2BF">, </span><span style="color:#E5C07B">event</span><span style="color:#ABB2BF">.</span><span style="color:#E5C07B">data</span><span style="color:#ABB2BF">.</span><span style="color:#E06C75">reason</span><span style="color:#ABB2BF">);</span></span>
2409
+ <span class="line"><span style="color:#C678DD"> break</span><span style="color:#ABB2BF">;</span></span>
2410
+ <span class="line"><span style="color:#C678DD"> case</span><span style="color:#98C379"> 'paymos:close'</span><span style="color:#ABB2BF">:</span></span>
2411
+ <span class="line"><span style="color:#E5C07B"> iframe</span><span style="color:#ABB2BF">.</span><span style="color:#61AFEF">remove</span><span style="color:#ABB2BF">();</span></span>
2412
+ <span class="line"><span style="color:#C678DD"> break</span><span style="color:#ABB2BF">;</span></span>
2413
+ <span class="line"><span style="color:#ABB2BF"> }</span></span>
2414
+ <span class="line"><span style="color:#ABB2BF">});</span></span>
2415
+ <span class="line"></span></code></pre>
2416
+ <div class="callout callout--danger"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 2.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15ZM7 7l6 6m0-6-6 6"></path></svg><div class="callout__body"><p>Treat these events as UX hints, not proof of payment. Drive spinners, redirects, and analytics from them \u2014 but never ship goods, credit balances, or mark an order paid based on a <code>postMessage</code>. A <code>postMessage</code> is trivial to spoof: any page sharing the customer's origin can post a fake <code>paymos:succeeded</code>. Settlement is confirmed only by the signed server-side webhook \u2014 the one source of truth for fulfillment.</p></div></div>
2417
+ <h2 id="security-model">Security model</h2>
2418
+ <p>The recommended iframe sandbox is deliberately small:</p>
2419
+ <ul class="list-none p-0 m-0 flex flex-col gap-3"><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>allow-scripts</code> is required for checkout interactivity, API calls, timers, copy buttons, and live status updates.</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>allow-same-origin</code> lets the Paymos-hosted checkout run with its own origin instead of an opaque sandbox origin.</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>allow-forms</code> allows normal form interactions inside checkout.</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>allow-top-navigation</code> is omitted so the iframe cannot navigate the merchant page.</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>allow-popups</code> lets the buyer open the terms and other checkout links in a new tab.</span></li></ul>
2420
+ <h2 id="when-to-use-low-code-sdk-instead">When to use Low-Code SDK instead</h2>
2421
+ <p>Use <a href="/docs/widget-sdk">Low-Code SDK</a> when you want Paymos to create invoices from browser-side config, render the payment button, manage the modal lifecycle, validate iframe messages, and dispatch <code>paymos:*</code> <code>CustomEvent</code>s for you.</p>
2422
+ <p>Use manual iframe embed when your backend already owns invoice creation and you only need to place the hosted checkout UI inside your page.</p>`
2423
+ },
2424
+ {
2425
+ "name": "webhooks",
2426
+ "slug": "webhooks",
2427
+ "uri": "paymos://docs/webhooks",
2428
+ "description": "Webhooks: event types, payloads, retries and signature verification.",
2429
+ "mimeType": "text/html",
2430
+ "text": '<p>Paymos sends an HTTPS <code>POST</code> when an invoice, a withdrawal, or a payment-channel deposit changes state. Webhooks are the authoritative asynchronous signal for your backend: API responses start an operation, while webhook events tell you what happened after blockchain processing.</p>\n<h2 id="integration-flow">Integration flow</h2>\n<ol>\n<li>Create a webhook endpoint in <strong>Dashboard \u2192 Developer \u2192 Webhooks</strong>.</li>\n<li>Choose one or more event categories: <code>Invoice</code>, <code>Withdrawal</code>, <code>Payment channel</code>.</li>\n<li>Optionally restrict invoice and payment-channel events to selected projects \u2014 one filter covers both. Withdrawal events are merchant-wide and ignore it.</li>\n<li>Store the displayed <code>whsec_\u2026</code> secret on your server.</li>\n<li>Verify every delivery against the unchanged raw request body.</li>\n<li>Persist <code>event_id</code>, acknowledge with <code>2xx</code>, and process the event asynchronously.</li>\n</ol>\n<p>Production and Sandbox have separate endpoints, secrets, and events. A sandbox event is never delivered to a production endpoint.</p>\n<h2 id="endpoint-rules">Endpoint rules</h2>\n<ul>\n<li>The URL must use HTTPS.</li>\n<li>The URL may name port 443 \u2014 what a URL without a port uses \u2014 or any port from 1024 up. Other ports are refused when you save, and an endpoint that already has one gets no deliveries.</li>\n<li>Up to 10 endpoints can be configured per merchant and environment.</li>\n<li>The same active URL cannot be registered twice in one environment.</li>\n<li>An endpoint must subscribe to at least one category.</li>\n<li>No project filter means every project is included.</li>\n<li>Suspending or deleting an endpoint stops new deliveries to it.</li>\n</ul>\n<h2 id="delivery-headers">Delivery headers</h2>\n<table>\n<thead>\n<tr>\n<th>Header</th>\n<th>Contract</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>Content-Type</code></td>\n<td><code>application/json; charset=utf-8</code></td>\n</tr>\n<tr>\n<td><code>X-Webhook-Id</code></td>\n<td>Same <code>evt_\u2026</code> value as <code>event_id</code> in the body; not covered by the signature</td>\n</tr>\n<tr>\n<td><code>X-Webhook-Timestamp</code></td>\n<td>Unix seconds for this delivery attempt</td>\n</tr>\n<tr>\n<td><code>X-Webhook-Signature</code></td>\n<td><code>t={timestamp},v1={hmac_hex}</code>; may contain two <code>v1</code> values during rotation</td>\n</tr>\n</tbody>\n</table>\n<p>Delivery is at-least-once and ordering is not guaranteed. Deduplicate on <code>event_id</code> from the verified body, then apply the resource state from <code>data</code> instead of counting events or assuming arrival order.</p>\n<p><code>X-Webhook-Id</code> is there for your logs, not for deduplication. The signature covers only the timestamp and the body, so a captured delivery can be resent with a different <code>X-Webhook-Id</code> and still verify while its timestamp passes your check \u2014 and a handler keyed on the header processes that copy a second time.</p>\n<h2 id="webhook-documentation">Webhook documentation</h2>\n<ul>\n<li><a href="/docs/webhooks/events">Event catalog</a> \u2014 every invoice, withdrawal, and payment-channel event type</li>\n<li><a href="/docs/webhooks/payloads">Payload contract</a> \u2014 envelope and resource snapshots</li>\n<li><a href="/docs/webhooks/verify">Verify signatures</a> \u2014 raw-body HMAC verification and secret rotation</li>\n<li><a href="/docs/webhooks/retry">Delivery and retries</a> \u2014 timeout, backoff, idempotency, and replay</li>\n<li><a href="/docs/webhooks/testing">Test webhooks</a> \u2014 sandbox prerequisites and the interactive playground</li>\n</ul>'
2431
+ },
2432
+ {
2433
+ "name": "testing-sandbox",
2434
+ "slug": "testing",
2435
+ "uri": "paymos://docs/testing-sandbox",
2436
+ "description": "Testing in the sandbox: simulate payments, test key pairs, the go-live checklist.",
2437
+ "mimeType": "text/html",
2438
+ "text": `<p>Test your integration end-to-end in sandbox. Same API surface as production, simulated blockchain, signed webhooks, no real money at risk.</p>
2439
+ <h2 id="sandbox-vs-production">Sandbox vs production</h2>
2440
+ <table>
2441
+ <thead>
2442
+ <tr>
2443
+ <th>Feature</th>
2444
+ <th>Sandbox</th>
2445
+ <th>Production</th>
2446
+ </tr>
2447
+ </thead>
2448
+ <tbody>
2449
+ <tr>
2450
+ <td>Base URL</td>
2451
+ <td><code>api.paymos.io/v1</code></td>
2452
+ <td><code>api.paymos.io/v1</code></td>
2453
+ </tr>
2454
+ <tr>
2455
+ <td>API Keys</td>
2456
+ <td><code>pk_test_</code> / <code>rk_test_</code> IDs with <code>sk_test_</code> secrets</td>
2457
+ <td><code>pk_live_</code> / <code>rk_live_</code> IDs with <code>sk_live_</code> secrets</td>
2458
+ </tr>
2459
+ <tr>
2460
+ <td>Transactions</td>
2461
+ <td>Simulated</td>
2462
+ <td>Real blockchain</td>
2463
+ </tr>
2464
+ <tr>
2465
+ <td>Webhooks</td>
2466
+ <td>Sent normally</td>
2467
+ <td>Sent normally</td>
2468
+ </tr>
2469
+ <tr>
2470
+ <td>Funds</td>
2471
+ <td>No real value</td>
2472
+ <td>Real crypto</td>
2473
+ </tr>
2474
+ </tbody>
2475
+ </table>
2476
+ <h2 id="simulating-payments">Simulating payments</h2>
2477
+ <p>Sandbox payments are not auto-confirmed by a timer. Trigger them explicitly:</p>
2478
+ <div class="api-endpoint-badge"><span class="api-method-badge api-method-post">POST</span><span class="api-endpoint-badge__path">/v1/sandbox/invoices/:invoice_id/simulate-payment</span></div>
2479
+ <div class="callout callout--info"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 2.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15Zm0 6.5v5m0-7.5h.01"></path></svg><div class="callout__body"><p>Body: <code>{ "stage": "paid" }</code> \u2014 <code>stage</code> is one of <code>paid</code>, <code>overpaid</code>, <code>underpay</code>, or <code>cancel</code>. Authenticate it like any other signed <code>/v1</code> call; it acts on sandbox invoices only, so a production key is rejected with <code>403 not_sandbox</code>. It fires the same lifecycle and webhook events as a real on-chain payment, so your verification path stays identical between sandbox and production.</p></div></div>
2480
+ <h2 id="simulating-withdrawals">Simulating withdrawals</h2>
2481
+ <p>Sandbox withdrawals don't settle on a real chain. Mark a pending sandbox withdrawal as completed to exercise your full payout flow:</p>
2482
+ <div class="api-endpoint-badge"><span class="api-method-badge api-method-post">POST</span><span class="api-endpoint-badge__path">/v1/sandbox/withdrawals/:withdrawal_id/simulate-completion</span></div>
2483
+ <p>No request body. Authenticate it like any other <code>/v1</code> call with your Payout key; it acts on sandbox withdrawals only. It transitions the withdrawal to <code>completed</code> and emits the same <code>withdrawal.completed</code> webhook as a real on-chain payout, so your reconciliation path stays identical between sandbox and production.</p>
2484
+ <h2 id="simulating-refunds">Simulating refunds</h2>
2485
+ <p>Create a sandbox refund first with <a href="/docs/refunds/create"><code>POST /v1/refunds</code></a> using your sandbox Payment key (<code>pk_test_</code>), then drive it to a terminal status:</p>
2486
+ <div class="api-endpoint-badge"><span class="api-method-badge api-method-post">POST</span><span class="api-endpoint-badge__path">/v1/sandbox/refunds/:withdrawal_id/simulate</span></div>
2487
+ <div class="callout callout--info"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 2.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15Zm0 6.5v5m0-7.5h.01"></path></svg><div class="callout__body"><p>Body: <code>{ "status": "completed" }</code> \u2014 <code>status</code> is one of <code>completed</code>, <code>failed</code>, or <code>cancelled</code>. Sign it with your sandbox Payment key (<code>pk_test_</code>). It updates the sandbox ledger and emits the corresponding <code>withdrawal.completed</code>, <code>withdrawal.failed</code>, or <code>withdrawal.cancelled</code> webhook with the full refund payload. See <a href="/docs/refunds/simulate">Simulate Refund</a> for the full contract.</p></div></div>
2488
+ <h2 id="simulating-channel-deposits">Simulating channel deposits</h2>
2489
+ <p>Sandbox payment channels derive their addresses locally and watch no chain, so deposits are created explicitly:</p>
2490
+ <div class="api-endpoint-badge"><span class="api-method-badge api-method-post">POST</span><span class="api-endpoint-badge__path">/v1/sandbox/payment-channels/:payment_channel_id/simulate-deposit</span></div>
2491
+ <div class="callout callout--info"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 2.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15Zm0 6.5v5m0-7.5h.01"></path></svg><div class="callout__body"><p>Body: <code>{ "amount": "100", "currency": "USDT", "network": "TRC20", "stage": "confirmed" }</code> \u2014 <code>stage</code> is one of <code>confirming</code>, <code>reorged</code> or <code>confirmed</code> and defaults to <code>confirmed</code>. Sign it with your sandbox Payment key; a production key is rejected before anything is created. Every call emits <code>payment_channel.deposit.confirming</code> first, then the terminal event for the stage you asked for, so your webhook path is identical between sandbox and production. See <a href="/docs/payment-channels/simulate-deposit">Simulate Channel Deposit</a> for the full contract.</p></div></div>
2492
+ <h2 id="testing-webhooks-locally">Testing webhooks locally</h2>
2493
+ <p>Expose your local server through a tunnel:</p>
2494
+ <pre class="shiki one-dark-pro" style="background-color:#282c34;color:#abb2bf" tabindex="0" data-lang="bash"><code><span class="line"><span style="color:#61AFEF">ngrok</span><span style="color:#98C379"> http</span><span style="color:#D19A66"> 3000</span></span>
2495
+ <span class="line"></span></code></pre>
2496
+ <p>Set the webhook URL in <a href="/developers/webhooks"><strong>Dashboard \u2192 Developer \u2192 Webhooks</strong></a>:</p>
2497
+ <p><code>https://abc123.ngrok.io/api/paymos-webhook</code></p>
2498
+ <h2 id="webhook-playground">Webhook playground</h2>
2499
+ <p>The documentation includes a sandbox-only <strong>Webhook Playground</strong> that runs the real delivery path: it creates a sandbox invoice, drives it to the outcome you picked, and lets the delivery worker call your registered endpoint. Nothing is posted straight to your URL, so signature handling is verified against the same signing and retry code production uses.</p>
2500
+ <ul class="list-none p-0 m-0 flex flex-col gap-3"><li class="flex gap-3"><span class="font-mono text-primary shrink-0">01</span><span>Go to <strong>Dashboard \u2192 Developer \u2192 Documentation</strong> in the sandbox environment</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">02</span><span>Open <a href="/docs/webhooks/testing"><strong>Webhooks \u2192 Testing</strong></a>, then select <strong>Playground</strong></span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">03</span><span>Pick an event type (<code>invoice.paid</code>, <code>invoice.paid_over</code>, <code>invoice.underpaid</code>, or <code>invoice.cancelled</code>), set the amount and currency, then <strong>Simulate</strong></span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">04</span><span>Check your server logs for the received event and the <code>X-Webhook-Signature</code> header</span></li></ul>
2501
+ <p>It needs an active sandbox webhook endpoint and a sandbox Payment key. Production sending is disabled there by design.</p>
2502
+ <h2 id="checklist-before-going-live">Checklist before going live</h2>
2503
+ <ul class="list-none p-0 m-0 flex flex-col gap-3"><li class="flex gap-3"><span class="text-gray-300 shrink-0">\u2610</span><span>Webhook signature verification works</span></li><li class="flex gap-3"><span class="text-gray-300 shrink-0">\u2610</span><span>Invoice creation returns correct data</span></li><li class="flex gap-3"><span class="text-gray-300 shrink-0">\u2610</span><span>Payment flow redirects properly</span></li><li class="flex gap-3"><span class="text-gray-300 shrink-0">\u2610</span><span>Error handling covers non-2xx responses (4xx validation, 409 conflicts)</span></li><li class="flex gap-3"><span class="text-gray-300 shrink-0">\u2610</span><span>Idempotency with <code>external_order_id</code> works</span></li><li class="flex gap-3"><span class="text-gray-300 shrink-0">\u2610</span><span>Switch API key IDs from <code>pk_test_</code> / <code>rk_test_</code> to <code>pk_live_</code> / <code>rk_live_</code>, and secrets from <code>sk_test_</code> to <code>sk_live_</code></span></li></ul>`
2504
+ },
2505
+ {
2506
+ "name": "server-sdks",
2507
+ "slug": "server-sdks",
2508
+ "uri": "paymos://docs/server-sdks",
2509
+ "description": "Server SDKs: pick the SDK for your stack.",
2510
+ "mimeType": "text/html",
2511
+ "text": `<p>Paymos maintains official server-side SDKs for eight language ecosystems. Every
2512
+ SDK covers the same invoices, withdrawals, payment channels, channel deposits,
2513
+ balances, server-time, cursor pagination, error, retry, request-signing, and
2514
+ webhook-verification contract.</p>
2515
+ <p>All eight are published to their ecosystem's package registry. Install from
2516
+ there; the repository stays the place to read the source.</p>
2517
+ <table>
2518
+ <thead>
2519
+ <tr>
2520
+ <th>Language</th>
2521
+ <th>Registry</th>
2522
+ <th>Install</th>
2523
+ <th>Official source</th>
2524
+ </tr>
2525
+ </thead>
2526
+ <tbody>
2527
+ <tr>
2528
+ <td>JavaScript / TypeScript</td>
2529
+ <td>npm</td>
2530
+ <td><code>npm i @paymos/sdk</code></td>
2531
+ <td><a href="https://github.com/Paymos-labs/typescript-sdk">Paymos-labs/typescript-sdk</a></td>
2532
+ </tr>
2533
+ <tr>
2534
+ <td>Python</td>
2535
+ <td>PyPI</td>
2536
+ <td><code>pip install paymos-sdk</code></td>
2537
+ <td><a href="https://github.com/Paymos-labs/python-sdk">Paymos-labs/python-sdk</a></td>
2538
+ </tr>
2539
+ <tr>
2540
+ <td>PHP</td>
2541
+ <td>Packagist</td>
2542
+ <td><code>composer require paymos/php-sdk</code></td>
2543
+ <td><a href="https://github.com/Paymos-labs/php-sdk">Paymos-labs/php-sdk</a></td>
2544
+ </tr>
2545
+ <tr>
2546
+ <td>Go</td>
2547
+ <td>Go modules</td>
2548
+ <td><code>go get github.com/Paymos-labs/go-sdk/v2</code></td>
2549
+ <td><a href="https://github.com/Paymos-labs/go-sdk">Paymos-labs/go-sdk</a></td>
2550
+ </tr>
2551
+ <tr>
2552
+ <td>.NET</td>
2553
+ <td>NuGet</td>
2554
+ <td><code>dotnet add package Paymos</code></td>
2555
+ <td><a href="https://github.com/Paymos-labs/dotnet-sdk">Paymos-labs/dotnet-sdk</a></td>
2556
+ </tr>
2557
+ <tr>
2558
+ <td>Java</td>
2559
+ <td>Maven Central</td>
2560
+ <td><code>io.paymos:paymos-java</code></td>
2561
+ <td><a href="https://github.com/Paymos-labs/java-sdk">Paymos-labs/java-sdk</a></td>
2562
+ </tr>
2563
+ <tr>
2564
+ <td>Ruby</td>
2565
+ <td>RubyGems</td>
2566
+ <td><code>gem install paymos</code></td>
2567
+ <td><a href="https://github.com/Paymos-labs/ruby-sdk">Paymos-labs/ruby-sdk</a></td>
2568
+ </tr>
2569
+ <tr>
2570
+ <td>Rust</td>
2571
+ <td>crates.io</td>
2572
+ <td><code>cargo add paymos</code></td>
2573
+ <td><a href="https://github.com/Paymos-labs/rust-sdk">Paymos-labs/rust-sdk</a></td>
2574
+ </tr>
2575
+ </tbody>
2576
+ </table>
2577
+ <p>Java resolves by coordinates rather than a one-line command: add the
2578
+ <code>io.paymos:paymos-java</code> dependency to your <code>pom.xml</code> or your Gradle build.</p>
2579
+ <p>Use an immutable <code>vMAJOR.MINOR.PATCH</code> release tag. Each repository's release page
2580
+ contains the supported runtime, the changelog, and the source commit from which
2581
+ the release was produced.</p>
2582
+ <h2 id="shared-api-surface">Shared API surface</h2>
2583
+ <p>All clients expose six resources:</p>
2584
+ <ul class="list-none p-0 m-0 flex flex-col gap-3"><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>system</code> \u2014 fetch server time for request-clock alignment</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>invoices</code> \u2014 create, get, list, cancel, confirm payment, and sandbox simulation</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>withdrawals</code> \u2014 create, get, list, cancel, and sandbox completion simulation</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>paymentChannels</code> \u2014 create, get, list, block, unblock, and sandbox deposit simulation</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>paymentChannelDeposits</code> \u2014 get one deposit, and poll the confirmed-deposit feed</span></li><li class="flex gap-3"><span class="font-mono text-primary shrink-0">\u2014</span><span><code>balances</code> \u2014 list available balances grouped by currency</span></li></ul>
2585
+ <p>Each client spells the two channel resources in its own language's convention:
2586
+ <code>paymentChannels</code> in TypeScript, PHP and Java, <code>payment_channels</code> in Python,
2587
+ Ruby and Rust, <code>PaymentChannels</code> in Go and .NET.</p>
2588
+ <p>List helpers use cursor pagination with a maximum-page bound and reject a cursor
2589
+ returned twice. Automatic retries honor <code>Retry-After</code>; mutating requests are not
2590
+ retried on transport errors or generic server errors. A rate-limited request may
2591
+ be retried because the API did not accept it for processing.</p>
2592
+ <h2 id="one-contract-eight-languages">One contract, eight languages</h2>
2593
+ <p>The eight are held to a shared behavioural contract, not only to a shared endpoint
2594
+ list. A single language-neutral conformance suite fixes the bytes that go into a
2595
+ request signature, the retry rules above, the cursor iterators and the webhook
2596
+ verifier, and a release ships only once its own tests run against that suite.</p>
2597
+ <p>The practical consequence: an integration ported from one of these languages to
2598
+ another keeps its signing, paging, retry and webhook semantics. Two SDKs building
2599
+ the same filtered list request sign identical bytes.</p>
2600
+ <h2 id="what-php-adds">What PHP adds</h2>
2601
+ <p>The PHP SDK carries a plugin-integration layer that exists in no other client:
2602
+ reverse verification of a webhook against a fresh read of the API, an amount and
2603
+ currency guard before an order is released, replay deduplication behind a
2604
+ pluggable event store, a verifier that holds the Sandbox and Live secrets at
2605
+ once, a reconciler, a mapper from event to order action, and encrypted credential
2606
+ storage.</p>
2607
+ <p>That layer is why the CMS plugins are thin \u2014 the order-state logic sits once in
2608
+ the SDK underneath them instead of eight times above it. None of it applies to
2609
+ the other seven: they are client, signing, resources, pagination and webhook
2610
+ verification, and building on more than that will find nothing there.</p>
2611
+ <h2 id="security-rules">Security rules</h2>
2612
+ <div class="callout callout--warning"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 3 1.7 17h16.6L10 3Zm0 5v4m0 3h.01"></path></svg><div class="callout__body"><p>These SDKs are server-side only. Never put an API secret in browser JavaScript,
2613
+ a mobile application, a public repository, a URL, or a log.</p></div></div>
2614
+ <p>Request authentication and webhook authentication use different signatures.
2615
+ API requests use base64 HMAC-SHA256 over the canonical request. Webhooks use a
2616
+ hex HMAC-SHA256 over <code>{timestamp}.{exact raw body}</code>. Pass the unparsed request
2617
+ bytes to the SDK verifier before decoding JSON. The verifier refuses a timestamp
2618
+ more than five minutes away from now by default, and accepts a header carrying
2619
+ two <code>v1</code> values, so a <a href="/docs/webhooks/verify">secret rotation</a> costs you no code
2620
+ change.</p>
2621
+ <p>For endpoint schemas and examples, continue with <a href="/docs/authentication">Authentication</a>,
2622
+ <a href="/docs/invoices/create">Invoices</a>, <a href="/docs/withdrawals/create">Withdrawals</a>,
2623
+ <a href="/docs/balances/get">Balances</a>, and <a href="/docs/webhooks">Webhooks</a>.</p>`
1443
2624
  }
1444
- }
1445
- function snapshot(path) {
1446
- let fd;
1447
- try {
1448
- const stat = lstatSync3(path);
1449
- if (stat.isSymbolicLink()) error("symlink");
1450
- if (!stat.isFile() || stat.size > 4194304) error("configFile");
1451
- fd = openSync3(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
1452
- if (fstatSync3(fd).ino !== stat.ino) error("changed");
1453
- return { path, content: readFileSync2(fd, "utf8") };
1454
- } catch (cause) {
1455
- if (cause.code === "ENOENT") return { path, content: null };
1456
- if (cause instanceof Error && Object.values(SETUP_COPY.errors).includes(cause.message)) throw cause;
1457
- return error("configFile");
1458
- } finally {
1459
- if (fd !== void 0) closeSync3(fd);
2625
+ ];
2626
+
2627
+ // src/resources.ts
2628
+ function registerResources(server) {
2629
+ for (const resource2 of DOC_RESOURCES) {
2630
+ server.registerResource(
2631
+ resource2.name,
2632
+ resource2.uri,
2633
+ { description: resource2.description, mimeType: resource2.mimeType },
2634
+ async (uri) => ({
2635
+ contents: [{ uri: uri.href, mimeType: resource2.mimeType, text: resource2.text }]
2636
+ })
2637
+ );
1460
2638
  }
1461
2639
  }
1462
- function assertUnchanged(before) {
1463
- if (snapshot(before.path).content !== before.content) error("changed");
1464
- }
1465
- function assertUniqueKeys(node) {
1466
- if (node.type === "object") {
1467
- const keys = /* @__PURE__ */ new Set();
1468
- for (const property of node.children ?? []) {
1469
- const key = property.children?.[0]?.value;
1470
- if (keys.has(key)) error("configFile");
1471
- keys.add(key);
1472
- }
2640
+
2641
+ // src/integration-recommendation.ts
2642
+ import { z as z2 } from "zod";
2643
+ var INTEGRATION_INSTRUCTIONS = "When helping a developer choose a payment integration, call recommend_payment_integration with scenario order_checkout, repeat_deposits, both, or unsure. Respect the merchant\u2019s stated preference; do not replace an explicit choice. Explain why the recommended flow fits their needs and identify missing information. Use unsure when the need is unclear; ask whether the customer will pay for each order, repeatedly top up an account, or do both. This MCP server calls sandbox only and rejects live and payout credentials. Check availability in the target environment.";
2644
+ var GUIDE = `Choose the flow before creating a payment resource.
2645
+
2646
+ Use an invoice when your customer pays for a specific order. An invoice has a set amount, an expiry, and payment statuses; its hosted checkout gives the customer a page to pay that invoice.
2647
+
2648
+ Choose a payment channel for repeated customer deposits. It belongs to one payer and keeps a permanent address per supported network. The channel sets no amount or expiry and has no terminal payment status. Each credited transfer becomes a separate deposit, so track deposits individually when crediting the customer\u2019s account. Transfers below the minimum deposit are not credited or returned.
2649
+
2650
+ You can use both in the same integration. For example, use invoices for purchases and a payment channel for account top-ups. If the intended flow is unclear, ask: \u201CWill your customer pay for each order, repeatedly top up an account, or do both?\u201D
2651
+
2652
+ Test the chosen flow in sandbox. This MCP server calls sandbox only and rejects live and payout credentials. Create sandbox and production channels separately, and check availability in the target environment. Sandbox addresses are synthetic; each deposit simulation creates a new test deposit rather than updating an earlier simulation.
2653
+
2654
+ Credit channel deposits only after confirmation. Verify webhook signatures and require \`confirmed\` with \`is_final\` before crediting a deposit. Webhooks can repeat or arrive out of order: deduplicate deliveries by \`event_id\` and prevent duplicate credit for the same deposit.
2655
+
2656
+ Use the confirmed-deposit feed to reconcile deposits. Save every returned \`next_cursor\`, even on empty pages, and inspect \`blocked\` when present. \`confirmed_from\` bounds the first poll and forms part of the cursor\u2019s fingerprint; keep its value unchanged when continuing with that cursor. Feed cursors expire 24 hours after issue, so poll at least daily. If a cursor expires, restart with a bounded \`confirmed_from\` and retain deposit deduplication.
2657
+
2658
+ Start with the flow you chose. The recommendation needs no credentials; API calls need test credentials.
2659
+
2660
+ For invoices, call \`create_invoice\` with \`project_id\`, \`external_order_id\`, \`amount\` as a decimal string, and \`currency\`. Save the invoice\u2019s link to your order, and use the returned \`payment_url\` for checkout. Test a payment with \`simulate_invoice_payment\`, passing \`invoice_id\` and \`stage\`.
2661
+
2662
+ For payment channels, call \`create_payment_channel\` with \`project_id\` and your customer\u2019s \`external_id\`. Save the channel\u2019s link to that customer. Check the returned networks and addresses; an address may still be provisioning. Call \`get_payment_channel\` again to check readiness and addresses. Call \`simulate_payment_channel_deposit\` with \`payment_channel_id\`, \`amount\` as a decimal string, \`currency\`, and \`network\`; \`stage\` is optional. Read any deposit status with \`get_payment_channel_deposit\`, or use \`list_payment_channel_deposits\` for the confirmed-deposit feed.
2663
+
2664
+ If you chose both, follow both paths. Before changing an order or customer balance, verify webhook signatures, apply the flow\u2019s confirmation checks, and deduplicate events. Credit channel deposits only when \`confirmed\` and \`is_final\`.`;
2665
+ var RECOMMENDATIONS = {
2666
+ order_checkout: {
2667
+ recommendation: "invoice",
2668
+ summary: "Use an invoice for each order: it has a set amount, an expiry, payment statuses, and hosted checkout. Explain how this fits the order flow while respecting the merchant\u2019s stated preference."
2669
+ },
2670
+ repeat_deposits: {
2671
+ recommendation: "payment_channel",
2672
+ summary: "Use a payment channel for repeated deposits from one payer to reusable addresses per network. Track credited deposits separately; transfers below the minimum are not credited or returned. The channel sets no amount or expiry."
2673
+ },
2674
+ both: {
2675
+ recommendation: "both",
2676
+ summary: "Use invoices for individual orders and payment channels for repeated account top-ups. Explain which customer action uses each flow, and respect any preference the merchant has already stated."
2677
+ },
2678
+ unsure: {
2679
+ recommendation: "unsure",
2680
+ summary: "Do not choose a flow yet. Ask: \u201CWill your customer pay for each order, repeatedly top up an account, or do both?\u201D Use the answer and the merchant\u2019s preferences to guide the recommendation."
1473
2681
  }
1474
- for (const child of node.children ?? []) assertUniqueKeys(child);
1475
- }
1476
- function jsonConfig(text) {
1477
- const errors = [];
1478
- const value = parseJson(text, errors, { allowTrailingComma: true, allowEmptyContent: false });
1479
- const tree = parseTree(text, [], { allowTrailingComma: true });
1480
- if (errors.length !== 0 || !object(value) || !tree) error("configFile");
1481
- assertUniqueKeys(tree);
1482
- return value;
1483
- }
1484
- function planClientConfig(client, original, credentialsPath, platform) {
1485
- const command = platform === "win32" ? "cmd" : "npx";
1486
- const args = platform === "win32" ? ["/d", "/c", "npx", "-y", "@paymos/mcp"] : ["-y", "@paymos/mcp"];
1487
- const env = { PAYMOS_CREDENTIALS_FILE: credentialsPath };
1488
- const entry = client === "opencode" ? { type: "local", command: [command, ...args], environment: env, enabled: true } : { ...client === "vscode" ? { type: "stdio" } : {}, command, args, env };
1489
- const text = original ?? "{}\n";
1490
- if (client === "codex") {
1491
- let root2;
1492
- try {
1493
- root2 = parseToml(original ?? "");
1494
- } catch {
1495
- return error("configFile");
1496
- }
1497
- const servers2 = root2.mcp_servers;
1498
- if (servers2 !== void 0 && !object(servers2)) error("configFile");
1499
- const existing2 = servers2?.paymos;
1500
- if (existing2 !== void 0) {
1501
- if (!equalData(existing2, entry)) error("conflict");
1502
- return original;
1503
- }
1504
- const eol = text.includes("\r\n") ? "\r\n" : "\n";
1505
- const block = stringifyToml({ mcp_servers: { paymos: entry } }).replace(/\r?\n/g, eol);
1506
- const next2 = (original ?? "") + eol + block;
1507
- try {
1508
- const expected2 = { ...root2, mcp_servers: { ...servers2, paymos: entry } };
1509
- if (!equalData(parseToml(next2), expected2)) error("configFile");
1510
- } catch {
1511
- return error("configFile");
2682
+ };
2683
+ function registerIntegrationRecommendation(server) {
2684
+ server.registerTool(
2685
+ "recommend_payment_integration",
2686
+ {
2687
+ title: "Recommend a payment integration",
2688
+ description: "Recommend invoices, payment channels, or both from the merchant\u2019s payment flow. Explain the fit and relevant lifecycle. When information is missing, return a targeted question instead of choosing. Respect an explicit merchant choice.",
2689
+ inputSchema: {
2690
+ scenario: z2.enum(["order_checkout", "repeat_deposits", "both", "unsure"]).optional().describe("Choose order_checkout for payment per order, repeat_deposits for repeated customer account top-ups, or both when both flows are needed. Use unsure when the payment flow is unclear; ask whether the customer pays for each order, repeatedly tops up an account, or does both. Respect the merchant\u2019s explicit choice.")
2691
+ },
2692
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }
2693
+ },
2694
+ async ({ scenario }) => {
2695
+ const selected = scenario ?? "unsure";
2696
+ return {
2697
+ content: [{
2698
+ type: "text",
2699
+ text: JSON.stringify({ scenario: selected, ...RECOMMENDATIONS[selected], guide: GUIDE }, null, 2)
2700
+ }]
2701
+ };
1512
2702
  }
1513
- return next2;
1514
- }
1515
- const root = jsonConfig(text);
1516
- const group = client === "opencode" ? "mcp" : client === "vscode" ? "servers" : "mcpServers";
1517
- const servers = root[group];
1518
- if (servers !== void 0 && !object(servers)) error("configFile");
1519
- const existing = servers?.paymos;
1520
- if (existing !== void 0) {
1521
- if (!isDeepStrictEqual(existing, entry)) error("conflict");
1522
- return text;
1523
- }
1524
- const next = applyEdits(text, modify(text, [group, "paymos"], entry, {
1525
- formattingOptions: { insertSpaces: true, tabSize: 2, eol: text.includes("\r\n") ? "\r\n" : "\n" }
1526
- }));
1527
- const expected = { ...root, [group]: { ...servers, paymos: entry } };
1528
- if (!isDeepStrictEqual(jsonConfig(next), expected)) error("configFile");
1529
- return next;
1530
- }
1531
- function writeConfig(before, content) {
1532
- mkdirSync2(dirname2(before.path), { recursive: true, mode: 448 });
1533
- const temp = join(dirname2(before.path), `.paymos-${randomUUID()}.tmp`);
1534
- let created = false;
1535
- try {
1536
- writeFileSync(temp, content, { encoding: "utf8", mode: 384, flag: "wx" });
1537
- created = true;
1538
- if (process.platform !== "win32") chmodSync(temp, 384);
1539
- const identity = lstatSync3(temp);
1540
- assertUnchanged(before);
1541
- if (before.content === null) linkSync(temp, before.path);
1542
- else renameSync(temp, before.path);
1543
- return { ino: identity.ino, dev: identity.dev };
1544
- } finally {
1545
- if (created && existsSync(temp)) unlinkSync2(temp);
1546
- }
1547
- }
1548
- async function ask(io, label, secret = false) {
1549
- if (!io.interactive) error("nonInteractive");
1550
- return (await io.ask(label, secret)).trim();
2703
+ );
1551
2704
  }
1552
- function terminalIO() {
1553
- return {
1554
- interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
1555
- log: (message) => console.log(message),
1556
- ask: (label, secret) => new Promise((accept, reject) => {
1557
- let muted = false;
1558
- const output = new Writable({ write(chunk, _encoding, done) {
1559
- if (!muted) process.stdout.write(chunk);
1560
- done();
1561
- } });
1562
- const reader = createInterface({ input: process.stdin, output, terminal: true });
1563
- let settled = false;
1564
- const cancel = () => {
1565
- if (settled) return;
1566
- settled = true;
1567
- muted = false;
1568
- process.stdout.write("\n");
1569
- reader.close();
1570
- reject(new Error(SETUP_COPY.errors.cancelled));
1571
- };
1572
- reader.once("SIGINT", cancel);
1573
- reader.once("close", () => {
1574
- if (!settled) cancel();
1575
- });
1576
- process.stdout.write(`${label}: `);
1577
- muted = secret;
1578
- reader.question("", (answer) => {
1579
- settled = true;
1580
- muted = false;
1581
- if (secret) process.stdout.write("\n");
1582
- reader.close();
1583
- accept(answer);
1584
- });
1585
- })
1586
- };
2705
+
2706
+ // src/version.ts
2707
+ var MCP_VERSION = "1.6.0";
2708
+
2709
+ // src/server.ts
2710
+ function buildServer(gateway) {
2711
+ const server = new McpServer(
2712
+ { name: "paymos", version: MCP_VERSION },
2713
+ { instructions: INTEGRATION_INSTRUCTIONS }
2714
+ );
2715
+ registerTools(server, gateway);
2716
+ registerIntegrationRecommendation(server);
2717
+ registerResources(server);
2718
+ return server;
1587
2719
  }
1588
- async function runSetup(argv, env = process.env, io = terminalIO(), context = { home: homedir(), cwd: process.cwd(), platform: process.platform }) {
1589
- const flags = options(argv);
1590
- if (flags.help) {
1591
- io.log(SETUP_COPY.help);
2720
+
2721
+ // src/index.ts
2722
+ async function main(env = process.env, argv = process.argv.slice(2)) {
2723
+ if (argv[0] === "setup") {
2724
+ await runSetup(argv.slice(1), env);
1592
2725
  return;
1593
2726
  }
1594
- io.log(SETUP_COPY.title);
1595
- const requested = flags.client ?? await ask(io, `${SETUP_COPY.chooseClient} (${SETUP_CLIENTS.join(", ")})`);
1596
- if (!SETUP_CLIENTS.includes(requested)) error("client");
1597
- const client = requested;
1598
- const configPath = absolute(flags.config ?? defaultConfigPath(client, env, context), context);
1599
- const credentialsPath = absolute(flags.credentialsFile ?? env.PAYMOS_CREDENTIALS_FILE ?? join(env.XDG_CONFIG_HOME || join(context.home, ".config"), "paymos", "mcp", "credentials.json"), context);
1600
- const samePath = context.platform === "win32" ? configPath.toLowerCase() === credentialsPath.toLowerCase() : configPath === credentialsPath;
1601
- if (samePath || !isAbsolute(configPath) || !isAbsolute(credentialsPath)) error("conflict");
1602
- const before = snapshot(configPath);
1603
- const beforeKeys = snapshot(credentialsPath);
1604
- const stored = beforeKeys.content === null ? void 0 : readCredentialFile(credentialsPath);
1605
- const apiKeyId = (env.PAYMOS_API_KEY_ID ?? stored?.apiKeyId ?? await ask(io, SETUP_COPY.apiKey)).trim();
1606
- const apiSecret = (env.PAYMOS_API_SECRET ?? stored?.apiSecret ?? await ask(io, SETUP_COPY.apiSecret, true)).trim();
1607
- const webhookSecret = (env.PAYMOS_WEBHOOK_SECRET ?? stored?.webhookSecret ?? (io.interactive ? await ask(io, SETUP_COPY.webhookSecret, true) : "")).trim();
1608
- const credentials = {
1609
- apiKeyId,
1610
- apiSecret,
1611
- ...webhookSecret === "" ? {} : { webhookSecret }
1612
- };
1613
- if (!checkCredentials(credentials).ok) error("credentials");
1614
- if (stored !== void 0 && !isDeepStrictEqual(stored, credentials)) error("conflict");
1615
- const next = planClientConfig(client, before.content, credentialsPath, context.platform);
1616
- if (flags.dryRun) {
1617
- io.log(SETUP_COPY.preview(configPath));
1618
- io.log(SETUP_COPY.preview(credentialsPath));
2727
+ if (argv[0] === "auth") {
2728
+ const code = await runAuth(argv.slice(1), env);
2729
+ if (code !== 0) process.exitCode = code;
1619
2730
  return;
1620
2731
  }
1621
- if (before.content === next && stored !== void 0) {
1622
- io.log(SETUP_COPY.unchanged(configPath));
2732
+ if (argv[0] === "install-secret") {
2733
+ await runInstallSecret(argv.slice(1));
1623
2734
  return;
1624
2735
  }
1625
- let createdKeys;
1626
- try {
1627
- withDestinationLock(configPath, () => {
1628
- assertUnchanged(before);
1629
- assertUnchanged(beforeKeys);
1630
- if (stored === void 0) {
1631
- createdKeys = writeConfig(beforeKeys, JSON.stringify(credentials, null, 2) + "\n");
1632
- }
1633
- if (before.content !== next) writeConfig(before, next);
1634
- });
1635
- } catch (cause) {
1636
- if (cause instanceof DestinationBusyError) error("changed");
1637
- if (createdKeys !== void 0) {
1638
- try {
1639
- const stat = lstatSync3(credentialsPath);
1640
- if (!stat.isSymbolicLink() && stat.ino === createdKeys.ino && stat.dev === createdKeys.dev && isDeepStrictEqual(readCredentialFile(credentialsPath), credentials)) unlinkSync2(credentialsPath);
1641
- } catch {
1642
- }
1643
- }
1644
- if (cause instanceof Error && Object.values(SETUP_COPY.errors).includes(cause.message)) throw cause;
1645
- error("write");
2736
+ if (argv[0] === "upload-file") {
2737
+ await runUploadFile(argv.slice(1));
2738
+ return;
1646
2739
  }
1647
- io.log(SETUP_COPY.configured(configPath));
1648
- io.log(SETUP_COPY.restart);
1649
- }
1650
-
1651
- // src/index.ts
1652
- async function main(env = process.env, argv = process.argv.slice(2)) {
1653
- if (argv[0] === "setup") {
1654
- await runSetup(argv.slice(1), env);
2740
+ if (argv[0] === "download-file") {
2741
+ await runDownloadFile(argv.slice(1));
1655
2742
  return;
1656
2743
  }
1657
2744
  if (argv[0] === "--help" || argv[0] === "-h") {
@@ -1664,7 +2751,7 @@ async function main(env = process.env, argv = process.argv.slice(2)) {
1664
2751
  const server = buildServer(gateway);
1665
2752
  await server.connect(new StdioServerTransport());
1666
2753
  }
1667
- var isDirectRun = process.argv[1] !== void 0 && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
2754
+ var isDirectRun = process.argv[1] !== void 0 && import.meta.url === pathToFileURL(realpathSync3(process.argv[1])).href;
1668
2755
  if (isDirectRun) {
1669
2756
  main().catch((error2) => {
1670
2757
  console.error(`[paymos-mcp] fatal: ${error2 instanceof Error ? error2.message : String(error2)}`);