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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-20 06:41:21 +00:00
co-authored by Claude Opus 5.5
parent 55101f8637
commit 42a982010d
31 changed files with 842 additions and 37 deletions
+7 -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,10 @@ 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; 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(),
+183 -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,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<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 })))
}