//! Stripe test helpers — webhook signature computation and mock payment provider. use hmac::{Hmac, Mac}; use sha2::Sha256; use std::sync::Mutex; use std::time::{SystemTime, UNIX_EPOCH}; use makenotwork::error::{AppError, Result}; use makenotwork::payments::{ AccountUpdate, BalanceSummary, CheckoutParams, CheckoutResult, PaymentProvider, SubscriptionCheckoutParams, TipCheckoutParams, }; #[allow(dead_code)] type HmacSha256 = Hmac; /// Known test webhook secret used by the test harness `with_stripe()` builder. #[allow(dead_code)] pub const TEST_WEBHOOK_SECRET: &str = "whsec_test_secret"; /// Known test webhook secret for v2 thin events. #[allow(dead_code)] pub const TEST_WEBHOOK_SECRET_V2: &str = "whsec_test_secret_v2"; /// Compute a valid `Stripe-Signature` header value for the given payload. /// /// Mirrors Stripe's signing scheme: /// signed_payload = "{timestamp}.{payload}" /// signature = HMAC-SHA256(secret, signed_payload) /// header = "t={timestamp},v1={hex(signature)}" #[allow(dead_code)] pub fn sign_webhook_payload(payload: &str, secret: &str) -> String { let timestamp = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs(); sign_webhook_payload_with_timestamp(payload, secret, timestamp) } /// Like [`sign_webhook_payload`] but with an explicit timestamp (seconds since epoch). #[allow(dead_code)] pub fn sign_webhook_payload_with_timestamp(payload: &str, secret: &str, timestamp: u64) -> String { let signed_payload = format!("{}.{}", timestamp, payload); let mut mac = HmacSha256::new_from_slice(secret.as_bytes()) .expect("HMAC accepts any key length"); mac.update(signed_payload.as_bytes()); let result = mac.finalize(); let hex_sig = hex::encode(result.into_bytes()); format!("t={},v1={}", timestamp, hex_sig) } /// Record of a checkout session created by the mock. #[derive(Debug, Clone)] #[allow(dead_code)] pub struct MockCheckout { pub id: String, pub url: String, } /// Mock payment provider for integration tests. /// /// Returns predictable fake data for all operations. Records checkout /// creations so tests can assert on them. Webhook verification uses the /// test webhook secrets defined above. pub struct MockPaymentProvider { checkouts: Mutex>, next_checkout_id: Mutex, } #[allow(dead_code)] impl MockPaymentProvider { pub fn new() -> Self { MockPaymentProvider { checkouts: Mutex::new(Vec::new()), next_checkout_id: Mutex::new(1), } } /// Return all checkouts created so far. pub fn checkouts(&self) -> Vec { self.checkouts.lock().unwrap().clone() } fn next_session(&self) -> CheckoutResult { let mut counter = self.next_checkout_id.lock().unwrap(); let id = format!("cs_test_{}", *counter); let url = format!("https://checkout.stripe.com/test/{}", id); *counter += 1; self.checkouts.lock().unwrap().push(MockCheckout { id: id.clone(), url: url.clone(), }); CheckoutResult { id, url: Some(url) } } } #[async_trait::async_trait] impl PaymentProvider for MockPaymentProvider { async fn create_checkout_session(&self, _params: &CheckoutParams<'_>) -> Result { Ok(self.next_session()) } async fn create_guest_checkout_session(&self, _params: &makenotwork::payments::GuestCheckoutParams<'_>) -> Result { Ok(self.next_session()) } async fn create_subscription_checkout_session(&self, _params: &SubscriptionCheckoutParams<'_>) -> Result { Ok(self.next_session()) } async fn create_tip_checkout_session(&self, _params: &TipCheckoutParams<'_>) -> Result { Ok(self.next_session()) } async fn create_fan_plus_checkout_session(&self, _price_id: &str, _user_id: makenotwork::db::UserId, _success_url: &str, _cancel_url: &str) -> Result { Ok(self.next_session()) } async fn create_creator_tier_checkout_session(&self, _price_id: &str, _user_id: makenotwork::db::UserId, _tier: &str, _success_url: &str, _cancel_url: &str) -> Result { Ok(self.next_session()) } async fn create_cart_checkout_session(&self, _params: &makenotwork::payments::CartCheckoutParams<'_>) -> Result { Ok(self.next_session()) } async fn create_connect_account(&self, _email: &str) -> Result { Ok("acct_test_mock".to_string()) } async fn create_account_link(&self, _account_id: &str, _return_url: &str, _refresh_url: &str) -> Result { Ok("https://connect.stripe.com/test/onboarding".to_string()) } async fn fetch_account(&self, account_id: &str) -> Result { Ok(AccountUpdate { account_id: account_id.to_string(), charges_enabled: true, payouts_enabled: true, details_submitted: true, }) } async fn create_subscription_product_and_price(&self, _connected_account_id: &str, _tier_name: &str, _tier_description: Option<&str>, _price_cents: i64) -> Result<(String, String)> { Ok(("prod_test_mock".to_string(), "price_test_mock".to_string())) } async fn get_balance(&self, _account_id: &str) -> Result { Ok(BalanceSummary { available_cents: 0, pending_cents: 0 }) } fn verify_webhook(&self, payload: &str, signature: &str) -> Result { makenotwork::payments::verify_signature(payload, signature, TEST_WEBHOOK_SECRET) .map_err(AppError::BadRequest)?; makenotwork::payments::UntypedEvent::from_payload(payload) } fn verify_webhook_v2(&self, payload: &str, signature: &str) -> Result { makenotwork::payments::verify_signature(payload, signature, TEST_WEBHOOK_SECRET_V2) .map_err(AppError::BadRequest)?; serde_json::from_str(payload) .map_err(|e| AppError::BadRequest(format!("Invalid payload: {}", e))) } async fn pause_subscription(&self, _stripe_sub_id: &str, _connected_account_id: &str) -> Result<()> { Ok(()) } async fn resume_subscription(&self, _stripe_sub_id: &str, _connected_account_id: &str) -> Result<()> { Ok(()) } async fn cancel_subscription(&self, _stripe_sub_id: &str, _connected_account_id: &str) -> Result<()> { Ok(()) } async fn set_cancel_at_period_end(&self, _stripe_sub_id: &str, _connected_account_id: &str, _cancel: bool) -> Result<()> { Ok(()) } async fn cancel_platform_subscription(&self, _stripe_sub_id: &str) -> Result<()> { Ok(()) } async fn set_platform_cancel_at_period_end(&self, _stripe_sub_id: &str, _cancel: bool) -> Result<()> { Ok(()) } async fn create_billing_portal_session(&self, _stripe_customer_id: &str, return_url: &str) -> Result { // Echo a deterministic URL so tests can assert the redirect target. Ok(format!("https://billing.stripe.test/portal?return={}", urlencoding::encode(return_url))) } async fn create_refund(&self, _payment_intent_id: &str, _connected_account_id: &str) -> Result<()> { Ok(()) } async fn create_synckit_customer(&self, _developer_user_id: makenotwork::db::UserId, _email: &str, _app_name: &str) -> Result { // Deterministic dummy; tests assert on shape, not content. Ok("cus_test_synckit".to_string()) } async fn create_synckit_subscription(&self, _customer_id: &str, app_id: makenotwork::db::SyncAppId, _app_name: &str, _price_cents: i64) -> Result { let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64; Ok(makenotwork::payments::SynckitSubResult { subscription_id: format!("sub_test_{}", app_id), current_period_start: now, current_period_end: now + 30 * 24 * 60 * 60, }) } async fn update_synckit_subscription_price(&self, _subscription_id: &str, _new_price_cents: i64, _app_name: &str) -> Result<()> { Ok(()) } async fn update_synckit_app_sub_price(&self, _subscription_id: &str, _new_price_cents: i64, _interval: makenotwork::payments::SyncBillingInterval, _product_name: &str) -> Result<()> { Ok(()) } async fn create_synckit_app_sub_checkout_session(&self, _params: &makenotwork::payments::SynckitAppSubCheckoutParams<'_>) -> Result { Ok(self.next_session()) } async fn cancel_synckit_subscription(&self, _subscription_id: &str) -> Result<()> { Ok(()) } async fn create_synckit_billing_portal(&self, _customer_id: &str, return_url: &str) -> Result { Ok(format!("https://billing.stripe.test/portal?return={}", urlencoding::encode(return_url))) } }