Packages paid through Stripe Checkout
CI / test (push) Successful in 1m25s
CI / build (push) Successful in 5m24s
CI / deploy (push) Skipped

The catalog stays in packages.rs: every checkout session carries the
package's name and gross price, nothing has to be kept in Stripe. The
package is granted once, when Stripe confirms the payment: by the signed
webhook, or by the return page asking Stripe when the webhook is late.
With a test key only admins can buy, so Stripe's test cards give nobody
free packages. Without the keys nothing changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-20 06:41:21 +00:00
co-authored by Claude Opus 5.5
parent 55101f8637
commit 42a982010d
31 changed files with 842 additions and 37 deletions
@@ -4,7 +4,7 @@ import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { api, ApiError, errorText } from "@/lib/api";
import type { Question, UnitBalance } from "@/lib/types";
import type { PayMethod, Question, UnitBalance } from "@/lib/types";
import { AnalysisLoading } from "./AnalysisLoading";
import { PackageChooser } from "./PackageCards";
@@ -49,7 +49,7 @@ export function AnalysisQuestions({
analysisId: string;
left: number;
isAdmin: boolean;
canPay: boolean;
canPay: PayMethod | null;
/** What the analysis is about: the heading and the example question follow it. */
about: "natal" | "synastry" | "forecast";
}) {
@@ -4,7 +4,7 @@ import Link from "next/link";
import { useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import type { Analysis } from "@/lib/types";
import type { Analysis, PayMethod } from "@/lib/types";
import { AI_SHORT } from "./AiNote";
import { AnalysisLoading } from "./AnalysisLoading";
@@ -96,8 +96,8 @@ export function DetailedAnalysis({
initial: Analysis | null;
left: number;
isAdmin: boolean;
/** The stand-in payment is on (MOCK_PAYMENTS). */
canPay: boolean;
/** How the user can buy a package (null: purchases are off). */
canPay: PayMethod | null;
/** Shown above a finished analysis (e.g. who is the first and the second person). */
note?: string;
/** Questions left; given where questions can be asked. */
@@ -245,7 +245,11 @@ export function DetailedAnalysis({
step === "pay" ? (
<div className="pay-box">
<p className="pay-lead">
Válassz csomagot. A vásárlás után az elemzés azonnal elindul, a maradék elemzések pedig nem járnak le.
Válassz csomagot.{" "}
{canPay === "mock"
? "A vásárlás után az elemzés azonnal elindul"
: "A fizetés után visszajössz ide, és rögtön elindíthatod az elemzést"}
, a maradék elemzések pedig nem járnak le.
</p>
<PackageChooser ids={t.packages} canPay={canPay} onBought={start} />
<div className="form-actions">
@@ -5,7 +5,7 @@ import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import type { Package } from "@/lib/types";
import type { Package, PayMethod } from "@/lib/types";
export const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
@@ -22,8 +22,9 @@ export function contents(p: Package): string[] {
/**
* Package cards with a buy button. Bigger packages show what they save and
* how little more they cost than the previous one. Until Stripe is connected
* the payment is a stand-in (MOCK_PAYMENTS) that grants the package at once.
* how little more they cost than the previous one. With Stripe the button
* goes to Stripe's payment page and comes back to this page (PaymentReturn
* shows the result); the stand-in payment (MOCK_PAYMENTS) grants at once.
*/
export function PackageCards({
packages,
@@ -35,15 +36,24 @@ export function PackageCards({
packages: Package[];
/** Which packages, in this order (default: the main ladder). */
ids?: string[];
canPay: boolean;
/** How the user can pay (null: purchases are off, the buttons say "soon"). */
canPay: PayMethod | null;
compact?: boolean;
/** After a purchase (default: reload the page data). */
/** After a stand-in purchase (default: reload the page data). */
onBought?: (p: Package) => Promise<void> | void;
}) {
const router = useRouter();
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [done, setDone] = useState<string | null>(null);
// Back from Stripe's page (the browser may restore this page as it was).
useEffect(() => {
const reset = (e: PageTransitionEvent) => {
if (e.persisted) setBusy(null);
};
window.addEventListener("pageshow", reset);
return () => window.removeEventListener("pageshow", reset);
}, []);
const shown = ids
? ids.map((id) => packages.find((p) => p.id === id)).filter((p): p is Package => p !== undefined)
: packages.filter((p) => p.tier === "main");
@@ -53,15 +63,22 @@ export function PackageCards({
setError(null);
setDone(null);
try {
if (canPay === "stripe" || canPay === "stripe_test") {
const { url } = await api<{ url: string }>("/payments/checkout", {
body: { package: p.id, return_path: window.location.pathname },
});
window.location.assign(url);
return;
}
await api("/payments/mock", { body: { package: p.id } });
if (onBought) await onBought(p);
else {
setDone(p.name);
router.refresh();
}
setBusy(null);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(null);
}
}
@@ -110,7 +127,7 @@ export function PackageCards({
onClick={() => buy(p)}
disabled={busy !== null}
>
{busy === p.id ? "Fizetés…" : "Megveszem"}
{busy === p.id ? (canPay === "mock" ? "Fizetés…" : "Átirányítás…") : "Megveszem"}
</button>
) : (
<button type="button" className="btn" disabled>
@@ -131,7 +148,19 @@ export function PackageCards({
A(z) {done} csomag jóváírva.
</p>
)}
{canPay && <p className="hint">Tesztüzem: a fizetés még nincs bekötve, a gomb nem terhel semmit.</p>}
{canPay === "mock" && <p className="hint">Tesztüzem: a fizetés még nincs bekötve, a gomb nem terhel semmit.</p>}
{canPay === "stripe" && !compact && (
<p className="hint">
A fizetés a Stripe biztonságos oldalán történik (bankkártya, Apple Pay, Google Pay); a kártyaadataidat mi nem
látjuk.
</p>
)}
{canPay === "stripe_test" && (
<p className="hint">
Stripe tesztmód (csak adminoknak látszik): kártyaszám 4242 4242 4242 4242, bármilyen jövőbeli lejárat és CVC.
Valódi pénz nem mozdul.
</p>
)}
</div>
);
}
@@ -154,7 +183,7 @@ export function PackageChooser({
onBought,
}: {
ids: string[];
canPay: boolean;
canPay: PayMethod | null;
onBought?: (p: Package) => Promise<void> | void;
}) {
const packages = usePackages();
@@ -0,0 +1,90 @@
"use client";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
type Notice = { kind: "wait" | "ok" | "info" | "error"; text: string };
const POLLS = 20;
const POLL_MS = 2000;
/**
* Back from Stripe's payment page (`?fizetes=<session>` or
* `?fizetes=megszakitva`): waits until the payment is confirmed, then shows
* it and reloads the page data. Lives in the layout, so it works on every
* page a purchase can start from.
*/
export function PaymentReturn() {
const params = useSearchParams();
const pathname = usePathname();
const router = useRouter();
const value = params.get("fizetes");
const [notice, setNotice] = useState<Notice | null>(null);
useEffect(() => {
if (!value) return;
// A reload should not show it again.
const clean = () => {
const rest = new URLSearchParams(window.location.search);
rest.delete("fizetes");
router.replace(rest.size ? `${pathname}?${rest}` : pathname, { scroll: false });
};
if (value === "megszakitva") {
setNotice({ kind: "info", text: "A fizetés megszakadt, nem terheltünk semmit." });
clean();
return;
}
let stopped = false;
setNotice({ kind: "wait", text: "A fizetés visszaigazolására várunk…" });
(async () => {
for (let i = 0; i < POLLS && !stopped; i++) {
try {
const r = await api<{ status: string; name: string | null }>(
`/payments/checkout/${encodeURIComponent(value)}`,
);
if (stopped) return;
if (r.status === "paid") {
setNotice({ kind: "ok", text: `Köszönjük! Jóváírtuk: ${r.name ?? "a csomagod"}.` });
clean();
router.refresh();
return;
}
if (r.status === "expired") {
setNotice({ kind: "info", text: "A fizetési oldal lejárt, nem terheltünk semmit." });
clean();
return;
}
} catch (e) {
if (!stopped) setNotice({ kind: "error", text: errorText(e) });
return;
}
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
}
if (!stopped)
setNotice({
kind: "error",
text: "A Stripe még nem igazolta vissza a fizetést. Pár perc múlva frissítsd az oldalt: ha a pénz levonódott, a csomag megérkezik.",
});
})();
return () => {
stopped = true;
};
}, [value, pathname, router]);
if (!notice) return null;
const cls = notice.kind === "ok" ? "msg msg-ok" : notice.kind === "error" ? "msg msg-error" : "msg";
return (
<div className="pay-return" role={notice.kind === "error" ? "alert" : "status"}>
<p className={cls}>
<span>{notice.text}</span>
{notice.kind !== "wait" && (
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setNotice(null)} aria-label="Bezárás">
×
</button>
)}
</p>
</div>
);
}
@@ -1,8 +1,10 @@
"use client";
import type { PayMethod } from "@/lib/types";
import { PackageChooser } from "./PackageCards";
/** Packages that give more persons: a few more, or the family package. */
export function PersonPacks({ canPay }: { canPay: boolean }) {
export function PersonPacks({ canPay }: { canPay: PayMethod | null }) {
return <PackageChooser ids={["addon_persons", "family"]} canPay={canPay} />;
}