| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
use axum::{ |
| 7 |
Json, |
| 8 |
extract::{Path, State}, |
| 9 |
http::{HeaderValue, StatusCode, header}, |
| 10 |
response::{IntoResponse, Redirect, Response}, |
| 11 |
}; |
| 12 |
use serde::{Deserialize, Serialize}; |
| 13 |
|
| 14 |
use crate::background::BackgroundTx; |
| 15 |
use crate::config::Config; |
| 16 |
use crate::email::EmailClient; |
| 17 |
use crate::{AppStorage, Billing, Integrations}; |
| 18 |
use sqlx::PgPool; |
| 19 |
|
| 20 |
use crate::{ |
| 21 |
db::{self, Cents, ItemId}, |
| 22 |
error::{AppError, Result, ResultExt}, |
| 23 |
}; |
| 24 |
|
| 25 |
|
| 26 |
#[derive(Debug, Deserialize)] |
| 27 |
pub(super) struct GuestCheckoutRequest { |
| 28 |
|
| 29 |
pub amount_cents: Option<i32>, |
| 30 |
|
| 31 |
pub promo_code: Option<String>, |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
#[derive(Serialize)] |
| 36 |
struct CheckoutResponse { |
| 37 |
checkout_url: String, |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
#[tracing::instrument(skip_all, name = "guest_checkout::create")] |
| 46 |
pub(super) async fn create_guest_checkout( |
| 47 |
State(db): State<PgPool>, |
| 48 |
State(config): State<Config>, |
| 49 |
State(payments): State<Billing>, |
| 50 |
Path(item_id): Path<ItemId>, |
| 51 |
Json(body): Json<GuestCheckoutRequest>, |
| 52 |
) -> Result<Response> { |
| 53 |
|
| 54 |
let item = db::items::get_item_by_id(&db, item_id) |
| 55 |
.await? |
| 56 |
.ok_or(AppError::NotFound)?; |
| 57 |
|
| 58 |
if !item.is_public || !item.listed { |
| 59 |
return Err(AppError::NotFound); |
| 60 |
} |
| 61 |
|
| 62 |
|
| 63 |
let project = db::projects::get_project_by_id(&db, item.project_id) |
| 64 |
.await? |
| 65 |
.ok_or(AppError::NotFound)?; |
| 66 |
let seller = db::users::get_user_by_id(&db, project.user_id) |
| 67 |
.await? |
| 68 |
.ok_or(AppError::NotFound)?; |
| 69 |
|
| 70 |
if seller.is_suspended() || seller.is_deactivated() || seller.is_creator_paused() { |
| 71 |
return Err(AppError::NotFound); |
| 72 |
} |
| 73 |
|
| 74 |
let seller_id = seller.id; |
| 75 |
|
| 76 |
|
| 77 |
let pricing = crate::pricing::for_item(&item); |
| 78 |
let mut final_price_cents = if item.pwyw_enabled { |
| 79 |
let buyer_amount = body.amount_cents.unwrap_or(item.price_cents); |
| 80 |
pricing |
| 81 |
.validate_amount(buyer_amount, seller.settlement_currency) |
| 82 |
.map_err(AppError::BadRequest)?; |
| 83 |
buyer_amount |
| 84 |
} else { |
| 85 |
item.price_cents |
| 86 |
}; |
| 87 |
|
| 88 |
|
| 89 |
if final_price_cents == 0 { |
| 90 |
return Err(AppError::BadRequest( |
| 91 |
"Free items use /api/checkout/guest-free/{item_id} instead".to_string(), |
| 92 |
)); |
| 93 |
} |
| 94 |
|
| 95 |
|
| 96 |
let mut promo_code_id = None; |
| 97 |
if let Some(code_str) = body |
| 98 |
.promo_code |
| 99 |
.as_deref() |
| 100 |
.map(str::trim) |
| 101 |
.filter(|s| !s.is_empty()) |
| 102 |
{ |
| 103 |
if item.pwyw_enabled { |
| 104 |
return Err(AppError::BadRequest( |
| 105 |
"Promo codes cannot be applied to pay-what-you-want items".to_string(), |
| 106 |
)); |
| 107 |
} |
| 108 |
|
| 109 |
if let Some(validated) = |
| 110 |
db::promo_codes::lookup_and_validate_promo(&db, seller_id, None, code_str).await? |
| 111 |
{ |
| 112 |
use db::promo_codes::{PromoApplication, PromoIneligible}; |
| 113 |
match db::promo_codes::apply_promo_to_item( |
| 114 |
&validated, |
| 115 |
item_id, |
| 116 |
item.project_id, |
| 117 |
item.price_cents, |
| 118 |
)? { |
| 119 |
PromoApplication::Apply(applied) => { |
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
if applied.funding.platform_credit_cents() > 0 { |
| 124 |
return Err(AppError::BadRequest( |
| 125 |
"This code cannot be used for guest checkout".to_string(), |
| 126 |
)); |
| 127 |
} |
| 128 |
final_price_cents = applied.price_cents; |
| 129 |
} |
| 130 |
PromoApplication::Ineligible(PromoIneligible::ScopeMismatch) => { |
| 131 |
return Err(AppError::BadRequest( |
| 132 |
"This promo code is not valid for this item".to_string(), |
| 133 |
)); |
| 134 |
} |
| 135 |
PromoApplication::Ineligible(PromoIneligible::BelowMinPrice) => { |
| 136 |
return Err(AppError::BadRequest( |
| 137 |
"This item does not meet the minimum price for this code".to_string(), |
| 138 |
)); |
| 139 |
} |
| 140 |
} |
| 141 |
promo_code_id = Some(validated.id()); |
| 142 |
} |
| 143 |
} |
| 144 |
|
| 145 |
|
| 146 |
if final_price_cents == 0 { |
| 147 |
return Err(AppError::BadRequest( |
| 148 |
"Free items use /api/checkout/guest-free/{item_id} instead".to_string(), |
| 149 |
)); |
| 150 |
} |
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
crate::payments::check_min_charge(final_price_cents as i64, seller.settlement_currency)?; |
| 157 |
|
| 158 |
|
| 159 |
let stripe_account_id = seller |
| 160 |
.stripe_account_id |
| 161 |
.as_deref() |
| 162 |
.ok_or_else(|| AppError::BadRequest("Creator hasn't set up payments yet".to_string()))?; |
| 163 |
if !seller.stripe_charges_enabled { |
| 164 |
return Err(AppError::BadRequest( |
| 165 |
"Creator's payment account is not ready".to_string(), |
| 166 |
)); |
| 167 |
} |
| 168 |
|
| 169 |
let stripe = payments |
| 170 |
.stripe |
| 171 |
.as_ref() |
| 172 |
.ok_or_else(|| AppError::BadRequest("Stripe is not configured".to_string()))?; |
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
if let Some(pc_id) = promo_code_id { |
| 181 |
let reserved = db::promo_codes::try_increment_use_count(&db, pc_id) |
| 182 |
.await |
| 183 |
.context("reserve promo code use at guest checkout")?; |
| 184 |
if !reserved { |
| 185 |
return Err(AppError::BadRequest( |
| 186 |
"This promo code has reached its usage limit".to_string(), |
| 187 |
)); |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
|
| 192 |
let release_promo = || async { |
| 193 |
if let Some(pc_id) = promo_code_id { |
| 194 |
db::promo_codes::release_use_count(&db, pc_id).await.ok(); |
| 195 |
} |
| 196 |
}; |
| 197 |
|
| 198 |
|
| 199 |
let success_url = format!( |
| 200 |
"{}/stripe/success?session_id={{CHECKOUT_SESSION_ID}}", |
| 201 |
config.host_url |
| 202 |
); |
| 203 |
let cancel_url = format!("{}/i/{}", config.host_url, item_id); |
| 204 |
|
| 205 |
|
| 206 |
let checkout_params = crate::payments::GuestCheckoutParams { |
| 207 |
connected_account_id: stripe_account_id, |
| 208 |
item_title: &item.title, |
| 209 |
amount_cents: Cents::new(final_price_cents as i64), |
| 210 |
seller_id, |
| 211 |
item_id, |
| 212 |
success_url: &success_url, |
| 213 |
cancel_url: &cancel_url, |
| 214 |
promo_code_id, |
| 215 |
enable_stripe_tax: seller.stripe_tax_enabled, |
| 216 |
currency: seller.settlement_currency, |
| 217 |
|
| 218 |
|
| 219 |
conversion: crate::currency::ConversionChoice::default(), |
| 220 |
}; |
| 221 |
let result = match stripe.create_guest_checkout_session(&checkout_params).await { |
| 222 |
Ok(r) => r, |
| 223 |
Err(e) => { |
| 224 |
release_promo().await; |
| 225 |
return Err(e) |
| 226 |
.with_context(|| format!("create guest Stripe checkout for item {item_id}")); |
| 227 |
} |
| 228 |
}; |
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
match db::transactions::create_transaction( |
| 236 |
&db, |
| 237 |
&db::transactions::CreateTransactionParams { |
| 238 |
buyer_id: None, |
| 239 |
seller_id, |
| 240 |
item_id: Some(item_id), |
| 241 |
amount_cents: final_price_cents.into(), |
| 242 |
platform_fee_cents: Cents::ZERO, |
| 243 |
stripe_checkout_session_id: &result.id, |
| 244 |
item_title: &item.title, |
| 245 |
seller_username: &seller.username, |
| 246 |
share_contact: false, |
| 247 |
project_id: Some(item.project_id), |
| 248 |
promo_code_id, |
| 249 |
guest_email: None, |
| 250 |
platform_credit_cents: 0, |
| 251 |
}, |
| 252 |
) |
| 253 |
.await |
| 254 |
{ |
| 255 |
Ok(_) => {} |
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
Err(AppError::Database(sqlx::Error::Database(ref db_err))) |
| 267 |
if db_err.code().as_deref() == Some("23505") => |
| 268 |
{ |
| 269 |
release_promo().await; |
| 270 |
tracing::info!(item_id = %item_id, "duplicate pending guest checkout blocked"); |
| 271 |
return Err(AppError::BadRequest( |
| 272 |
"A checkout for this item is already in progress. Please complete or cancel it before starting another.".to_string(), |
| 273 |
)); |
| 274 |
} |
| 275 |
Err(e) => { |
| 276 |
release_promo().await; |
| 277 |
return Err(e).context("create pending guest transaction"); |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
let checkout_url = result |
| 282 |
.url |
| 283 |
.ok_or_else(|| AppError::BadRequest("No checkout URL returned".to_string()))?; |
| 284 |
|
| 285 |
let mut response = Json(CheckoutResponse { checkout_url }).into_response(); |
| 286 |
|
| 287 |
|
| 288 |
let headers = response.headers_mut(); |
| 289 |
headers.insert( |
| 290 |
header::ACCESS_CONTROL_ALLOW_ORIGIN, |
| 291 |
HeaderValue::from_static("*"), |
| 292 |
); |
| 293 |
headers.insert( |
| 294 |
header::ACCESS_CONTROL_ALLOW_METHODS, |
| 295 |
HeaderValue::from_static("POST, OPTIONS"), |
| 296 |
); |
| 297 |
headers.insert( |
| 298 |
header::ACCESS_CONTROL_ALLOW_HEADERS, |
| 299 |
HeaderValue::from_static("content-type"), |
| 300 |
); |
| 301 |
|
| 302 |
Ok(response) |
| 303 |
} |
| 304 |
|
| 305 |
|
| 306 |
pub(super) async fn guest_checkout_preflight() -> Response { |
| 307 |
let mut response = StatusCode::NO_CONTENT.into_response(); |
| 308 |
let headers = response.headers_mut(); |
| 309 |
headers.insert( |
| 310 |
header::ACCESS_CONTROL_ALLOW_ORIGIN, |
| 311 |
HeaderValue::from_static("*"), |
| 312 |
); |
| 313 |
headers.insert( |
| 314 |
header::ACCESS_CONTROL_ALLOW_METHODS, |
| 315 |
HeaderValue::from_static("POST, OPTIONS"), |
| 316 |
); |
| 317 |
headers.insert( |
| 318 |
header::ACCESS_CONTROL_ALLOW_HEADERS, |
| 319 |
HeaderValue::from_static("content-type"), |
| 320 |
); |
| 321 |
headers.insert( |
| 322 |
header::ACCESS_CONTROL_MAX_AGE, |
| 323 |
HeaderValue::from_static("86400"), |
| 324 |
); |
| 325 |
response |
| 326 |
} |
| 327 |
|
| 328 |
|
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
#[tracing::instrument(skip_all, name = "guest_checkout::download")] |
| 333 |
pub(super) async fn guest_download( |
| 334 |
State(db): State<PgPool>, |
| 335 |
State(storage): State<AppStorage>, |
| 336 |
Path(token): Path<db::DownloadToken>, |
| 337 |
) -> Result<Response> { |
| 338 |
let tx = db::transactions::get_transaction_by_download_token(&db, token) |
| 339 |
.await? |
| 340 |
.ok_or(AppError::NotFound)?; |
| 341 |
|
| 342 |
let item_id = tx.item_id.ok_or(AppError::NotFound)?; |
| 343 |
let item = db::items::get_item_by_id(&db, item_id) |
| 344 |
.await? |
| 345 |
.ok_or(AppError::NotFound)?; |
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
|
| 353 |
|
| 354 |
let (s3_key, scan_status) = match item.audio_s3_key.clone().or(item.video_s3_key.clone()) { |
| 355 |
Some(key) => (key, item.scan_status), |
| 356 |
None => db::versions::get_versions_by_item(&db, item_id) |
| 357 |
.await? |
| 358 |
.into_iter() |
| 359 |
.filter_map(|v| { |
| 360 |
v.s3_key |
| 361 |
.map(|k| (k, v.scan_status, v.is_current, v.created_at)) |
| 362 |
}) |
| 363 |
|
| 364 |
|
| 365 |
.max_by(|a, b| a.2.cmp(&b.2).then(a.3.cmp(&b.3))) |
| 366 |
.map(|(key, status, _, _)| (key, status)) |
| 367 |
.ok_or(AppError::NotFound)?, |
| 368 |
}; |
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
if scan_status != db::FileScanStatus::Clean { |
| 376 |
return Err(AppError::NotFound); |
| 377 |
} |
| 378 |
|
| 379 |
let s3 = storage.s3.as_ref().ok_or_else(|| { |
| 380 |
AppError::ServiceUnavailable("File storage is not configured".to_string()) |
| 381 |
})?; |
| 382 |
|
| 383 |
let download_url = s3 |
| 384 |
.presign_download(&crate::storage::S3Key::from_stored(&s3_key), Some(3600)) |
| 385 |
.await?; |
| 386 |
|
| 387 |
Ok(Redirect::temporary(&download_url).into_response()) |
| 388 |
} |
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
#[tracing::instrument(skip_all, name = "guest_checkout::claim")] |
| 394 |
pub(super) async fn claim_purchase( |
| 395 |
State(db): State<PgPool>, |
| 396 |
State(integrations): State<Integrations>, |
| 397 |
crate::auth::AuthUser(user): crate::auth::AuthUser, |
| 398 |
Json(body): Json<ClaimRequest>, |
| 399 |
) -> Result<Response> { |
| 400 |
user.check_not_sandbox()?; |
| 401 |
let tx = db::transactions::claim_guest_purchase(&db, body.claim_token, user.id) |
| 402 |
.await? |
| 403 |
.ok_or_else(|| AppError::BadRequest("Invalid or already-claimed token".to_string()))?; |
| 404 |
|
| 405 |
tracing::info!( |
| 406 |
user_id = %user.id, |
| 407 |
transaction_id = %tx.id, |
| 408 |
"guest purchase claimed" |
| 409 |
); |
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
if let Some(item_id) = tx.item_id { |
| 418 |
crate::routes::stripe::webhook::checkout_helpers::maybe_generate_license_key( |
| 419 |
&db, |
| 420 |
integrations.wam.as_ref(), |
| 421 |
item_id, |
| 422 |
user.id, |
| 423 |
tx.id, |
| 424 |
) |
| 425 |
.await; |
| 426 |
} |
| 427 |
|
| 428 |
Ok(StatusCode::OK.into_response()) |
| 429 |
} |
| 430 |
|
| 431 |
#[derive(Debug, Deserialize)] |
| 432 |
pub(super) struct ClaimRequest { |
| 433 |
pub claim_token: db::ClaimToken, |
| 434 |
} |
| 435 |
|
| 436 |
|
| 437 |
#[derive(Debug, Deserialize)] |
| 438 |
pub(super) struct FreeGuestClaimRequest { |
| 439 |
pub email: String, |
| 440 |
} |
| 441 |
|
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
#[tracing::instrument(skip_all, name = "guest_checkout::claim_free")] |
| 447 |
pub(super) async fn claim_free_guest( |
| 448 |
State(db): State<PgPool>, |
| 449 |
State(config): State<Config>, |
| 450 |
State(email_client): State<EmailClient>, |
| 451 |
State(bg): State<BackgroundTx>, |
| 452 |
Path(item_id): Path<ItemId>, |
| 453 |
Json(body): Json<FreeGuestClaimRequest>, |
| 454 |
) -> Result<Response> { |
| 455 |
let email = db::Email::new(&body.email) |
| 456 |
.map_err(|_| AppError::BadRequest("Invalid email address".to_string()))?; |
| 457 |
|
| 458 |
let item = db::items::get_item_by_id(&db, item_id) |
| 459 |
.await? |
| 460 |
.ok_or(AppError::NotFound)?; |
| 461 |
|
| 462 |
if !item.is_public || !item.listed || item.price_cents != 0 { |
| 463 |
return Err(AppError::NotFound); |
| 464 |
} |
| 465 |
|
| 466 |
|
| 467 |
let project = db::projects::get_project_by_id(&db, item.project_id) |
| 468 |
.await? |
| 469 |
.ok_or(AppError::NotFound)?; |
| 470 |
let seller = db::users::get_user_by_id(&db, project.user_id) |
| 471 |
.await? |
| 472 |
.ok_or(AppError::NotFound)?; |
| 473 |
|
| 474 |
if seller.is_suspended() || seller.is_deactivated() || seller.is_creator_paused() { |
| 475 |
return Err(AppError::NotFound); |
| 476 |
} |
| 477 |
|
| 478 |
|
| 479 |
|
| 480 |
|
| 481 |
let claim_token = db::ClaimToken::new(); |
| 482 |
let download_token = db::DownloadToken::new(); |
| 483 |
let checkout_session_id = format!("free-guest-{email}-{item_id}"); |
| 484 |
|
| 485 |
|
| 486 |
let result = db::transactions::create_free_guest_transaction( |
| 487 |
&db, |
| 488 |
None, |
| 489 |
seller.id, |
| 490 |
item_id, |
| 491 |
&checkout_session_id, |
| 492 |
&item.title, |
| 493 |
&seller.username, |
| 494 |
email.as_str(), |
| 495 |
Some(claim_token), |
| 496 |
download_token, |
| 497 |
) |
| 498 |
.await; |
| 499 |
|
| 500 |
match result { |
| 501 |
Ok(0) => { |
| 502 |
|
| 503 |
} |
| 504 |
Ok(_) => { |
| 505 |
let _ = db::items::increment_sales_count(&db, item_id).await; |
| 506 |
} |
| 507 |
Err(e) => { |
| 508 |
|
| 509 |
if let sqlx::Error::Database(ref db_err) = e { |
| 510 |
if db_err.code().as_deref() == Some("23505") { |
| 511 |
|
| 512 |
} else { |
| 513 |
return Err(AppError::Database(e)); |
| 514 |
} |
| 515 |
} else { |
| 516 |
return Err(AppError::Database(e)); |
| 517 |
} |
| 518 |
} |
| 519 |
} |
| 520 |
|
| 521 |
|
| 522 |
let host_url = &config.host_url; |
| 523 |
let download_url = format!("{host_url}/download/{download_token}"); |
| 524 |
let claim_url = format!("{host_url}/claim?token={claim_token}"); |
| 525 |
|
| 526 |
|
| 527 |
{ |
| 528 |
let email_client = email_client.clone(); |
| 529 |
let email_addr = email.clone().into_inner(); |
| 530 |
let item_title = item.title.clone(); |
| 531 |
let dl_url = download_url.clone(); |
| 532 |
let cl_url = claim_url; |
| 533 |
bg.spawn("free guest claim email", async move { |
| 534 |
if let Err(e) = email_client |
| 535 |
.send_guest_purchase_confirmation( |
| 536 |
&email_addr, |
| 537 |
&item_title, |
| 538 |
"Free", |
| 539 |
&dl_url, |
| 540 |
&cl_url, |
| 541 |
) |
| 542 |
.await |
| 543 |
{ |
| 544 |
tracing::error!(error = ?e, "failed to send free guest claim email"); |
| 545 |
} |
| 546 |
}); |
| 547 |
} |
| 548 |
|
| 549 |
let mut response = Json(serde_json::json!({ |
| 550 |
"status": "claimed", |
| 551 |
"download_url": download_url, |
| 552 |
})) |
| 553 |
.into_response(); |
| 554 |
|
| 555 |
|
| 556 |
let headers = response.headers_mut(); |
| 557 |
headers.insert( |
| 558 |
header::ACCESS_CONTROL_ALLOW_ORIGIN, |
| 559 |
HeaderValue::from_static("*"), |
| 560 |
); |
| 561 |
|
| 562 |
Ok(response) |
| 563 |
} |
| 564 |
|