Compare commits

...
Author SHA1 Message Date
sagifer 5e633b959d Merge pull request 'Main' (#28) from main into prod
CI / test (push) Successful in 1m29s
CI / build (push) Successful in 2m29s
CI / deploy (push) Successful in 50s
Reviewed-on: #28
2026-11-20 08:01:11 +01:00
fecoandClaude Opus 5.5 d9e71ed349 Purchases for admins only until the opening; brand images for Stripe
CI / test (push) Successful in 1m22s
CI / build (push) Successful in 7m0s
CI / deploy (push) Skipped
PURCHASES_OPEN (default false) keeps Stripe purchases to admins, also with
a live key, so nobody types a real card before the opening.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 06:57:00 +00:00
fecoandClaude Opus 5.5 42a982010d 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
2026-11-20 06:41:21 +00:00
sagifer a4df094191 Merge pull request 'Sitemap for the public pages, linked from robots.txt' (#27) from main into prod
CI / test (push) Successful in 1m18s
CI / build (push) Successful in 21s
CI / deploy (push) Successful in 37s
Reviewed-on: #27
2026-11-20 03:15:22 +01:00
fecoandClaude Opus 5.5 55101f8637 Sitemap for the public pages, linked from robots.txt
CI / test (push) Successful in 1m22s
CI / build (push) Successful in 4m53s
CI / deploy (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 02:11:26 +00:00
37 changed files with 926 additions and 38 deletions
Generated
+1
View File
@@ -170,6 +170,7 @@ dependencies = [
"axum-extra",
"db",
"email-templates",
"hmac",
"horoscope-client",
"http-body-util",
"jsonwebtoken",
@@ -0,0 +1,16 @@
-- Stripe Checkout sessions started from the package cards. The package is
-- granted once, when the payment is confirmed (webhook, or the return page
-- asking Stripe), and the session id keeps that from happening twice.
CREATE TABLE stripe_checkouts (
-- Stripe's Checkout Session id (cs_test_… / cs_live_…).
id text PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
package text NOT NULL,
price_huf integer NOT NULL CHECK (price_huf > 0),
live boolean NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
completed_at timestamptz,
order_id uuid REFERENCES package_orders ON DELETE SET NULL
);
CREATE INDEX stripe_checkouts_user_idx ON stripe_checkouts (user_id, created_at DESC);
+1 -1
View File
@@ -68,7 +68,7 @@ A Docker által kinyitott portokat az ufw magától nem szűri, ezért a 80-as
`deploy` felhasználóként, a `/opt/sorsfonalak` mappában:
- `.env`: az itteni `.env.example` kitöltve.
- `.env.secrets`: `OPENROUTER_API_KEY=...`.
- `.env.secrets`: `OPENROUTER_API_KEY=...`, a levélküldés adatai, és ha van, `STRIPE_SECRET_KEY` / `STRIPE_WEBHOOK_SECRET` (`docs/fizetes.md`).
- `docker login registry.sagifer.com` egy `read:package` jogú tokennel. Amíg a `sagifer` fiók nyilvános, erre nincs szükség.
### Cloudflare (sorsfonalak.hu)
+10 -2
View File
@@ -85,9 +85,12 @@ services:
ANALYSIS_MODEL: ${ANALYSIS_MODEL:-}
SUMMARY_MODEL: ${SUMMARY_MODEL:-}
PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false}
# Purchases are off until real payments are connected; packages come
# from promo codes and admins (MOCK_PAYMENTS=true: pretend purchases).
# Without the Stripe keys purchases are off; packages come from promo
# codes and admins (MOCK_PAYMENTS=true: pretend purchases).
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-false}
# Stripe purchases for everyone (false: admins only, until the opening;
# with a test key always admins only).
PURCHASES_OPEN: ${PURCHASES_OPEN:-false}
# Users inviting others ("Meghívom"): shown but off until the launch.
USER_INVITES: ${USER_INVITES:-false}
# A new user from a shared link earns the sharer an analysis: off until sign-up opens.
@@ -95,6 +98,11 @@ services:
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0}
# invite: new accounts need an invitation (admin page "Meghívók"); open: anyone.
SIGNUP_MODE: ${SIGNUP_MODE:-invite}
# STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET (docs/fizetes.md): with them
# packages can be bought (a test key: by admins only).
env_file:
- path: .env.secrets
required: false
depends_on:
postgres:
condition: service_healthy
+8
View File
@@ -55,9 +55,17 @@ services:
PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false}
# Stand-in payment (adds an analysis unit at once) until Stripe is connected.
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
# Stripe purchases for everyone (false: admins only, until the opening;
# with a test key always admins only).
PURCHASES_OPEN: ${PURCHASES_OPEN:-false}
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0}
# invite: new accounts need an invitation (admin page "Meghívók"); open: anyone.
SIGNUP_MODE: ${SIGNUP_MODE:-invite}
# STRIPE_SECRET_KEY / STRIPE_WEBHOOK_SECRET (test keys; docs/fizetes.md).
# With them Stripe replaces the stand-in payment.
env_file:
- path: .env.secrets
required: false
depends_on:
postgres:
condition: service_healthy
+21
View File
@@ -0,0 +1,21 @@
# Arculat
- `sorsfonalak-ikon-512.png`: négyzetes ikon (512×512, sötét háttér, teljes kitöltés).
- `sorsfonalak-logo-sotet-hatterre.png`: logó átlátszó háttérrel, sötét felületre (1200×300).
- `sorsfonalak-logo-vilagos-hatterre.png`: ugyanez világos felületre.
A jel forrása: `services/frontend/src/app/icon.svg`.
## Színek
| Szerep | Szín |
|---|---|
| Háttér | `#0d1220` |
| Panel | `#111729` |
| Arany (kiemelés, gombok) | `#d9b46a` |
| Arany, világos háttéren | `#a7802f` |
| Szöveg sötét háttéren | `#ece6d8` |
| Szöveg világos háttéren | `#1b2236` |
| Gomb felirata arany gombon | `#141a2c` |
Stripe (Settings → Branding): Brand color `#0d1220`, Accent color `#d9b46a`, ikon és a sötét háttérre szánt logó.
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+1 -2
View File
@@ -39,7 +39,6 @@ Az éves előrejelzés (2026 novembere óta) a Páros és a Család csomagban mi
## Későbbre
- Stripe-bekötés: a `package_orders.source = 'stripe'` már helyet kapott.
- Bevezető kedvezmény vagy kupon (pl. az első 100 vásárlónak).
- Ajándékba adható csomag (karácsony, Valentin-nap): a Páros és a Család jó ajándék.
- Számlázás (NAV Online Számla) a vásárlásokhoz.
- Számlázás (NAV Online Számla) a vásárlásokhoz. A fizetés a Stripe-on megy: [fizetes.md](fizetes.md).
+45
View File
@@ -0,0 +1,45 @@
# Fizetés (Stripe)
A csomagokat a Stripe Checkout fizetési oldalán lehet megvenni. A csomagok neve, tartalma és ára a `services/backend/src/packages.rs`-ben van; minden fizetés ezekkel indul, a Stripe-ban nem kell termékeket felvenni.
## Menete
1. A „Megveszem” gomb a `POST /v1/payments/checkout` végpontot hívja (`package`, `return_path`: az oldal, ahonnan indult).
2. A backend létrehoz egy Checkout Sessiont (bruttó ár forintban, a csomag neve, a felhasználó e-mail-címe, kötelező számlázási cím), elmenti a `stripe_checkouts` táblába, és visszaadja a fizetési oldal címét.
3. Fizetés után a Stripe visszaküld ugyanarra az oldalra `?fizetes=<session id>` paraméterrel (megszakításkor `?fizetes=megszakitva`). A `PaymentReturn` komponens a `GET /v1/payments/checkout/{id}` végpontot kérdezi, amíg a fizetés be nem igazolódik.
4. A csomagot a backend akkor adja meg, amikor a Stripe igazolja a fizetést:
- a webhook (`POST /api/v1/payments/stripe/webhook`, aláírással ellenőrizve), vagy
- ha a webhook még nem jött meg (vagy helyben nincs beállítva), a visszatérő oldal kérdésére a backend maga kérdezi meg a Stripe-ot.
A session id miatt egy fizetés csak egyszer ír jóvá (`package_orders.source = 'stripe'`).
## Beállítás
A kulcsok a `.env.secrets` fájlba kerülnek (helyben a repó gyökerében, a szerveren a `/opt/sorsfonalak` mappában), git-be soha:
```
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
```
- **A megnyitásig csak az adminok vásárolhatnak** (`PURCHASES_OPEN=false`, az alapértelmezés), a többieknek a gombok „Hamarosan” feliratúak; így senki nem ad meg valódi kártyát egy teszt- vagy félkész beállításnál.
- Teszt kulccsal (`sk_test_…`) `PURCHASES_OPEN=true` mellett is csak adminok vásárolhatnak (a Stripe tesztkártyáival senki nem jut csomaghoz). Tesztkártya: `4242 4242 4242 4242`, bármilyen jövőbeli lejárat és CVC.
- Élő kulccsal és `PURCHASES_OPEN=true` mellett mindenki vásárolhat (megnyitáskor, a `.env`-ben).
- Kulcs nélkül nincs vásárlás (helyben a `MOCK_PAYMENTS=true` próbafizetés működik; a Stripe-kulcs ezt felülírja).
A Stripe felületén:
1. **Developers → API keys**: a Secret key → `STRIPE_SECRET_KEY`.
2. **Developers → Webhooks → Add endpoint**: `https://sorsfonalak.hu/api/v1/payments/stripe/webhook`, események: `checkout.session.completed` és `checkout.session.async_payment_succeeded`. A Signing secret → `STRIPE_WEBHOOK_SECRET`. Teszt és élő módban külön végpontot kell felvenni, külön titokkal.
3. **Settings → Branding**: logó, színek (a fizetési oldal kinézete).
4. **Settings → Payment methods**: bankkártya, Apple Pay, Google Pay.
A kulcsok módosítása után a backendet újra kell indítani (`docker compose up -d backend`).
Helyben a webhook nem ér el a géphez; nem is kell, mert a visszatérő oldal a Stripe-tól kérdezi le a fizetést. Ha mégis próbálni kell: `stripe listen --forward-to localhost:3001/api/v1/payments/stripe/webhook`.
## Megnyitás előtt
- A Stripe-fiók aktiválása (céges adatok, bankszámla), élő kulcsok és élő webhook.
- Számla: Billingo API-val, minden sikeres fizetés után (a vásárló neve és címe a Checkoutból jön). A Stripe nyugtája nem magyar számla.
- Visszatérítés: egyelőre a Stripe felületén, a csomagot pedig az admin oldalon kell kézzel csökkenteni.
+1
View File
@@ -10,6 +10,7 @@ publish.workspace = true
db.workspace = true
analysis-prompt.workspace = true
email-templates.workspace = true
hmac.workspace = true
horoscope-client.workspace = true
service-kit.workspace = true
anyhow.workspace = true
+46
View File
@@ -45,6 +45,13 @@ pub struct Config {
/// `MOCK_PAYMENTS` (default `false`): a stand-in payment that adds an
/// analysis unit at once, until Stripe is connected.
pub mock_payments: bool,
/// Stripe Checkout, when `STRIPE_SECRET_KEY` is set (it wins over
/// `MOCK_PAYMENTS`).
pub stripe: Option<StripeConfig>,
/// `PURCHASES_OPEN` (default `false`): everyone may buy through Stripe.
/// Until the opening only admins can (and with a test key always only
/// admins), so nobody types a real card into a test or unfinished setup.
pub purchases_open: bool,
/// `USER_INVITES` (default `false`): users may invite others ("how
/// compatible are we?" links, which also let the invitee sign up). Off
/// until the launch; admins may always.
@@ -85,6 +92,34 @@ pub struct Config {
pub signup_mode: SignupMode,
}
/// `STRIPE_SECRET_KEY` (`sk_test_…` or `sk_live_…`), `STRIPE_WEBHOOK_SECRET`
/// (`whsec_…`, from the webhook endpoint in the Stripe dashboard) and
/// `STRIPE_API_URL` (default `https://api.stripe.com`, tests change it).
#[derive(Clone)]
pub struct StripeConfig {
pub secret_key: String,
pub webhook_secret: Option<String>,
pub api_url: String,
}
impl StripeConfig {
/// A test-mode key: no real money moves.
pub fn test_mode(&self) -> bool {
self.secret_key.starts_with("sk_test_") || self.secret_key.starts_with("rk_test_")
}
}
// The keys stay out of logs.
impl std::fmt::Debug for StripeConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StripeConfig")
.field("test_mode", &self.test_mode())
.field("webhook_secret", &self.webhook_secret.is_some())
.field("api_url", &self.api_url)
.finish()
}
}
fn var(name: &str) -> Option<String> {
std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty())
}
@@ -127,6 +162,15 @@ impl Config {
session_ttl_days: parsed("SESSION_TTL_DAYS", 30)?,
password_login: parsed("PASSWORD_LOGIN", false)?,
mock_payments: parsed("MOCK_PAYMENTS", false)?,
stripe: var("STRIPE_SECRET_KEY").map(|secret_key| StripeConfig {
secret_key,
webhook_secret: var("STRIPE_WEBHOOK_SECRET"),
api_url: var("STRIPE_API_URL")
.unwrap_or_else(|| "https://api.stripe.com".into())
.trim_end_matches('/')
.to_string(),
}),
purchases_open: parsed("PURCHASES_OPEN", false)?,
user_invites: parsed("USER_INVITES", false)?,
referral_rewards: parsed("REFERRAL_REWARDS", false)?,
google_client_ids: list("GOOGLE_CLIENT_IDS"),
@@ -166,6 +210,8 @@ impl Config {
session_ttl_days: 30,
password_login: true,
mock_payments: true,
stripe: None,
purchases_open: true,
user_invites: true,
referral_rewards: true,
google_client_ids: vec!["test-client.apps.googleusercontent.com".into()],
+3
View File
@@ -17,6 +17,7 @@ mod models;
mod packages;
mod persons;
mod routes;
mod stripe;
#[cfg(test)]
mod tests;
mod views;
@@ -41,6 +42,7 @@ pub struct AppState {
pub google: GoogleVerifier,
pub login_limiter: LoginLimiter,
pub models: models::Catalog,
pub stripe: stripe::Client,
}
impl AppState {
@@ -50,6 +52,7 @@ impl AppState {
google: GoogleVerifier::new(config.google_client_ids.clone(), config.google_jwks_url.clone()),
login_limiter: LoginLimiter::new(10, Duration::from_secs(15 * 60)),
models: models::Catalog::new(&config.openrouter_models_url),
stripe: stripe::Client::default(),
db,
config,
}
+4 -1
View File
@@ -186,6 +186,8 @@ pub enum Source {
Mock,
/// A redeemed promo code.
Promo,
/// Paid through Stripe Checkout.
Stripe,
}
impl Source {
@@ -194,6 +196,7 @@ impl Source {
Source::Admin => "admin",
Source::Mock => "mock",
Source::Promo => "promo",
Source::Stripe => "stripe",
}
}
}
@@ -268,7 +271,7 @@ async fn record(
let order = Uuid::now_v7();
let price = match source {
Source::Admin | Source::Promo => 0,
Source::Mock => package.price_huf,
Source::Mock | Source::Stripe => package.price_huf,
};
sqlx::query(
"INSERT INTO package_orders (id, user_id, package, source, price_huf, note, created_by) \
+9 -1
View File
@@ -77,6 +77,9 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/me/export", get(account::export))
.route("/v1/credits", get(account::credits))
.route("/v1/payments/mock", post(payments::mock))
.route("/v1/payments/checkout", post(payments::checkout))
.route("/v1/payments/checkout/{id}", get(payments::checkout_status))
.route("/v1/payments/stripe/webhook", post(payments::stripe_webhook))
// charts
.route("/v1/charts", get(charts::list).post(charts::create))
.route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove))
@@ -161,7 +164,12 @@ async fn public_config(State(state): St) -> Json<Value> {
"google_login": { "enabled": state.google.enabled(), "client_id": c.google_client_ids.first() },
"locales": c.supported_locales,
"password_login": c.password_login,
"mock_payments": c.mock_payments,
"mock_payments": payments::method(c) == Some("mock"),
// "stripe", "mock" or null; Stripe purchases are for admins only
// until PURCHASES_OPEN (and always with a test key).
"payments": payments::method(c),
"payments_admins_only": payments::admins_only(c),
"payments_test": c.stripe.as_ref().is_some_and(|s| s.test_mode()),
"user_invites": c.user_invites,
"referral_rewards": c.referral_rewards,
"signup_mode": c.signup_mode.as_str(),
+189 -6
View File
@@ -1,19 +1,27 @@
//! Packages and payments. Until Stripe is connected, `MOCK_PAYMENTS=true`
//! turns on a stand-in: "paying" grants the package right away, so the paid
//! flow can be used end to end.
//! Packages and payments. With `STRIPE_SECRET_KEY` a package is paid on
//! Stripe's hosted Checkout page and granted when Stripe confirms the payment
//! (webhook, or the return page asking). Without it `MOCK_PAYMENTS=true`
//! turns on a stand-in: "paying" grants the package right away.
use axum::Json;
use axum::extract::State;
use axum::body::Bytes;
use axum::extract::{Path, State};
use axum::http::HeaderMap;
use axum_extra::extract::WithRejection;
use db::Role;
use serde::Deserialize;
use serde_json::{Value, json};
use time::OffsetDateTime;
use uuid::Uuid;
use super::{Body, St};
use crate::AppState;
use crate::auth::AuthUser;
use crate::config::StripeConfig;
use crate::credits::{self, Unit};
use crate::error::{ApiError, ApiResult};
use crate::packages::{self, CATALOG, Source};
use crate::persons;
use crate::{persons, stripe};
/// The package catalog (public).
pub async fn catalog() -> Json<Value> {
@@ -46,7 +54,7 @@ pub async fn mock(
auth: AuthUser,
WithRejection(Json(req), _): Body<MockPayment>,
) -> ApiResult<Json<Value>> {
if !state.config.mock_payments {
if !state.config.mock_payments || state.config.stripe.is_some() {
return Err(ApiError::NotFound("payment method"));
}
let id = match (req.package.as_deref(), req.unit) {
@@ -65,3 +73,178 @@ pub async fn mock(
tracing::info!(user = %auth.id(), package = package.id, "mock payment");
Ok(Json(holdings(&state, &auth).await?))
}
/// How the frontend should offer purchases: `"stripe"`, `"mock"` or `None`
/// (no purchases).
pub fn method(config: &crate::config::Config) -> Option<&'static str> {
match (&config.stripe, config.mock_payments) {
(Some(_), _) => Some("stripe"),
(None, true) => Some("mock"),
(None, false) => None,
}
}
/// Only admins can buy through Stripe: until purchases open, and always with a
/// test key (nobody gets packages with Stripe's test cards, nobody types a
/// real card into a test page).
pub fn admins_only(config: &crate::config::Config) -> bool {
!config.purchases_open || config.stripe.as_ref().is_some_and(StripeConfig::test_mode)
}
/// Stripe, if this user may pay through it.
fn stripe_for<'a>(state: &'a AppState, auth: &AuthUser) -> Result<&'a StripeConfig, ApiError> {
let config = state.config.stripe.as_ref().ok_or(ApiError::NotFound("payment method"))?;
if admins_only(&state.config) && !auth.user.has_role(Role::Admin) {
return Err(ApiError::Forbidden("purchases are being tested; they open soon".into()));
}
Ok(config)
}
/// The page to come back to after paying: a plain path of this site, without
/// its query (anything else: the packages page).
fn return_path(path: Option<&str>) -> String {
let path = path.unwrap_or("").split(['?', '#']).next().unwrap_or("");
let plain = path.starts_with('/')
&& !path.starts_with("//")
&& path.len() <= 200
&& path.chars().all(|c| c.is_ascii_alphanumeric() || "/-_.".contains(c));
if plain { path.to_string() } else { "/csomagok".to_string() }
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CheckoutRequest {
package: String,
/// The page the purchase started on (default: the packages page).
return_path: Option<String>,
}
/// Starts paying for a package: returns the address of Stripe's payment page.
pub async fn checkout(
State(state): St,
auth: AuthUser,
WithRejection(Json(req), _): Body<CheckoutRequest>,
) -> ApiResult<Json<Value>> {
let config = stripe_for(&state, &auth)?;
let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?;
let back = format!("{}{}", state.config.public_base_url, return_path(req.return_path.as_deref()));
let field = |k: &str, v: &str| (k.to_string(), v.to_string());
let form = vec![
field("mode", "payment"),
field("locale", "hu"),
field("client_reference_id", &auth.id().to_string()),
field("customer_email", &auth.user.email),
// Name and address go on the invoice.
field("billing_address_collection", "required"),
field("line_items[0][quantity]", "1"),
field("line_items[0][price_data][currency]", "huf"),
// Stripe counts forints in fillér.
field("line_items[0][price_data][unit_amount]", &(package.price_huf * 100).to_string()),
field("line_items[0][price_data][product_data][name]", &format!("Sorsfonalak – {}", package.name)),
field("line_items[0][price_data][product_data][description]", package.tagline),
field("metadata[package]", package.id),
field("metadata[user_id]", &auth.id().to_string()),
field("payment_intent_data[description]", &format!("Sorsfonalak – {}", package.name)),
field("payment_intent_data[metadata][package]", package.id),
field("success_url", &format!("{back}?fizetes={{CHECKOUT_SESSION_ID}}")),
field("cancel_url", &format!("{back}?fizetes=megszakitva")),
];
let session = state.stripe.create_session(config, &form).await?;
let url = session.url.ok_or_else(|| ApiError::Internal(format!("checkout session {} has no url", session.id)))?;
sqlx::query("INSERT INTO stripe_checkouts (id, user_id, package, price_huf, live) VALUES ($1, $2, $3, $4, $5)")
.bind(&session.id)
.bind(auth.id())
.bind(package.id)
.bind(package.price_huf as i32)
.bind(!config.test_mode())
.execute(&state.db)
.await?;
tracing::info!(user = %auth.id(), package = package.id, session = %session.id, "checkout started");
Ok(Json(json!({ "url": url })))
}
/// Grants the package of a paid session, once. `false`: not our session.
async fn complete(state: &AppState, session_id: &str) -> Result<bool, ApiError> {
let mut tx = state.db.begin().await?;
let row: Option<(Uuid, String, Option<OffsetDateTime>)> =
sqlx::query_as("SELECT user_id, package, completed_at FROM stripe_checkouts WHERE id = $1 FOR UPDATE")
.bind(session_id)
.fetch_optional(&mut *tx)
.await?;
let Some((user_id, package_id, completed_at)) = row else { return Ok(false) };
if completed_at.is_some() {
return Ok(true);
}
let package =
packages::find(&package_id).ok_or_else(|| ApiError::Internal(format!("unknown package {package_id}")))?;
let note = format!("Stripe {session_id}");
let order = packages::grant(&mut tx, user_id, package, Source::Stripe, Some(user_id), Some(&note)).await?;
sqlx::query("UPDATE stripe_checkouts SET completed_at = now(), order_id = $2 WHERE id = $1")
.bind(session_id)
.bind(order)
.execute(&mut *tx)
.await?;
tx.commit().await?;
tracing::info!(user = %user_id, package = package.id, session = session_id, "package paid");
Ok(true)
}
/// Where a payment stands (the return page asks until it is paid). If the
/// webhook has not arrived yet, Stripe is asked directly.
pub async fn checkout_status(
State(state): St,
auth: AuthUser,
WithRejection(Path(id), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<Json<Value>> {
let row: Option<(String, Option<OffsetDateTime>)> =
sqlx::query_as("SELECT package, completed_at FROM stripe_checkouts WHERE id = $1 AND user_id = $2")
.bind(&id)
.bind(auth.id())
.fetch_optional(&state.db)
.await?;
let (package_id, completed_at) = row.ok_or(ApiError::NotFound("payment"))?;
let mut status = if completed_at.is_some() { "paid" } else { "pending" };
if let (None, Some(config)) = (completed_at, &state.config.stripe) {
let session = state.stripe.get_session(config, &id).await?;
if session.paid() {
complete(&state, &id).await?;
status = "paid";
} else if session.status.as_deref() == Some("expired") {
status = "expired";
}
}
Ok(Json(json!({
"status": status,
"package": package_id,
"name": packages::find(&package_id).map(|p| p.name),
})))
}
/// Stripe's webhook (Developers → Webhooks; event `checkout.session.completed`,
/// for delayed methods also `checkout.session.async_payment_succeeded`).
pub async fn stripe_webhook(State(state): St, headers: HeaderMap, body: Bytes) -> ApiResult<Json<Value>> {
let secret = state
.config
.stripe
.as_ref()
.and_then(|c| c.webhook_secret.as_deref())
.ok_or(ApiError::NotFound("payment method"))?;
let signature = headers.get("stripe-signature").and_then(|v| v.to_str().ok()).unwrap_or("");
let now = OffsetDateTime::now_utc().unix_timestamp();
if !stripe::verify_signature(secret, signature, &body, now) {
tracing::warn!("stripe webhook with a bad signature");
return Err(ApiError::BadRequest("invalid signature".into()));
}
let event: Value = serde_json::from_slice(&body).map_err(|e| ApiError::BadRequest(e.to_string()))?;
let kind = event["type"].as_str().unwrap_or_default();
let session = &event["data"]["object"];
if matches!(kind, "checkout.session.completed" | "checkout.session.async_payment_succeeded")
&& session["payment_status"] == "paid"
{
let id = session["id"].as_str().unwrap_or_default();
if !complete(&state, id).await? {
tracing::warn!(session = id, "stripe webhook for a session we did not start");
}
}
Ok(Json(json!({ "received": true })))
}
+157
View File
@@ -0,0 +1,157 @@
//! The little of Stripe's API we use: Checkout Sessions (a hosted payment
//! page for one package) and webhook signature checking. The package catalog
//! stays in `packages.rs`; each session carries its name and price, so no
//! products have to be kept in the Stripe dashboard.
use std::time::Duration;
use hmac::{Hmac, Mac};
use serde::Deserialize;
use sha2::Sha256;
use crate::config::StripeConfig;
use crate::error::ApiError;
/// How old a webhook signature may be (Stripe's own libraries use 5 minutes).
const SIGNATURE_TOLERANCE: i64 = 300;
#[derive(Debug, Deserialize)]
pub struct Session {
pub id: String,
/// The payment page (only while the session is open).
pub url: Option<String>,
/// `paid`, `unpaid` or `no_payment_required`.
pub payment_status: String,
/// `open`, `complete` or `expired`.
pub status: Option<String>,
}
impl Session {
pub fn paid(&self) -> bool {
self.payment_status == "paid"
}
}
pub struct Client {
http: reqwest::Client,
}
impl Default for Client {
fn default() -> Self {
let http = reqwest::Client::builder().timeout(Duration::from_secs(20)).build().expect("static configuration");
Self { http }
}
}
/// What the user sees when Stripe cannot be reached.
fn unavailable(detail: String) -> ApiError {
tracing::error!(error = %detail, "stripe request failed");
ApiError::Limited {
code: "payment_unavailable",
message: "A fizetési oldal most nem érhető el. Próbáld újra pár perc múlva.".into(),
}
}
impl Client {
/// Creates a Checkout Session from form fields (Stripe's API takes
/// `application/x-www-form-urlencoded` with `a[b][c]` keys).
pub async fn create_session(&self, config: &StripeConfig, form: &[(String, String)]) -> Result<Session, ApiError> {
let res = self
.http
.post(format!("{}/v1/checkout/sessions", config.api_url))
.bearer_auth(&config.secret_key)
.form(form)
.send()
.await
.map_err(|e| unavailable(e.to_string()))?;
Self::session(res).await
}
pub async fn get_session(&self, config: &StripeConfig, id: &str) -> Result<Session, ApiError> {
let res = self
.http
.get(format!("{}/v1/checkout/sessions/{id}", config.api_url))
.bearer_auth(&config.secret_key)
.send()
.await
.map_err(|e| unavailable(e.to_string()))?;
Self::session(res).await
}
async fn session(res: reqwest::Response) -> Result<Session, ApiError> {
let status = res.status();
if !status.is_success() {
let body = res.text().await.unwrap_or_default();
return Err(unavailable(format!("HTTP {status}: {}", body.chars().take(500).collect::<String>())));
}
res.json().await.map_err(|e| unavailable(format!("unexpected response: {e}")))
}
}
/// Checks a `Stripe-Signature` header (`t=…,v1=…[,v1=…]`): an HMAC-SHA256 of
/// `"{t}.{body}"` with the endpoint's signing secret, at most five minutes old.
pub fn verify_signature(secret: &str, header: &str, body: &[u8], now: i64) -> bool {
let mut timestamp = None;
let mut signatures = Vec::new();
for part in header.split(',') {
match part.trim().split_once('=') {
Some(("t", v)) => timestamp = v.parse::<i64>().ok(),
Some(("v1", v)) => signatures.push(v),
_ => {}
}
}
let Some(timestamp) = timestamp else { return false };
if (now - timestamp).abs() > SIGNATURE_TOLERANCE {
return false;
}
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC takes any key length");
mac.update(timestamp.to_string().as_bytes());
mac.update(b".");
mac.update(body);
let expected = mac.finalize().into_bytes();
signatures.iter().any(|s| decode_hex(s).is_some_and(|sig| constant_time_eq(&sig, &expected)))
}
/// The signature header for a body, as Stripe would send it (tests).
#[cfg(test)]
pub fn sign(secret: &str, body: &[u8], timestamp: i64) -> String {
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
mac.update(format!("{timestamp}.").as_bytes());
mac.update(body);
let hex: String = mac.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect();
format!("t={timestamp},v1={hex}")
}
fn decode_hex(s: &str) -> Option<Vec<u8>> {
if !s.len().is_multiple_of(2) {
return None;
}
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect()
}
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn signatures_are_checked() {
let body = br#"{"id":"evt_1"}"#;
let now = 1_800_000_000;
let header = sign("whsec_test", body, now);
assert!(verify_signature("whsec_test", &header, body, now));
assert!(verify_signature("whsec_test", &header, body, now + 299));
// Another secret, a changed body, an old or missing timestamp.
assert!(!verify_signature("whsec_other", &header, body, now));
assert!(!verify_signature("whsec_test", &header, br#"{"id":"evt_2"}"#, now));
assert!(!verify_signature("whsec_test", &header, body, now + 301));
assert!(!verify_signature("whsec_test", header.split_once(',').unwrap().1, body, now));
// One good signature among others (during a secret rotation) is enough.
let rotated = format!("{header},v1=00ff");
assert!(verify_signature("whsec_test", &rotated, body, now));
assert!(!verify_signature("whsec_test", "t=1800000000,v1=zz", body, now));
}
}
+195 -1
View File
@@ -111,9 +111,54 @@ async fn fake_openrouter_models() -> Json<Value> {
]}))
}
/// Checkout sessions the fake Stripe created: form fields and whether paid.
type FakeSessions = std::sync::Mutex<std::collections::HashMap<String, (Vec<(String, String)>, bool)>>;
static STRIPE_SESSIONS: std::sync::LazyLock<FakeSessions> = std::sync::LazyLock::new(Default::default);
static STRIPE_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
fn stripe_form(id: &str, key: &str) -> Option<String> {
let sessions = STRIPE_SESSIONS.lock().unwrap();
sessions.get(id)?.0.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone())
}
fn stripe_pay(id: &str) {
STRIPE_SESSIONS.lock().unwrap().get_mut(id).unwrap().1 = true;
}
async fn fake_stripe_create(
headers: HeaderMap,
axum::Form(form): axum::Form<Vec<(String, String)>>,
) -> (StatusCode, Json<Value>) {
if headers.get("authorization").and_then(|v| v.to_str().ok()) != Some("Bearer sk_live_fake") {
return (StatusCode::UNAUTHORIZED, Json(json!({"error": {"message": "bad key"}})));
}
let id = format!("cs_fake_{}", STRIPE_IDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
STRIPE_SESSIONS.lock().unwrap().insert(id.clone(), (form, false));
(
StatusCode::OK,
Json(
json!({"id": id, "url": format!("https://checkout.stripe.test/{id}"), "payment_status": "unpaid", "status": "open"}),
),
)
}
async fn fake_stripe_get(axum::extract::Path(id): axum::extract::Path<String>) -> (StatusCode, Json<Value>) {
match STRIPE_SESSIONS.lock().unwrap().get(&id) {
Some((_, paid)) => (
StatusCode::OK,
Json(json!({"id": id, "url": null,
"payment_status": if *paid { "paid" } else { "unpaid" },
"status": if *paid { "complete" } else { "open" }})),
),
None => (StatusCode::NOT_FOUND, Json(json!({"error": {"message": "no such session"}}))),
}
}
async fn fake_services() -> String {
let app = Router::new()
.route("/openrouter/models", get(fake_openrouter_models))
.route("/v1/checkout/sessions", post(fake_stripe_create))
.route("/v1/checkout/sessions/{id}", get(fake_stripe_get))
.route("/v1/natal", post(fake_natal))
.route("/v1/synastry", post(fake_synastry))
.route("/v1/forecast", post(fake_forecast))
@@ -782,8 +827,10 @@ async fn export_and_delete_account(pool: PgPool) {
/// config and catalog, shared links, invitation pages, the waitlist and
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
/// logged-in user, so other apps cannot use them.
const PUBLIC_ROUTES: [&str; 15] = [
const PUBLIC_ROUTES: [&str; 16] = [
"/healthz",
// Stripe calls it; the signature proves it.
"/v1/payments/stripe/webhook",
"/v1/config",
"/v1/packages",
"/v1/auth/register",
@@ -2207,3 +2254,150 @@ async fn a_new_user_from_a_shared_link_earns_an_analysis(pool: PgPool) {
.unwrap();
assert_eq!(count, 0);
}
fn with_stripe(config: &mut Config, key: &str) {
config.stripe = Some(crate::config::StripeConfig {
secret_key: key.into(),
webhook_secret: Some("whsec_fake".into()),
api_url: config.horoscope_api_url.clone(),
});
}
async fn stripe_orders(pool: &PgPool, email: &str) -> Vec<(String, i32)> {
sqlx::query_as(
"SELECT o.package, o.price_huf FROM package_orders o JOIN users u ON u.id = o.user_id \
WHERE u.email = $1 AND o.source = 'stripe' ORDER BY o.created_at",
)
.bind(email)
.fetch_all(pool)
.await
.unwrap()
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) {
let app = TestApp::with_config(pool, |c| with_stripe(c, "sk_live_fake")).await;
let r = app.get("/v1/config", None).await;
assert_eq!(r.body["payments"], "stripe");
assert_eq!(r.body["payments_test"], false);
// Stripe replaces the stand-in payment.
assert_eq!(r.body["mock_payments"], false);
let anna = app.register("anna@example.com", "Anna").await;
let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "couple"})).await;
assert_eq!(r.status, StatusCode::NOT_FOUND);
let r = app.post("/v1/payments/checkout", Some(&anna), json!({"package": "nincs"})).await;
assert_eq!(r.status, StatusCode::NOT_FOUND);
let r = app
.post("/v1/payments/checkout", Some(&anna), json!({"package": "couple", "return_path": "/kepletek/abc?x=1"}))
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let url = r.body["url"].as_str().unwrap();
let id = url.rsplit('/').next().unwrap().to_string();
assert_eq!(stripe_form(&id, "line_items[0][price_data][currency]").as_deref(), Some("huf"));
assert_eq!(stripe_form(&id, "line_items[0][price_data][unit_amount]").as_deref(), Some("600000"));
assert_eq!(
stripe_form(&id, "line_items[0][price_data][product_data][name]").as_deref(),
Some("Sorsfonalak – Páros")
);
assert_eq!(stripe_form(&id, "customer_email").as_deref(), Some("anna@example.com"));
assert_eq!(
stripe_form(&id, "success_url").as_deref(),
Some("https://sorsfonalak.test/kepletek/abc?fizetes={CHECKOUT_SESSION_ID}")
);
// Only paths of this site to come back to.
let r = app
.post("/v1/payments/checkout", Some(&anna), json!({"package": "single", "return_path": "//evil.example/x"}))
.await;
let other = r.body["url"].as_str().unwrap().rsplit('/').next().unwrap().to_string();
assert_eq!(
stripe_form(&other, "cancel_url").as_deref(),
Some("https://sorsfonalak.test/csomagok?fizetes=megszakitva")
);
// Not paid yet: nothing granted.
let r = app.get(&format!("/v1/payments/checkout/{id}"), Some(&anna)).await;
assert_eq!(r.body["status"], "pending", "{}", r.body);
assert!(stripe_orders(&app.pool, "anna@example.com").await.is_empty());
// Someone else's payment is not found.
let bela = app.register("bela@example.com", "Béla").await;
let r = app.get(&format!("/v1/payments/checkout/{id}"), Some(&bela)).await;
assert_eq!(r.status, StatusCode::NOT_FOUND);
// The webhook: a bad signature is refused, a good one grants the package,
// and Stripe's retries do not grant it again.
let event = json!({"id": "evt_1", "type": "checkout.session.completed",
"data": {"object": {"id": id, "payment_status": "paid"}}});
let body = event.to_string();
let now = time::OffsetDateTime::now_utc().unix_timestamp();
let bad = crate::stripe::sign("whsec_other", body.as_bytes(), now);
let r = app
.call_with("POST", "/v1/payments/stripe/webhook", None, Some(event.clone()), &[("stripe-signature", &bad)])
.await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
assert!(stripe_orders(&app.pool, "anna@example.com").await.is_empty());
let good = crate::stripe::sign("whsec_fake", body.as_bytes(), now);
for _ in 0..2 {
let r = app
.call_with("POST", "/v1/payments/stripe/webhook", None, Some(event.clone()), &[("stripe-signature", &good)])
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
}
assert_eq!(stripe_orders(&app.pool, "anna@example.com").await, vec![("couple".to_string(), 6000)]);
let r = app.get(&format!("/v1/payments/checkout/{id}"), Some(&anna)).await;
assert_eq!(r.body["status"], "paid");
assert_eq!(r.body["name"], "Páros");
let r = app.get("/v1/me", Some(&anna)).await;
assert_eq!(r.status, StatusCode::OK);
// A session we did not start is ignored.
let stray = json!({"type": "checkout.session.completed", "data": {"object": {"id": "cs_unknown", "payment_status": "paid"}}});
let sig = crate::stripe::sign("whsec_fake", stray.to_string().as_bytes(), now);
let r =
app.call_with("POST", "/v1/payments/stripe/webhook", None, Some(stray), &[("stripe-signature", &sig)]).await;
assert_eq!(r.status, StatusCode::OK);
// Without the webhook (late or not set up) the return page asks Stripe.
stripe_pay(&other);
let r = app.get(&format!("/v1/payments/checkout/{other}"), Some(&anna)).await;
assert_eq!(r.body["status"], "paid", "{}", r.body);
let r = app.get(&format!("/v1/payments/checkout/{other}"), Some(&anna)).await;
assert_eq!(r.body["status"], "paid");
assert_eq!(
stripe_orders(&app.pool, "anna@example.com").await,
vec![("couple".to_string(), 6000), ("single".to_string(), 2000)]
);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn stripe_test_mode_is_for_admins_only(pool: PgPool) {
let app = TestApp::with_config(pool, |c| with_stripe(c, "sk_test_fake")).await;
let r = app.get("/v1/config", None).await;
assert_eq!(r.body["payments"], "stripe");
assert_eq!(r.body["payments_test"], true);
assert_eq!(r.body["payments_admins_only"], true);
let anna = app.register("anna@example.com", "Anna").await;
let r = app.post("/v1/payments/checkout", Some(&anna), json!({"package": "single"})).await;
assert_eq!(r.status, StatusCode::FORBIDDEN);
// The admin gets as far as Stripe (the fake one only knows the live key).
let admin = app.register("admin@example.com", "Admin").await;
let r = app.post("/v1/payments/checkout", Some(&admin), json!({"package": "single"})).await;
assert_eq!(r.body["error"]["code"], "payment_unavailable", "{}", r.body);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn stripe_purchases_wait_for_the_opening(pool: PgPool) {
let app = TestApp::with_config(pool, |c| {
with_stripe(c, "sk_live_fake");
c.purchases_open = false;
})
.await;
let r = app.get("/v1/config", None).await;
assert_eq!((&r.body["payments_test"], &r.body["payments_admins_only"]), (&json!(false), &json!(true)));
let anna = app.register("anna@example.com", "Anna").await;
let r = app.post("/v1/payments/checkout", Some(&anna), json!({"package": "single"})).await;
assert_eq!(r.status, StatusCode::FORBIDDEN);
let admin = app.register("admin@example.com", "Admin").await;
let r = app.post("/v1/payments/checkout", Some(&admin), json!({"package": "single"})).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
}
@@ -6,7 +6,16 @@ import type { NextRequest } from "next/server";
import { BACKEND_URL } from "@/lib/server";
import { SHARES_TAG } from "@/lib/share";
const REQUEST_HEADERS = ["accept", "accept-language", "authorization", "content-type", "cookie", "user-agent"];
// stripe-signature: Stripe's webhook (the body is passed on byte for byte).
const REQUEST_HEADERS = [
"accept",
"accept-language",
"authorization",
"content-type",
"cookie",
"stripe-signature",
"user-agent",
];
// Hop-by-hop or re-computed by the runtime.
const SKIP_RESPONSE_HEADERS = new Set(["connection", "content-encoding", "content-length", "set-cookie", "transfer-encoding"]);
+2 -1
View File
@@ -3,6 +3,7 @@ import type { Metadata } from "next";
import { AiNote } from "@/components/AiNote";
import { PackageCards } from "@/components/PackageCards";
import { RedeemCode } from "@/components/RedeemCode";
import { payMethod } from "@/lib/payments";
import { backendGet, requireMe } from "@/lib/server";
import type { Package, PublicConfig } from "@/lib/types";
@@ -39,7 +40,7 @@ export default async function PackagesPage() {
backendGet<PublicConfig>("/v1/config"),
]);
const packages = catalog?.packages ?? [];
const canPay = config?.mock_payments ?? false;
const canPay = payMethod(config, me);
const left = me.analyses_left;
const slots = me.persons;
+9
View File
@@ -948,3 +948,12 @@ a.pair-row:hover strong { color: var(--gold); }
/* Chart page: below the wheel and the summary, the facts and the next steps side by side */
.chart-extras { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(300px, 100%), 1fr)); gap: 16px; align-items: stretch; }
.chart-extras > .card { margin: 0; }
/* Back from Stripe: the payment's result at the bottom of the screen. */
.pay-return { position: fixed; left: 50%; bottom: 20px; transform: translateX(-50%); z-index: 60; width: min(560px, calc(100% - 32px)); }
.pay-return .msg {
display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 0; padding: 14px 16px;
background: var(--panel-2); border: 1px solid var(--line); border-radius: 14px; box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
}
.pay-return .msg-ok { border-color: color-mix(in srgb, var(--ok) 55%, var(--line)); }
.pay-return .msg-error { border-color: color-mix(in srgb, var(--danger) 55%, var(--line)); }
@@ -6,6 +6,7 @@ import { ChartWheel } from "@/components/ChartWheel";
import { DetailedAnalysis } from "@/components/DetailedAnalysis";
import { ForecastKeys, ForecastTimeline, ForecastTransits, longDay } from "@/components/ForecastViews";
import { Tabs } from "@/components/Tabs";
import { payMethod } from "@/lib/payments";
import { backendGet, requireMe } from "@/lib/server";
import type { Analysis, Chart, ForecastDetail, ForecastList, PublicConfig } from "@/lib/types";
@@ -134,7 +135,7 @@ export default async function ForecastPage({
initial={detailed}
left={me.analyses_left.forecast}
isAdmin={me.user.roles.includes("admin")}
canPay={config?.mock_payments ?? false}
canPay={payMethod(config, me)}
questionsLeft={me.analyses_left.question ?? 0}
/>
),
@@ -10,6 +10,7 @@ import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
import { CompareButton } from "@/components/CompareButton";
import { Tabs } from "@/components/Tabs";
import { ASPECTS, ELEMENTS, MODALITIES, MOON_PHASES, countryName, formatBirthDate, pointName } from "@/lib/astro";
import { payMethod } from "@/lib/payments";
import { backendGet, requireMe } from "@/lib/server";
import type { Analysis, Chart, ChartListItem, PublicConfig } from "@/lib/types";
@@ -181,7 +182,7 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
initial={detailed}
left={me.analyses_left.natal}
isAdmin={me.user.roles.includes("admin")}
canPay={config?.mock_payments ?? false}
canPay={payMethod(config, me)}
questionsLeft={me.analyses_left.question ?? 0}
/>
),
+7
View File
@@ -1,6 +1,8 @@
import type { Metadata } from "next";
import { Cormorant_Garamond, Inter } from "next/font/google";
import { Suspense } from "react";
import { PaymentReturn } from "@/components/PaymentReturn";
import { SiteHeader } from "@/components/SiteHeader";
import { getMe } from "@/lib/server";
@@ -25,6 +27,11 @@ export default async function RootLayout({ children }: { children: React.ReactNo
<body>
{me && <SiteHeader me={me} />}
{children}
{me && (
<Suspense fallback={null}>
<PaymentReturn />
</Suspense>
)}
</body>
</html>
);
@@ -8,6 +8,7 @@ import { CompositeTables, CrossGrid, HouseOverlays, InterAspectList, NatureBar }
import { SynastryLegend, SynastryWheel } from "@/components/SynastryWheel";
import { Tabs } from "@/components/Tabs";
import { ASPECTS, formatBirthDate } from "@/lib/astro";
import { payMethod } from "@/lib/payments";
import { backendGet, requireMe } from "@/lib/server";
import { sideName, sideTimeKnown } from "@/lib/synastry";
import type { Analysis, ChartListItem, PublicConfig, Synastry, SynastrySide } from "@/lib/types";
@@ -127,7 +128,7 @@ export default async function ComparisonPage({ params }: { params: Promise<{ id:
initial={detailed}
left={me.analyses_left.synastry}
isAdmin={me.user.roles.includes("admin")}
canPay={config?.mock_payments ?? false}
canPay={payMethod(config, me)}
note={`Az elemzésben az első fél: ${name1}, a második fél: ${name2}.`}
questionsLeft={me.analyses_left.question ?? 0}
/>
+4 -1
View File
@@ -1,5 +1,7 @@
import type { MetadataRoute } from "next";
import { siteUrl } from "@/lib/share";
// AI crawlers that train models or answer from the site: they load pages
// far more often than visitors do. Link preview robots (Facebook, Messenger,
// Slack, WhatsApp, X, LinkedIn) stay allowed, they make the shared links work.
@@ -38,8 +40,9 @@ const AI_CRAWLERS = [
"Scrapy",
];
export default function robots(): MetadataRoute.Robots {
export default async function robots(): Promise<MetadataRoute.Robots> {
return {
sitemap: `${await siteUrl()}/sitemap.xml`,
rules: [
{ userAgent: AI_CRAWLERS, disallow: "/" },
// Logged-in pages redirect anyway; shared links carry noindex.
+15
View File
@@ -0,0 +1,15 @@
import type { MetadataRoute } from "next";
import { siteUrl } from "@/lib/share";
/** The public pages for search engines; everything else needs a login. */
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const base = await siteUrl();
const privacy = { languages: { hu: `${base}/adatvedelem`, en: `${base}/privacy` } };
return [
{ url: `${base}/`, changeFrequency: "weekly", priority: 1 },
{ url: `${base}/pelda`, changeFrequency: "monthly", priority: 0.8 },
{ url: `${base}/adatvedelem`, changeFrequency: "yearly", priority: 0.2, alternates: privacy },
{ url: `${base}/privacy`, changeFrequency: "yearly", priority: 0.2, alternates: privacy },
];
}
+2 -1
View File
@@ -5,6 +5,7 @@ import { ChartCard } from "@/components/ChartCard";
import { PersonActions } from "@/components/PersonActions";
import { PendingInvites } from "@/components/PendingInvites";
import { PersonPacks } from "@/components/PersonPacks";
import { payMethod } from "@/lib/payments";
import { backendGet, requireMe } from "@/lib/server";
import type { ChartListItem, PublicConfig } from "@/lib/types";
@@ -102,7 +103,7 @@ export default async function PersonsPage() {
? "Elfogytak a helyeid. Újabb személyhez válassz csomagot."
: "A felvett személyek képletét és elemzéseit itt éred el. Egy törölt személy helye nem szabadul fel."}
</p>
<PersonPacks canPay={config?.mock_payments ?? false} />
<PersonPacks canPay={payMethod(config, me)} />
</section>
)}
</main>
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { PersonPacks } from "@/components/PersonPacks";
import { payMethod } from "@/lib/payments";
import { backendGet, requireMe } from "@/lib/server";
import type { PublicConfig } from "@/lib/types";
@@ -31,7 +32,7 @@ export default async function NewPersonPage() {
full={
<>
<p className="muted">Elfogytak a helyeid. Újabb személyhez válassz csomagot, vagy hívd meg.</p>
<PersonPacks canPay={config?.mock_payments ?? false} />
<PersonPacks canPay={payMethod(config, me)} />
</>
}
/>
@@ -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} />;
}
+12
View File
@@ -0,0 +1,12 @@
import type { Me, PayMethod, PublicConfig } from "./types";
/**
* How this user can buy packages. Until purchases open (and with a Stripe
* test key) only admins can; everyone else sees "soon".
*/
export function payMethod(config: PublicConfig | null | undefined, me: Me): PayMethod | null {
if (config?.payments === "mock") return "mock";
if (config?.payments !== "stripe") return null;
if (config.payments_admins_only && !me.user.roles.includes("admin")) return null;
return config.payments_test ? "stripe_test" : "stripe";
}
+9
View File
@@ -92,6 +92,12 @@ export interface PublicConfig {
password_login: boolean;
password_min_length: number;
mock_payments: boolean;
/** How packages are paid: Stripe Checkout, the stand-in, or not at all. */
payments: "stripe" | "mock" | null;
/** Only admins can buy through Stripe (until the opening, and with a test key). */
payments_admins_only: boolean;
/** Stripe has a test key (test cards work, no real money). */
payments_test: boolean;
/** "invite": new accounts need an invitation. */
signup_mode: "invite" | "open";
/** Users may invite others (off until the launch; admins always may). */
@@ -573,3 +579,6 @@ export interface PersonInviteLanding {
status: "pending" | "accepted" | "expired";
expires_at: string;
}
/** How this user can buy a package; `null`: purchases are off. */
export type PayMethod = "stripe" | "stripe_test" | "mock";