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.
|
2026-11-17 06:45:33 +00:00
|
|
|
|
|
|
|
|
|
|
use axum::Json;
|
2026-11-20 06:41:21 +00:00
|
|
|
|
use axum::body::Bytes;
|
|
|
|
|
|
use axum::extract::{Path, State};
|
|
|
|
|
|
use axum::http::HeaderMap;
|
2026-11-17 06:45:33 +00:00
|
|
|
|
use axum_extra::extract::WithRejection;
|
2026-11-20 06:41:21 +00:00
|
|
|
|
use db::Role;
|
2026-11-17 06:45:33 +00:00
|
|
|
|
use serde::Deserialize;
|
|
|
|
|
|
use serde_json::{Value, json};
|
2026-11-20 06:41:21 +00:00
|
|
|
|
use time::OffsetDateTime;
|
|
|
|
|
|
use uuid::Uuid;
|
2026-11-17 06:45:33 +00:00
|
|
|
|
|
|
|
|
|
|
use super::{Body, St};
|
2026-11-20 06:41:21 +00:00
|
|
|
|
use crate::AppState;
|
2026-11-17 06:45:33 +00:00
|
|
|
|
use crate::auth::AuthUser;
|
2026-11-20 06:41:21 +00:00
|
|
|
|
use crate::config::StripeConfig;
|
2026-11-17 06:45:33 +00:00
|
|
|
|
use crate::credits::{self, Unit};
|
|
|
|
|
|
use crate::error::{ApiError, ApiResult};
|
2026-11-17 16:19:20 +00:00
|
|
|
|
use crate::packages::{self, CATALOG, Source};
|
2026-11-20 06:41:21 +00:00
|
|
|
|
use crate::{persons, stripe};
|
2026-11-17 16:19:20 +00:00
|
|
|
|
|
|
|
|
|
|
/// The package catalog (public).
|
|
|
|
|
|
pub async fn catalog() -> Json<Value> {
|
|
|
|
|
|
Json(json!({ "packages": CATALOG.iter().map(packages::Package::view).collect::<Vec<_>>() }))
|
|
|
|
|
|
}
|
2026-11-17 06:45:33 +00:00
|
|
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
|
|
#[serde(deny_unknown_fields)]
|
|
|
|
|
|
pub struct MockPayment {
|
2026-11-17 16:19:20 +00:00
|
|
|
|
/// A package id from the catalog.
|
|
|
|
|
|
package: Option<String>,
|
|
|
|
|
|
/// Shorthand: the cheapest package with one unit of this kind.
|
2026-11-17 11:03:55 +00:00
|
|
|
|
unit: Option<Unit>,
|
2026-11-17 06:45:33 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-18 06:20:31 +00:00
|
|
|
|
/// What the user has now: units left and person slots.
|
2026-11-17 16:19:20 +00:00
|
|
|
|
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(),
|
|
|
|
|
|
}))
|
2026-11-17 11:03:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-17 16:19:20 +00:00
|
|
|
|
/// Grants a package as a (pretend) purchase.
|
2026-11-17 06:45:33 +00:00
|
|
|
|
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() {
|
2026-11-17 06:45:33 +00:00
|
|
|
|
return Err(ApiError::NotFound("payment method"));
|
|
|
|
|
|
}
|
2026-11-17 16:19:20 +00:00
|
|
|
|
let id = match (req.package.as_deref(), req.unit) {
|
|
|
|
|
|
(Some(id), None) => id,
|
|
|
|
|
|
(None, Some(Unit::Natal)) => "single",
|
|
|
|
|
|
(None, Some(Unit::Synastry)) => "addon_synastry",
|
2026-11-18 08:19:13 +00:00
|
|
|
|
(None, Some(Unit::Forecast)) => "addon_forecast",
|
2026-11-17 16:19:20 +00:00
|
|
|
|
(None, Some(Unit::Person)) => "addon_persons",
|
2026-11-18 18:44:20 +00:00
|
|
|
|
(None, Some(Unit::Question)) => "addon_questions",
|
2026-11-17 16:19:20 +00:00
|
|
|
|
_ => return Err(ApiError::BadRequest("give either package or unit".into())),
|
2026-11-17 11:03:55 +00:00
|
|
|
|
};
|
2026-11-17 16:19:20 +00:00
|
|
|
|
let package = packages::find(id).ok_or(ApiError::NotFound("package"))?;
|
2026-11-17 06:45:33 +00:00
|
|
|
|
let mut tx = state.db.begin().await?;
|
2026-11-17 16:19:20 +00:00
|
|
|
|
packages::grant(&mut tx, auth.id(), package, Source::Mock, Some(auth.id()), Some("mock payment")).await?;
|
2026-11-17 06:45:33 +00:00
|
|
|
|
tx.commit().await?;
|
2026-11-17 16:19:20 +00:00
|
|
|
|
tracing::info!(user = %auth.id(), package = package.id, "mock payment");
|
|
|
|
|
|
Ok(Json(holdings(&state, &auth).await?))
|
2026-11-17 06:45:33 +00:00
|
|
|
|
}
|
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,
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-20 06:57:00 +00:00
|
|
|
|
/// 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"))?;
|
2026-11-20 06:57:00 +00:00
|
|
|
|
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.
|
|
|
|
|
|
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(¬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<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 })))
|
|
|
|
|
|
}
|