consolidate checkout code paths

This commit is contained in:
Brandon Thomas committed 2026-01-30 22:36:20 -05:00
1 parent 1a49fc5ed9
commit e756bf095c
7 files changed
+166 -179

No files matched your search

@@ -4,7 +4,7 @@ use tokens::tokens::users::UserToken;
pub (super) struct CreationPayload {
pub checkout_session: CheckoutSession,
pub maybe_user_metadata: Option<UserMetadata>
pub maybe_new_user_metadata: Option<UserMetadata>
}
pub (super) struct UserMetadata {
@@ -1,5 +1,6 @@
use crate::configs::stripe_artcraft_metadata_keys::{STRIPE_ARTCRAFT_METADATA_EMAIL, STRIPE_ARTCRAFT_METADATA_USERNAME, STRIPE_ARTCRAFT_METADATA_USER_TOKEN};
use crate::configs::subscriptions::get_artcraft_subscription_by_slug_and_env::get_artcraft_subscription_by_slug_and_env;
use crate::endpoints::checkout_with_user_signup::creation_payload::{CreationPayload, UserMetadata};
use crate::endpoints::checkout_with_user_signup::user_creation_case::user_creation_case;
use crate::endpoints::checkout_with_user_signup::user_exists_case::user_exists_case;
use crate::utils::artcraft_stripe_config::ArtcraftStripeConfigWithClient;
@@ -8,10 +9,10 @@ use actix_artcraft::sessions::http_user_session_manager::HttpUserSessionManager;
use actix_web::web::{Data, Json};
use actix_web::{web, HttpRequest, HttpResponse};
use artcraft_api_defs::stripe_artcraft::create_create_new_user_account_and_subscription_checkout::{PlanBillingCadence, SessionDetails, StripeArtcraftCreateSubscriptionCheckoutWithUserSignupRequest, StripeArtcraftCreateSubscriptionCheckoutWithUserSignupResponse, UserDetails};
use http_headers::
use component_traits::traits::internal_user_lookup::InternalUserLookup;
use enums::common::artcraft_subscription_slug::ArtcraftSubscriptionSlug;
use enums::common::payments_namespace::PaymentsNamespace;
use http_headers::values::content_type::CONTENT_TYPE_APPLICATION_JSON;
use log::{error, info, warn};
use mysql_queries::queries::users::user_stripe_customer_links::find_user_stripe_customer_link::find_user_stripe_customer_link_using_connection;
use mysql_queries::queries::users::user_subscriptions::find_possibly_inactive_first_subscription_for_owner_user::find_possibly_inactive_first_subscription_for_owner_user_using_connection;
@@ -25,9 +26,8 @@ use stripe_checkout::checkout_session::{CreateCheckoutSession, CreateCheckoutSes
use stripe_checkout::CheckoutSessionMode;
use stripe_core::CustomerId;
use stripe_shared::CheckoutSession;
use http_headers::values::content_type::CONTENT_TYPE_APPLICATION_JSON;
use user_traits_component::traits::internal_session_cache_purge::InternalSessionCachePurge;
use crate::endpoints::checkout_with_user_signup::creation_payload::{CreationPayload, UserMetadata};
// /// Create a new user account and Stripe Checkout session and return the redirect URL in Json.
// #[utoipa::path(
// get,
@@ -111,9 +111,15 @@ pub async fn stripe_artcraft_create_checkout_with_user_signup_handler(
// Best effort to delete Redis session cache
internal_session_cache_purge.best_effort_purge_session_cache(&http_request);
match creation_payload.maybe_user_metadata {
None => create_http_response_existing_user(creation_payload.checkout_session)
Some(_) => {}
match creation_payload.maybe_new_user_metadata {
None => {
info!("delevering response for existing user...");
create_http_response_existing_user(creation_payload.checkout_session)
}
Some(user_metadata) => {
info!("delevering response for new user...");
create_http_response_new_user(&session_cookie_manager, creation_payload.checkout_session, user_metadata)
}
}
}
@@ -2,6 +2,7 @@ use crate::configs::stripe_artcraft_metadata_keys::{STRIPE_ARTCRAFT_METADATA_EMA
use crate::endpoints::checkout_with_user_signup::creation_payload::{CreationPayload, UserMetadata};
use crate::utils::artcraft_stripe_config::ArtcraftStripeConfigWithClient;
use crate::utils::common_web_error::CommonWebError;
use crate::utils::create_checkout::create_subscription_checkout_session::{create_subscription_checkout_session, CreateSubscriptionCheckoutSessionArgs};
use actix_artcraft::requests::get_request_signup_source_enum::get_request_signup_source_enum;
use actix_web::HttpRequest;
use enums::by_table::users::user_feature_flag::UserFeatureFlag;
@@ -10,20 +11,20 @@ use log::{error, info, warn};
use mysql_queries::queries::users::user::create::create_account_error::CreateAccountError;
use mysql_queries::queries::users::user::create::create_account_from_google_sso::{create_account_from_google_sso, CreateAccountFromGoogleSsoArgs};
use mysql_queries::queries::users::user::create::create_account_from_stripe_checkout::{create_account_from_stripe_checkout, CreateAccountFromStripeCheckoutArgs};
use mysql_queries::queries::users::user_sessions::create_user_session_with_transactor::create_user_session_with_transactor;
use mysql_queries::utils::transactor::Transactor;
use sqlx::pool::PoolConnection;
use sqlx::{Acquire, MySql};
use std::collections::HashMap;
use stripe_checkout::checkout_session::{CreateCheckoutSession, CreateCheckoutSessionAutomaticTax, CreateCheckoutSessionLineItems, CreateCheckoutSessionSavedPaymentMethodOptions, CreateCheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilters, CreateCheckoutSessionSavedPaymentMethodOptionsPaymentMethodSave, CreateCheckoutSessionSubscriptionData};
use stripe_shared::{CheckoutSession, CheckoutSessionMode};
use mysql_queries::queries::users::user_sessions::create_user_session_with_transactor::create_user_session_with_transactor;
use stripe_shared::{CheckoutSession, CheckoutSessionMode, PriceId};
use users::email::email_to_gravatar::email_to_gravatar;
use users::email::generate_random_synthetic_email::generate_random_synthetic_email;
use users::username::generate_random_username::generate_random_username;
pub (super) async fn user_creation_case(
http_request: &HttpRequest,
price_id: &str,
price_id: &PriceId,
mysql_connection: &mut PoolConnection<MySql>,
stripe_config: &ArtcraftStripeConfigWithClient,
) -> Result<CreationPayload, CommonWebError> {
@@ -131,87 +132,20 @@ pub (super) async fn user_creation_case(
CommonWebError::ServerError
})?;
let success_url = stripe_config.checkout_success_url.clone();
let cancel_url = stripe_config.checkout_cancel_url.clone();
let checkout_session = {
// `client_reference_id`
// Stripe Docs:
// A unique string to reference the Checkout Session.
// This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session
// with your internal systems.
//
// Our Notes:
// This gets reported back in the Checkout Session (and related webhooks) as
// `client_reference_id`. Passing the same ID on multiple checkouts does not unify or
// cross-correlate customers and only seems to be metadata for the checkout session itself.
// This is probably only useful for tracking checkout session engagement.
//params.client_reference_id = Some("SOME_INTERNAL_ID");
// `customer_email`
// Stripe Docs:
// If provided, this value will be used when the Customer object is created. If not provided,
// customers will be asked to enter their email address. Use this parameter to prefill
// customer data if you already have an email on file. To access information about the
// customer once a session is complete, use the customer field.
//
// Our Notes:
// This does not look up previous customers with the same email and will not unify or
// cross-correlate customers. By default the field will be un-editable in the checkout flow
// if this is specified.
//params.customer_email = Some("email@example.com");
let mut metadata = HashMap::new();
// NB: We don't insert email or username as these are synthetic.
metadata.insert(STRIPE_ARTCRAFT_METADATA_USER_TOKEN.to_string(), final_user_token.to_string());
let mut checkout_builder = CreateCheckoutSession::new()
.success_url(&success_url)
.cancel_url(&cancel_url)
.mode(CheckoutSessionMode::Subscription)
.line_items(vec![
CreateCheckoutSessionLineItems {
price: Some(price_id.to_string()),
quantity: Some(1),
..Default::default()
}
])
.saved_payment_method_options(CreateCheckoutSessionSavedPaymentMethodOptions {
allow_redisplay_filters: Some(vec![
CreateCheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilters::Always,
CreateCheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilters::Limited,
CreateCheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilters::Unspecified,
]),
// The user can choose to tick a checkbox that saves their card for redisplay later.
payment_method_save: Some(CreateCheckoutSessionSavedPaymentMethodOptionsPaymentMethodSave::Enabled),
})
.allow_promotion_codes(true) // Allow promo codes / coupons
.automatic_tax(CreateCheckoutSessionAutomaticTax {
enabled: true, // This will ask for the customer's location
liability: None,
})
.metadata(metadata.clone())
.subscription_data(CreateCheckoutSessionSubscriptionData {
metadata: Some(metadata),
..Default::default()
})
;
let checkout_session = checkout_builder
.send(&stripe_config.client)
.await
.map_err(|err| {
error!("Stripe Error: {:?}", err);
CommonWebError::ServerError
})?;
checkout_session
};
let checkout_session = create_subscription_checkout_session(CreateSubscriptionCheckoutSessionArgs {
subscription_price_id: price_id,
maybe_existing_stripe_customer_id: None,
user_token: &final_user_token,
username: None,
user_email: None,
stripe_client: &stripe_config.client,
success_url: &stripe_config.checkout_success_url,
cancel_url: &stripe_config.checkout_cancel_url,
}).await?;
Ok(CreationPayload {
checkout_session,
maybe_user_metadata: Some(UserMetadata {
maybe_new_user_metadata: Some(UserMetadata {
user_token: final_user_token,
session_token,
username: final_username,
@@ -2,6 +2,7 @@ use crate::configs::stripe_artcraft_metadata_keys::{STRIPE_ARTCRAFT_METADATA_EMA
use crate::endpoints::checkout_with_user_signup::creation_payload::CreationPayload;
use crate::utils::artcraft_stripe_config::ArtcraftStripeConfigWithClient;
use crate::utils::common_web_error::CommonWebError;
use crate::utils::create_checkout::create_subscription_checkout_session::{create_subscription_checkout_session, CreateSubscriptionCheckoutSessionArgs};
use actix_web::web::Data;
use component_traits::traits::internal_user_lookup::UserMetadata;
use enums::common::payments_namespace::PaymentsNamespace;
@@ -16,7 +17,7 @@ use stripe_checkout::checkout_session::{CreateCheckoutSession, CreateCheckoutSes
use stripe_shared::{CheckoutSession, CheckoutSessionMode, CustomerId, PriceId};
pub (super) async fn user_exists_case(
price_id: &str,
price_id: &PriceId,
user_metadata: &UserMetadata,
mysql_connection: &mut PoolConnection<MySql>,
stripe_config: &ArtcraftStripeConfigWithClient,
@@ -70,98 +71,19 @@ pub (super) async fn user_exists_case(
warn!("Error looking up user's ({}) existing stripe customer link: {:?}", &user_metadata.user_token_typed, err);
}
let success_url = stripe_config.checkout_success_url.clone();
let cancel_url = stripe_config.checkout_cancel_url.clone();
let checkout_session = {
// `client_reference_id`
// Stripe Docs:
// A unique string to reference the Checkout Session.
// This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session
// with your internal systems.
//
// Our Notes:
// This gets reported back in the Checkout Session (and related webhooks) as
// `client_reference_id`. Passing the same ID on multiple checkouts does not unify or
// cross-correlate customers and only seems to be metadata for the checkout session itself.
// This is probably only useful for tracking checkout session engagement.
//params.client_reference_id = Some("SOME_INTERNAL_ID");
// `customer_email`
// Stripe Docs:
// If provided, this value will be used when the Customer object is created. If not provided,
// customers will be asked to enter their email address. Use this parameter to prefill
// customer data if you already have an email on file. To access information about the
// customer once a session is complete, use the customer field.
//
// Our Notes:
// This does not look up previous customers with the same email and will not unify or
// cross-correlate customers. By default the field will be un-editable in the checkout flow
// if this is specified.
//params.customer_email = Some("email@example.com");
let mut metadata = HashMap::new();
metadata.insert(STRIPE_ARTCRAFT_METADATA_USER_TOKEN.to_string(), user_metadata.user_token.to_string());
if let Some(username) = user_metadata.username.as_deref() {
metadata.insert(STRIPE_ARTCRAFT_METADATA_USERNAME.to_string(), username.to_string());
}
if let Some(user_email) = user_metadata.user_email.as_deref() {
metadata.insert(STRIPE_ARTCRAFT_METADATA_EMAIL.to_string(), user_email.to_string());
}
let mut checkout_builder = CreateCheckoutSession::new()
.success_url(&success_url)
.cancel_url(&cancel_url)
.mode(CheckoutSessionMode::Subscription)
.line_items(vec![
CreateCheckoutSessionLineItems {
price: Some(price_id.to_string()),
quantity: Some(1),
..Default::default()
}
])
.saved_payment_method_options(CreateCheckoutSessionSavedPaymentMethodOptions {
allow_redisplay_filters: Some(vec![
CreateCheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilters::Always,
CreateCheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilters::Limited,
CreateCheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilters::Unspecified,
]),
// The user can choose to tick a checkbox that saves their card for redisplay later.
payment_method_save: Some(CreateCheckoutSessionSavedPaymentMethodOptionsPaymentMethodSave::Enabled),
})
.allow_promotion_codes(true) // Allow promo codes / coupons
.automatic_tax(CreateCheckoutSessionAutomaticTax {
enabled: true, // This will ask for the customer's location
liability: None,
})
.metadata(metadata.clone())
.subscription_data(CreateCheckoutSessionSubscriptionData {
metadata: Some(metadata),
..Default::default()
})
;
if let Some(customer_id) = maybe_existing_stripe_customer_id {
info!("Adding existing stripe customer id to checkout session: {}", customer_id.as_str());
checkout_builder = checkout_builder.customer(customer_id);
}
let checkout_session = checkout_builder
.send(&stripe_config.client)
.await
.map_err(|err| {
error!("Stripe Error: {:?}", err);
CommonWebError::ServerError
})?;
checkout_session
};
let checkout_session = create_subscription_checkout_session(CreateSubscriptionCheckoutSessionArgs {
subscription_price_id: price_id,
maybe_existing_stripe_customer_id: maybe_existing_stripe_customer_id.as_ref(),
user_token: &user_metadata.user_token_typed,
username: user_metadata.username.as_deref(),
user_email: user_metadata.user_email.as_deref(),
stripe_client: &stripe_config.client,
success_url: &stripe_config.checkout_success_url,
cancel_url: &stripe_config.checkout_cancel_url,
}).await?;
Ok(CreationPayload {
checkout_session,
maybe_user_metadata: None,
maybe_new_user_metadata: None,
})
}
@@ -0,0 +1,123 @@
use crate::configs::stripe_artcraft_metadata_keys::{STRIPE_ARTCRAFT_METADATA_EMAIL, STRIPE_ARTCRAFT_METADATA_USERNAME, STRIPE_ARTCRAFT_METADATA_USER_TOKEN};
use crate::utils::common_web_error::CommonWebError;
use log::{error, info};
use std::collections::HashMap;
use stripe::Client;
use stripe_checkout::checkout_session::{CreateCheckoutSession, CreateCheckoutSessionAutomaticTax, CreateCheckoutSessionLineItems, CreateCheckoutSessionSavedPaymentMethodOptions, CreateCheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilters, CreateCheckoutSessionSavedPaymentMethodOptionsPaymentMethodSave, CreateCheckoutSessionSubscriptionData};
use stripe_shared::{CheckoutSession, CheckoutSessionMode, CustomerId, PriceId};
use tokens::tokens::users::UserToken;
pub struct CreateSubscriptionCheckoutSessionArgs<'a> {
/// Subscription is required
pub subscription_price_id: &'a PriceId,
/// Optional: Existing user's Stripe customer id, if it exists.
/// You MUST look this up.
pub maybe_existing_stripe_customer_id: Option<&'a CustomerId>,
/// User is required
pub user_token: &'a UserToken,
/// Username is optional in the case we eagerly created a user account for the user.
pub username: Option<&'a str>,
/// User email is optional in the case we eagerly created a user account for the user.
pub user_email: Option<&'a str>,
pub stripe_client: &'a Client,
pub success_url: &'a str,
pub cancel_url: &'a str,
}
pub async fn create_subscription_checkout_session(args: CreateSubscriptionCheckoutSessionArgs<'_>) -> Result<CheckoutSession, CommonWebError> {
let checkout_session = {
// `client_reference_id`
// Stripe Docs:
// A unique string to reference the Checkout Session.
// This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session
// with your internal systems.
//
// Our Notes:
// This gets reported back in the Checkout Session (and related webhooks) as
// `client_reference_id`. Passing the same ID on multiple checkouts does not unify or
// cross-correlate customers and only seems to be metadata for the checkout session itself.
// This is probably only useful for tracking checkout session engagement.
//params.client_reference_id = Some("SOME_INTERNAL_ID");
// `customer_email`
// Stripe Docs:
// If provided, this value will be used when the Customer object is created. If not provided,
// customers will be asked to enter their email address. Use this parameter to prefill
// customer data if you already have an email on file. To access information about the
// customer once a session is complete, use the customer field.
//
// Our Notes:
// This does not look up previous customers with the same email and will not unify or
// cross-correlate customers. By default the field will be un-editable in the checkout flow
// if this is specified.
//params.customer_email = Some("email@example.com");
let mut metadata = HashMap::new();
metadata.insert(STRIPE_ARTCRAFT_METADATA_USER_TOKEN.to_string(), args.user_token.to_string());
if let Some(username) = args.username.as_deref() {
metadata.insert(STRIPE_ARTCRAFT_METADATA_USERNAME.to_string(), username.to_string());
}
if let Some(user_email) = args.user_email.as_deref() {
metadata.insert(STRIPE_ARTCRAFT_METADATA_EMAIL.to_string(), user_email.to_string());
}
let mut checkout_builder = CreateCheckoutSession::new()
.success_url(args.success_url)
.cancel_url(args.cancel_url)
.mode(CheckoutSessionMode::Subscription)
.line_items(vec![
CreateCheckoutSessionLineItems {
price: Some(args.subscription_price_id.to_string()),
quantity: Some(1),
..Default::default()
}
])
.saved_payment_method_options(CreateCheckoutSessionSavedPaymentMethodOptions {
allow_redisplay_filters: Some(vec![
CreateCheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilters::Always,
CreateCheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilters::Limited,
CreateCheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilters::Unspecified,
]),
// The user can choose to tick a checkbox that saves their card for redisplay later.
payment_method_save: Some(CreateCheckoutSessionSavedPaymentMethodOptionsPaymentMethodSave::Enabled),
})
.allow_promotion_codes(true) // Allow promo codes / coupons
.automatic_tax(CreateCheckoutSessionAutomaticTax {
enabled: true, // This will ask for the customer's location
liability: None,
})
.metadata(metadata.clone())
.subscription_data(CreateCheckoutSessionSubscriptionData {
metadata: Some(metadata),
..Default::default()
})
;
if let Some(customer_id) = args.maybe_existing_stripe_customer_id {
info!("Adding existing stripe customer id to checkout session: {}", customer_id.as_str());
checkout_builder = checkout_builder.customer(customer_id);
}
let checkout_session = checkout_builder
.send(args.stripe_client)
.await
.map_err(|err| {
error!("Stripe Error: {:?}", err);
CommonWebError::ServerError
})?;
checkout_session
};
Ok(checkout_session)
}
@@ -0,0 +1 @@
pub mod create_subscription_checkout_session;
@@ -1,6 +1,7 @@
pub (crate) mod metadata;
pub mod artcraft_stripe_config;
pub mod common_web_error;
pub mod create_checkout;
pub mod enum_conversion;
pub mod expand_ids;
pub mod stripe_event_descriptor;