| 1 |
|
| 2 |
|
| 3 |
mod billing; |
| 4 |
mod checkout; |
| 5 |
pub(crate) mod checkout_helpers; |
| 6 |
mod subscriptions; |
| 7 |
|
| 8 |
use axum::{ |
| 9 |
body::Bytes, |
| 10 |
extract::State, |
| 11 |
http::{StatusCode, header::HeaderMap}, |
| 12 |
response::IntoResponse, |
| 13 |
}; |
| 14 |
use sqlx::PgPool; |
| 15 |
|
| 16 |
use crate::{ |
| 17 |
Billing, Integrations, |
| 18 |
config::Config, |
| 19 |
db, |
| 20 |
email::EmailClient, |
| 21 |
error::{AppError, Result, ResultExt}, |
| 22 |
payments::{AccountUpdate, CheckoutCompletion, CheckoutKind, MnwEvent, UntypedEvent}, |
| 23 |
wam_client::WamClient, |
| 24 |
}; |
| 25 |
|
| 26 |
|
| 27 |
#[tracing::instrument(skip_all, name = "stripe::webhook")] |
| 28 |
#[allow(clippy::too_many_arguments)] |
| 29 |
pub(in crate::routes::stripe) async fn webhook( |
| 30 |
State(db): State<PgPool>, |
| 31 |
State(bg): State<crate::background::BackgroundTx>, |
| 32 |
State(email): State<EmailClient>, |
| 33 |
State(integrations): State<Integrations>, |
| 34 |
State(payments): State<Billing>, |
| 35 |
State(config): State<Config>, |
| 36 |
headers: HeaderMap, |
| 37 |
body: Bytes, |
| 38 |
) -> Result<impl IntoResponse> { |
| 39 |
let stripe = payments |
| 40 |
.stripe |
| 41 |
.as_ref() |
| 42 |
.ok_or_else(|| AppError::BadRequest("Stripe is not configured".to_string()))?; |
| 43 |
|
| 44 |
|
| 45 |
let signature = headers |
| 46 |
.get("stripe-signature") |
| 47 |
.and_then(|v| v.to_str().ok()) |
| 48 |
.ok_or_else(|| AppError::BadRequest("Missing Stripe signature".to_string()))?; |
| 49 |
|
| 50 |
|
| 51 |
let payload = std::str::from_utf8(&body) |
| 52 |
.map_err(|_| AppError::BadRequest("Invalid payload encoding".to_string()))?; |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
let event = stripe.verify_webhook(payload, signature).inspect_err(|_| { |
| 57 |
crate::security_signals::note_webhook_signature_failure("stripe"); |
| 58 |
})?; |
| 59 |
tracing::info!(event_type = %event.type_, event_id = %event.id, "received webhook event"); |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
let _event_lock = match db::webhook_events::try_lock_event(&db, &event.id).await { |
| 72 |
Ok(Some(tx)) => tx, |
| 73 |
Ok(None) => { |
| 74 |
tracing::info!(event_id = %event.id, "concurrent delivery of this webhook event is in flight; returning 503 for redelivery"); |
| 75 |
return Ok(StatusCode::SERVICE_UNAVAILABLE); |
| 76 |
} |
| 77 |
Err(e) => { |
| 78 |
tracing::error!(event_id = %event.id, error = ?e, "failed to acquire webhook event lock, returning 503 for retry"); |
| 79 |
return Ok(StatusCode::SERVICE_UNAVAILABLE); |
| 80 |
} |
| 81 |
}; |
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
match db::webhook_events::is_event_processed(&db, &event.id).await { |
| 91 |
Ok(true) => { |
| 92 |
tracing::info!(event_id = %event.id, "duplicate webhook event, skipping"); |
| 93 |
return Ok(StatusCode::OK); |
| 94 |
} |
| 95 |
Err(e) => { |
| 96 |
tracing::error!(event_id = %event.id, error = ?e, "webhook dedup check failed, returning 503 for retry"); |
| 97 |
return Ok(StatusCode::SERVICE_UNAVAILABLE); |
| 98 |
} |
| 99 |
Ok(false) => {} |
| 100 |
} |
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
let UntypedEvent { |
| 105 |
id: event_id, |
| 106 |
type_: event_type_str, |
| 107 |
data_object, |
| 108 |
} = event; |
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
let result = match MnwEvent::normalize(&event_type_str, data_object) { |
| 114 |
Ok(mnw_event) => { |
| 115 |
process_webhook_event( |
| 116 |
&db, |
| 117 |
&bg, |
| 118 |
&email, |
| 119 |
integrations.wam.as_ref(), |
| 120 |
&payments, |
| 121 |
&config, |
| 122 |
mnw_event, |
| 123 |
&event_id, |
| 124 |
) |
| 125 |
.await |
| 126 |
} |
| 127 |
Err(e) => Err(e), |
| 128 |
}; |
| 129 |
|
| 130 |
match result { |
| 131 |
Ok(()) => { |
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
if let Err(e) = db::webhook_events::mark_event_processed(&db, &event_id).await { |
| 137 |
tracing::error!(event_id = %event_id, error = ?e, "failed to record processed webhook event; returning 503 for redelivery"); |
| 138 |
return Ok(StatusCode::SERVICE_UNAVAILABLE); |
| 139 |
} |
| 140 |
} |
| 141 |
Err(ref e) => { |
| 142 |
tracing::error!( |
| 143 |
event_id = %event_id, event_type = %event_type_str, |
| 144 |
error = ?e, "webhook handler failed, queueing for retry" |
| 145 |
); |
| 146 |
|
| 147 |
if let Err(queue_err) = db::webhook_events::insert_failed_event( |
| 148 |
&db, |
| 149 |
"stripe", |
| 150 |
&event_type_str, |
| 151 |
payload, |
| 152 |
Some(signature), |
| 153 |
&format!("{e:?}"), |
| 154 |
) |
| 155 |
.await |
| 156 |
{ |
| 157 |
tracing::error!(error = ?queue_err, "failed to queue webhook event for retry; returning 503 to trigger Stripe redelivery"); |
| 158 |
return Ok(StatusCode::SERVICE_UNAVAILABLE); |
| 159 |
} |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
Ok(StatusCode::OK) |
| 164 |
} |
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
#[allow(clippy::too_many_arguments)] |
| 177 |
pub(crate) async fn process_webhook_event( |
| 178 |
db: &PgPool, |
| 179 |
bg: &crate::background::BackgroundTx, |
| 180 |
email: &EmailClient, |
| 181 |
wam: Option<&WamClient>, |
| 182 |
payments: &Billing, |
| 183 |
config: &Config, |
| 184 |
event: MnwEvent, |
| 185 |
event_id: &str, |
| 186 |
) -> Result<()> { |
| 187 |
match event { |
| 188 |
MnwEvent::Checkout { kind, session } => { |
| 189 |
dispatch_checkout_session( |
| 190 |
db, bg, email, wam, payments, config, kind, &session, event_id, |
| 191 |
) |
| 192 |
.await?; |
| 193 |
} |
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
MnwEvent::CheckoutAsyncPaymentFailed { session_id } => { |
| 198 |
tracing::warn!( |
| 199 |
%session_id, |
| 200 |
"checkout async payment failed; no funds captured, pending rows will be released by cleanup" |
| 201 |
); |
| 202 |
} |
| 203 |
MnwEvent::AccountUpdated(update) => { |
| 204 |
handle_account_updated(db, wam, &config.signing_secret, &update).await?; |
| 205 |
} |
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
MnwEvent::ChargeRefunded(Some(refund_data)) => { |
| 211 |
billing::handle_charge_refunded(db, &refund_data, true).await?; |
| 212 |
} |
| 213 |
MnwEvent::ChargeRefunded(None) => {} |
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
MnwEvent::RefundSettled(refund) => { |
| 219 |
billing::handle_refund_created(db, &refund).await?; |
| 220 |
} |
| 221 |
MnwEvent::SubscriptionUpdated(sub) => { |
| 222 |
subscriptions::handle_subscription_updated(db, &sub, event_id).await?; |
| 223 |
} |
| 224 |
MnwEvent::SubscriptionDeleted(sub) => { |
| 225 |
subscriptions::handle_subscription_deleted(db, bg, email, &sub, event_id).await?; |
| 226 |
} |
| 227 |
MnwEvent::InvoicePaymentSucceeded(invoice) => { |
| 228 |
billing::handle_invoice_payment_succeeded(db, bg, email, wam, &invoice, event_id) |
| 229 |
.await?; |
| 230 |
} |
| 231 |
MnwEvent::InvoicePaymentFailed(invoice) => { |
| 232 |
billing::handle_invoice_payment_failed(db, wam, &invoice, event_id).await?; |
| 233 |
} |
| 234 |
MnwEvent::Unhandled { stripe_type } => { |
| 235 |
tracing::debug!(event_type = %stripe_type, "unhandled webhook event type"); |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
Ok(()) |
| 240 |
} |
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
|
| 258 |
#[allow(clippy::too_many_arguments)] |
| 259 |
async fn dispatch_checkout_session( |
| 260 |
db: &PgPool, |
| 261 |
bg: &crate::background::BackgroundTx, |
| 262 |
email: &EmailClient, |
| 263 |
wam: Option<&WamClient>, |
| 264 |
payments: &Billing, |
| 265 |
config: &Config, |
| 266 |
kind: CheckoutKind, |
| 267 |
session: &CheckoutCompletion, |
| 268 |
event_id: &str, |
| 269 |
) -> Result<()> { |
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
|
| 274 |
if kind.captures_funds_at_checkout() && !session.settled { |
| 275 |
tracing::info!( |
| 276 |
session_id = %session.session_id, |
| 277 |
?kind, |
| 278 |
"one-time checkout not yet settled (async payment); deferring finalize until async_payment_succeeded" |
| 279 |
); |
| 280 |
return Ok(()); |
| 281 |
} |
| 282 |
|
| 283 |
match kind { |
| 284 |
CheckoutKind::FanPlus => { |
| 285 |
checkout::handle_fan_plus_checkout_completed(db, bg, email, session, event_id).await |
| 286 |
} |
| 287 |
CheckoutKind::CreatorTier => { |
| 288 |
checkout::handle_creator_tier_checkout_completed( |
| 289 |
db, bg, wam, payments, session, event_id, |
| 290 |
) |
| 291 |
.await |
| 292 |
} |
| 293 |
CheckoutKind::SyncKitAppSub => { |
| 294 |
checkout::handle_synckit_app_sub_checkout_completed(db, session, event_id).await |
| 295 |
} |
| 296 |
CheckoutKind::ProjectSubscription => { |
| 297 |
checkout::handle_subscription_checkout_completed(db, bg, email, session, event_id).await |
| 298 |
} |
| 299 |
CheckoutKind::Tip => { |
| 300 |
checkout::handle_tip_checkout_completed(db, bg, email, wam, config, session, event_id) |
| 301 |
.await |
| 302 |
} |
| 303 |
CheckoutKind::Guest => { |
| 304 |
checkout::handle_guest_checkout_completed(db, bg, email, wam, config, session, event_id) |
| 305 |
.await |
| 306 |
} |
| 307 |
CheckoutKind::Cart => { |
| 308 |
checkout::handle_cart_checkout_completed(db, bg, email, wam, config, session, event_id) |
| 309 |
.await |
| 310 |
} |
| 311 |
CheckoutKind::Purchase => { |
| 312 |
checkout::handle_purchase_checkout_completed( |
| 313 |
db, bg, email, wam, config, session, event_id, |
| 314 |
) |
| 315 |
.await |
| 316 |
} |
| 317 |
} |
| 318 |
} |
| 319 |
|
| 320 |
|
| 321 |
pub(in crate::routes::stripe) async fn handle_account_updated_from_v2( |
| 322 |
db: &PgPool, |
| 323 |
wam: Option<&WamClient>, |
| 324 |
signing_secret: &str, |
| 325 |
update: &AccountUpdate, |
| 326 |
) -> Result<()> { |
| 327 |
handle_account_updated(db, wam, signing_secret, update).await |
| 328 |
} |
| 329 |
|
| 330 |
|
| 331 |
async fn handle_account_updated( |
| 332 |
db: &PgPool, |
| 333 |
wam: Option<&WamClient>, |
| 334 |
signing_secret: &str, |
| 335 |
update: &AccountUpdate, |
| 336 |
) -> Result<()> { |
| 337 |
tracing::info!( |
| 338 |
account_id = %update.account_id, charges_enabled = %update.charges_enabled, |
| 339 |
payouts_enabled = %update.payouts_enabled, details_submitted = %update.details_submitted, |
| 340 |
settlement_currency = ?update.settlement_currency, |
| 341 |
"account updated" |
| 342 |
); |
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
let previous_currency = |
| 348 |
db::users::get_settlement_currency_by_stripe_account(db, &update.account_id) |
| 349 |
.await |
| 350 |
.unwrap_or(None); |
| 351 |
|
| 352 |
|
| 353 |
db::users::update_user_stripe_status( |
| 354 |
db, |
| 355 |
&update.account_id, |
| 356 |
update.details_submitted, |
| 357 |
update.payouts_enabled, |
| 358 |
update.charges_enabled, |
| 359 |
update.settlement_currency, |
| 360 |
) |
| 361 |
.await |
| 362 |
.with_context(|| format!("update Stripe status for account {}", update.account_id))?; |
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
|
| 376 |
if let (Some(new_currency), Some(old_currency)) = |
| 377 |
(update.settlement_currency, previous_currency) |
| 378 |
&& new_currency != old_currency |
| 379 |
{ |
| 380 |
tracing::warn!( |
| 381 |
account_id = %update.account_id, |
| 382 |
%old_currency, %new_currency, |
| 383 |
"settlement currency changed; the creator's existing prices now mean different money" |
| 384 |
); |
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
match db::users::get_user_id_by_stripe_account(db, &update.account_id).await { |
| 391 |
Ok(Some(user_id)) => { |
| 392 |
let details = serde_json::json!({ |
| 393 |
"from": old_currency.to_string(), |
| 394 |
"to": new_currency.to_string(), |
| 395 |
}); |
| 396 |
let opened = db::acknowledgements::open( |
| 397 |
db, |
| 398 |
user_id, |
| 399 |
db::AckKind::SettlementCurrencyChanged, |
| 400 |
&format!("{old_currency}->{new_currency}"), |
| 401 |
details, |
| 402 |
signing_secret, |
| 403 |
) |
| 404 |
.await; |
| 405 |
match opened { |
| 406 |
Ok(true) => tracing::info!( |
| 407 |
%user_id, |
| 408 |
"opened a settlement-currency acknowledgement for the creator" |
| 409 |
), |
| 410 |
Ok(false) => {} |
| 411 |
Err(e) => tracing::error!( |
| 412 |
error = ?e, %user_id, |
| 413 |
"could not open the settlement-currency acknowledgement; the wam \ |
| 414 |
ticket below is the only alarm left" |
| 415 |
), |
| 416 |
} |
| 417 |
} |
| 418 |
Ok(None) => tracing::warn!( |
| 419 |
account_id = %update.account_id, |
| 420 |
"settlement currency changed on an account with no user; cannot notify anyone" |
| 421 |
), |
| 422 |
Err(e) => tracing::error!( |
| 423 |
error = ?e, |
| 424 |
"could not resolve the user behind the settlement-currency change" |
| 425 |
), |
| 426 |
} |
| 427 |
|
| 428 |
if let Some(wam) = wam { |
| 429 |
let title = format!("Settlement currency changed: {}", update.account_id); |
| 430 |
let body = format!( |
| 431 |
"This creator's Stripe account moved from {old_currency} to {new_currency}.\n\n\ |
| 432 |
Every price they have already set is stored as a bare number, so those \ |
| 433 |
numbers now mean {new_currency} instead of {old_currency}. Nothing has been \ |
| 434 |
converted and nothing has been rewritten.\n\n\ |
| 435 |
They need to re-check their prices. Contact them." |
| 436 |
); |
| 437 |
wam.create_ticket( |
| 438 |
&title, |
| 439 |
Some(&body), |
| 440 |
"high", |
| 441 |
"settlement-currency-changed", |
| 442 |
Some(&update.account_id), |
| 443 |
) |
| 444 |
.await; |
| 445 |
} |
| 446 |
} |
| 447 |
|
| 448 |
|
| 449 |
if (!update.charges_enabled || !update.payouts_enabled) |
| 450 |
&& let Some(wam) = wam |
| 451 |
{ |
| 452 |
let title = format!("Stripe Connect degraded: {}", update.account_id); |
| 453 |
let body = format!( |
| 454 |
"charges_enabled: {}\npayouts_enabled: {}\ndetails_submitted: {}", |
| 455 |
update.charges_enabled, update.payouts_enabled, update.details_submitted, |
| 456 |
); |
| 457 |
wam.create_ticket( |
| 458 |
&title, |
| 459 |
Some(&body), |
| 460 |
"high", |
| 461 |
"stripe-connect-degraded", |
| 462 |
Some(&update.account_id), |
| 463 |
) |
| 464 |
.await; |
| 465 |
} |
| 466 |
|
| 467 |
Ok(()) |
| 468 |
} |
| 469 |
|