@siglume/direct-request-payment 0.4.17 → 0.4.18

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.
@@ -0,0 +1,52 @@
1
+ export type OrderStatus = "created" | "pending" | "paid" | "fulfilled_unsettled" | "review_required";
2
+
3
+ export interface Order {
4
+ id: string;
5
+ amount_minor: number;
6
+ currency: "JPY" | "USD";
7
+ payment_attempt: number;
8
+ siglume_challenge_hash?: string;
9
+ siglume_checkout_session_id?: string;
10
+ siglume_requirement_id?: string;
11
+ siglume_chain_receipt_id?: string;
12
+ siglume_payment_status: OrderStatus;
13
+ }
14
+
15
+ const orders = new Map<string, Order>([
16
+ [
17
+ "order_123",
18
+ {
19
+ id: "order_123",
20
+ amount_minor: 1200,
21
+ currency: "JPY",
22
+ payment_attempt: 0,
23
+ siglume_payment_status: "created",
24
+ },
25
+ ],
26
+ ]);
27
+
28
+ const processedWebhookEvents = new Set<string>();
29
+
30
+ export function getOrder(orderId: string): Order | undefined {
31
+ return orders.get(orderId);
32
+ }
33
+
34
+ export function allOrders(): Order[] {
35
+ return [...orders.values()];
36
+ }
37
+
38
+ export function saveOrder(order: Order): void {
39
+ orders.set(order.id, order);
40
+ }
41
+
42
+ export function findOrderByChallengeHash(challengeHash: string): Order | undefined {
43
+ return [...orders.values()].find((order) => order.siglume_challenge_hash === challengeHash);
44
+ }
45
+
46
+ export function markWebhookEventProcessedOnce(eventId: string): boolean {
47
+ if (processedWebhookEvents.has(eventId)) {
48
+ return false;
49
+ }
50
+ processedWebhookEvents.add(eventId);
51
+ return true;
52
+ }
@@ -0,0 +1,139 @@
1
+ import "dotenv/config";
2
+
3
+ import express from "express";
4
+ import {
5
+ classifyDirectPaymentConfirmation,
6
+ DirectRequestPaymentMerchantClient,
7
+ HostedCheckoutNotAvailableError,
8
+ verifyDirectRequestPaymentWebhook,
9
+ } from "@siglume/direct-request-payment";
10
+
11
+ import {
12
+ allOrders,
13
+ findOrderByChallengeHash,
14
+ getOrder,
15
+ markWebhookEventProcessedOnce,
16
+ saveOrder,
17
+ } from "./order-store.js";
18
+
19
+ const app = express();
20
+ const port = Number(process.env.PORT || 3000);
21
+ const merchantKey = process.env.SIGLUME_DIRECT_PAYMENT_MERCHANT || "example_merchant";
22
+ const shopOrigin = process.env.SHOP_PUBLIC_ORIGIN || "https://www.example.com";
23
+
24
+ const siglumeMerchant = new DirectRequestPaymentMerchantClient({
25
+ auth_token: process.env.SIGLUME_MERCHANT_AUTH_TOKEN,
26
+ });
27
+
28
+ const asyncRoute =
29
+ (handler: express.RequestHandler): express.RequestHandler =>
30
+ (req, res, next) => {
31
+ Promise.resolve(handler(req, res, next)).catch(next);
32
+ };
33
+
34
+ app.get("/orders", (_req, res) => {
35
+ res.json({ orders: allOrders() });
36
+ });
37
+
38
+ app.post(
39
+ "/checkout/siglume/start",
40
+ express.json(),
41
+ asyncRoute(async (req, res) => {
42
+ const orderId = String(req.body?.order_id || "");
43
+ const order = getOrder(orderId);
44
+ if (!order) {
45
+ res.status(404).json({ error: "order_not_found" });
46
+ return;
47
+ }
48
+
49
+ order.payment_attempt += 1;
50
+ const session = await siglumeMerchant.createCheckoutSession({
51
+ merchant: merchantKey,
52
+ amount_minor: order.amount_minor,
53
+ currency: order.currency,
54
+ nonce: `${order.id}-attempt_${order.payment_attempt}`,
55
+ success_url: `${shopOrigin}/thanks`,
56
+ cancel_url: `${shopOrigin}/cart`,
57
+ metadata: { order_id: order.id },
58
+ });
59
+
60
+ order.siglume_challenge_hash = session.challenge_hash;
61
+ order.siglume_checkout_session_id = session.session_id;
62
+ order.siglume_payment_status = "pending";
63
+ saveOrder(order);
64
+
65
+ res.json({
66
+ order_id: order.id,
67
+ amount_minor: order.amount_minor,
68
+ currency: order.currency,
69
+ checkout_url: session.checkout_url,
70
+ session_id: session.session_id,
71
+ });
72
+ }),
73
+ );
74
+
75
+ app.post(
76
+ "/siglume/webhook",
77
+ express.raw({ type: "application/json" }),
78
+ asyncRoute(async (req, res) => {
79
+ const { event } = await verifyDirectRequestPaymentWebhook(
80
+ process.env.SIGLUME_WEBHOOK_SECRET || "",
81
+ req.body,
82
+ req.header("siglume-signature") || "",
83
+ );
84
+
85
+ if (!markWebhookEventProcessedOnce(event.id)) {
86
+ res.status(204).send();
87
+ return;
88
+ }
89
+
90
+ if (event.type === "direct_payment.confirmed") {
91
+ const confirmation = classifyDirectPaymentConfirmation(event);
92
+
93
+ if (confirmation.kind === "standard_settled") {
94
+ const order = findOrderByChallengeHash(confirmation.challenge_hash);
95
+ if (order) {
96
+ order.siglume_payment_status = "paid";
97
+ order.siglume_requirement_id = confirmation.requirement_id;
98
+ order.siglume_chain_receipt_id = confirmation.chain_receipt_id;
99
+ saveOrder(order);
100
+ }
101
+ } else if (confirmation.kind === "metered_usage_accepted") {
102
+ const order = findOrderByChallengeHash(confirmation.challenge_hash);
103
+ if (order) {
104
+ order.siglume_payment_status = "fulfilled_unsettled";
105
+ order.siglume_requirement_id = confirmation.requirement_id;
106
+ saveOrder(order);
107
+ }
108
+ } else if (confirmation.kind === "metered_batch_settled") {
109
+ console.info("metered batch settled", {
110
+ settlement_batch_id: confirmation.settlement_batch_id,
111
+ chain_receipt_id: confirmation.chain_receipt_id,
112
+ });
113
+ } else {
114
+ console.warn("manual payment review required", {
115
+ event_id: event.id,
116
+ reason: confirmation.reason,
117
+ requirement_id: confirmation.requirement_id,
118
+ });
119
+ }
120
+ }
121
+
122
+ res.status(204).send();
123
+ }),
124
+ );
125
+
126
+ app.use((error: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
127
+ if (error instanceof HostedCheckoutNotAvailableError) {
128
+ res.status(409).json({ error: "hosted_checkout_not_enabled" });
129
+ return;
130
+ }
131
+ console.error("checkout starter error:", {
132
+ name: error instanceof Error ? error.name : "Error",
133
+ });
134
+ res.status(500).json({ error: "internal_error" });
135
+ });
136
+
137
+ app.listen(port, () => {
138
+ console.log(`Siglume Hosted Checkout starter listening on http://localhost:${port}`);
139
+ });
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "strict": true,
7
+ "esModuleInterop": true,
8
+ "forceConsistentCasingInFileNames": true,
9
+ "skipLibCheck": true,
10
+ "types": ["node"]
11
+ },
12
+ "include": ["src/**/*.ts"]
13
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@siglume/direct-request-payment",
3
- "version": "0.4.17",
3
+ "version": "0.4.18",
4
4
  "description": "SDK for the Siglume Direct Request Payment SDRP payment protocol",
5
5
  "keywords": [
6
6
  "siglume",
@@ -54,6 +54,9 @@
54
54
  "dist",
55
55
  "docs",
56
56
  "examples",
57
+ "!examples/**/node_modules",
58
+ "!examples/**/__pycache__",
59
+ "!examples/**/*.pyc",
57
60
  "README.md",
58
61
  "CHANGELOG.md",
59
62
  "LICENSE"