qarpeo 0.2.0 → 0.3.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/chunks/tools.mjs +993 -31
- package/dist/cli/index.mjs +1102 -31
- package/dist/fate/index.d.ts +9 -1
- package/dist/fate/index.mjs +20 -3
- package/dist/module.mjs +296 -753
- package/dist/runtime/browser.mjs +2 -2
- package/dist/runtime/comments-server.d.ts +3 -0
- package/dist/runtime/comments-server.mjs +2 -0
- package/dist/runtime/comments.d.ts +0 -2
- package/dist/runtime/comments.mjs +0 -2
- package/dist/runtime/db.d.ts +10 -9
- package/dist/runtime/db.mjs +79 -8
- package/dist/runtime/drizzle.mjs +21 -6
- package/dist/runtime/index.d.ts +4 -0
- package/dist/runtime/realtime-server.d.ts +4 -0
- package/dist/runtime/realtime-server.mjs +13 -0
- package/dist/runtime/realtime.d.ts +1 -4
- package/dist/runtime/realtime.mjs +0 -13
- package/dist/runtime/replica.d.ts +27 -0
- package/dist/runtime/replica.mjs +229 -0
- package/dist/runtime/server/durable-objects/agent.mjs +14 -2
- package/dist/runtime/server/durable-objects/room.d.ts +10 -0
- package/dist/runtime/server/durable-objects/room.mjs +119 -28
- package/dist/runtime/server/middleware/devtools.mjs +1 -1
- package/dist/runtime/server/middleware/tenancy.mjs +7 -4
- package/dist/runtime/server/plugins/store.mjs +1 -1
- package/dist/runtime/server/routes/__qarpeo/mail/track/click/[id].get.mjs +57 -17
- package/dist/runtime/server/routes/agents/[agent]/chat.post.mjs +19 -12
- package/dist/runtime/server/routes/agents/[agent]/clear.post.mjs +8 -9
- package/dist/runtime/server/routes/agents/[agent]/history.get.mjs +8 -9
- package/dist/runtime/server/routes/analytics/events.get.mjs +12 -2
- package/dist/runtime/server/routes/analytics/pageviews.get.mjs +10 -1
- package/dist/runtime/server/routes/analytics/summary.get.mjs +10 -1
- package/dist/runtime/server/routes/auth/2fa/disable.post.mjs +11 -2
- package/dist/runtime/server/routes/auth/2fa/setup.post.mjs +7 -0
- package/dist/runtime/server/routes/auth/2fa/verify.post.mjs +11 -2
- package/dist/runtime/server/routes/auth/account.delete.mjs +7 -0
- package/dist/runtime/server/routes/auth/magic-link/verify.get.mjs +5 -3
- package/dist/runtime/server/routes/auth/organization/sso/index.post.mjs +10 -0
- package/dist/runtime/server/routes/auth/otp/verify.post.mjs +5 -3
- package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +18 -0
- package/dist/runtime/server/routes/auth/webauthn/login/options.post.d.ts +1 -1
- package/dist/runtime/server/routes/auth/webauthn/login/options.post.mjs +11 -2
- package/dist/runtime/server/routes/auth/webauthn/login/verify.post.mjs +10 -1
- package/dist/runtime/server/routes/auth/webauthn/register/options.post.d.ts +1 -1
- package/dist/runtime/server/routes/auth/webauthn/register/options.post.mjs +10 -1
- package/dist/runtime/server/routes/auth/webauthn/register/verify.post.mjs +10 -1
- package/dist/runtime/server/routes/browser/crawl.post.mjs +13 -0
- package/dist/runtime/server/routes/browser/invoice.post.mjs +15 -1
- package/dist/runtime/server/routes/browser/og-image.post.mjs +13 -0
- package/dist/runtime/server/routes/browser/pdf.post.mjs +15 -1
- package/dist/runtime/server/routes/browser/screenshot.post.mjs +13 -0
- package/dist/runtime/server/routes/cms/[collection]/[id]/preview-token.post.mjs +23 -8
- package/dist/runtime/server/routes/cms/[collection]/[id]/publish.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id]/review.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id]/revisions/[revId]/restore.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id].put.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/index.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/categories/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/categories/[id].put.mjs +2 -1
- package/dist/runtime/server/routes/cms/categories.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/collections/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/collections/[id].put.mjs +2 -1
- package/dist/runtime/server/routes/cms/collections/index.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/export.post.mjs +1 -1
- package/dist/runtime/server/routes/cms/subscribers/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/subscribers/[id].patch.mjs +2 -1
- package/dist/runtime/server/routes/cms/tags/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/tags.post.mjs +2 -1
- package/dist/runtime/server/routes/comments/[id]/react.post.mjs +7 -3
- package/dist/runtime/server/routes/comments/[id]/report.post.mjs +3 -0
- package/dist/runtime/server/routes/comments/[id].delete.mjs +1 -1
- package/dist/runtime/server/routes/comments/[id].get.mjs +13 -0
- package/dist/runtime/server/routes/comments/[id].patch.mjs +1 -1
- package/dist/runtime/server/routes/fate.d.ts +6 -0
- package/dist/runtime/server/routes/fate.mjs +32 -3
- package/dist/runtime/server/routes/mail/bounce.post.mjs +14 -2
- package/dist/runtime/server/routes/mail/unsubscribe.mjs +2 -1
- package/dist/runtime/server/routes/mail/webhooks.post.mjs +18 -4
- package/dist/runtime/server/routes/notifications/[id].get.mjs +3 -4
- package/dist/runtime/server/routes/notifications/index.get.mjs +4 -2
- package/dist/runtime/server/routes/notifications/push/subscribe.post.mjs +3 -1
- package/dist/runtime/server/routes/notifications/push/unsubscribe.post.mjs +5 -3
- package/dist/runtime/server/routes/notifications/read-all.post.mjs +6 -2
- package/dist/runtime/server/routes/notifications/send.post.mjs +13 -2
- package/dist/runtime/server/routes/payments/cancel.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/change-plan.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/checkout.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/pause.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/portal.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/subscription.get.mjs +1 -1
- package/dist/runtime/server/routes/payments/usage.get.mjs +1 -1
- package/dist/runtime/server/routes/payments/usage.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/webhook.post.mjs +8 -1
- package/dist/runtime/server/routes/realtime/broadcast.post.mjs +3 -2
- package/dist/runtime/server/routes/realtime/history.delete.mjs +2 -2
- package/dist/runtime/server/routes/realtime/history.get.mjs +2 -2
- package/dist/runtime/server/routes/realtime/presence.get.mjs +3 -3
- package/dist/runtime/server/routes/realtime/state.get.mjs +3 -3
- package/dist/runtime/server/routes/realtime/state.post.mjs +13 -4
- package/dist/runtime/server/routes/realtime/ws.get.mjs +2 -2
- package/dist/runtime/server/routes/storage/file/[...key].delete.mjs +1 -1
- package/dist/runtime/server/routes/storage/file/[...key].get.mjs +7 -0
- package/dist/runtime/server/routes/storage/files.get.d.ts +1 -1
- package/dist/runtime/server/routes/storage/files.get.mjs +24 -4
- package/dist/runtime/server/routes/storage/multipart/abort.post.mjs +16 -1
- package/dist/runtime/server/routes/storage/multipart/complete.post.d.ts +1 -1
- package/dist/runtime/server/routes/storage/multipart/complete.post.mjs +15 -1
- package/dist/runtime/server/routes/storage/multipart/create.post.mjs +7 -0
- package/dist/runtime/server/routes/storage/multipart/part.put.mjs +15 -1
- package/dist/runtime/server/routes/storage/presigned-r2.post.mjs +8 -1
- package/dist/runtime/server/routes/storage/presigned.post.d.ts +1 -1
- package/dist/runtime/server/routes/storage/presigned.post.mjs +8 -1
- package/dist/runtime/server/routes/storage/sign.post.mjs +7 -0
- package/dist/runtime/server/routes/storage/upload.post.d.ts +2 -2
- package/dist/runtime/server/routes/store/cart/index.delete.mjs +3 -4
- package/dist/runtime/server/routes/store/cart/index.get.mjs +3 -10
- package/dist/runtime/server/routes/store/cart/items/[id].delete.mjs +6 -4
- package/dist/runtime/server/routes/store/cart/items/[id].patch.mjs +12 -4
- package/dist/runtime/server/routes/store/cart/items.post.mjs +9 -10
- package/dist/runtime/server/routes/store/categories/index.get.mjs +4 -2
- package/dist/runtime/server/routes/store/checkout.post.mjs +13 -3
- package/dist/runtime/server/routes/store/coupons/apply.post.mjs +6 -5
- package/dist/runtime/server/routes/store/orders/[id].get.mjs +2 -2
- package/dist/runtime/server/routes/store/orders/download/[token].get.mjs +6 -3
- package/dist/runtime/server/routes/store/orders/index.get.mjs +1 -1
- package/dist/runtime/server/routes/store/products/[slug].get.mjs +2 -2
- package/dist/runtime/server/routes/store/products/index.get.mjs +1 -1
- package/dist/runtime/server/routes/store/tax/calculate.post.mjs +10 -0
- package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/index.delete.mjs +26 -25
- package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/verify.post.mjs +26 -25
- package/dist/runtime/server/utils/ai.d.ts +6 -0
- package/dist/runtime/server/utils/ai.mjs +12 -2
- package/dist/runtime/server/utils/analytics-query.mjs +8 -4
- package/dist/runtime/server/utils/browser-utils.d.ts +9 -0
- package/dist/runtime/server/utils/browser-utils.mjs +135 -0
- package/dist/runtime/server/utils/cms/cache.d.ts +13 -0
- package/dist/runtime/server/utils/cms/cache.mjs +95 -0
- package/dist/runtime/server/utils/cms/common.mjs +1 -1
- package/dist/runtime/server/utils/cms/markdown.mjs +38 -8
- package/dist/runtime/server/utils/cms/mutations.d.ts +26 -0
- package/dist/runtime/server/utils/cms/mutations.mjs +569 -0
- package/dist/runtime/server/utils/cms/path.d.ts +8 -0
- package/dist/runtime/server/utils/cms/path.mjs +23 -0
- package/dist/runtime/server/utils/cms/queries.d.ts +27 -0
- package/dist/runtime/server/utils/cms/queries.mjs +366 -0
- package/dist/runtime/server/utils/cms/references.d.ts +48 -0
- package/dist/runtime/server/utils/cms/references.mjs +309 -0
- package/dist/runtime/server/utils/cms/revisions.d.ts +7 -0
- package/dist/runtime/server/utils/cms/revisions.mjs +60 -0
- package/dist/runtime/server/utils/cms/sync.mjs +3 -3
- package/dist/runtime/server/utils/cms.d.ts +5 -82
- package/dist/runtime/server/utils/cms.mjs +28 -1367
- package/dist/runtime/server/utils/comments.d.ts +11 -0
- package/dist/runtime/server/utils/comments.mjs +65 -17
- package/dist/runtime/server/utils/crypto.mjs +1 -1
- package/dist/runtime/server/utils/domains.mjs +9 -0
- package/dist/runtime/server/utils/drizzle.d.ts +26 -1
- package/dist/runtime/server/utils/drizzle.mjs +78 -19
- package/dist/runtime/server/utils/email-inbound.mjs +9 -1
- package/dist/runtime/server/utils/impersonation.mjs +58 -1
- package/dist/runtime/server/utils/lock.d.ts +11 -0
- package/dist/runtime/server/utils/lock.mjs +4 -0
- package/dist/runtime/server/utils/mail-suppression.mjs +48 -13
- package/dist/runtime/server/utils/mail.d.ts +2 -1
- package/dist/runtime/server/utils/mail.mjs +17 -11
- package/dist/runtime/server/utils/notifications.d.ts +13 -4
- package/dist/runtime/server/utils/notifications.mjs +20 -4
- package/dist/runtime/server/utils/organization.mjs +36 -1
- package/dist/runtime/server/utils/passwordless.mjs +8 -0
- package/dist/runtime/server/utils/payments/checkout.d.ts +34 -0
- package/dist/runtime/server/utils/payments/checkout.mjs +158 -0
- package/dist/runtime/server/utils/payments/common.d.ts +45 -0
- package/dist/runtime/server/utils/payments/common.mjs +234 -0
- package/dist/runtime/server/utils/payments/index.d.ts +9 -0
- package/dist/runtime/server/utils/payments/index.mjs +21 -0
- package/dist/runtime/server/utils/payments/lemonsqueezy.d.ts +7 -0
- package/dist/runtime/server/utils/payments/lemonsqueezy.mjs +55 -0
- package/dist/runtime/server/utils/payments/paddle.d.ts +7 -0
- package/dist/runtime/server/utils/payments/paddle.mjs +92 -0
- package/dist/runtime/server/utils/payments/polar.d.ts +11 -0
- package/dist/runtime/server/utils/payments/polar.mjs +66 -0
- package/dist/runtime/server/utils/payments/stripe.d.ts +7 -0
- package/dist/runtime/server/utils/payments/stripe.mjs +159 -0
- package/dist/runtime/server/utils/payments/subscriptions.d.ts +89 -0
- package/dist/runtime/server/utils/payments/subscriptions.mjs +236 -0
- package/dist/runtime/server/utils/payments/usage.d.ts +12 -0
- package/dist/runtime/server/utils/payments/usage.mjs +143 -0
- package/dist/runtime/server/utils/payments/webhooks.d.ts +10 -0
- package/dist/runtime/server/utils/payments/webhooks.mjs +200 -0
- package/dist/runtime/server/utils/payments.d.ts +1 -158
- package/dist/runtime/server/utils/payments.mjs +1 -1289
- package/dist/runtime/server/utils/queue.d.ts +2 -0
- package/dist/runtime/server/utils/queue.mjs +34 -21
- package/dist/runtime/server/utils/rag.mjs +30 -17
- package/dist/runtime/server/utils/realtime.d.ts +5 -1
- package/dist/runtime/server/utils/realtime.mjs +43 -7
- package/dist/runtime/server/utils/session.mjs +16 -3
- package/dist/runtime/server/utils/sso.d.ts +3 -0
- package/dist/runtime/server/utils/sso.mjs +43 -0
- package/dist/runtime/server/utils/storage.mjs +12 -1
- package/dist/runtime/server/utils/store/cart.d.ts +63 -0
- package/dist/runtime/server/utils/store/cart.mjs +542 -0
- package/dist/runtime/server/utils/store/checkout.d.ts +14 -0
- package/dist/runtime/server/utils/store/checkout.mjs +118 -0
- package/dist/runtime/server/utils/store/common.d.ts +29 -0
- package/dist/runtime/server/utils/store/common.mjs +479 -0
- package/dist/runtime/server/utils/store/index.d.ts +7 -0
- package/dist/runtime/server/utils/store/index.mjs +30 -0
- package/dist/runtime/server/utils/store/inventory.d.ts +25 -0
- package/dist/runtime/server/utils/store/inventory.mjs +190 -0
- package/dist/runtime/server/utils/store/orders.d.ts +60 -0
- package/dist/runtime/server/utils/store/orders.mjs +590 -0
- package/dist/runtime/server/utils/store/products.d.ts +35 -0
- package/dist/runtime/server/utils/store/products.mjs +461 -0
- package/dist/runtime/server/utils/store/vendor.d.ts +18 -0
- package/dist/runtime/server/utils/store/vendor.mjs +68 -0
- package/dist/runtime/server/utils/store.d.ts +1 -207
- package/dist/runtime/server/utils/store.mjs +1 -2227
- package/dist/runtime/server/utils/string.d.ts +1 -1
- package/dist/runtime/server/utils/string.mjs +12 -4
- package/dist/runtime/server/utils/tenant.mjs +19 -5
- package/dist/runtime/server/utils/tracker.mjs +2 -0
- package/dist/runtime/server.d.ts +3 -3
- package/dist/runtime/server.mjs +4 -4
- package/dist/runtime/storage-server.d.ts +2 -0
- package/dist/runtime/storage-server.mjs +1 -0
- package/dist/runtime/storage.d.ts +1 -1
- package/dist/runtime/storage.mjs +0 -1
- package/dist/runtime/store.d.ts +0 -1
- package/dist/runtime/store.mjs +0 -1
- package/dist/runtime/test-utils.d.ts +4 -0
- package/dist/runtime/test-utils.mjs +54 -0
- package/dist/runtime/types/d1.d.ts +43 -0
- package/dist/runtime/types/drizzle.d.ts +6 -0
- package/dist/runtime/types/store.d.ts +1 -1
- package/dist/types/analytics.d.ts +80 -0
- package/dist/types/auth.d.ts +282 -0
- package/dist/types/cache.d.ts +55 -0
- package/dist/types/comments.d.ts +130 -0
- package/dist/types/db.d.ts +29 -0
- package/dist/types/email.d.ts +182 -0
- package/dist/types/index.d.ts +22 -0
- package/dist/types/jobs.d.ts +58 -0
- package/dist/types/notifications.d.ts +77 -0
- package/dist/types/options.d.ts +363 -0
- package/dist/types/payments.d.ts +145 -0
- package/dist/types/ratelimit.d.ts +71 -0
- package/dist/types/realtime.d.ts +136 -0
- package/dist/types/site.d.ts +121 -0
- package/dist/types/storage.d.ts +164 -0
- package/dist/types/store-options.d.ts +199 -0
- package/dist/types/tenant.d.ts +100 -0
- package/dist/types.d.ts +1 -2174
- package/dist/utils/migration-lock.d.ts +139 -0
- package/dist/utils/pkg.d.ts +14 -1
- package/dist/utils/schema-diff.d.ts +39 -0
- package/package.json +55 -17
- package/dist/chunks/auth-schema.mjs +0 -364
|
@@ -1,1289 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { getD1Binding } from "../../db.mjs";
|
|
3
|
-
import { getKVBinding } from "../../kv.mjs";
|
|
4
|
-
import { getQarpeoConfig } from "./config.mjs";
|
|
5
|
-
import { getAuthContext } from "./context.mjs";
|
|
6
|
-
import { nanoid } from "./crypto.mjs";
|
|
7
|
-
import { updateStoreOrderStatus } from "./store.mjs";
|
|
8
|
-
import { resolveTableName, resolveIndexName } from "./table-names.mjs";
|
|
9
|
-
function getTbl(base, event) {
|
|
10
|
-
return resolveTableName(base, event);
|
|
11
|
-
}
|
|
12
|
-
function customerTbl(event) {
|
|
13
|
-
return getTbl("customer", event);
|
|
14
|
-
}
|
|
15
|
-
function subscriptionTbl(event) {
|
|
16
|
-
return getTbl("subscription", event);
|
|
17
|
-
}
|
|
18
|
-
function webhookEventTbl(event) {
|
|
19
|
-
return getTbl("webhook_event", event);
|
|
20
|
-
}
|
|
21
|
-
function usageRecordTbl(event) {
|
|
22
|
-
return getTbl("usage_record", event);
|
|
23
|
-
}
|
|
24
|
-
const STRIPE_API_VERSION = "2024-06-20";
|
|
25
|
-
function getPaymentsDb(event) {
|
|
26
|
-
const bindingName = globalThis.process?.env?.QARPEO_DEFAULT_DB_BINDING || "DB";
|
|
27
|
-
return getD1Binding(bindingName, event);
|
|
28
|
-
}
|
|
29
|
-
export function getPaymentsConfig(event) {
|
|
30
|
-
const cfg = getQarpeoConfig(event).payments || {};
|
|
31
|
-
const cfEnv = event?.context?.cloudflare?.env || globalThis.__qarpeo_env__ || {};
|
|
32
|
-
const provider = cfg.provider || "stripe";
|
|
33
|
-
let secretKey = cfg.secretKey || "";
|
|
34
|
-
let webhookSecret = cfg.webhookSecret || "";
|
|
35
|
-
if (!secretKey) {
|
|
36
|
-
if (provider === "stripe") {
|
|
37
|
-
secretKey = cfEnv.STRIPE_SECRET_KEY || process.env.STRIPE_SECRET_KEY || "";
|
|
38
|
-
} else if (provider === "lemonsqueezy") {
|
|
39
|
-
secretKey = cfEnv.LEMONSQUEEZY_API_KEY || process.env.LEMONSQUEEZY_API_KEY || "";
|
|
40
|
-
} else if (provider === "polar") {
|
|
41
|
-
secretKey = cfEnv.POLAR_ACCESS_TOKEN || process.env.POLAR_ACCESS_TOKEN || "";
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
if (!webhookSecret) {
|
|
45
|
-
if (provider === "stripe") {
|
|
46
|
-
webhookSecret = cfEnv.STRIPE_WEBHOOK_SECRET || process.env.STRIPE_WEBHOOK_SECRET || "";
|
|
47
|
-
} else if (provider === "lemonsqueezy") {
|
|
48
|
-
webhookSecret = cfEnv.LEMONSQUEEZY_WEBHOOK_SECRET || process.env.LEMONSQUEEZY_WEBHOOK_SECRET || "";
|
|
49
|
-
} else if (provider === "polar") {
|
|
50
|
-
webhookSecret = cfEnv.POLAR_WEBHOOK_SECRET || process.env.POLAR_WEBHOOK_SECRET || "";
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
return {
|
|
54
|
-
prefix: "/api/payments",
|
|
55
|
-
portalReturnUrl: "/",
|
|
56
|
-
...cfg,
|
|
57
|
-
provider,
|
|
58
|
-
secretKey,
|
|
59
|
-
webhookSecret
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
let ensurePaymentsTablesPromise = null;
|
|
63
|
-
export async function ensurePaymentsTables(event) {
|
|
64
|
-
if (!ensurePaymentsTablesPromise) {
|
|
65
|
-
ensurePaymentsTablesPromise = (async () => {
|
|
66
|
-
const db = getPaymentsDb(event);
|
|
67
|
-
const ct = customerTbl(event);
|
|
68
|
-
const st = subscriptionTbl(event);
|
|
69
|
-
const wt = webhookEventTbl(event);
|
|
70
|
-
const ut = usageRecordTbl(event);
|
|
71
|
-
const statements = [
|
|
72
|
-
`CREATE TABLE IF NOT EXISTS ${ct} (
|
|
73
|
-
id TEXT PRIMARY KEY,
|
|
74
|
-
user_id TEXT NOT NULL,
|
|
75
|
-
org_id TEXT,
|
|
76
|
-
provider TEXT NOT NULL DEFAULT 'stripe',
|
|
77
|
-
customer_id TEXT NOT NULL,
|
|
78
|
-
email TEXT NOT NULL,
|
|
79
|
-
name TEXT,
|
|
80
|
-
metadata_json TEXT DEFAULT '{}',
|
|
81
|
-
created_at INTEGER NOT NULL,
|
|
82
|
-
updated_at INTEGER NOT NULL
|
|
83
|
-
);`,
|
|
84
|
-
`CREATE TABLE IF NOT EXISTS ${st} (
|
|
85
|
-
id TEXT PRIMARY KEY,
|
|
86
|
-
customer_id TEXT NOT NULL,
|
|
87
|
-
user_id TEXT NOT NULL,
|
|
88
|
-
org_id TEXT,
|
|
89
|
-
provider TEXT NOT NULL DEFAULT 'stripe',
|
|
90
|
-
subscription_id TEXT NOT NULL UNIQUE,
|
|
91
|
-
plan_id TEXT NOT NULL,
|
|
92
|
-
price_id TEXT NOT NULL,
|
|
93
|
-
status TEXT NOT NULL,
|
|
94
|
-
quantity INTEGER NOT NULL DEFAULT 1,
|
|
95
|
-
cancel_at_period_end INTEGER NOT NULL DEFAULT 0,
|
|
96
|
-
current_period_start INTEGER NOT NULL,
|
|
97
|
-
current_period_end INTEGER NOT NULL,
|
|
98
|
-
trial_end INTEGER,
|
|
99
|
-
canceled_at INTEGER,
|
|
100
|
-
metadata_json TEXT DEFAULT '{}',
|
|
101
|
-
created_at INTEGER NOT NULL,
|
|
102
|
-
updated_at INTEGER NOT NULL
|
|
103
|
-
);`,
|
|
104
|
-
`CREATE TABLE IF NOT EXISTS ${wt} (
|
|
105
|
-
event_id TEXT PRIMARY KEY,
|
|
106
|
-
provider TEXT NOT NULL,
|
|
107
|
-
event_type TEXT,
|
|
108
|
-
processed_at INTEGER NOT NULL
|
|
109
|
-
);`,
|
|
110
|
-
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(ct, "user_idx")} ON ${ct}(user_id);`,
|
|
111
|
-
`CREATE UNIQUE INDEX IF NOT EXISTS ${resolveIndexName(ct, "customer_idx")} ON ${ct}(customer_id);`,
|
|
112
|
-
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(ct, "org_idx")} ON ${ct}(org_id);`,
|
|
113
|
-
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(st, "user_idx")} ON ${st}(user_id);`,
|
|
114
|
-
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(st, "subscription_idx")} ON ${st}(subscription_id);`,
|
|
115
|
-
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(st, "customer_idx")} ON ${st}(customer_id);`,
|
|
116
|
-
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(st, "status_idx")} ON ${st}(status);`,
|
|
117
|
-
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(st, "org_idx")} ON ${st}(org_id);`,
|
|
118
|
-
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(wt, "event_idx")} ON ${wt}(event_id);`,
|
|
119
|
-
`CREATE TABLE IF NOT EXISTS ${ut} (
|
|
120
|
-
id TEXT PRIMARY KEY,
|
|
121
|
-
user_id TEXT,
|
|
122
|
-
org_id TEXT,
|
|
123
|
-
customer_id TEXT,
|
|
124
|
-
subscription_id TEXT,
|
|
125
|
-
event_name TEXT NOT NULL,
|
|
126
|
-
quantity REAL NOT NULL DEFAULT 1,
|
|
127
|
-
action TEXT NOT NULL DEFAULT 'increment',
|
|
128
|
-
metadata_json TEXT DEFAULT '{}',
|
|
129
|
-
timestamp INTEGER NOT NULL,
|
|
130
|
-
created_at INTEGER NOT NULL
|
|
131
|
-
);`,
|
|
132
|
-
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(ut, "user_idx")} ON ${ut}(user_id);`,
|
|
133
|
-
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(ut, "sub_idx")} ON ${ut}(subscription_id);`,
|
|
134
|
-
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(ut, "event_idx")} ON ${ut}(event_name);`,
|
|
135
|
-
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(ut, "timestamp_idx")} ON ${ut}(timestamp);`
|
|
136
|
-
];
|
|
137
|
-
for (const rawSql of statements) {
|
|
138
|
-
const sql = rawSql.replace(/\s+/g, " ").trim();
|
|
139
|
-
try {
|
|
140
|
-
await db.exec(sql);
|
|
141
|
-
} catch (err) {
|
|
142
|
-
console.warn("[qarpeo:payments] ensurePaymentsTables warning:", err);
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
})().catch((err) => {
|
|
146
|
-
ensurePaymentsTablesPromise = null;
|
|
147
|
-
throw err;
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
return ensurePaymentsTablesPromise;
|
|
151
|
-
}
|
|
152
|
-
import { timingSafeEqualString } from "./crypto.mjs";
|
|
153
|
-
async function computeHmacSha256(keyStr, dataStr) {
|
|
154
|
-
const encoder = new TextEncoder();
|
|
155
|
-
const key = await crypto.subtle.importKey(
|
|
156
|
-
"raw",
|
|
157
|
-
encoder.encode(keyStr),
|
|
158
|
-
{ name: "HMAC", hash: "SHA-256" },
|
|
159
|
-
false,
|
|
160
|
-
["sign"]
|
|
161
|
-
);
|
|
162
|
-
const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(dataStr));
|
|
163
|
-
return Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
164
|
-
}
|
|
165
|
-
async function computeHmacSha256Base64(keyStr, dataStr) {
|
|
166
|
-
const encoder = new TextEncoder();
|
|
167
|
-
const key = await crypto.subtle.importKey(
|
|
168
|
-
"raw",
|
|
169
|
-
encoder.encode(keyStr),
|
|
170
|
-
{ name: "HMAC", hash: "SHA-256" },
|
|
171
|
-
false,
|
|
172
|
-
["sign"]
|
|
173
|
-
);
|
|
174
|
-
const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(dataStr));
|
|
175
|
-
const binary = String.fromCharCode(...new Uint8Array(sig));
|
|
176
|
-
return btoa(binary);
|
|
177
|
-
}
|
|
178
|
-
export async function verifyStripeSignature(rawBody, signatureHeader, secret, toleranceSec = 300) {
|
|
179
|
-
if (!signatureHeader || !secret) return false;
|
|
180
|
-
const parts = signatureHeader.split(",");
|
|
181
|
-
let timestamp = "";
|
|
182
|
-
const signatures = [];
|
|
183
|
-
for (const p of parts) {
|
|
184
|
-
const [k, v] = p.split("=");
|
|
185
|
-
if (k === "t") timestamp = v;
|
|
186
|
-
if (k === "v1") signatures.push(v);
|
|
187
|
-
}
|
|
188
|
-
if (!timestamp || !signatures.length) return false;
|
|
189
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
190
|
-
const tsNum = parseInt(timestamp, 10);
|
|
191
|
-
if (isNaN(tsNum) || Math.abs(now - tsNum) > toleranceSec) {
|
|
192
|
-
return false;
|
|
193
|
-
}
|
|
194
|
-
const payload = `${timestamp}.${rawBody}`;
|
|
195
|
-
const expectedSignature = await computeHmacSha256(secret, payload);
|
|
196
|
-
return signatures.some((sig) => timingSafeEqualString(sig, expectedSignature));
|
|
197
|
-
}
|
|
198
|
-
export async function verifyLemonSqueezySignature(rawBody, signatureHeader, secret) {
|
|
199
|
-
if (!signatureHeader || !secret) return false;
|
|
200
|
-
const expected = await computeHmacSha256(secret, rawBody);
|
|
201
|
-
return timingSafeEqualString(signatureHeader, expected);
|
|
202
|
-
}
|
|
203
|
-
export async function verifyPolarSignature(rawBody, signatureHeader, secret, options) {
|
|
204
|
-
if (!signatureHeader || !secret) return false;
|
|
205
|
-
const toleranceSec = options?.toleranceSec ?? 300;
|
|
206
|
-
const ts = options?.timestamp;
|
|
207
|
-
if (ts) {
|
|
208
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
209
|
-
const tsNum = parseInt(ts, 10);
|
|
210
|
-
if (isNaN(tsNum) || Math.abs(now - tsNum) > toleranceSec) {
|
|
211
|
-
return false;
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
if (options?.webhookId && ts) {
|
|
215
|
-
const payload = `${options.webhookId}.${ts}.${rawBody}`;
|
|
216
|
-
const rawSecret = secret.startsWith("whsec_") ? secret.slice(6) : secret;
|
|
217
|
-
const expectedHex = await computeHmacSha256(secret, payload);
|
|
218
|
-
const expectedBase64 = await computeHmacSha256Base64(rawSecret, payload);
|
|
219
|
-
const signatures = signatureHeader.split(" ");
|
|
220
|
-
return signatures.some((sig) => {
|
|
221
|
-
const cleanSig = sig.replace(/^v1,/, "");
|
|
222
|
-
return timingSafeEqualString(cleanSig, expectedHex) || timingSafeEqualString(cleanSig, expectedBase64);
|
|
223
|
-
});
|
|
224
|
-
}
|
|
225
|
-
const expected = await computeHmacSha256(secret, rawBody);
|
|
226
|
-
return timingSafeEqualString(signatureHeader, expected);
|
|
227
|
-
}
|
|
228
|
-
export async function verifyPaddleSignature(rawBody, signatureHeader, secret, toleranceSec = 300) {
|
|
229
|
-
if (!signatureHeader || !secret) return false;
|
|
230
|
-
const parts = {};
|
|
231
|
-
for (const item of signatureHeader.split(";")) {
|
|
232
|
-
const idx = item.indexOf("=");
|
|
233
|
-
if (idx !== -1) {
|
|
234
|
-
parts[item.slice(0, idx).trim()] = item.slice(idx + 1).trim();
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
const ts = parts.ts;
|
|
238
|
-
const h1 = parts.h1;
|
|
239
|
-
if (!ts || !h1) return false;
|
|
240
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
241
|
-
const tsNum = parseInt(ts, 10);
|
|
242
|
-
if (isNaN(tsNum) || Math.abs(now - tsNum) > toleranceSec) {
|
|
243
|
-
return false;
|
|
244
|
-
}
|
|
245
|
-
const payload = `${ts}:${rawBody}`;
|
|
246
|
-
const expected = await computeHmacSha256(secret, payload);
|
|
247
|
-
return timingSafeEqualString(h1, expected);
|
|
248
|
-
}
|
|
249
|
-
export async function processPaymentWebhook(event, rawBody) {
|
|
250
|
-
await ensurePaymentsTables(event);
|
|
251
|
-
const db = getPaymentsDb(event);
|
|
252
|
-
const config = getPaymentsConfig(event);
|
|
253
|
-
const provider = config.provider;
|
|
254
|
-
const ct = customerTbl(event);
|
|
255
|
-
const st = subscriptionTbl(event);
|
|
256
|
-
const wt = webhookEventTbl(event);
|
|
257
|
-
let isValid = false;
|
|
258
|
-
if (provider === "stripe") {
|
|
259
|
-
const sig = getRequestHeader(event, "stripe-signature");
|
|
260
|
-
isValid = await verifyStripeSignature(rawBody, sig, config.webhookSecret);
|
|
261
|
-
} else if (provider === "lemonsqueezy") {
|
|
262
|
-
const sig = getRequestHeader(event, "x-signature");
|
|
263
|
-
isValid = await verifyLemonSqueezySignature(rawBody, sig, config.webhookSecret);
|
|
264
|
-
} else if (provider === "polar") {
|
|
265
|
-
const sig = getRequestHeader(event, "webhook-signature");
|
|
266
|
-
const ts = getRequestHeader(event, "webhook-timestamp");
|
|
267
|
-
const webhookId = getRequestHeader(event, "webhook-id");
|
|
268
|
-
isValid = await verifyPolarSignature(rawBody, sig, config.webhookSecret, {
|
|
269
|
-
timestamp: ts,
|
|
270
|
-
webhookId
|
|
271
|
-
});
|
|
272
|
-
} else if (provider === "paddle") {
|
|
273
|
-
const sig = getRequestHeader(event, "paddle-signature");
|
|
274
|
-
isValid = await verifyPaddleSignature(rawBody, sig, config.webhookSecret);
|
|
275
|
-
}
|
|
276
|
-
if (!isValid) {
|
|
277
|
-
console.warn(`[qarpeo:payments] Invalid webhook signature from provider: ${provider}`);
|
|
278
|
-
return { success: false, error: "invalid_signature" };
|
|
279
|
-
}
|
|
280
|
-
let payload;
|
|
281
|
-
try {
|
|
282
|
-
payload = JSON.parse(rawBody);
|
|
283
|
-
} catch {
|
|
284
|
-
throw createError({
|
|
285
|
-
statusCode: 400,
|
|
286
|
-
statusMessage: "Bad Request",
|
|
287
|
-
message: "Invalid JSON payload"
|
|
288
|
-
});
|
|
289
|
-
}
|
|
290
|
-
const now = Date.now();
|
|
291
|
-
let eventType = "";
|
|
292
|
-
let eventData = null;
|
|
293
|
-
let affectedSubId = null;
|
|
294
|
-
let eventId = "";
|
|
295
|
-
if (provider === "stripe") {
|
|
296
|
-
eventId = payload.id || "";
|
|
297
|
-
} else if (provider === "lemonsqueezy") {
|
|
298
|
-
eventId = String(payload.meta?.event_id || payload.meta?.id || payload.data?.id || "");
|
|
299
|
-
} else if (provider === "polar") {
|
|
300
|
-
eventId = payload.id || "";
|
|
301
|
-
} else if (provider === "paddle") {
|
|
302
|
-
eventId = payload.event_id || payload.id || "";
|
|
303
|
-
}
|
|
304
|
-
if (provider === "lemonsqueezy") {
|
|
305
|
-
eventType = payload.meta?.event_name || "";
|
|
306
|
-
} else if (provider === "paddle") {
|
|
307
|
-
eventType = payload.event_type || payload.type || "";
|
|
308
|
-
} else {
|
|
309
|
-
eventType = payload.type || "";
|
|
310
|
-
}
|
|
311
|
-
let kv = null;
|
|
312
|
-
try {
|
|
313
|
-
kv = getKVBinding("KV", event);
|
|
314
|
-
} catch {
|
|
315
|
-
}
|
|
316
|
-
const kvKey = `payments:idempotency:${provider}:${eventId}`;
|
|
317
|
-
if (kv && eventId) {
|
|
318
|
-
try {
|
|
319
|
-
const cached = await kv.get(kvKey);
|
|
320
|
-
if (cached === "completed") {
|
|
321
|
-
return { received: true, skipped: true, reason: "duplicate" };
|
|
322
|
-
}
|
|
323
|
-
} catch {
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
if (eventId) {
|
|
327
|
-
const dedupRes = await db.prepare(
|
|
328
|
-
`INSERT OR IGNORE INTO ${wt} (event_id, provider, event_type, processed_at) VALUES (?, ?, ?, ?)`
|
|
329
|
-
).bind(eventId, provider, eventType || null, now).run();
|
|
330
|
-
if (!dedupRes?.meta?.changes) {
|
|
331
|
-
if (kv) {
|
|
332
|
-
try {
|
|
333
|
-
await kv.put(kvKey, "completed", { expirationTtl: 604800 });
|
|
334
|
-
} catch {
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
return { received: true, skipped: true, reason: "duplicate" };
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
try {
|
|
341
|
-
if (provider === "stripe") {
|
|
342
|
-
eventType = payload.type;
|
|
343
|
-
const obj = payload.data?.object || {};
|
|
344
|
-
eventData = obj;
|
|
345
|
-
switch (eventType) {
|
|
346
|
-
case "checkout.session.completed": {
|
|
347
|
-
const customerId = obj.customer;
|
|
348
|
-
const customerEmail = obj.customer_details?.email || obj.customer_email || "";
|
|
349
|
-
const customerName = obj.customer_details?.name || null;
|
|
350
|
-
const userId = obj.metadata?.userId || obj.client_reference_id;
|
|
351
|
-
const orgId = obj.metadata?.orgId || null;
|
|
352
|
-
if (userId && customerId) {
|
|
353
|
-
await db.prepare(
|
|
354
|
-
`INSERT INTO ${ct} (id, user_id, org_id, provider, customer_id, email, name, metadata_json, created_at, updated_at)
|
|
355
|
-
VALUES (?, ?, ?, 'stripe', ?, ?, ?, ?, ?, ?)
|
|
356
|
-
ON CONFLICT(customer_id) DO UPDATE SET email = excluded.email, name = excluded.name, org_id = excluded.org_id, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at`
|
|
357
|
-
).bind(
|
|
358
|
-
nanoid(),
|
|
359
|
-
userId,
|
|
360
|
-
orgId,
|
|
361
|
-
customerId,
|
|
362
|
-
customerEmail,
|
|
363
|
-
customerName,
|
|
364
|
-
JSON.stringify(obj.metadata || {}),
|
|
365
|
-
now,
|
|
366
|
-
now
|
|
367
|
-
).run();
|
|
368
|
-
}
|
|
369
|
-
const subId = obj.subscription;
|
|
370
|
-
if (subId) {
|
|
371
|
-
affectedSubId = subId;
|
|
372
|
-
const planId = obj.metadata?.planId || `default`;
|
|
373
|
-
await db.prepare(
|
|
374
|
-
`INSERT INTO ${st}
|
|
375
|
-
(id, customer_id, user_id, org_id, provider, subscription_id, plan_id, price_id, status, quantity, cancel_at_period_end, current_period_start, current_period_end, trial_end, canceled_at, metadata_json, created_at, updated_at)
|
|
376
|
-
VALUES (?, ?, ?, ?, 'stripe', ?, ?, '', 'active', 1, 0, ?, ?, null, null, ?, ?, ?)
|
|
377
|
-
ON CONFLICT(subscription_id) DO NOTHING`
|
|
378
|
-
).bind(
|
|
379
|
-
nanoid(),
|
|
380
|
-
customerId || "",
|
|
381
|
-
userId || "",
|
|
382
|
-
orgId,
|
|
383
|
-
subId,
|
|
384
|
-
planId,
|
|
385
|
-
now,
|
|
386
|
-
now + 30 * 864e5,
|
|
387
|
-
JSON.stringify(obj.metadata || {}),
|
|
388
|
-
now,
|
|
389
|
-
now
|
|
390
|
-
).run();
|
|
391
|
-
}
|
|
392
|
-
if (obj.metadata?.type === "store_order" || obj.metadata?.orderId) {
|
|
393
|
-
const orderId = obj.metadata.orderId;
|
|
394
|
-
if (orderId) {
|
|
395
|
-
const paymentIntentId = obj.payment_intent || obj.id;
|
|
396
|
-
await updateStoreOrderStatus(
|
|
397
|
-
orderId,
|
|
398
|
-
"paid",
|
|
399
|
-
{ paymentProvider: "stripe", paymentIntentId, event }
|
|
400
|
-
).catch((err) => {
|
|
401
|
-
console.warn("[qarpeo:store] Webhook failed to update order to paid:", err?.message || err);
|
|
402
|
-
});
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
break;
|
|
406
|
-
}
|
|
407
|
-
case "payment_intent.succeeded": {
|
|
408
|
-
const orderId = obj.metadata?.orderId;
|
|
409
|
-
if (orderId && (obj.metadata?.type === "store_order" || obj.metadata?.type === "store")) {
|
|
410
|
-
await updateStoreOrderStatus(
|
|
411
|
-
orderId,
|
|
412
|
-
"paid",
|
|
413
|
-
{ paymentProvider: "stripe", paymentIntentId: obj.id, event }
|
|
414
|
-
).catch((err) => {
|
|
415
|
-
console.warn("[qarpeo:store] payment_intent.succeeded failed to update order:", err?.message || err);
|
|
416
|
-
});
|
|
417
|
-
}
|
|
418
|
-
break;
|
|
419
|
-
}
|
|
420
|
-
case "payment_intent.payment_failed": {
|
|
421
|
-
const orderId = obj.metadata?.orderId;
|
|
422
|
-
if (orderId && (obj.metadata?.type === "store_order" || obj.metadata?.type === "store")) {
|
|
423
|
-
await updateStoreOrderStatus(orderId, "cancelled", { event }).catch(() => {
|
|
424
|
-
});
|
|
425
|
-
}
|
|
426
|
-
break;
|
|
427
|
-
}
|
|
428
|
-
case "charge.refunded": {
|
|
429
|
-
const orderId = obj.metadata?.orderId;
|
|
430
|
-
if (orderId) {
|
|
431
|
-
await updateStoreOrderStatus(orderId, "refunded", { event }).catch(() => {
|
|
432
|
-
});
|
|
433
|
-
}
|
|
434
|
-
break;
|
|
435
|
-
}
|
|
436
|
-
case "customer.subscription.created":
|
|
437
|
-
case "customer.subscription.updated": {
|
|
438
|
-
const subId = obj.id;
|
|
439
|
-
affectedSubId = subId;
|
|
440
|
-
const customerId = obj.customer;
|
|
441
|
-
const status = obj.status;
|
|
442
|
-
const priceId = obj.items?.data?.[0]?.price?.id || obj.plan?.id || "";
|
|
443
|
-
const planId = obj.metadata?.planId || obj.items?.data?.[0]?.price?.lookup_key || priceId;
|
|
444
|
-
const quantity = obj.items?.data?.[0]?.quantity || obj.quantity || 1;
|
|
445
|
-
const cancelAtPeriodEnd = obj.cancel_at_period_end ? 1 : 0;
|
|
446
|
-
const periodStart = obj.current_period_start ? obj.current_period_start * 1e3 : now;
|
|
447
|
-
const periodEnd = obj.current_period_end ? obj.current_period_end * 1e3 : now + 30 * 864e5;
|
|
448
|
-
const trialEnd = obj.trial_end ? obj.trial_end * 1e3 : null;
|
|
449
|
-
const canceledAt = obj.canceled_at ? obj.canceled_at * 1e3 : null;
|
|
450
|
-
const cust = await db.prepare(`SELECT user_id, org_id FROM ${ct} WHERE customer_id = ? LIMIT 1`).bind(customerId).first();
|
|
451
|
-
const userId = cust?.user_id || obj.metadata?.userId || "";
|
|
452
|
-
const orgId = cust?.org_id || obj.metadata?.orgId || null;
|
|
453
|
-
await db.prepare(
|
|
454
|
-
`INSERT INTO ${st}
|
|
455
|
-
(id, customer_id, user_id, org_id, provider, subscription_id, plan_id, price_id, status, quantity, cancel_at_period_end, current_period_start, current_period_end, trial_end, canceled_at, metadata_json, created_at, updated_at)
|
|
456
|
-
VALUES (?, ?, ?, ?, 'stripe', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
457
|
-
ON CONFLICT(subscription_id) DO UPDATE SET
|
|
458
|
-
plan_id = excluded.plan_id, price_id = excluded.price_id, status = excluded.status,
|
|
459
|
-
quantity = excluded.quantity, cancel_at_period_end = excluded.cancel_at_period_end,
|
|
460
|
-
current_period_start = excluded.current_period_start, current_period_end = excluded.current_period_end,
|
|
461
|
-
trial_end = excluded.trial_end, canceled_at = excluded.canceled_at,
|
|
462
|
-
metadata_json = excluded.metadata_json, updated_at = excluded.updated_at`
|
|
463
|
-
).bind(
|
|
464
|
-
nanoid(),
|
|
465
|
-
customerId,
|
|
466
|
-
userId,
|
|
467
|
-
orgId,
|
|
468
|
-
subId,
|
|
469
|
-
planId,
|
|
470
|
-
priceId,
|
|
471
|
-
status,
|
|
472
|
-
quantity,
|
|
473
|
-
cancelAtPeriodEnd,
|
|
474
|
-
periodStart,
|
|
475
|
-
periodEnd,
|
|
476
|
-
trialEnd,
|
|
477
|
-
canceledAt,
|
|
478
|
-
JSON.stringify(obj.metadata || {}),
|
|
479
|
-
now,
|
|
480
|
-
now
|
|
481
|
-
).run();
|
|
482
|
-
break;
|
|
483
|
-
}
|
|
484
|
-
case "customer.subscription.deleted": {
|
|
485
|
-
const subId = obj.id;
|
|
486
|
-
affectedSubId = subId;
|
|
487
|
-
await db.prepare(
|
|
488
|
-
`UPDATE ${st} SET status = 'canceled', canceled_at = ?, updated_at = ? WHERE subscription_id = ?`
|
|
489
|
-
).bind(now, now, subId).run();
|
|
490
|
-
break;
|
|
491
|
-
}
|
|
492
|
-
case "invoice.payment_succeeded": {
|
|
493
|
-
const subId = obj.subscription;
|
|
494
|
-
if (subId) {
|
|
495
|
-
affectedSubId = subId;
|
|
496
|
-
await db.prepare(
|
|
497
|
-
`UPDATE ${st} SET status = 'active', updated_at = ? WHERE subscription_id = ?`
|
|
498
|
-
).bind(now, subId).run();
|
|
499
|
-
}
|
|
500
|
-
break;
|
|
501
|
-
}
|
|
502
|
-
case "invoice.payment_failed": {
|
|
503
|
-
const subId = obj.subscription;
|
|
504
|
-
if (subId) {
|
|
505
|
-
affectedSubId = subId;
|
|
506
|
-
await db.prepare(
|
|
507
|
-
`UPDATE ${st} SET status = 'past_due', updated_at = ? WHERE subscription_id = ?`
|
|
508
|
-
).bind(now, subId).run();
|
|
509
|
-
}
|
|
510
|
-
break;
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
if (provider === "lemonsqueezy") {
|
|
515
|
-
eventType = payload.meta?.event_name;
|
|
516
|
-
const data = payload.data?.attributes || {};
|
|
517
|
-
eventData = data;
|
|
518
|
-
const subId = String(payload.data?.id || "");
|
|
519
|
-
affectedSubId = subId;
|
|
520
|
-
const customerId = String(data.customer_id || "");
|
|
521
|
-
const userEmail = data.user_email || "";
|
|
522
|
-
const customData = payload.meta?.custom_data || {};
|
|
523
|
-
const userId = customData.user_id || customData.userId || "";
|
|
524
|
-
const orgId = customData.org_id || customData.orgId || null;
|
|
525
|
-
const planId = String(data.variant_id || "");
|
|
526
|
-
if (eventType === "subscription_created" || eventType === "subscription_updated" || eventType === "subscription_resumed") {
|
|
527
|
-
const status = data.status === "active" ? "active" : data.status === "on_trial" ? "trialing" : data.status === "past_due" ? "past_due" : "canceled";
|
|
528
|
-
const periodStart = data.renews_at ? new Date(data.created_at).getTime() : now;
|
|
529
|
-
const periodEnd = data.renews_at ? new Date(data.renews_at).getTime() : now + 30 * 864e5;
|
|
530
|
-
const cancelAtPeriodEnd = data.cancelled ? 1 : 0;
|
|
531
|
-
if (customerId && userId) {
|
|
532
|
-
await db.prepare(
|
|
533
|
-
`INSERT INTO ${ct} (id, user_id, org_id, provider, customer_id, email, name, metadata_json, created_at, updated_at) VALUES (?, ?, ?, 'lemonsqueezy', ?, ?, ?, '{}', ?, ?) ON CONFLICT(customer_id) DO UPDATE SET email = excluded.email, name = excluded.name, updated_at = excluded.updated_at`
|
|
534
|
-
).bind(nanoid(), userId, orgId, customerId, userEmail, data.user_name || null, now, now).run();
|
|
535
|
-
}
|
|
536
|
-
await db.prepare(
|
|
537
|
-
`INSERT INTO ${st} (id, customer_id, user_id, org_id, provider, subscription_id, plan_id, price_id, status, quantity, cancel_at_period_end, current_period_start, current_period_end, trial_end, canceled_at, metadata_json, created_at, updated_at)
|
|
538
|
-
VALUES (?, ?, ?, ?, 'lemonsqueezy', ?, ?, ?, ?, 1, ?, ?, ?, null, null, '{}', ?, ?)
|
|
539
|
-
ON CONFLICT(subscription_id) DO UPDATE SET status = excluded.status, cancel_at_period_end = excluded.cancel_at_period_end, current_period_start = excluded.current_period_start, current_period_end = excluded.current_period_end, updated_at = excluded.updated_at`
|
|
540
|
-
).bind(
|
|
541
|
-
nanoid(),
|
|
542
|
-
customerId,
|
|
543
|
-
userId,
|
|
544
|
-
orgId,
|
|
545
|
-
subId,
|
|
546
|
-
planId,
|
|
547
|
-
planId,
|
|
548
|
-
status,
|
|
549
|
-
cancelAtPeriodEnd,
|
|
550
|
-
periodStart,
|
|
551
|
-
periodEnd,
|
|
552
|
-
now,
|
|
553
|
-
now
|
|
554
|
-
).run();
|
|
555
|
-
} else if (eventType === "subscription_cancelled" || eventType === "subscription_expired") {
|
|
556
|
-
await db.prepare(
|
|
557
|
-
`UPDATE ${st} SET status = 'canceled', canceled_at = ?, updated_at = ? WHERE subscription_id = ?`
|
|
558
|
-
).bind(now, now, subId).run();
|
|
559
|
-
} else if (eventType === "order_created") {
|
|
560
|
-
const orderId = customData.orderId || customData.order_id;
|
|
561
|
-
if (orderId && (customData.type === "store_order" || customData.type === "store")) {
|
|
562
|
-
await updateStoreOrderStatus(
|
|
563
|
-
orderId,
|
|
564
|
-
"paid",
|
|
565
|
-
{ paymentProvider: "lemonsqueezy", paymentIntentId: String(data.id), event }
|
|
566
|
-
).catch(() => {
|
|
567
|
-
});
|
|
568
|
-
}
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
if (provider === "polar") {
|
|
572
|
-
eventType = payload.type;
|
|
573
|
-
const data = payload.data || {};
|
|
574
|
-
eventData = data;
|
|
575
|
-
const subId = data.id;
|
|
576
|
-
affectedSubId = subId;
|
|
577
|
-
const customerId = data.customer_id || data.user_id || "";
|
|
578
|
-
const userId = data.metadata?.userId || data.user?.id || "";
|
|
579
|
-
const orgId = data.metadata?.orgId || null;
|
|
580
|
-
const priceId = data.price_id || data.product_id || "";
|
|
581
|
-
if (eventType === "subscription.created" || eventType === "subscription.updated" || eventType === "subscription.active") {
|
|
582
|
-
const status = data.status === "active" ? "active" : data.status === "canceled" ? "canceled" : "past_due";
|
|
583
|
-
const periodStart = data.current_period_start ? new Date(data.current_period_start).getTime() : now;
|
|
584
|
-
const periodEnd = data.current_period_end ? new Date(data.current_period_end).getTime() : now + 30 * 864e5;
|
|
585
|
-
await db.prepare(
|
|
586
|
-
`INSERT INTO ${st} (id, customer_id, user_id, org_id, provider, subscription_id, plan_id, price_id, status, quantity, cancel_at_period_end, current_period_start, current_period_end, trial_end, canceled_at, metadata_json, created_at, updated_at)
|
|
587
|
-
VALUES (?, ?, ?, ?, 'polar', ?, ?, ?, ?, 1, 0, ?, ?, null, null, '{}', ?, ?)
|
|
588
|
-
ON CONFLICT(subscription_id) DO UPDATE SET status = excluded.status, current_period_start = excluded.current_period_start, current_period_end = excluded.current_period_end, updated_at = excluded.updated_at`
|
|
589
|
-
).bind(
|
|
590
|
-
nanoid(),
|
|
591
|
-
customerId,
|
|
592
|
-
userId,
|
|
593
|
-
orgId,
|
|
594
|
-
subId,
|
|
595
|
-
priceId,
|
|
596
|
-
priceId,
|
|
597
|
-
status,
|
|
598
|
-
periodStart,
|
|
599
|
-
periodEnd,
|
|
600
|
-
now,
|
|
601
|
-
now
|
|
602
|
-
).run();
|
|
603
|
-
} else if (eventType === "subscription.canceled" || eventType === "subscription.revoked") {
|
|
604
|
-
await db.prepare(
|
|
605
|
-
`UPDATE ${st} SET status = 'canceled', canceled_at = ?, updated_at = ? WHERE subscription_id = ?`
|
|
606
|
-
).bind(now, now, subId).run();
|
|
607
|
-
} else if (eventType === "order.created" || eventType === "payment.succeeded") {
|
|
608
|
-
const meta = data.metadata || {};
|
|
609
|
-
const orderId = meta.orderId || meta.order_id;
|
|
610
|
-
if (orderId && (meta.type === "store_order" || meta.type === "store")) {
|
|
611
|
-
await updateStoreOrderStatus(
|
|
612
|
-
orderId,
|
|
613
|
-
"paid",
|
|
614
|
-
{ paymentProvider: "polar", paymentIntentId: String(data.id), event }
|
|
615
|
-
).catch(() => {
|
|
616
|
-
});
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
}
|
|
620
|
-
if (provider === "paddle") {
|
|
621
|
-
eventType = payload.event_type || payload.type || "";
|
|
622
|
-
const data = payload.data || {};
|
|
623
|
-
eventData = data;
|
|
624
|
-
const subId = String(data.id || "");
|
|
625
|
-
affectedSubId = subId;
|
|
626
|
-
const customerId = String(data.customer_id || "");
|
|
627
|
-
const customData = data.custom_data || {};
|
|
628
|
-
const userId = customData.userId || customData.user_id || "";
|
|
629
|
-
const orgId = customData.orgId || customData.org_id || null;
|
|
630
|
-
const priceId = data.items?.[0]?.price?.id || "";
|
|
631
|
-
const planId = customData.planId || priceId;
|
|
632
|
-
if (eventType === "subscription.created" || eventType === "subscription.updated" || eventType === "subscription.activated" || eventType === "subscription.resumed") {
|
|
633
|
-
const status = data.status === "active" ? "active" : data.status === "trialing" ? "trialing" : data.status === "past_due" ? "past_due" : data.status === "paused" ? "paused" : "canceled";
|
|
634
|
-
const periodStart = data.current_billing_period?.starts_at ? new Date(data.current_billing_period.starts_at).getTime() : now;
|
|
635
|
-
const periodEnd = data.current_billing_period?.ends_at ? new Date(data.current_billing_period.ends_at).getTime() : now + 30 * 864e5;
|
|
636
|
-
const cancelAtPeriodEnd = data.scheduled_change?.action === "cancel" ? 1 : 0;
|
|
637
|
-
const quantity = data.items?.[0]?.quantity || 1;
|
|
638
|
-
if (customerId && userId) {
|
|
639
|
-
await db.prepare(
|
|
640
|
-
`INSERT INTO ${ct} (id, user_id, org_id, provider, customer_id, email, name, metadata_json, created_at, updated_at)
|
|
641
|
-
VALUES (?, ?, ?, 'paddle', ?, ?, ?, ?, ?, ?)
|
|
642
|
-
ON CONFLICT(customer_id) DO UPDATE SET org_id = excluded.org_id, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at`
|
|
643
|
-
).bind(
|
|
644
|
-
nanoid(),
|
|
645
|
-
userId,
|
|
646
|
-
orgId,
|
|
647
|
-
customerId,
|
|
648
|
-
customData.email || ``,
|
|
649
|
-
customData.name || null,
|
|
650
|
-
JSON.stringify(customData),
|
|
651
|
-
now,
|
|
652
|
-
now
|
|
653
|
-
).run();
|
|
654
|
-
}
|
|
655
|
-
await db.prepare(
|
|
656
|
-
`INSERT INTO ${st}
|
|
657
|
-
(id, customer_id, user_id, org_id, provider, subscription_id, plan_id, price_id, status, quantity, cancel_at_period_end, current_period_start, current_period_end, trial_end, canceled_at, metadata_json, created_at, updated_at)
|
|
658
|
-
VALUES (?, ?, ?, ?, 'paddle', ?, ?, ?, ?, ?, ?, ?, ?, null, null, ?, ?, ?)
|
|
659
|
-
ON CONFLICT(subscription_id) DO UPDATE SET
|
|
660
|
-
plan_id = excluded.plan_id, price_id = excluded.price_id, status = excluded.status,
|
|
661
|
-
quantity = excluded.quantity, cancel_at_period_end = excluded.cancel_at_period_end,
|
|
662
|
-
current_period_start = excluded.current_period_start, current_period_end = excluded.current_period_end,
|
|
663
|
-
metadata_json = excluded.metadata_json, updated_at = excluded.updated_at`
|
|
664
|
-
).bind(
|
|
665
|
-
nanoid(),
|
|
666
|
-
customerId,
|
|
667
|
-
userId,
|
|
668
|
-
orgId,
|
|
669
|
-
subId,
|
|
670
|
-
planId,
|
|
671
|
-
priceId,
|
|
672
|
-
status,
|
|
673
|
-
quantity,
|
|
674
|
-
cancelAtPeriodEnd,
|
|
675
|
-
periodStart,
|
|
676
|
-
periodEnd,
|
|
677
|
-
JSON.stringify(customData),
|
|
678
|
-
now,
|
|
679
|
-
now
|
|
680
|
-
).run();
|
|
681
|
-
} else if (eventType === "subscription.canceled" || eventType === "subscription.past_due") {
|
|
682
|
-
const newStatus = eventType === "subscription.past_due" ? "past_due" : "canceled";
|
|
683
|
-
await db.prepare(
|
|
684
|
-
`UPDATE ${st} SET status = ?, canceled_at = ?, updated_at = ? WHERE subscription_id = ?`
|
|
685
|
-
).bind(newStatus, newStatus === "canceled" ? now : null, now, subId).run();
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
let syncedSubscription = null;
|
|
689
|
-
if (affectedSubId) {
|
|
690
|
-
try {
|
|
691
|
-
const subRow = await db.prepare(`SELECT * FROM ${st} WHERE subscription_id = ? LIMIT 1`).bind(affectedSubId).first();
|
|
692
|
-
if (subRow) {
|
|
693
|
-
syncedSubscription = rowToSubscription(subRow);
|
|
694
|
-
}
|
|
695
|
-
} catch {
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
try {
|
|
699
|
-
const nitroApp = globalThis.useNitroApp?.();
|
|
700
|
-
await nitroApp?.hooks?.callHook("qarpeo:payments:webhook", {
|
|
701
|
-
event,
|
|
702
|
-
type: eventType,
|
|
703
|
-
data: eventData,
|
|
704
|
-
subscription: syncedSubscription,
|
|
705
|
-
provider
|
|
706
|
-
});
|
|
707
|
-
} catch (hookErr) {
|
|
708
|
-
console.warn(
|
|
709
|
-
"[qarpeo:payments] Error calling qarpeo:payments:webhook hook:",
|
|
710
|
-
hookErr?.message || hookErr
|
|
711
|
-
);
|
|
712
|
-
}
|
|
713
|
-
if (kv && eventId) {
|
|
714
|
-
try {
|
|
715
|
-
await kv.put(kvKey, "completed", { expirationTtl: 604800 });
|
|
716
|
-
} catch {
|
|
717
|
-
}
|
|
718
|
-
}
|
|
719
|
-
return { success: true, eventType };
|
|
720
|
-
} catch (processingErr) {
|
|
721
|
-
if (eventId) {
|
|
722
|
-
try {
|
|
723
|
-
await db.prepare(`DELETE FROM ${wt} WHERE event_id = ?`).bind(eventId).run();
|
|
724
|
-
} catch {
|
|
725
|
-
}
|
|
726
|
-
if (kv) {
|
|
727
|
-
try {
|
|
728
|
-
await kv.delete(kvKey);
|
|
729
|
-
} catch {
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
throw processingErr;
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
export async function createCheckoutSession(event, options) {
|
|
737
|
-
await ensurePaymentsTables(event);
|
|
738
|
-
const ct = customerTbl(event);
|
|
739
|
-
const db = getPaymentsDb(event);
|
|
740
|
-
const config = getPaymentsConfig(event);
|
|
741
|
-
const auth = await getAuthContext(event);
|
|
742
|
-
const user = auth?.user;
|
|
743
|
-
if (!config.secretKey) {
|
|
744
|
-
throw createError({
|
|
745
|
-
statusCode: 500,
|
|
746
|
-
statusMessage: "Internal Server Error",
|
|
747
|
-
message: "Payment provider secret key is not configured (STRIPE_SECRET_KEY)"
|
|
748
|
-
});
|
|
749
|
-
}
|
|
750
|
-
let priceId = options.priceId;
|
|
751
|
-
const planId = options.planId || "default";
|
|
752
|
-
if (!priceId && config.plans && config.plans[planId]) {
|
|
753
|
-
priceId = config.plans[planId].priceId;
|
|
754
|
-
}
|
|
755
|
-
if (!priceId) {
|
|
756
|
-
throw createError({
|
|
757
|
-
statusCode: 400,
|
|
758
|
-
message: `Could not resolve price ID for plan "${planId}"`
|
|
759
|
-
});
|
|
760
|
-
}
|
|
761
|
-
const siteUrl = useRuntimeConfig().public?.siteUrl || "http://localhost:3000";
|
|
762
|
-
const successUrl = safeReturnUrl(
|
|
763
|
-
options.successUrl || config.checkoutUrls?.success,
|
|
764
|
-
siteUrl,
|
|
765
|
-
"/?checkout=success"
|
|
766
|
-
);
|
|
767
|
-
const cancelUrl = safeReturnUrl(
|
|
768
|
-
options.cancelUrl || config.checkoutUrls?.cancel,
|
|
769
|
-
siteUrl,
|
|
770
|
-
"/?checkout=cancelled"
|
|
771
|
-
);
|
|
772
|
-
const metadata = {
|
|
773
|
-
planId,
|
|
774
|
-
...options.metadata
|
|
775
|
-
};
|
|
776
|
-
if (user?.id) metadata.userId = user.id;
|
|
777
|
-
if (auth?.organization?.id) metadata.orgId = auth.organization.id;
|
|
778
|
-
if (config.provider === "stripe") {
|
|
779
|
-
let customerId = null;
|
|
780
|
-
if (user?.id) {
|
|
781
|
-
const cust = await db.prepare(
|
|
782
|
-
`SELECT customer_id FROM ${ct} WHERE user_id = ? AND provider = 'stripe' LIMIT 1`
|
|
783
|
-
).bind(user.id).first();
|
|
784
|
-
if (cust) customerId = cust.customer_id;
|
|
785
|
-
}
|
|
786
|
-
const mode = options.mode || "subscription";
|
|
787
|
-
const params = new URLSearchParams();
|
|
788
|
-
params.set("mode", mode);
|
|
789
|
-
params.set("line_items[0][price]", priceId);
|
|
790
|
-
params.set("line_items[0][quantity]", "1");
|
|
791
|
-
params.set("success_url", successUrl);
|
|
792
|
-
params.set("cancel_url", cancelUrl);
|
|
793
|
-
if (customerId) {
|
|
794
|
-
params.set("customer", customerId);
|
|
795
|
-
} else {
|
|
796
|
-
const email = options.customerEmail || user?.email;
|
|
797
|
-
if (email) params.set("customer_email", email);
|
|
798
|
-
}
|
|
799
|
-
if (user?.id) params.set("client_reference_id", user.id);
|
|
800
|
-
for (const [k, v] of Object.entries(metadata)) {
|
|
801
|
-
params.set(`metadata[${k}]`, String(v));
|
|
802
|
-
if (mode === "subscription") {
|
|
803
|
-
params.set(`subscription_data[metadata][${k}]`, String(v));
|
|
804
|
-
} else if (mode === "payment") {
|
|
805
|
-
params.set(`payment_intent_data[metadata][${k}]`, String(v));
|
|
806
|
-
} else if (mode === "setup") {
|
|
807
|
-
params.set(`setup_intent_data[metadata][${k}]`, String(v));
|
|
808
|
-
}
|
|
809
|
-
}
|
|
810
|
-
if (mode === "subscription") {
|
|
811
|
-
const trialDays = options.trialDays || config.trialDays;
|
|
812
|
-
if (trialDays && trialDays > 0) {
|
|
813
|
-
params.set("subscription_data[trial_period_days]", String(trialDays));
|
|
814
|
-
}
|
|
815
|
-
}
|
|
816
|
-
const res = await fetch("https://api.stripe.com/v1/checkout/sessions", {
|
|
817
|
-
method: "POST",
|
|
818
|
-
signal: AbortSignal.timeout(1e4),
|
|
819
|
-
headers: {
|
|
820
|
-
Authorization: `Bearer ${config.secretKey}`,
|
|
821
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
822
|
-
"Stripe-Version": STRIPE_API_VERSION
|
|
823
|
-
},
|
|
824
|
-
body: params.toString()
|
|
825
|
-
});
|
|
826
|
-
if (!res.ok) {
|
|
827
|
-
const errText = await res.text();
|
|
828
|
-
console.error("[qarpeo:payments] Stripe Checkout error:", errText);
|
|
829
|
-
throw createError({ statusCode: res.status, message: `Stripe checkout failed: ${errText}` });
|
|
830
|
-
}
|
|
831
|
-
const session = await res.json();
|
|
832
|
-
return { id: session.id, url: session.url };
|
|
833
|
-
}
|
|
834
|
-
throw createError({
|
|
835
|
-
statusCode: 501,
|
|
836
|
-
message: `Checkout not implemented for provider ${config.provider}`
|
|
837
|
-
});
|
|
838
|
-
}
|
|
839
|
-
function safeReturnUrl(url, siteUrl, fallbackPath = "/") {
|
|
840
|
-
const cleanSiteUrl = siteUrl.replace(/\/+$/, "");
|
|
841
|
-
const fallback = `${cleanSiteUrl}${fallbackPath.startsWith("/") ? fallbackPath : "/" + fallbackPath}`;
|
|
842
|
-
if (typeof url !== "string" || !url.trim()) return fallback;
|
|
843
|
-
const trimmed = url.trim();
|
|
844
|
-
if (trimmed.startsWith("/") && !trimmed.startsWith("//") && !trimmed.startsWith("/\\") && !trimmed.startsWith("\\")) {
|
|
845
|
-
if (/[\r\n\0]/.test(trimmed)) return fallback;
|
|
846
|
-
return `${cleanSiteUrl}${trimmed}`;
|
|
847
|
-
}
|
|
848
|
-
try {
|
|
849
|
-
const parsed = new URL(trimmed);
|
|
850
|
-
const site = new URL(cleanSiteUrl);
|
|
851
|
-
if (parsed.origin === site.origin) {
|
|
852
|
-
return parsed.toString();
|
|
853
|
-
}
|
|
854
|
-
} catch {
|
|
855
|
-
}
|
|
856
|
-
return fallback;
|
|
857
|
-
}
|
|
858
|
-
export async function createCustomerPortalSession(event, options) {
|
|
859
|
-
await ensurePaymentsTables(event);
|
|
860
|
-
const ct = customerTbl(event);
|
|
861
|
-
const db = getPaymentsDb(event);
|
|
862
|
-
const config = getPaymentsConfig(event);
|
|
863
|
-
const auth = await getAuthContext(event);
|
|
864
|
-
const user = auth?.user;
|
|
865
|
-
if (!user?.id) {
|
|
866
|
-
throw createError({
|
|
867
|
-
statusCode: 401,
|
|
868
|
-
message: "Authentication required to access billing portal"
|
|
869
|
-
});
|
|
870
|
-
}
|
|
871
|
-
const cust = await db.prepare(`SELECT customer_id FROM ${ct} WHERE user_id = ? AND provider = ? LIMIT 1`).bind(user.id, config.provider).first();
|
|
872
|
-
if (!cust?.customer_id) {
|
|
873
|
-
throw createError({ statusCode: 404, message: "No customer account found for this user" });
|
|
874
|
-
}
|
|
875
|
-
const siteUrl = useRuntimeConfig().public?.siteUrl || "http://localhost:3000";
|
|
876
|
-
const returnUrl = safeReturnUrl(options?.returnUrl || config.portalReturnUrl, siteUrl, "/");
|
|
877
|
-
if (config.provider === "stripe") {
|
|
878
|
-
const params = new URLSearchParams();
|
|
879
|
-
params.set("customer", cust.customer_id);
|
|
880
|
-
params.set("return_url", returnUrl);
|
|
881
|
-
const res = await fetch("https://api.stripe.com/v1/billing_portal/sessions", {
|
|
882
|
-
method: "POST",
|
|
883
|
-
signal: AbortSignal.timeout(1e4),
|
|
884
|
-
headers: {
|
|
885
|
-
Authorization: `Bearer ${config.secretKey}`,
|
|
886
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
887
|
-
"Stripe-Version": STRIPE_API_VERSION
|
|
888
|
-
},
|
|
889
|
-
body: params.toString()
|
|
890
|
-
});
|
|
891
|
-
if (!res.ok) {
|
|
892
|
-
const errText = await res.text();
|
|
893
|
-
throw createError({ statusCode: res.status, message: `Billing portal failed: ${errText}` });
|
|
894
|
-
}
|
|
895
|
-
const session = await res.json();
|
|
896
|
-
return { url: session.url };
|
|
897
|
-
}
|
|
898
|
-
throw createError({
|
|
899
|
-
statusCode: 501,
|
|
900
|
-
message: `Billing portal not supported for provider ${config.provider}`
|
|
901
|
-
});
|
|
902
|
-
}
|
|
903
|
-
export async function cancelSubscription(event, subscriptionId) {
|
|
904
|
-
await ensurePaymentsTables(event);
|
|
905
|
-
const st = subscriptionTbl(event);
|
|
906
|
-
const db = getPaymentsDb(event);
|
|
907
|
-
const config = getPaymentsConfig(event);
|
|
908
|
-
if (!subscriptionId) {
|
|
909
|
-
throw createError({ statusCode: 400, message: "subscriptionId is required" });
|
|
910
|
-
}
|
|
911
|
-
if (!config.secretKey) {
|
|
912
|
-
throw createError({
|
|
913
|
-
statusCode: 500,
|
|
914
|
-
statusMessage: "Internal Server Error",
|
|
915
|
-
message: "Payment provider secret key is not configured (STRIPE_SECRET_KEY)"
|
|
916
|
-
});
|
|
917
|
-
}
|
|
918
|
-
if (config.provider !== "stripe") {
|
|
919
|
-
throw createError({
|
|
920
|
-
statusCode: 501,
|
|
921
|
-
message: `Subscription cancel not implemented for provider ${config.provider}`
|
|
922
|
-
});
|
|
923
|
-
}
|
|
924
|
-
const params = new URLSearchParams();
|
|
925
|
-
params.set("cancel_at_period_end", "true");
|
|
926
|
-
const res = await fetch(`https://api.stripe.com/v1/subscriptions/${subscriptionId}`, {
|
|
927
|
-
method: "POST",
|
|
928
|
-
signal: AbortSignal.timeout(1e4),
|
|
929
|
-
headers: {
|
|
930
|
-
Authorization: `Bearer ${config.secretKey}`,
|
|
931
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
932
|
-
"Stripe-Version": STRIPE_API_VERSION
|
|
933
|
-
},
|
|
934
|
-
body: params.toString()
|
|
935
|
-
});
|
|
936
|
-
if (!res.ok) {
|
|
937
|
-
const errText = await res.text();
|
|
938
|
-
throw createError({ statusCode: res.status, message: `Stripe cancel failed: ${errText}` });
|
|
939
|
-
}
|
|
940
|
-
const now = Date.now();
|
|
941
|
-
await db.prepare(
|
|
942
|
-
`UPDATE ${st} SET status = 'canceled', cancel_at_period_end = 1, updated_at = ? WHERE subscription_id = ?`
|
|
943
|
-
).bind(now, subscriptionId).run();
|
|
944
|
-
return { success: true, subscriptionId, status: "canceled" };
|
|
945
|
-
}
|
|
946
|
-
export async function pauseSubscription(event, subscriptionId) {
|
|
947
|
-
await ensurePaymentsTables(event);
|
|
948
|
-
const st = subscriptionTbl(event);
|
|
949
|
-
const db = getPaymentsDb(event);
|
|
950
|
-
const config = getPaymentsConfig(event);
|
|
951
|
-
if (!subscriptionId) {
|
|
952
|
-
throw createError({ statusCode: 400, message: "subscriptionId is required" });
|
|
953
|
-
}
|
|
954
|
-
if (!config.secretKey) {
|
|
955
|
-
throw createError({
|
|
956
|
-
statusCode: 500,
|
|
957
|
-
statusMessage: "Internal Server Error",
|
|
958
|
-
message: "Payment provider secret key is not configured (STRIPE_SECRET_KEY)"
|
|
959
|
-
});
|
|
960
|
-
}
|
|
961
|
-
if (config.provider !== "stripe") {
|
|
962
|
-
throw createError({
|
|
963
|
-
statusCode: 501,
|
|
964
|
-
message: `Subscription pause not implemented for provider ${config.provider}`
|
|
965
|
-
});
|
|
966
|
-
}
|
|
967
|
-
const params = new URLSearchParams();
|
|
968
|
-
params.set("pause_collection[behavior]", "void");
|
|
969
|
-
params.set("pause_collection[resumes_at]", "");
|
|
970
|
-
const res = await fetch(`https://api.stripe.com/v1/subscriptions/${subscriptionId}`, {
|
|
971
|
-
method: "POST",
|
|
972
|
-
signal: AbortSignal.timeout(1e4),
|
|
973
|
-
headers: {
|
|
974
|
-
Authorization: `Bearer ${config.secretKey}`,
|
|
975
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
976
|
-
"Stripe-Version": STRIPE_API_VERSION
|
|
977
|
-
},
|
|
978
|
-
body: params.toString()
|
|
979
|
-
});
|
|
980
|
-
if (!res.ok) {
|
|
981
|
-
const errText = await res.text();
|
|
982
|
-
throw createError({ statusCode: res.status, message: `Stripe pause failed: ${errText}` });
|
|
983
|
-
}
|
|
984
|
-
const now = Date.now();
|
|
985
|
-
await db.prepare(
|
|
986
|
-
`UPDATE ${st} SET status = 'paused', updated_at = ? WHERE subscription_id = ?`
|
|
987
|
-
).bind(now, subscriptionId).run();
|
|
988
|
-
return { success: true, subscriptionId, status: "paused" };
|
|
989
|
-
}
|
|
990
|
-
export async function changePlan(event, subscriptionId, newPriceId) {
|
|
991
|
-
await ensurePaymentsTables(event);
|
|
992
|
-
const st = subscriptionTbl(event);
|
|
993
|
-
const db = getPaymentsDb(event);
|
|
994
|
-
const config = getPaymentsConfig(event);
|
|
995
|
-
if (!subscriptionId) {
|
|
996
|
-
throw createError({ statusCode: 400, message: "subscriptionId is required" });
|
|
997
|
-
}
|
|
998
|
-
if (!newPriceId) {
|
|
999
|
-
throw createError({ statusCode: 400, message: "newPriceId is required" });
|
|
1000
|
-
}
|
|
1001
|
-
if (!config.secretKey) {
|
|
1002
|
-
throw createError({
|
|
1003
|
-
statusCode: 500,
|
|
1004
|
-
statusMessage: "Internal Server Error",
|
|
1005
|
-
message: "Payment provider secret key is not configured (STRIPE_SECRET_KEY)"
|
|
1006
|
-
});
|
|
1007
|
-
}
|
|
1008
|
-
if (config.provider !== "stripe") {
|
|
1009
|
-
throw createError({
|
|
1010
|
-
statusCode: 501,
|
|
1011
|
-
message: `Plan change not implemented for provider ${config.provider}`
|
|
1012
|
-
});
|
|
1013
|
-
}
|
|
1014
|
-
const getRes = await fetch(`https://api.stripe.com/v1/subscriptions/${subscriptionId}`, {
|
|
1015
|
-
method: "GET",
|
|
1016
|
-
signal: AbortSignal.timeout(1e4),
|
|
1017
|
-
headers: {
|
|
1018
|
-
Authorization: `Bearer ${config.secretKey}`,
|
|
1019
|
-
"Stripe-Version": STRIPE_API_VERSION
|
|
1020
|
-
}
|
|
1021
|
-
});
|
|
1022
|
-
if (!getRes.ok) {
|
|
1023
|
-
const errText = await getRes.text();
|
|
1024
|
-
throw createError({
|
|
1025
|
-
statusCode: getRes.status,
|
|
1026
|
-
message: `Stripe fetch subscription failed: ${errText}`
|
|
1027
|
-
});
|
|
1028
|
-
}
|
|
1029
|
-
const sub = await getRes.json();
|
|
1030
|
-
const currentItemId = sub?.items?.data?.[0]?.id;
|
|
1031
|
-
if (!currentItemId) {
|
|
1032
|
-
throw createError({ statusCode: 409, message: "Subscription has no item to change" });
|
|
1033
|
-
}
|
|
1034
|
-
const params = new URLSearchParams();
|
|
1035
|
-
params.set("items[0][id]", currentItemId);
|
|
1036
|
-
params.set("items[0][price]", newPriceId);
|
|
1037
|
-
params.set("proration_behavior", "create_prorations");
|
|
1038
|
-
const res = await fetch(`https://api.stripe.com/v1/subscriptions/${subscriptionId}`, {
|
|
1039
|
-
method: "POST",
|
|
1040
|
-
signal: AbortSignal.timeout(1e4),
|
|
1041
|
-
headers: {
|
|
1042
|
-
Authorization: `Bearer ${config.secretKey}`,
|
|
1043
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
1044
|
-
"Stripe-Version": STRIPE_API_VERSION
|
|
1045
|
-
},
|
|
1046
|
-
body: params.toString()
|
|
1047
|
-
});
|
|
1048
|
-
if (!res.ok) {
|
|
1049
|
-
const errText = await res.text();
|
|
1050
|
-
throw createError({ statusCode: res.status, message: `Stripe plan change failed: ${errText}` });
|
|
1051
|
-
}
|
|
1052
|
-
const updated = await res.json();
|
|
1053
|
-
const newPlanId = updated?.items?.data?.[0]?.price?.id || newPriceId;
|
|
1054
|
-
const now = Date.now();
|
|
1055
|
-
await db.prepare(
|
|
1056
|
-
`UPDATE ${st} SET plan_id = ?, price_id = ?, updated_at = ? WHERE subscription_id = ?`
|
|
1057
|
-
).bind(newPlanId, newPriceId, now, subscriptionId).run();
|
|
1058
|
-
return { success: true, subscriptionId, planId: newPlanId };
|
|
1059
|
-
}
|
|
1060
|
-
function rowToSubscription(row) {
|
|
1061
|
-
let metadata = {};
|
|
1062
|
-
try {
|
|
1063
|
-
metadata = JSON.parse(row.metadata_json || "{}");
|
|
1064
|
-
} catch {
|
|
1065
|
-
}
|
|
1066
|
-
return {
|
|
1067
|
-
id: row.id,
|
|
1068
|
-
customerId: row.customer_id,
|
|
1069
|
-
userId: row.user_id,
|
|
1070
|
-
orgId: row.org_id || null,
|
|
1071
|
-
provider: row.provider,
|
|
1072
|
-
subscriptionId: row.subscription_id,
|
|
1073
|
-
planId: row.plan_id,
|
|
1074
|
-
priceId: row.price_id,
|
|
1075
|
-
status: row.status,
|
|
1076
|
-
quantity: row.quantity || 1,
|
|
1077
|
-
cancelAtPeriodEnd: Boolean(row.cancel_at_period_end),
|
|
1078
|
-
currentPeriodStart: row.current_period_start,
|
|
1079
|
-
currentPeriodEnd: row.current_period_end,
|
|
1080
|
-
trialEnd: row.trial_end || null,
|
|
1081
|
-
canceledAt: row.canceled_at || null,
|
|
1082
|
-
metadata,
|
|
1083
|
-
metadataJson: row.metadata_json || "{}",
|
|
1084
|
-
createdAt: row.created_at,
|
|
1085
|
-
updatedAt: row.updated_at
|
|
1086
|
-
};
|
|
1087
|
-
}
|
|
1088
|
-
export async function getSubscription(event, options) {
|
|
1089
|
-
await ensurePaymentsTables(event);
|
|
1090
|
-
const st = subscriptionTbl(event);
|
|
1091
|
-
const db = getPaymentsDb(event);
|
|
1092
|
-
const auth = await getAuthContext(event);
|
|
1093
|
-
const userId = options?.userId || auth?.user?.id;
|
|
1094
|
-
const orgId = options?.orgId || auth?.organization?.id;
|
|
1095
|
-
if (!userId && !orgId) return null;
|
|
1096
|
-
let row = null;
|
|
1097
|
-
if (orgId) {
|
|
1098
|
-
row = await db.prepare(
|
|
1099
|
-
`SELECT * FROM ${st} WHERE org_id = ? AND status IN ('active', 'trialing') ORDER BY created_at DESC LIMIT 1`
|
|
1100
|
-
).bind(orgId).first();
|
|
1101
|
-
}
|
|
1102
|
-
if (!row && userId) {
|
|
1103
|
-
row = await db.prepare(
|
|
1104
|
-
`SELECT * FROM ${st} WHERE user_id = ? AND status IN ('active', 'trialing') ORDER BY created_at DESC LIMIT 1`
|
|
1105
|
-
).bind(userId).first();
|
|
1106
|
-
}
|
|
1107
|
-
return row ? rowToSubscription(row) : null;
|
|
1108
|
-
}
|
|
1109
|
-
export async function requireSubscription(event, options) {
|
|
1110
|
-
const sub = await getSubscription(event);
|
|
1111
|
-
if (!sub) {
|
|
1112
|
-
throw createError({
|
|
1113
|
-
statusCode: 402,
|
|
1114
|
-
statusMessage: "Payment Required",
|
|
1115
|
-
message: options?.message || "Active subscription required to access this resource"
|
|
1116
|
-
});
|
|
1117
|
-
}
|
|
1118
|
-
const allowedStatuses = options?.status || ["active", "trialing"];
|
|
1119
|
-
if (!allowedStatuses.includes(sub.status)) {
|
|
1120
|
-
throw createError({
|
|
1121
|
-
statusCode: 402,
|
|
1122
|
-
statusMessage: "Payment Required",
|
|
1123
|
-
message: options?.message || `Subscription status is ${sub.status}. Active subscription required.`
|
|
1124
|
-
});
|
|
1125
|
-
}
|
|
1126
|
-
const requiredPlans = options?.plan ? Array.isArray(options.plan) ? options.plan : [options.plan] : [];
|
|
1127
|
-
const requiredTiers = options?.tier ? Array.isArray(options.tier) ? options.tier : [options.tier] : [];
|
|
1128
|
-
const allRequired = [...requiredPlans, ...requiredTiers];
|
|
1129
|
-
if (allRequired.length > 0 && !allRequired.includes(sub.planId)) {
|
|
1130
|
-
throw createError({
|
|
1131
|
-
statusCode: 403,
|
|
1132
|
-
statusMessage: "Forbidden",
|
|
1133
|
-
message: options?.message || `Subscription tier "${sub.planId}" does not satisfy required plan (${allRequired.join(", ")})`
|
|
1134
|
-
});
|
|
1135
|
-
}
|
|
1136
|
-
return sub;
|
|
1137
|
-
}
|
|
1138
|
-
export async function hasFeature(event, feature) {
|
|
1139
|
-
const sub = await getSubscription(event);
|
|
1140
|
-
if (!sub || sub.status !== "active" && sub.status !== "trialing") return false;
|
|
1141
|
-
const config = getPaymentsConfig(event);
|
|
1142
|
-
const plan = config.plans?.[sub.planId];
|
|
1143
|
-
if (!plan?.features) return false;
|
|
1144
|
-
return plan.features.includes(feature);
|
|
1145
|
-
}
|
|
1146
|
-
export async function checkLimit(event, limitKey, currentUsage) {
|
|
1147
|
-
const sub = await getSubscription(event);
|
|
1148
|
-
const config = getPaymentsConfig(event);
|
|
1149
|
-
const plan = sub ? config.plans?.[sub.planId] : void 0;
|
|
1150
|
-
const limit = plan?.limits?.[limitKey] ?? Infinity;
|
|
1151
|
-
return {
|
|
1152
|
-
allowed: currentUsage < limit,
|
|
1153
|
-
limit,
|
|
1154
|
-
current: currentUsage
|
|
1155
|
-
};
|
|
1156
|
-
}
|
|
1157
|
-
export async function reportUsage(event, options) {
|
|
1158
|
-
await ensurePaymentsTables(event);
|
|
1159
|
-
const ct = customerTbl(event);
|
|
1160
|
-
const ut = usageRecordTbl(event);
|
|
1161
|
-
const db = getPaymentsDb(event);
|
|
1162
|
-
const config = getPaymentsConfig(event);
|
|
1163
|
-
const auth = await getAuthContext(event).catch(() => null);
|
|
1164
|
-
const userId = options.userId || auth?.user?.id || null;
|
|
1165
|
-
const orgId = options.orgId || auth?.organization?.id || null;
|
|
1166
|
-
const now = Date.now();
|
|
1167
|
-
const timestamp = options.timestamp || now;
|
|
1168
|
-
const id = nanoid();
|
|
1169
|
-
const quantity = options.quantity ?? 1;
|
|
1170
|
-
const action = options.action || "increment";
|
|
1171
|
-
const metadataJson = options.metadata ? JSON.stringify(options.metadata) : "{}";
|
|
1172
|
-
await db.prepare(
|
|
1173
|
-
`INSERT INTO ${ut}
|
|
1174
|
-
(id, user_id, org_id, customer_id, subscription_id, event_name, quantity, action, metadata_json, timestamp, created_at)
|
|
1175
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
1176
|
-
).bind(
|
|
1177
|
-
id,
|
|
1178
|
-
userId,
|
|
1179
|
-
orgId,
|
|
1180
|
-
options.customerId || null,
|
|
1181
|
-
options.subscriptionId || null,
|
|
1182
|
-
options.eventName,
|
|
1183
|
-
quantity,
|
|
1184
|
-
action,
|
|
1185
|
-
metadataJson,
|
|
1186
|
-
timestamp,
|
|
1187
|
-
now
|
|
1188
|
-
).run();
|
|
1189
|
-
if (config.provider === "stripe" && config.secretKey) {
|
|
1190
|
-
let custId = options.customerId;
|
|
1191
|
-
if (!custId && userId) {
|
|
1192
|
-
const cust = await db.prepare(
|
|
1193
|
-
`SELECT customer_id FROM ${ct} WHERE user_id = ? AND provider = 'stripe' LIMIT 1`
|
|
1194
|
-
).bind(userId).first();
|
|
1195
|
-
if (cust) custId = cust.customer_id;
|
|
1196
|
-
}
|
|
1197
|
-
if (custId) {
|
|
1198
|
-
try {
|
|
1199
|
-
const params = new URLSearchParams();
|
|
1200
|
-
params.set("event_name", options.eventName);
|
|
1201
|
-
params.set("payload[value]", String(quantity));
|
|
1202
|
-
params.set("payload[stripe_customer_id]", custId);
|
|
1203
|
-
params.set("timestamp", String(Math.floor(timestamp / 1e3)));
|
|
1204
|
-
const res = await fetch("https://api.stripe.com/v1/billing/meter_events", {
|
|
1205
|
-
method: "POST",
|
|
1206
|
-
signal: AbortSignal.timeout(1e4),
|
|
1207
|
-
headers: {
|
|
1208
|
-
Authorization: `Bearer ${config.secretKey}`,
|
|
1209
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
1210
|
-
"Stripe-Version": STRIPE_API_VERSION
|
|
1211
|
-
},
|
|
1212
|
-
body: params.toString()
|
|
1213
|
-
});
|
|
1214
|
-
if (!res.ok) {
|
|
1215
|
-
const errText = await res.text();
|
|
1216
|
-
console.warn("[qarpeo:payments] Stripe meter event reported non-ok:", errText);
|
|
1217
|
-
}
|
|
1218
|
-
} catch (err) {
|
|
1219
|
-
console.warn("[qarpeo:payments] Failed to report meter event to Stripe:", err);
|
|
1220
|
-
}
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
return {
|
|
1224
|
-
success: true,
|
|
1225
|
-
id,
|
|
1226
|
-
eventName: options.eventName,
|
|
1227
|
-
quantity,
|
|
1228
|
-
timestamp
|
|
1229
|
-
};
|
|
1230
|
-
}
|
|
1231
|
-
export async function getUsageSummary(event, options) {
|
|
1232
|
-
await ensurePaymentsTables(event);
|
|
1233
|
-
const ut = usageRecordTbl(event);
|
|
1234
|
-
const db = getPaymentsDb(event);
|
|
1235
|
-
const auth = await getAuthContext(event).catch(() => null);
|
|
1236
|
-
const userId = options.userId || auth?.user?.id;
|
|
1237
|
-
const orgId = options.orgId || auth?.organization?.id;
|
|
1238
|
-
let sql = `SELECT * FROM ${ut} WHERE 1=1`;
|
|
1239
|
-
const params = [];
|
|
1240
|
-
if (options.eventName) {
|
|
1241
|
-
sql += " AND event_name = ?";
|
|
1242
|
-
params.push(options.eventName);
|
|
1243
|
-
}
|
|
1244
|
-
if (orgId) {
|
|
1245
|
-
sql += " AND org_id = ?";
|
|
1246
|
-
params.push(orgId);
|
|
1247
|
-
} else if (userId) {
|
|
1248
|
-
sql += " AND user_id = ?";
|
|
1249
|
-
params.push(userId);
|
|
1250
|
-
}
|
|
1251
|
-
if (options.since) {
|
|
1252
|
-
sql += " AND timestamp >= ?";
|
|
1253
|
-
params.push(options.since);
|
|
1254
|
-
}
|
|
1255
|
-
if (options.until) {
|
|
1256
|
-
sql += " AND timestamp <= ?";
|
|
1257
|
-
params.push(options.until);
|
|
1258
|
-
}
|
|
1259
|
-
sql += " ORDER BY timestamp DESC LIMIT 500";
|
|
1260
|
-
const stmt = db.prepare(sql);
|
|
1261
|
-
const bound = params.length > 0 ? stmt.bind(...params) : stmt;
|
|
1262
|
-
const result = await bound.all();
|
|
1263
|
-
const rows = result.results || [];
|
|
1264
|
-
let total = 0;
|
|
1265
|
-
for (const row of rows) {
|
|
1266
|
-
if (row.action === "set") {
|
|
1267
|
-
total = row.quantity;
|
|
1268
|
-
} else {
|
|
1269
|
-
total += row.quantity;
|
|
1270
|
-
}
|
|
1271
|
-
}
|
|
1272
|
-
return {
|
|
1273
|
-
eventName: options.eventName || "all",
|
|
1274
|
-
total,
|
|
1275
|
-
count: rows.length,
|
|
1276
|
-
records: rows.map((r) => ({
|
|
1277
|
-
id: r.id,
|
|
1278
|
-
userId: r.user_id,
|
|
1279
|
-
orgId: r.org_id,
|
|
1280
|
-
customerId: r.customer_id,
|
|
1281
|
-
subscriptionId: r.subscription_id,
|
|
1282
|
-
eventName: r.event_name,
|
|
1283
|
-
quantity: r.quantity,
|
|
1284
|
-
action: r.action,
|
|
1285
|
-
metadata: JSON.parse(r.metadata_json || "{}"),
|
|
1286
|
-
timestamp: r.timestamp
|
|
1287
|
-
}))
|
|
1288
|
-
};
|
|
1289
|
-
}
|
|
1
|
+
export * from "./payments/index.mjs";
|