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 07:52:34 +00:00
|
|
|
|
use crate::{invoices, 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 12:06:10 +00:00
|
|
|
|
/// The terms (ÁSZF) version a purchase accepts; the frontend's `TERMS_UPDATED`.
|
|
|
|
|
|
pub const TERMS_VERSION: &str = "2026-11-20";
|
|
|
|
|
|
|
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());
|
2026-11-20 14:03:12 +00:00
|
|
|
|
let mut form = vec![
|
2026-11-20 06:41:21 +00:00
|
|
|
|
field("mode", "payment"),
|
|
|
|
|
|
field("locale", "hu"),
|
|
|
|
|
|
field("client_reference_id", &auth.id().to_string()),
|
|
|
|
|
|
field("customer_email", &auth.user.email),
|
2026-11-20 07:26:03 +00:00
|
|
|
|
// 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"),
|
2026-11-20 07:26:03 +00:00
|
|
|
|
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),
|
2026-11-20 14:03:12 +00:00
|
|
|
|
field("success_url", &format!("{back}?fizetes={{CHECKOUT_SESSION_ID}}")),
|
|
|
|
|
|
field("cancel_url", &format!("{back}?fizetes=megszakitva")),
|
|
|
|
|
|
];
|
|
|
|
|
|
if state.config.terms_consent {
|
2026-11-20 12:06:10 +00:00
|
|
|
|
// 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.
|
2026-11-20 14:03:12 +00:00
|
|
|
|
form.push(field("consent_collection[terms_of_service]", "required"));
|
|
|
|
|
|
form.push(field(
|
2026-11-20 12:06:10 +00:00
|
|
|
|
"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
|
|
|
|
|
|
),
|
2026-11-20 14:03:12 +00:00
|
|
|
|
));
|
|
|
|
|
|
}
|
2026-11-20 06:41:21 +00:00
|
|
|
|
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 })))
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-20 07:26:03 +00:00
|
|
|
|
/// 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?;
|
2026-11-20 10:00:48 +00:00
|
|
|
|
type Checkout = (Option<Uuid>, String, i32, Option<OffsetDateTime>);
|
2026-11-20 08:30:54 +00:00
|
|
|
|
let row: Option<Checkout> = sqlx::query_as(
|
2026-11-20 10:00:48 +00:00
|
|
|
|
"SELECT user_id, package, price_huf, completed_at FROM stripe_checkouts WHERE id = $1 FOR UPDATE",
|
2026-11-20 07:26:03 +00:00
|
|
|
|
)
|
|
|
|
|
|
.bind(&session.id)
|
|
|
|
|
|
.fetch_optional(&mut *tx)
|
|
|
|
|
|
.await?;
|
2026-11-20 10:00:48 +00:00
|
|
|
|
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);
|
|
|
|
|
|
}
|
2026-11-20 07:26:03 +00:00
|
|
|
|
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");
|
|
|
|
|
|
}
|
2026-11-20 07:52:34 +00:00
|
|
|
|
let package =
|
|
|
|
|
|
packages::find(&package_id).ok_or_else(|| ApiError::Internal(format!("unknown package {package_id}")))?;
|
2026-11-20 07:26:03 +00:00
|
|
|
|
// 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,
|
|
|
|
|
|
};
|
2026-11-20 14:03:12 +00:00
|
|
|
|
if state.config.terms_consent && !session.terms_accepted() {
|
2026-11-20 12:06:10 +00:00
|
|
|
|
tracing::warn!(session = %session.id, "paid without the terms consent");
|
|
|
|
|
|
}
|
2026-11-20 07:26:03 +00:00
|
|
|
|
sqlx::query(
|
|
|
|
|
|
"UPDATE stripe_checkouts SET completed_at = now(), order_id = $2, payment_intent = $3, amount_huf = $4, \
|
2026-11-20 12:06:10 +00:00
|
|
|
|
customer = $5, terms_accepted_at = CASE WHEN $6 THEN now() END, terms_version = CASE WHEN $6 THEN $7 END \
|
|
|
|
|
|
WHERE id = $1",
|
2026-11-20 07:26:03 +00:00
|
|
|
|
)
|
|
|
|
|
|
.bind(&session.id)
|
|
|
|
|
|
.bind(order)
|
|
|
|
|
|
.bind(&session.payment_intent)
|
|
|
|
|
|
.bind(amount_huf.map(|a| a as i32))
|
|
|
|
|
|
.bind(&session.customer_details)
|
2026-11-20 12:06:10 +00:00
|
|
|
|
.bind(session.terms_accepted())
|
|
|
|
|
|
.bind(TERMS_VERSION)
|
2026-11-20 07:26:03 +00:00
|
|
|
|
.execute(&mut *tx)
|
|
|
|
|
|
.await?;
|
2026-11-20 14:03:12 +00:00
|
|
|
|
// 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?;
|
|
|
|
|
|
}
|
2026-11-20 10:00:48 +00:00
|
|
|
|
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?;
|
2026-11-20 06:41:21 +00:00
|
|
|
|
tx.commit().await?;
|
2026-11-20 07:26:03 +00:00
|
|
|
|
tracing::info!(user = ?user_id, package = %package_id, session = %session.id, "package paid");
|
2026-11-20 06:41:21 +00:00
|
|
|
|
Ok(true)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-20 12:06:10 +00:00
|
|
|
|
/// 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<Uuid>,
|
|
|
|
|
|
package: &packages::Package,
|
|
|
|
|
|
amount_huf: i64,
|
|
|
|
|
|
) -> Result<(), ApiError> {
|
|
|
|
|
|
let account: Option<(String, String, Option<String>)> = 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")
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-20 06:41:21 +00:00
|
|
|
|
/// 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() {
|
2026-11-20 07:26:03 +00:00
|
|
|
|
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()));
|
|
|
|
|
|
}
|
2026-11-20 07:26:03 +00:00
|
|
|
|
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();
|
2026-11-20 07:26:03 +00:00
|
|
|
|
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 })))
|
|
|
|
|
|
}
|