Stripe: company purchases, payment details kept for the invoice
CI / test (push) Successful in 1m25s
CI / build (push) Successful in 5m20s
CI / deploy (push) Skipped

The checkout offers buying as a company (name, tax number). A confirmed
payment keeps Stripe's payment id, the amount charged and the buyer's
billing details, and queues the invoice for a background job (Billingo,
once the company exists). Payments outlive a deleted account for the
accounting law's 8 years. The package cards, the FAQ and the privacy
policy say that card details go to Stripe only.

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 07:26:03 +00:00
co-authored by Claude Opus 5.5
parent d9e71ed349
commit e530e78c54
10 changed files with 180 additions and 48 deletions
+47 -28
View File
@@ -134,8 +134,11 @@ pub async fn checkout(
field("locale", "hu"),
field("client_reference_id", &auth.id().to_string()),
field("customer_email", &auth.user.email),
// Name and address go on the invoice.
// 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.
@@ -163,29 +166,47 @@ pub async fn checkout(
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> {
/// 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> {
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) };
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) };
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?;
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?;
tx.commit().await?;
tracing::info!(user = %user_id, package = package.id, session = session_id, "package paid");
tracing::info!(user = ?user_id, package = %package_id, session = %session.id, "package paid");
Ok(true)
}
@@ -207,7 +228,7 @@ pub async fn checkout_status(
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?;
complete(&state, &session).await?;
status = "paid";
} else if session.status.as_deref() == Some("expired") {
status = "expired";
@@ -235,15 +256,13 @@ pub async fn stripe_webhook(State(state): St, headers: HeaderMap, body: Bytes) -
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 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();
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");
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 })))