//! 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::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::{invoices, persons, stripe}; /// The package catalog (public). pub async fn catalog() -> Json { Json(json!({ "packages": CATALOG.iter().map(packages::Package::view).collect::>() })) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct MockPayment { /// A package id from the catalog. package: Option, /// Shorthand: the cheapest package with one unit of this kind. unit: Option, } /// What the user has now: units left and person slots. pub async fn holdings(state: &crate::AppState, auth: &AuthUser) -> Result { let mut conn = state.db.acquire().await?; let balance = credits::balance(&mut conn, auth.id()).await?; let persons = persons::slots(&mut conn, auth, state.config.free_person_slots).await?; Ok(json!({ "analyses_left": balance.view(), "persons": persons.view(), })) } /// Grants a package as a (pretend) purchase. pub async fn mock( State(state): St, auth: AuthUser, WithRejection(Json(req), _): Body, ) -> ApiResult> { 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) { (Some(id), None) => id, (None, Some(Unit::Natal)) => "single", (None, Some(Unit::Synastry)) => "addon_synastry", (None, Some(Unit::Forecast)) => "addon_forecast", (None, Some(Unit::Person)) => "addon_persons", (None, Some(Unit::Question)) => "addon_questions", (None, Some(Unit::Tarot)) => "addon_tarot", _ => return Err(ApiError::BadRequest("give either package or unit".into())), }; let package = packages::find(id).ok_or(ApiError::NotFound("package"))?; let mut tx = state.db.begin().await?; packages::grant(&mut tx, auth.id(), package, Source::Mock, Some(auth.id()), Some("mock payment")).await?; tx.commit().await?; 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, } } /// The terms (ÁSZF) version a purchase accepts; the frontend's `TERMS_UPDATED`. pub const TERMS_VERSION: &str = "2026-11-20"; /// 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, } /// 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 mut 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; a company also gives its name // and tax number ("I'm buying as a business"). field("billing_address_collection", "required"), field("tax_id_collection[enabled]", "true"), field("customer_creation", "always"), 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")), ]; if state.config.terms_consent { // Every purchase accepts the terms and asks for immediate delivery, // giving up the 14-day withdrawal right (45/2014. Korm. rendelet 29. §). // Stripe needs the terms URL in its dashboard (Public details) for this. form.push(field("consent_collection[terms_of_service]", "required")); form.push(field( "custom_text[terms_of_service_acceptance][message]", &format!( "Elfogadom az [ÁSZF-et]({}/aszf), kérem a szolgáltatás azonnali megkezdését, és tudomásul veszem, \ hogy ezzel elveszítem a 14 napos elállási jogomat.", state.config.public_base_url ), )); } 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 }))) } /// Records a paid session (what was charged, the buyer's billing details), /// grants its package and queues the invoice, once. `false`: not our session. async fn complete(state: &AppState, session: &stripe::Session) -> Result { let mut tx = state.db.begin().await?; type Checkout = (Option, String, i32, Option); let row: Option = sqlx::query_as( "SELECT user_id, package, price_huf, completed_at FROM stripe_checkouts WHERE id = $1 FOR UPDATE", ) .bind(&session.id) .fetch_optional(&mut *tx) .await?; let Some((user_id, package_id, price_huf, completed_at)) = row else { return Ok(false) }; if completed_at.is_some() { return Ok(true); } let amount_huf = session.amount_total.map(|minor| minor / 100); if amount_huf != Some(i64::from(price_huf)) || session.currency.as_deref() != Some("huf") { tracing::error!(session = %session.id, ?amount_huf, currency = ?session.currency, price_huf, "paid amount differs from the price"); } let package = packages::find(&package_id).ok_or_else(|| ApiError::Internal(format!("unknown package {package_id}")))?; // A deleted account still gets its invoice, but no package. let order = match user_id { Some(user_id) => { let note = format!("Stripe {}", session.id); Some(packages::grant(&mut tx, user_id, package, Source::Stripe, Some(user_id), Some(¬e)).await?) } None => None, }; if state.config.terms_consent && !session.terms_accepted() { tracing::warn!(session = %session.id, "paid without the terms consent"); } sqlx::query( "UPDATE stripe_checkouts SET completed_at = now(), order_id = $2, payment_intent = $3, amount_huf = $4, \ customer = $5, terms_accepted_at = CASE WHEN $6 THEN now() END, terms_version = CASE WHEN $6 THEN $7 END \ WHERE id = $1", ) .bind(&session.id) .bind(order) .bind(&session.payment_intent) .bind(amount_huf.map(|a| a as i32)) .bind(&session.customer_details) .bind(session.terms_accepted()) .bind(TERMS_VERSION) .execute(&mut *tx) .await?; // The confirmation confirms the withdrawal waiver: only when it was given. if session.terms_accepted() { confirm_by_email(&mut tx, state, session, user_id, package, amount_huf.unwrap_or(i64::from(price_huf))).await?; } let buyer = invoices::Buyer::from_stripe(session.customer_details.as_ref().unwrap_or(&Value::Null), None); let (item, comment) = package.invoice_item(); let gross = amount_huf.unwrap_or(i64::from(price_huf)); invoices::queue(&mut tx, &session.id, user_id, &buyer, (&item, &comment), gross, state.config.invoice_vat).await?; tx.commit().await?; tracing::info!(user = ?user_id, package = %package_id, session = %session.id, "package paid"); Ok(true) } /// The purchase confirmation (the "visszaigazolás" of the withdrawal waiver): /// to the account's address, or Stripe's if the account is gone. async fn confirm_by_email( tx: &mut sqlx::PgConnection, state: &AppState, session: &stripe::Session, user_id: Option, package: &packages::Package, amount_huf: i64, ) -> Result<(), ApiError> { let account: Option<(String, String, Option)> = match user_id { Some(id) => { sqlx::query_as("SELECT email, locale, display_name FROM users WHERE id = $1") .bind(id) .fetch_optional(&mut *tx) .await? } None => None, }; let stripe_email = session.customer_details.as_ref().and_then(|c| c["email"].as_str()).map(str::to_string); let (to, locale, name) = match account { Some((email, locale, name)) => (email, locale, name), None => match stripe_email { Some(email) => (email, "hu".to_string(), None), None => return Ok(()), }, }; let base = &state.config.public_base_url; let payload = json!({ "url": format!("{base}/csomagok"), "display_name": name, "package_name": package.name, "contents": package.contents_text(), "amount": format_huf(amount_huf), "paid_on": OffsetDateTime::now_utc().date().to_string(), "terms_url": format!("{base}/aszf"), "invoices_url": format!("{base}/szamlak"), }); super::auth::queue_email_to(tx, user_id, &to, "purchase_confirmation", &locale, payload).await } /// "6 000 Ft" fn format_huf(amount: i64) -> String { let digits = amount.to_string(); let mut out = String::new(); for (i, c) in digits.chars().enumerate() { if i > 0 && (digits.len() - i).is_multiple_of(3) { out.push('\u{a0}'); } out.push(c); } format!("{out}\u{a0}Ft") } /// 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, &session).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 mut event: Value = serde_json::from_slice(&body).map_err(|e| ApiError::BadRequest(e.to_string()))?; let kind = event["type"].as_str().unwrap_or_default(); if matches!(kind, "checkout.session.completed" | "checkout.session.async_payment_succeeded") { let session: stripe::Session = serde_json::from_value(event["data"]["object"].take()) .map_err(|e| ApiError::BadRequest(format!("checkout session: {e}")))?; if session.paid() && !complete(&state, &session).await? { tracing::warn!(session = %session.id, "stripe webhook for a session we did not start"); } } Ok(Json(json!({ "received": true }))) }