diff --git a/Cargo.lock b/Cargo.lock index 7b8ca1f..e9b1a74 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -170,6 +170,7 @@ dependencies = [ "axum-extra", "db", "email-templates", + "hmac", "horoscope-client", "http-body-util", "jsonwebtoken", diff --git a/crates/db/migrations/0027_stripe_checkouts.sql b/crates/db/migrations/0027_stripe_checkouts.sql new file mode 100644 index 0000000..f7d2114 --- /dev/null +++ b/crates/db/migrations/0027_stripe_checkouts.sql @@ -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); diff --git a/deploy/README.md b/deploy/README.md index 00abbda..f871589 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -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) diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index b09292f..5380da2 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -85,8 +85,8 @@ 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} # Users inviting others ("Meghívom"): shown but off until the launch. USER_INVITES: ${USER_INVITES:-false} @@ -95,6 +95,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 diff --git a/docker-compose.yml b/docker-compose.yml index b8eb6bb..c037b26 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -58,6 +58,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 / 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 diff --git a/docs/csomagok.md b/docs/csomagok.md index 02be815..71b7afe 100644 --- a/docs/csomagok.md +++ b/docs/csomagok.md @@ -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). diff --git a/docs/fizetes.md b/docs/fizetes.md new file mode 100644 index 0000000..d3661b0 --- /dev/null +++ b/docs/fizetes.md @@ -0,0 +1,44 @@ +# 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=` 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_... +``` + +- **Teszt kulccsal (`sk_test_…`) csak az adminok vásárolhatnak**, a többieknek a gombok „Hamarosan” feliratúak maradnak; így senki nem jut csomaghoz a Stripe tesztkártyáival. Tesztkártya: `4242 4242 4242 4242`, bármilyen jövőbeli lejárat és CVC. +- Élő kulccsal (`sk_live_…`) mindenki vásárolhat. +- 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. diff --git a/services/backend/Cargo.toml b/services/backend/Cargo.toml index 28871b1..ba06e2d 100644 --- a/services/backend/Cargo.toml +++ b/services/backend/Cargo.toml @@ -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 diff --git a/services/backend/src/config.rs b/services/backend/src/config.rs index d9fbc77..ab6744d 100644 --- a/services/backend/src/config.rs +++ b/services/backend/src/config.rs @@ -45,6 +45,9 @@ 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`). With a test key only admins can buy. + pub stripe: Option, /// `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 +88,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, + 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 { std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty()) } @@ -127,6 +158,14 @@ 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(), + }), user_invites: parsed("USER_INVITES", false)?, referral_rewards: parsed("REFERRAL_REWARDS", false)?, google_client_ids: list("GOOGLE_CLIENT_IDS"), @@ -166,6 +205,7 @@ impl Config { session_ttl_days: 30, password_login: true, mock_payments: true, + stripe: None, user_invites: true, referral_rewards: true, google_client_ids: vec!["test-client.apps.googleusercontent.com".into()], diff --git a/services/backend/src/main.rs b/services/backend/src/main.rs index 38fb618..56cf9e3 100644 --- a/services/backend/src/main.rs +++ b/services/backend/src/main.rs @@ -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, } diff --git a/services/backend/src/packages.rs b/services/backend/src/packages.rs index 939a277..8511eec 100644 --- a/services/backend/src/packages.rs +++ b/services/backend/src/packages.rs @@ -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) \ diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index 915a04f..61030d2 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -77,6 +77,9 @@ pub fn router(state: Arc) -> 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,10 @@ async fn public_config(State(state): St) -> Json { "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; with a Stripe test key only admins can buy. + "payments": payments::method(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(), diff --git a/services/backend/src/routes/payments.rs b/services/backend/src/routes/payments.rs index 20a50cc..bea3c18 100644 --- a/services/backend/src/routes/payments.rs +++ b/services/backend/src/routes/payments.rs @@ -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 { @@ -46,7 +54,7 @@ pub async fn mock( auth: AuthUser, WithRejection(Json(req), _): Body, ) -> ApiResult> { - 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,172 @@ 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, + } +} + +/// Stripe, if this user may pay through it (with a test key: admins only, so +/// nobody gets packages with Stripe's test cards). +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 config.test_mode() && !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, +} + +/// 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, +) -> ApiResult> { + 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 { + let mut tx = state.db.begin().await?; + let row: Option<(Uuid, String, Option)> = + 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(¬e)).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, ApiError>, +) -> ApiResult> { + let row: Option<(String, Option)> = + 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> { + 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 }))) +} diff --git a/services/backend/src/stripe.rs b/services/backend/src/stripe.rs new file mode 100644 index 0000000..98f6439 --- /dev/null +++ b/services/backend/src/stripe.rs @@ -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, + /// `paid`, `unpaid` or `no_payment_required`. + pub payment_status: String, + /// `open`, `complete` or `expired`. + pub status: Option, +} + +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 { + 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 { + 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 { + 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::()))); + } + 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::().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::::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::::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> { + 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)); + } +} diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index a6aa502..6948038 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -111,9 +111,54 @@ async fn fake_openrouter_models() -> Json { ]})) } +/// Checkout sessions the fake Stripe created: form fields and whether paid. +type FakeSessions = std::sync::Mutex, bool)>>; +static STRIPE_SESSIONS: std::sync::LazyLock = 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 { + 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>, +) -> (StatusCode, Json) { + 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) -> (StatusCode, Json) { + 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,132 @@ 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); + 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); +} diff --git a/services/frontend/src/app/api/v1/[...path]/route.ts b/services/frontend/src/app/api/v1/[...path]/route.ts index 8661709..158ee61 100644 --- a/services/frontend/src/app/api/v1/[...path]/route.ts +++ b/services/frontend/src/app/api/v1/[...path]/route.ts @@ -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"]); diff --git a/services/frontend/src/app/csomagok/page.tsx b/services/frontend/src/app/csomagok/page.tsx index 62b539a..dc42293 100644 --- a/services/frontend/src/app/csomagok/page.tsx +++ b/services/frontend/src/app/csomagok/page.tsx @@ -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("/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; diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css index eaf9460..0770685 100644 --- a/services/frontend/src/app/globals.css +++ b/services/frontend/src/app/globals.css @@ -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)); } diff --git a/services/frontend/src/app/kepletek/[id]/elorejelzes/page.tsx b/services/frontend/src/app/kepletek/[id]/elorejelzes/page.tsx index 03bf54e..d389fc4 100644 --- a/services/frontend/src/app/kepletek/[id]/elorejelzes/page.tsx +++ b/services/frontend/src/app/kepletek/[id]/elorejelzes/page.tsx @@ -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} /> ), diff --git a/services/frontend/src/app/kepletek/[id]/page.tsx b/services/frontend/src/app/kepletek/[id]/page.tsx index 295e569..0d46824 100644 --- a/services/frontend/src/app/kepletek/[id]/page.tsx +++ b/services/frontend/src/app/kepletek/[id]/page.tsx @@ -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} /> ), diff --git a/services/frontend/src/app/layout.tsx b/services/frontend/src/app/layout.tsx index a382e00..c452c83 100644 --- a/services/frontend/src/app/layout.tsx +++ b/services/frontend/src/app/layout.tsx @@ -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 {me && } {children} + {me && ( + + + + )} ); diff --git a/services/frontend/src/app/osszevetesek/[id]/page.tsx b/services/frontend/src/app/osszevetesek/[id]/page.tsx index 379244e..db69cea 100644 --- a/services/frontend/src/app/osszevetesek/[id]/page.tsx +++ b/services/frontend/src/app/osszevetesek/[id]/page.tsx @@ -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} /> diff --git a/services/frontend/src/app/szemelyek/page.tsx b/services/frontend/src/app/szemelyek/page.tsx index 4cd9fe1..0322d6e 100644 --- a/services/frontend/src/app/szemelyek/page.tsx +++ b/services/frontend/src/app/szemelyek/page.tsx @@ -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."}

