@tansy/payments-polar 0.0.0-stage → 0.1.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ What changed in each release of `@tansy/payments-polar`. Releases up to 0.1.0 went out with every other package
4
+ on one version and are described in [tansy's changelog](../../CHANGELOG.md).
5
+
6
+ ## 0.1.1 — 2026-11-22
7
+
8
+ No changes of its own. Released beside `tansy` 0.1.1, from which every package moves on its own
9
+ version, and it now requires it: the `tansy` peer range is ^0.1.1.
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-polar
4
+
5
+ Polar for @tansy/payments, through better-auth's Polar plugin.
6
+
7
+ ```bash
8
+ npm install @tansy/payments-polar
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,2 @@
1
+ /** Polar, through better-auth's Polar plugin. Payments keeps its subscriptions as memberships. */
2
+ export declare const polar: () => import("@tansy/payments/provider").PaymentProvider;
package/index.js ADDED
@@ -0,0 +1,113 @@
1
+ import { checkout, polar as polarPlugin, portal, webhooks } from "@polar-sh/better-auth";
2
+ import { createPolarCore } from "@polar-sh/sdk/2026-10";
3
+ import { createCheckouts, getCheckouts } from "@polar-sh/sdk/2026-10/services/checkouts";
4
+ import { definePaymentProvider, loadPlanRefs, newReference, productSlugs, recordPurchase, recordRefund, REFERENCE, rememberCheckout, startedCheckout, upsertMembership } from "@tansy/payments/provider";
5
+ const keys = (settings) => settings;
6
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
7
+ const client = (settings) => createPolarCore({ accessToken: keys(settings).polarAccessToken, environment: settings.testMode ? "sandbox" : "production" });
8
+ async function onOrderPaid(context, order) {
9
+ await recordPurchase(context, { provider: "polar", sessionId: String(order.metadata?.ref ?? ""), paymentRef: order.id, metadata: order.metadata, amount: order.total_amount, currency: order.currency });
10
+ }
11
+ async function onSubscription(context, subscription, timestamp, plans) {
12
+ await upsertMembership(context, {
13
+ provider: "polar",
14
+ subscriptionId: subscription.id,
15
+ // better-auth's Polar plugin makes the user's id the customer's external id.
16
+ user: subscription.customer?.external_id ?? null,
17
+ productId: subscription.product_id,
18
+ status: subscription.status,
19
+ periodEnd: subscription.current_period_end,
20
+ at: new Date(subscription.modified_at ?? timestamp).getTime(),
21
+ }, await plans());
22
+ }
23
+ /** Polar, through better-auth's Polar plugin. Payments keeps its subscriptions as memberships. */
24
+ export const polar = () => definePaymentProvider({
25
+ id: "polar",
26
+ label: "Polar",
27
+ webhookPath: "/polar/webhooks",
28
+ // Its settings in other interface languages. English is each setting's own label and description.
29
+ messages: (siteUrl) => ({
30
+ ar: { settings: {
31
+ polarAccessToken: { label: "رمز الوصول في Polar", description: "من Polar ← Settings ← Developers، رمز وصول للمؤسسة. فعّل وضع الاختبار لرمز sandbox." },
32
+ polarWebhookSecret: { label: "سرّ webhook في Polar", description: `وجّه webhook من Polar إلى ${siteUrl}/api/auth/polar/webhooks، مع أحداث الطلبات والاشتراكات، ثم الصق سرّه.` },
33
+ polarProductId: { label: "منتج Polar للمشتريات لمرة واحدة", description: "منتج لمرة واحدة في Polar. يُباع كل سجل تحته بسعره الخاص. اتركه فارغًا إن كنت تبيع الخطط فقط." },
34
+ } },
35
+ }),
36
+ settings: (siteUrl) => [
37
+ { name: "polarAccessToken", type: "secret", env: "POLAR_ACCESS_TOKEN", label: "Polar access token", description: "From Polar → Settings → Developers, an organization access token. Turn on test mode for a sandbox token." },
38
+ { name: "polarWebhookSecret", type: "secret", env: "POLAR_WEBHOOK_SECRET", label: "Polar webhook secret", description: `Point a Polar webhook at ${siteUrl}/api/auth/polar/webhooks, with order and subscription events, then paste its secret.` },
39
+ { name: "polarProductId", type: "text", default: "", maxLength: 100, label: "Polar product for one-time purchases", description: "A one-time product in Polar. Each record sells under it at its own price. Leave empty if you sell only plans." },
40
+ ],
41
+ // Polar's checkout takes any products and metadata from the caller.
42
+ serverOnlyPaths: ["/checkout"],
43
+ planIdProblem: (value) => (UUID.test(value) ? null : "Use a Polar product id, such as 1c4e2f6a-0b1c-4d2e-8f3a-123456789abc."),
44
+ ready: (settings) => Boolean(keys(settings).polarAccessToken && keys(settings).polarWebhookSecret),
45
+ authPlugins(settings, context, siteUrl) {
46
+ const plans = () => loadPlanRefs(context);
47
+ const subscription = async (payload) => onSubscription(context, payload.data, payload.timestamp, plans);
48
+ return [polarPlugin({
49
+ client: client(settings),
50
+ createCustomerOnSignUp: settings.createCustomerOnSignUp,
51
+ use: [
52
+ checkout({ products: async () => productSlugs(await plans()), authenticatedUsersOnly: true }),
53
+ portal({ returnUrl: siteUrl }),
54
+ webhooks({
55
+ secret: keys(settings).polarWebhookSecret,
56
+ onOrderPaid: async (payload) => onOrderPaid(context, payload.data),
57
+ onOrderRefunded: async (payload) => {
58
+ const order = payload.data;
59
+ if (order.status === "refunded")
60
+ await recordRefund(context, { sessionId: typeof order.metadata?.ref === "string" ? order.metadata.ref : null, paymentRef: order.id });
61
+ },
62
+ onSubscriptionCreated: subscription,
63
+ onSubscriptionUpdated: subscription,
64
+ onSubscriptionActive: subscription,
65
+ onSubscriptionCanceled: subscription,
66
+ onSubscriptionUncanceled: subscription,
67
+ onSubscriptionRevoked: subscription,
68
+ }),
69
+ ],
70
+ })];
71
+ },
72
+ async checkout({ context, settings, buyer, collection, recordId, amount, currency, successUrl, cancelUrl }) {
73
+ if (!keys(settings).polarProductId)
74
+ throw new Error("Payments → Settings needs the Polar product that one-time purchases are sold under.");
75
+ const ref = newReference();
76
+ const productId = keys(settings).polarProductId;
77
+ const created = await createCheckouts(client(settings))({
78
+ products: [productId],
79
+ // The record's own price, in place of the product's.
80
+ prices: { [productId]: [{ amount_type: "fixed", price_amount: amount, price_currency: currency }] },
81
+ external_customer_id: buyer.id,
82
+ customer_email: buyer.email,
83
+ metadata: { tansy: "purchase", collection, recordId: String(recordId), userId: buyer.id, ref },
84
+ success_url: `${successUrl}&session_id=${ref}`,
85
+ return_url: cancelUrl,
86
+ });
87
+ await rememberCheckout(context, ref, { id: created.id, userId: buyer.id, collection, recordId, at: Date.now() });
88
+ return created.url;
89
+ },
90
+ isReference: (value) => REFERENCE.test(value),
91
+ async confirm(context, settings, reference, buyer) {
92
+ const started = await startedCheckout(context, reference);
93
+ if (!started || started.userId !== buyer.id)
94
+ return null;
95
+ const found = await getCheckouts(client(settings))(started.id).catch(() => null);
96
+ if (!found)
97
+ return null;
98
+ const paid = found.status === "succeeded";
99
+ if (paid)
100
+ await recordPurchase(context, { provider: "polar", sessionId: reference, paymentRef: null, metadata: found.metadata, amount: found.total_amount, currency: found.currency });
101
+ context.auditTarget("record", `${started.collection}/${started.recordId}`, { paid });
102
+ return { paid };
103
+ },
104
+ async subscribe({ context, plan, annual, successUrl, cancelUrl }) {
105
+ const slug = annual && plan.annualProductId ? `${plan.name}-annual` : plan.name;
106
+ const { url } = await context.auth.call("/checkout", { body: { slug, success_url: successUrl, return_url: cancelUrl, redirect: false } });
107
+ return url;
108
+ },
109
+ async billing(context) {
110
+ const { url } = await context.auth.call("/customer/portal", { body: { redirect: false } });
111
+ return url;
112
+ },
113
+ });
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@tansy/payments-polar",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Polar for @tansy/payments, through better-auth's Polar 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-polar"
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.1",
26
+ "tansy": "^0.1.1"
27
+ },
28
+ "dependencies": {
29
+ "@polar-sh/better-auth": "^2.1.4",
30
+ "@polar-sh/sdk": "~1.0.2"
31
+ }
32
+ }