Files
sorsfonalak/services/backend/src/routes/payments.rs
T

270 lines
12 KiB
Rust
Raw Normal View History

2026-11-20 06:41:21 +00:00
//! 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;
2026-11-20 06:41:21 +00:00
use axum::body::Bytes;
use axum::extract::{Path, State};
use axum::http::HeaderMap;
use axum_extra::extract::WithRejection;
2026-11-20 06:41:21 +00:00
use db::Role;
use serde::Deserialize;
use serde_json::{Value, json};
2026-11-20 06:41:21 +00:00
use time::OffsetDateTime;
use uuid::Uuid;
use super::{Body, St};
2026-11-20 06:41:21 +00:00
use crate::AppState;
use crate::auth::AuthUser;
2026-11-20 06:41:21 +00:00
use crate::config::StripeConfig;
use crate::credits::{self, Unit};
use crate::error::{ApiError, ApiResult};
use crate::packages::{self, CATALOG, Source};
2026-11-20 06:41:21 +00:00
use crate::{persons, stripe};
/// The package catalog (public).
pub async fn catalog() -> Json<Value> {
Json(json!({ "packages": CATALOG.iter().map(packages::Package::view).collect::<Vec<_>>() }))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MockPayment {
/// A package id from the catalog.
package: Option<String>,
/// Shorthand: the cheapest package with one unit of this kind.
unit: Option<Unit>,
}
/// What the user has now: units left and person slots.
pub async fn holdings(state: &crate::AppState, auth: &AuthUser) -> Result<Value, ApiError> {
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<MockPayment>,
) -> ApiResult<Json<Value>> {
2026-11-20 06:41:21 +00:00
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",
_ => 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?))
}
2026-11-20 06:41:21 +00:00
/// 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.
2026-11-20 06:41:21 +00:00
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) {
2026-11-20 06:41:21 +00:00
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; a company also gives its name
// and tax number ("I'm buying as a business").
2026-11-20 06:41:21 +00:00
field("billing_address_collection", "required"),
field("tax_id_collection[enabled]", "true"),
field("customer_creation", "always"),
2026-11-20 06:41:21 +00:00
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 })))
}
/// 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<bool, ApiError> {
2026-11-20 06:41:21 +00:00
let mut tx = state.db.begin().await?;
let row: Option<(Option<Uuid>, String, i32, Option<OffsetDateTime>)> = 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) };
2026-11-20 06:41:21 +00:00
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");
}
// A deleted account still gets its invoice, but no package.
let order = match user_id {
Some(user_id) => {
let package = packages::find(&package_id)
.ok_or_else(|| ApiError::Internal(format!("unknown package {package_id}")))?;
let note = format!("Stripe {}", session.id);
Some(packages::grant(&mut tx, user_id, package, Source::Stripe, Some(user_id), Some(&note)).await?)
}
None => None,
};
sqlx::query(
"UPDATE stripe_checkouts SET completed_at = now(), order_id = $2, payment_intent = $3, amount_huf = $4, \
customer = $5, invoice_status = 'pending' WHERE id = $1",
)
.bind(&session.id)
.bind(order)
.bind(&session.payment_intent)
.bind(amount_huf.map(|a| a as i32))
.bind(&session.customer_details)
.execute(&mut *tx)
.await?;
2026-11-20 06:41:21 +00:00
tx.commit().await?;
tracing::info!(user = ?user_id, package = %package_id, session = %session.id, "package paid");
2026-11-20 06:41:21 +00:00
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, &session).await?;
2026-11-20 06:41:21 +00:00
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 mut event: Value = serde_json::from_slice(&body).map_err(|e| ApiError::BadRequest(e.to_string()))?;
2026-11-20 06:41:21 +00:00
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");
2026-11-20 06:41:21 +00:00
}
}
Ok(Json(json!({ "received": true })))
}