- + )} diff --git a/services/frontend/src/app/szemelyek/uj/page.tsx b/services/frontend/src/app/szemelyek/uj/page.tsx index 05d0fe6..d9ca428 100644 --- a/services/frontend/src/app/szemelyek/uj/page.tsx +++ b/services/frontend/src/app/szemelyek/uj/page.tsx @@ -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={ <>

Elfogytak a helyeid. Újabb személyhez válassz csomagot, vagy hívd meg.

- + } /> diff --git a/services/frontend/src/components/AnalysisQuestions.tsx b/services/frontend/src/components/AnalysisQuestions.tsx index b06aef5..cb1b5a8 100644 --- a/services/frontend/src/components/AnalysisQuestions.tsx +++ b/services/frontend/src/components/AnalysisQuestions.tsx @@ -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"; }) { diff --git a/services/frontend/src/components/DetailedAnalysis.tsx b/services/frontend/src/components/DetailedAnalysis.tsx index 6dfe4e0..5698a8d 100644 --- a/services/frontend/src/components/DetailedAnalysis.tsx +++ b/services/frontend/src/components/DetailedAnalysis.tsx @@ -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" ? (

- 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.

diff --git a/services/frontend/src/components/PackageCards.tsx b/services/frontend/src/components/PackageCards.tsx index 721dca1..6017449 100644 --- a/services/frontend/src/components/PackageCards.tsx +++ b/services/frontend/src/components/PackageCards.tsx @@ -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; }) { const router = useRouter(); const [busy, setBusy] = useState(null); const [error, setError] = useState(null); const [done, setDone] = useState(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"} ) : (
); } @@ -154,7 +183,7 @@ export function PackageChooser({ onBought, }: { ids: string[]; - canPay: boolean; + canPay: PayMethod | null; onBought?: (p: Package) => Promise | void; }) { const packages = usePackages(); diff --git a/services/frontend/src/components/PaymentReturn.tsx b/services/frontend/src/components/PaymentReturn.tsx new file mode 100644 index 0000000..a5d6bef --- /dev/null +++ b/services/frontend/src/components/PaymentReturn.tsx @@ -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=` 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(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 ( +
+

+ {notice.text} + {notice.kind !== "wait" && ( + + )} +

+
+ ); +} diff --git a/services/frontend/src/components/PersonPacks.tsx b/services/frontend/src/components/PersonPacks.tsx index 1177b05..0fe30d3 100644 --- a/services/frontend/src/components/PersonPacks.tsx +++ b/services/frontend/src/components/PersonPacks.tsx @@ -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 ; } diff --git a/services/frontend/src/lib/payments.ts b/services/frontend/src/lib/payments.ts new file mode 100644 index 0000000..d88f371 --- /dev/null +++ b/services/frontend/src/lib/payments.ts @@ -0,0 +1,9 @@ +import type { Me, PayMethod, PublicConfig } from "./types"; + +/** How this user can buy packages (with a Stripe test key: admins only). */ +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_test) return "stripe"; + return me.user.roles.includes("admin") ? "stripe_test" : null; +} diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts index e74b3e1..ce53995 100644 --- a/services/frontend/src/lib/types.ts +++ b/services/frontend/src/lib/types.ts @@ -92,6 +92,10 @@ 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; + /** Stripe has a test key: only admins can buy. */ + 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 +577,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";