- The buyer may withdraw from a gift purchase within 14 days while the
code is not redeemed (ÁSZF 3., 5., 6.; terms version 2026-11-23); the
consent on Stripe's page and the confirmation e-mail say so
- Admin → Ajándékok: the gifts with payment, invoice and storno; the
refund button locks the gift and refuses a redeemed one, withdraws the
code, refunds the PaymentIntent on Stripe (one refund per gift via the
Idempotency-Key, retry when Stripe refuses) and queues the storno
- Worker: cancels the issued invoice in Billingo (POST /documents/{id}/
cancel, e-mailed to the buyer), keeps the storno invoice's id and
number; a lost answer is not asked again but left for an admin
- A withdrawn code cannot be redeemed, sent or downloaded; "My gifts"
shows it as refunded
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
224 lines
8.2 KiB
Rust
224 lines
8.2 KiB
Rust
//! The little of Stripe's API we use: Checkout Sessions (a hosted payment
|
|
//! page for one package), refunds (a gift given back) and webhook signature
|
|
//! checking. The package catalog
|
|
//! stays in `packages.rs`; each session carries its name and price, so no
|
|
//! products have to be kept in the Stripe dashboard.
|
|
|
|
use std::time::Duration;
|
|
|
|
use hmac::{Hmac, Mac};
|
|
use serde::Deserialize;
|
|
use serde_json::Value;
|
|
use sha2::Sha256;
|
|
|
|
use crate::config::StripeConfig;
|
|
use crate::error::ApiError;
|
|
|
|
/// How old a webhook signature may be (Stripe's own libraries use 5 minutes).
|
|
const SIGNATURE_TOLERANCE: i64 = 300;
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct Session {
|
|
pub id: String,
|
|
/// The payment page (only while the session is open).
|
|
pub url: Option<String>,
|
|
/// `paid`, `unpaid` or `no_payment_required`.
|
|
pub payment_status: String,
|
|
/// `open`, `complete` or `expired`.
|
|
pub status: Option<String>,
|
|
/// In the smallest unit (fillér for forints).
|
|
#[serde(default)]
|
|
pub amount_total: Option<i64>,
|
|
#[serde(default)]
|
|
pub currency: Option<String>,
|
|
/// The PaymentIntent's id.
|
|
#[serde(default)]
|
|
pub payment_intent: Option<String>,
|
|
/// Name, e-mail, billing address; for a company its name and tax ids.
|
|
#[serde(default)]
|
|
pub customer_details: Option<Value>,
|
|
/// `{"terms_of_service": "accepted"}` once the buyer ticked the terms box.
|
|
#[serde(default)]
|
|
pub consent: Option<Value>,
|
|
}
|
|
|
|
impl Session {
|
|
/// The buyer accepted the terms (and gave up the withdrawal right).
|
|
pub fn terms_accepted(&self) -> bool {
|
|
self.consent.as_ref().is_some_and(|c| c["terms_of_service"] == "accepted")
|
|
}
|
|
}
|
|
|
|
impl Session {
|
|
pub fn paid(&self) -> bool {
|
|
self.payment_status == "paid"
|
|
}
|
|
}
|
|
|
|
/// A refund (`re_…`).
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct Refund {
|
|
pub id: String,
|
|
/// `pending`, `succeeded`, `failed`, …
|
|
#[serde(default)]
|
|
pub status: Option<String>,
|
|
}
|
|
|
|
pub struct Client {
|
|
http: reqwest::Client,
|
|
}
|
|
|
|
impl Default for Client {
|
|
fn default() -> Self {
|
|
let http = reqwest::Client::builder().timeout(Duration::from_secs(20)).build().expect("static configuration");
|
|
Self { http }
|
|
}
|
|
}
|
|
|
|
/// What the user sees when Stripe cannot be reached.
|
|
fn unavailable(detail: String) -> ApiError {
|
|
tracing::error!(error = %detail, "stripe request failed");
|
|
ApiError::Limited {
|
|
code: "payment_unavailable",
|
|
message: "A fizetési oldal most nem érhető el. Próbáld újra pár perc múlva.".into(),
|
|
}
|
|
}
|
|
|
|
impl Client {
|
|
/// Creates a Checkout Session from form fields (Stripe's API takes
|
|
/// `application/x-www-form-urlencoded` with `a[b][c]` keys).
|
|
pub async fn create_session(&self, config: &StripeConfig, form: &[(String, String)]) -> Result<Session, ApiError> {
|
|
let res = self
|
|
.http
|
|
.post(format!("{}/v1/checkout/sessions", config.api_url))
|
|
.bearer_auth(&config.secret_key)
|
|
.form(form)
|
|
.send()
|
|
.await
|
|
.map_err(|e| unavailable(e.to_string()))?;
|
|
Self::session(res).await
|
|
}
|
|
|
|
pub async fn get_session(&self, config: &StripeConfig, id: &str) -> Result<Session, ApiError> {
|
|
let res = self
|
|
.http
|
|
.get(format!("{}/v1/checkout/sessions/{id}", config.api_url))
|
|
.bearer_auth(&config.secret_key)
|
|
.send()
|
|
.await
|
|
.map_err(|e| unavailable(e.to_string()))?;
|
|
Self::session(res).await
|
|
}
|
|
|
|
/// Pays a PaymentIntent back in full. The same `key` (Stripe's
|
|
/// Idempotency-Key, kept for a day) never refunds twice.
|
|
pub async fn refund(
|
|
&self,
|
|
config: &StripeConfig,
|
|
payment_intent: &str,
|
|
key: &str,
|
|
metadata: &[(&str, &str)],
|
|
) -> Result<Refund, ApiError> {
|
|
let mut form = vec![
|
|
("payment_intent".to_string(), payment_intent.to_string()),
|
|
("reason".to_string(), "requested_by_customer".to_string()),
|
|
];
|
|
form.extend(metadata.iter().map(|(k, v)| (format!("metadata[{k}]"), (*v).to_string())));
|
|
let res = self
|
|
.http
|
|
.post(format!("{}/v1/refunds", config.api_url))
|
|
.bearer_auth(&config.secret_key)
|
|
.header("Idempotency-Key", key)
|
|
.form(&form)
|
|
.send()
|
|
.await
|
|
.map_err(|e| unavailable(e.to_string()))?;
|
|
let status = res.status();
|
|
if !status.is_success() {
|
|
// Stripe says why (e.g. already refunded): the admin sees it.
|
|
let body: Value = res.json().await.unwrap_or_default();
|
|
let message = body["error"]["message"].as_str().unwrap_or("ismeretlen hiba").to_string();
|
|
tracing::error!(%status, %message, "stripe refund refused");
|
|
return Err(ApiError::conflict("refund_failed", format!("A Stripe nem téríti vissza: {message}")));
|
|
}
|
|
res.json().await.map_err(|e| unavailable(format!("unexpected response: {e}")))
|
|
}
|
|
|
|
async fn session(res: reqwest::Response) -> Result<Session, ApiError> {
|
|
let status = res.status();
|
|
if !status.is_success() {
|
|
let body = res.text().await.unwrap_or_default();
|
|
return Err(unavailable(format!("HTTP {status}: {}", body.chars().take(500).collect::<String>())));
|
|
}
|
|
res.json().await.map_err(|e| unavailable(format!("unexpected response: {e}")))
|
|
}
|
|
}
|
|
|
|
/// Checks a `Stripe-Signature` header (`t=…,v1=…[,v1=…]`): an HMAC-SHA256 of
|
|
/// `"{t}.{body}"` with the endpoint's signing secret, at most five minutes old.
|
|
pub fn verify_signature(secret: &str, header: &str, body: &[u8], now: i64) -> bool {
|
|
let mut timestamp = None;
|
|
let mut signatures = Vec::new();
|
|
for part in header.split(',') {
|
|
match part.trim().split_once('=') {
|
|
Some(("t", v)) => timestamp = v.parse::<i64>().ok(),
|
|
Some(("v1", v)) => signatures.push(v),
|
|
_ => {}
|
|
}
|
|
}
|
|
let Some(timestamp) = timestamp else { return false };
|
|
if (now - timestamp).abs() > SIGNATURE_TOLERANCE {
|
|
return false;
|
|
}
|
|
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC takes any key length");
|
|
mac.update(timestamp.to_string().as_bytes());
|
|
mac.update(b".");
|
|
mac.update(body);
|
|
let expected = mac.finalize().into_bytes();
|
|
signatures.iter().any(|s| decode_hex(s).is_some_and(|sig| constant_time_eq(&sig, &expected)))
|
|
}
|
|
|
|
/// The signature header for a body, as Stripe would send it (tests).
|
|
#[cfg(test)]
|
|
pub fn sign(secret: &str, body: &[u8], timestamp: i64) -> String {
|
|
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
|
|
mac.update(format!("{timestamp}.").as_bytes());
|
|
mac.update(body);
|
|
let hex: String = mac.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect();
|
|
format!("t={timestamp},v1={hex}")
|
|
}
|
|
|
|
fn decode_hex(s: &str) -> Option<Vec<u8>> {
|
|
if !s.len().is_multiple_of(2) {
|
|
return None;
|
|
}
|
|
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect()
|
|
}
|
|
|
|
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
|
|
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn signatures_are_checked() {
|
|
let body = br#"{"id":"evt_1"}"#;
|
|
let now = 1_800_000_000;
|
|
let header = sign("whsec_test", body, now);
|
|
assert!(verify_signature("whsec_test", &header, body, now));
|
|
assert!(verify_signature("whsec_test", &header, body, now + 299));
|
|
// Another secret, a changed body, an old or missing timestamp.
|
|
assert!(!verify_signature("whsec_other", &header, body, now));
|
|
assert!(!verify_signature("whsec_test", &header, br#"{"id":"evt_2"}"#, now));
|
|
assert!(!verify_signature("whsec_test", &header, body, now + 301));
|
|
assert!(!verify_signature("whsec_test", header.split_once(',').unwrap().1, body, now));
|
|
// One good signature among others (during a secret rotation) is enough.
|
|
let rotated = format!("{header},v1=00ff");
|
|
assert!(verify_signature("whsec_test", &rotated, body, now));
|
|
assert!(!verify_signature("whsec_test", "t=1800000000,v1=zz", body, now));
|
|
}
|
|
}
|