@tansy/payments-creem 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohamed Salah
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ <!-- Generated by scripts/package-metadata.mjs. Change that script, not this file. -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @tansy/payments-creem
4
+
5
+ Creem for @tansy/payments, through better-auth's Creem plugin.
6
+
7
+ ```bash
8
+ npm install @tansy/payments-creem
9
+ ```
10
+
11
+ Add it to `tansy.config.ts`. See [the payments plugin documentation](https://github.com/mhmdsalahsebai/tansy/blob/main/docs/plugins/payments.md) for what it adds and the options it takes.
12
+
13
+ A first-party plugin for [tansy](https://github.com/mhmdsalahsebai/tansy), a self-hosted, runtime-schema CMS for Next.js. MIT licensed.
package/index.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /** Creem, through better-auth's Creem plugin. Payments keeps its subscriptions as memberships. */
2
+ export declare const creem: () => import("@tansy/payments/provider").PaymentProvider;
3
+ /**
4
+ * Creem's endpoints that take an id from the request without checking it belongs to the
5
+ * caller, and its checkout, which takes metadata of the caller's choosing. Payments' own
6
+ * routes call them after their checks.
7
+ */
8
+ export declare const CREEM_SERVER_ONLY: string[];
package/index.js ADDED
@@ -0,0 +1,130 @@
1
+ import { Creem } from "creem";
2
+ import { creem as creemPlugin } from "@creem_io/better-auth";
3
+ import { definePaymentProvider, loadPlanRefs, newReference, recordPurchase, recordRefund, REFERENCE, rememberCheckout, startedCheckout, str, upsertMembership } from "@tansy/payments/provider";
4
+ const keys = (settings) => settings;
5
+ const client = (settings) => new Creem({ apiKey: keys(settings).creemApiKey, serverURL: settings.testMode ? "https://test-api.creem.io" : "https://api.creem.io" });
6
+ const idOf = (value) => (typeof value === "string" ? value : str(value?.id));
7
+ const record = (value) => (value && typeof value === "object" ? value : {});
8
+ async function onSubscription(context, data, plans) {
9
+ await upsertMembership(context, {
10
+ provider: "creem",
11
+ subscriptionId: str(data.id),
12
+ // better-auth's Creem plugin puts the signed-in user's id in referenceId.
13
+ user: str(record(data.metadata).referenceId) || null,
14
+ productId: idOf(data.product),
15
+ status: str(data.status),
16
+ periodEnd: data.current_period_end_date ?? null,
17
+ at: Number(data.webhookCreatedAt) || Date.now(),
18
+ }, await plans());
19
+ }
20
+ /** Creem, through better-auth's Creem plugin. Payments keeps its subscriptions as memberships. */
21
+ export const creem = () => definePaymentProvider({
22
+ id: "creem",
23
+ label: "Creem",
24
+ webhookPath: "/creem/webhook",
25
+ // Its settings in other interface languages. English is each setting's own label and description.
26
+ messages: (siteUrl) => ({
27
+ ar: { settings: {
28
+ creemApiKey: { label: "مفتاح API لـ Creem", description: "من Creem ← Developers. فعّل وضع الاختبار لمفتاح اختبار." },
29
+ creemWebhookSecret: { label: "سرّ webhook في Creem", description: `وجّه webhook من Creem إلى ${siteUrl}/api/auth/creem/webhook، ثم الصق سرّه.` },
30
+ creemProductId: { label: "منتج Creem للمشتريات لمرة واحدة", description: "منتج لمرة واحدة مع تفعيل «ادفع ما تريد»، بعملة أسعارك (USD أو EUR). يُباع كل سجل تحته بسعره الخاص." },
31
+ } },
32
+ }),
33
+ settings: (siteUrl) => [
34
+ { name: "creemApiKey", type: "secret", env: "CREEM_API_KEY", label: "Creem API key", description: "From Creem → Developers. Turn on test mode for a test key." },
35
+ { name: "creemWebhookSecret", type: "secret", env: "CREEM_WEBHOOK_SECRET", label: "Creem webhook secret", description: `Point a Creem webhook at ${siteUrl}/api/auth/creem/webhook, then paste its secret.` },
36
+ { name: "creemProductId", type: "text", default: "", maxLength: 100, label: "Creem product for one-time purchases", description: "A one-time product with pay what you want turned on, in the currency of your prices (USD or EUR). Each record sells under it at its own price." },
37
+ ],
38
+ serverOnlyPaths: CREEM_SERVER_ONLY,
39
+ planIdProblem: (value) => (value.startsWith("prod_") ? null : "Use a Creem product id, which starts with prod_."),
40
+ ready: (settings) => Boolean(keys(settings).creemApiKey && keys(settings).creemWebhookSecret),
41
+ authPlugins(settings, context, siteUrl) {
42
+ const plans = () => loadPlanRefs(context);
43
+ const subscription = async (data) => onSubscription(context, data, plans);
44
+ return [creemPlugin({
45
+ apiKey: keys(settings).creemApiKey,
46
+ webhookSecret: keys(settings).creemWebhookSecret,
47
+ testMode: settings.testMode,
48
+ defaultSuccessUrl: siteUrl,
49
+ onCheckoutCompleted: async (data) => {
50
+ const order = data.order;
51
+ const metadata = record(data.metadata);
52
+ if (order && order.status !== "pending")
53
+ await recordPurchase(context, { provider: "creem", sessionId: str(metadata.ref), paymentRef: order.id, metadata, amount: order.amount, currency: order.currency });
54
+ },
55
+ onRefundCreated: async (data) => {
56
+ const order = data.order;
57
+ const total = typeof order === "object" ? order.amount : null;
58
+ // Only a refund of the whole order takes the purchase back.
59
+ if (total !== null && data.refund_amount < total)
60
+ return;
61
+ await recordRefund(context, { paymentRef: idOf(order) || null });
62
+ },
63
+ onSubscriptionActive: subscription,
64
+ onSubscriptionTrialing: subscription,
65
+ onSubscriptionPaid: subscription,
66
+ onSubscriptionCanceled: subscription,
67
+ onSubscriptionScheduledCancel: subscription,
68
+ onSubscriptionExpired: subscription,
69
+ onSubscriptionUnpaid: subscription,
70
+ onSubscriptionPastDue: subscription,
71
+ onSubscriptionPaused: subscription,
72
+ onSubscriptionUpdate: subscription,
73
+ })];
74
+ },
75
+ async currencyProblem(settings, currency) {
76
+ if (!keys(settings).creemProductId)
77
+ return "Payments → Settings needs the Creem product that one-time purchases are sold under.";
78
+ const product = await client(settings).products.get(keys(settings).creemProductId).catch(() => null);
79
+ if (!product)
80
+ return "The Creem product under Payments → Settings can't be found.";
81
+ const productCurrency = str(product.currency).toLowerCase();
82
+ return productCurrency && productCurrency !== currency ? `This is priced in ${currency.toUpperCase()}, and the Creem product sells in ${productCurrency.toUpperCase()}.` : null;
83
+ },
84
+ async checkout({ context, settings, buyer, collection, recordId, amount, successUrl }) {
85
+ const ref = newReference();
86
+ const created = await client(settings).checkouts.create({
87
+ // A pay-what-you-want product, at the record's own price.
88
+ productId: keys(settings).creemProductId,
89
+ customPrice: amount,
90
+ requestId: ref,
91
+ customer: { email: buyer.email },
92
+ metadata: { tansy: "purchase", collection, recordId: String(recordId), userId: buyer.id, ref, referenceId: buyer.id },
93
+ successUrl: `${successUrl}&session_id=${ref}`,
94
+ });
95
+ await rememberCheckout(context, ref, { id: created.id, userId: buyer.id, collection, recordId, at: Date.now() });
96
+ if (!created.checkoutUrl)
97
+ throw new Error("Creem returned no checkout address.");
98
+ return created.checkoutUrl;
99
+ },
100
+ isReference: (value) => REFERENCE.test(value),
101
+ async confirm(context, settings, reference, buyer) {
102
+ const started = await startedCheckout(context, reference);
103
+ if (!started || started.userId !== buyer.id)
104
+ return null;
105
+ const found = await client(settings).checkouts.retrieve(started.id).catch(() => null);
106
+ if (!found)
107
+ return null;
108
+ const order = found.order;
109
+ const paid = found.status === "completed" && Boolean(order) && order?.status !== "pending";
110
+ if (paid && order)
111
+ await recordPurchase(context, { provider: "creem", sessionId: reference, paymentRef: order.id, metadata: found.metadata, amount: order.amount, currency: order.currency });
112
+ context.auditTarget("record", `${started.collection}/${started.recordId}`, { paid });
113
+ return { paid };
114
+ },
115
+ async subscribe({ context, plan, annual, successUrl }) {
116
+ const { url } = await context.auth.call("/creem/create-checkout", { body: { productId: annual && plan.annualProductId ? plan.annualProductId : plan.productId, successUrl } });
117
+ return url;
118
+ },
119
+ async billing(context) {
120
+ // Without a customerId, the plugin uses the caller's own.
121
+ const { url } = await context.auth.call("/creem/create-portal", { body: {} });
122
+ return url;
123
+ },
124
+ });
125
+ /**
126
+ * Creem's endpoints that take an id from the request without checking it belongs to the
127
+ * caller, and its checkout, which takes metadata of the caller's choosing. Payments' own
128
+ * routes call them after their checks.
129
+ */
130
+ export const CREEM_SERVER_ONLY = ["/creem/create-checkout", "/creem/create-portal", "/creem/cancel-subscription", "/creem/retrieve-subscription", "/creem/search-transactions"];
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@tansy/payments-creem",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Creem for @tansy/payments, through better-auth's Creem plugin.",
5
+ "keywords": [
6
+ "tansy",
7
+ "tansy-payments-provider"
8
+ ],
9
+ "license": "MIT",
10
+ "author": "Mohamed Salah <mohamedsalahsebai@gmail.com>",
11
+ "homepage": "https://github.com/mhmdsalahsebai/tansy",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/mhmdsalahsebai/tansy.git",
15
+ "directory": "plugins/payments-creem"
16
+ },
17
+ "bugs": "https://github.com/mhmdsalahsebai/tansy/issues",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./index.d.ts",
21
+ "default": "./index.js"
22
+ }
23
+ },
24
+ "peerDependencies": {
25
+ "@tansy/payments": "^0.1.0",
26
+ "tansy": "^0.1.0"
27
+ },
28
+ "dependencies": {
29
+ "@creem_io/better-auth": "^2.0.5",
30
+ "creem": "^1.14.0"
31
+ }
32
+ }