mod fake;
mod stripe;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, RwLock};
use serde_json::{Value as Json, json};
pub use self::fake::Fake;
pub use self::stripe::Stripe;
use crate::db::migration::Schema;
use crate::db::{self, Sql, Timestamp, Value};
use crate::error::{Error, Result};
pub fn create_tables(s: &mut Schema) {
s.create_table("billing_customers", |t| {
t.string("owner_type");
t.bigint("owner_id");
t.string("processor").not_null();
t.string("processor_id");
t.timestamp("deleted_at");
t.timestamps();
});
s.add_unique_index("billing_customers", &["processor", "processor_id"]);
s.add_index("billing_customers", &["owner_type", "owner_id"]);
s.create_table("billing_subscriptions", |t| {
t.bigint("customer_id").not_null();
t.string("name").not_null();
t.string("processor_id").not_null();
t.string("price").not_null();
t.integer("quantity").not_null().default(1);
t.string("status").not_null();
t.timestamp("current_period_start");
t.timestamp("current_period_end");
t.timestamp("trial_ends_at");
t.timestamp("ends_at");
t.json("metadata");
t.json("data");
t.timestamps();
});
s.add_unique_index("billing_subscriptions", &["customer_id", "processor_id"]);
s.create_table("billing_charges", |t| {
t.bigint("customer_id").not_null();
t.bigint("subscription_id");
t.string("processor_id").not_null();
t.bigint("amount").not_null();
t.string("currency");
t.bigint("amount_refunded");
t.json("metadata");
t.json("data");
t.timestamps();
});
s.add_unique_index("billing_charges", &["customer_id", "processor_id"]);
s.add_index("billing_charges", &["subscription_id"]);
}
pub fn create_pay_tables(s: &mut Schema) {
s.create_table("pay_customers", |t| {
t.string("owner_type");
t.bigint("owner_id");
t.string("processor").not_null();
t.string("processor_id");
t.boolean("default");
t.json("data");
t.string("stripe_account");
t.timestamp("deleted_at");
t.timestamp("created_at").not_null();
t.timestamp("updated_at").not_null();
t.string("type");
t.json("object");
});
s.add_unique_index("pay_customers", &["processor", "processor_id"]);
s.add_unique_index("pay_customers", &["owner_type", "owner_id", "deleted_at"]);
s.create_table("pay_subscriptions", |t| {
t.bigint("customer_id").not_null();
t.string("name").not_null();
t.string("processor_id").not_null();
t.string("processor_plan").not_null();
t.integer("quantity").not_null().default(1);
t.string("status").not_null();
t.timestamp("current_period_start");
t.timestamp("current_period_end");
t.timestamp("trial_ends_at");
t.timestamp("ends_at");
t.boolean("metered");
t.string("pause_behavior");
t.timestamp("pause_starts_at");
t.timestamp("pause_resumes_at");
t.json("metadata");
t.json("data");
t.string("stripe_account");
t.string("payment_method_id");
t.timestamp("created_at").not_null();
t.timestamp("updated_at").not_null();
t.string("type");
t.json("object");
});
s.add_unique_index("pay_subscriptions", &["customer_id", "processor_id"]);
s.create_table("pay_charges", |t| {
t.bigint("customer_id").not_null();
t.bigint("subscription_id");
t.string("processor_id").not_null();
t.integer("amount").not_null();
t.string("currency");
t.integer("application_fee_amount");
t.integer("amount_refunded");
t.json("metadata");
t.json("data");
t.string("stripe_account");
t.timestamp("created_at").not_null();
t.timestamp("updated_at").not_null();
t.string("type");
t.json("object");
});
s.add_unique_index("pay_charges", &["customer_id", "processor_id"]);
}
pub fn copy_from_pay(s: &mut Schema) {
s.execute(
"INSERT INTO billing_customers (id, owner_type, owner_id, processor, processor_id, deleted_at, \
inserted_at, updated_at) \
SELECT id, owner_type, owner_id, processor, processor_id, deleted_at, created_at, updated_at \
FROM pay_customers",
);
s.execute(
"INSERT INTO billing_subscriptions (id, customer_id, name, processor_id, price, quantity, status, \
current_period_start, current_period_end, trial_ends_at, ends_at, metadata, data, inserted_at, updated_at) \
SELECT id, customer_id, name, processor_id, processor_plan, quantity, status, current_period_start, \
current_period_end, trial_ends_at, ends_at, metadata, COALESCE(object, data), created_at, updated_at \
FROM pay_subscriptions",
);
s.execute(
"INSERT INTO billing_charges (id, customer_id, subscription_id, processor_id, amount, currency, \
amount_refunded, metadata, data, inserted_at, updated_at) \
SELECT id, customer_id, subscription_id, processor_id, amount, currency, amount_refunded, metadata, \
COALESCE(object, data), created_at, updated_at FROM pay_charges",
);
if s.dialect() == crate::db::Dialect::Postgres {
for table in [
"billing_customers",
"billing_subscriptions",
"billing_charges",
] {
s.execute(&format!(
"SELECT setval(pg_get_serial_sequence('{table}', 'id'), \
COALESCE((SELECT MAX(id) FROM {table}), 0) + 1, false)"
));
}
}
}
#[derive(Clone, Copy, Debug)]
struct Tables {
customers: &'static str,
subscriptions: &'static str,
charges: &'static str,
inserted_at: &'static str,
price: &'static str,
data: &'static str,
}
const GLACIER_TABLES: Tables = Tables {
customers: "billing_customers",
subscriptions: "billing_subscriptions",
charges: "billing_charges",
inserted_at: "inserted_at",
price: "price",
data: "data",
};
const PAY_TABLES: Tables = Tables {
customers: "pay_customers",
subscriptions: "pay_subscriptions",
charges: "pay_charges",
inserted_at: "created_at",
price: "processor_plan",
data: "object",
};
#[derive(Debug, Clone, PartialEq)]
pub struct Customer {
pub id: i64,
pub owner_type: String,
pub owner_id: i64,
pub processor_id: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Charge {
pub id: i64,
pub customer_id: i64,
pub subscription_id: Option<i64>,
pub processor_id: String,
pub amount: i64,
pub currency: String,
pub amount_refunded: i64,
pub metadata: Json,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Subscription {
pub id: i64,
pub customer_id: i64,
pub processor_id: String,
pub price: String,
pub quantity: i64,
pub status: String,
pub current_period_end: Option<Timestamp>,
pub ends_at: Option<Timestamp>,
pub metadata: Json,
}
impl Subscription {
pub fn is_active(&self) -> bool {
matches!(self.status.as_str(), "active" | "trialing")
|| self.ends_at.is_some_and(|at| at > crate::time::now())
}
}
#[derive(Debug, Clone)]
pub struct Synced<T> {
pub record: T,
pub created: bool,
pub previous_status: Option<String>,
}
#[derive(Debug, Clone)]
pub struct Checkout {
pub mode: &'static str,
pub price: String,
pub quantity: u32,
pub success_url: String,
pub cancel_url: String,
pub metadata: Vec<(String, String)>,
pub allow_promotion_codes: bool,
}
impl Checkout {
pub fn payment(price: &str, success_url: &str, cancel_url: &str) -> Self {
Self {
mode: "payment",
price: price.to_owned(),
quantity: 1,
success_url: success_url.to_owned(),
cancel_url: cancel_url.to_owned(),
metadata: Vec::new(),
allow_promotion_codes: false,
}
}
pub fn subscription(price: &str, success_url: &str, cancel_url: &str) -> Self {
Self {
mode: "subscription",
..Self::payment(price, success_url, cancel_url)
}
}
#[must_use]
pub fn metadata(mut self, key: &str, value: impl ToString) -> Self {
self.metadata.push((key.to_owned(), value.to_string()));
self
}
#[must_use]
pub fn allow_promotion_codes(mut self) -> Self {
self.allow_promotion_codes = true;
self
}
fn success_url_with_id(&self) -> String {
if self.success_url.contains("{CHECKOUT_SESSION_ID}") {
self.success_url.clone()
} else {
let joiner = if self.success_url.contains('?') {
'&'
} else {
'?'
};
format!(
"{}{joiner}session_id={{CHECKOUT_SESSION_ID}}",
self.success_url
)
}
}
}
#[derive(Debug, Clone)]
pub struct CheckoutSession {
pub id: String,
pub url: String,
}
type Pending<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'a>>;
pub trait Processor: Send + Sync + 'static {
fn name(&self) -> &'static str {
"stripe"
}
fn create_customer<'a>(&'a self, email: &'a str) -> Pending<'a, String>;
fn create_checkout<'a>(
&'a self,
customer: &'a str,
checkout: &'a Checkout,
) -> Pending<'a, CheckoutSession>;
fn checkout_session<'a>(&'a self, id: &'a str) -> Pending<'a, Json>;
fn subscription<'a>(&'a self, id: &'a str) -> Pending<'a, Json>;
fn charge<'a>(&'a self, id: &'a str) -> Pending<'a, Json>;
}
type Hook<T> =
Arc<dyn Fn(Synced<T>) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> + Send + Sync>;
#[derive(Clone)]
pub struct Billing {
processor: Arc<dyn Processor>,
tables: Tables,
on_charge: Option<Hook<Charge>>,
on_subscription: Option<Hook<Subscription>>,
}
impl Billing {
pub fn stripe(secret_key: &str) -> Self {
Self::with(Stripe::new(secret_key))
}
pub fn fake() -> Self {
Self::with(Fake::default())
}
pub fn with(processor: impl Processor) -> Self {
Self {
processor: Arc::new(processor),
tables: GLACIER_TABLES,
on_charge: None,
on_subscription: None,
}
}
#[must_use]
pub fn pay_tables(mut self) -> Self {
self.tables = PAY_TABLES;
self
}
#[must_use]
pub fn on_charge<F, Fut>(mut self, hook: F) -> Self
where
F: Fn(Synced<Charge>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.on_charge = Some(Arc::new(move |synced| Box::pin(hook(synced))));
self
}
#[must_use]
pub fn on_subscription<F, Fut>(mut self, hook: F) -> Self
where
F: Fn(Synced<Subscription>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.on_subscription = Some(Arc::new(move |synced| Box::pin(hook(synced))));
self
}
pub fn stripe_webhooks(&self, signing_secrets: &[&str]) -> crate::webhooks::Provider {
let sync = |kind: &'static str| {
move |event: crate::webhooks::Event| async move {
let id = event.payload()["data"]["object"]["id"]
.as_str()
.unwrap_or_default()
.to_owned();
match kind {
"checkout" => sync_checkout(&id).await.map(|_| ()),
"subscription" => sync_subscription(&id).await.map(|_| ()),
_ => sync_charge(&id).await.map(|_| ()),
}
}
};
crate::webhooks::Stripe::new(signing_secrets)
.on("checkout.session.completed", sync("checkout"))
.on("customer.subscription.created", sync("subscription"))
.on("customer.subscription.updated", sync("subscription"))
.on("customer.subscription.deleted", sync("subscription"))
.on("charge.succeeded", sync("charge"))
.on("charge.refunded", sync("charge"))
}
}
static INSTALLED: RwLock<Option<Billing>> = RwLock::new(None);
tokio::task_local! {
static TEST_SLOT: Arc<RwLock<Option<Billing>>>;
}
#[doc(hidden)]
pub async fn with_test_slot<F: Future>(fut: F) -> F::Output {
TEST_SLOT.scope(Arc::default(), fut).await
}
pub(crate) fn install(billing: Billing) {
let in_test = TEST_SLOT
.try_with(|slot| *slot.write().unwrap_or_else(|e| e.into_inner()) = Some(billing.clone()))
.is_ok();
if !in_test {
*INSTALLED.write().unwrap_or_else(|e| e.into_inner()) = Some(billing);
}
}
fn installed() -> Result<Billing> {
TEST_SLOT
.try_with(|slot| slot.read().unwrap_or_else(|e| e.into_inner()).clone())
.ok()
.flatten()
.or_else(|| INSTALLED.read().unwrap_or_else(|e| e.into_inner()).clone())
.ok_or_else(|| Error::internal("billing isn't set up: pass a Billing to App::billing"))
}
pub async fn customer(owner_type: &str, owner_id: i64, email: &str) -> Result<Customer> {
let billing = installed()?;
let processor = billing.processor.name();
let mut sql = Sql::new();
let tables = billing.tables;
sql.push(&format!(
"SELECT id, processor_id FROM {} WHERE owner_type = ",
tables.customers
));
sql.push_value(Value::Text(owner_type.to_owned()));
sql.push(" AND owner_id = ");
sql.push_value(Value::Int(owner_id));
sql.push(" AND processor = ");
sql.push_value(Value::Text(processor.to_owned()));
sql.push(" AND deleted_at IS NULL");
let rows = db::current()?.fetch_all(&sql).await?;
if let Some(row) = rows.first()
&& let Some(processor_id) = row.get::<Option<String>>("processor_id")?
{
return Ok(Customer {
id: id_of(row, "id")?,
owner_type: owner_type.to_owned(),
owner_id,
processor_id,
});
}
let processor_id = billing.processor.create_customer(email).await?;
let now = crate::time::now();
let mut sql = Sql::new();
sql.push(&format!(
"INSERT INTO {} (owner_type, owner_id, processor, processor_id, {}, updated_at) VALUES (",
tables.customers, tables.inserted_at
));
push_values(
&mut sql,
vec![
Value::Text(owner_type.to_owned()),
Value::Int(owner_id),
Value::Text(processor.to_owned()),
Value::Text(processor_id.clone()),
Value::Timestamp(now),
Value::Timestamp(now),
],
);
sql.push(") RETURNING id");
let rows = db::current()?.fetch_all(&sql).await?;
Ok(Customer {
id: id_of(
rows.first()
.ok_or_else(|| Error::internal("no customer id"))?,
"id",
)?,
owner_type: owner_type.to_owned(),
owner_id,
processor_id,
})
}
pub async fn checkout(customer: &Customer, checkout: Checkout) -> Result<CheckoutSession> {
installed()?
.processor
.create_checkout(&customer.processor_id, &checkout)
.await
}
#[derive(Debug, Clone)]
pub enum Purchase {
Charge(Synced<Charge>),
Subscription(Synced<Subscription>),
Nothing(Json),
}
pub async fn sync_checkout(id: &str) -> Result<Purchase> {
let billing = installed()?;
let session = billing.processor.checkout_session(id).await?;
if session["status"] != "complete" {
return Ok(Purchase::Nothing(session));
}
if session["subscription"].is_object() {
return Ok(Purchase::Subscription(
sync_subscription_object(&billing, &session["subscription"]).await?,
));
}
let charge = &session["payment_intent"]["latest_charge"];
if charge.is_object() {
return Ok(Purchase::Charge(
sync_charge_object(&billing, charge).await?,
));
}
Ok(Purchase::Nothing(session))
}
pub async fn sync_subscription(id: &str) -> Result<Synced<Subscription>> {
let billing = installed()?;
let object = billing.processor.subscription(id).await?;
sync_subscription_object(&billing, &object).await
}
pub async fn sync_charge(id: &str) -> Result<Synced<Charge>> {
let billing = installed()?;
let object = billing.processor.charge(id).await?;
sync_charge_object(&billing, &object).await
}
async fn customer_id_for(billing: &Billing, processor_id: &str) -> Result<i64> {
let mut sql = Sql::new();
let tables = billing.tables;
sql.push(&format!(
"SELECT id FROM {} WHERE processor = ",
tables.customers
));
sql.push_value(Value::Text(billing.processor.name().to_owned()));
sql.push(" AND processor_id = ");
sql.push_value(Value::Text(processor_id.to_owned()));
let rows = db::current()?.fetch_all(&sql).await?;
if let Some(row) = rows.first() {
return id_of(row, "id");
}
let now = crate::time::now();
let mut sql = Sql::new();
sql.push(&format!(
"INSERT INTO {} (processor, processor_id, {}, updated_at) VALUES (",
tables.customers, tables.inserted_at
));
push_values(
&mut sql,
vec![
Value::Text(billing.processor.name().to_owned()),
Value::Text(processor_id.to_owned()),
Value::Timestamp(now),
Value::Timestamp(now),
],
);
sql.push(") RETURNING id");
let rows = db::current()?.fetch_all(&sql).await?;
id_of(
rows.first()
.ok_or_else(|| Error::internal("no customer id"))?,
"id",
)
}
fn time(value: &Json) -> Value {
value
.as_i64()
.and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0))
.map_or(Value::Null, Value::Timestamp)
}
async fn sync_subscription_object(
billing: &Billing,
object: &Json,
) -> Result<Synced<Subscription>> {
let customer = object["customer"]
.as_str()
.or_else(|| object["customer"]["id"].as_str())
.unwrap_or_default();
let customer_id = customer_id_for(billing, customer).await?;
let processor_id = object["id"].as_str().unwrap_or_default().to_owned();
let item = &object["items"]["data"][0];
let price = item["price"]["id"]
.as_str()
.or_else(|| object["plan"]["id"].as_str())
.unwrap_or_default()
.to_owned();
let quantity = item["quantity"]
.as_i64()
.or_else(|| object["quantity"].as_i64())
.unwrap_or(1);
let status = object["status"].as_str().unwrap_or("incomplete").to_owned();
let period_end = if object["current_period_end"].is_null() {
&item["current_period_end"]
} else {
&object["current_period_end"]
};
let period_start = if object["current_period_start"].is_null() {
&item["current_period_start"]
} else {
&object["current_period_start"]
};
let ends_at = if object["cancel_at_period_end"] == true {
period_end.clone()
} else {
object["ended_at"].clone()
};
db::transaction(async {
let tables = billing.tables;
let previous = previous_status(tables, customer_id, &processor_id).await?;
let now = crate::time::now();
let mut sql = Sql::new();
sql.push(&format!(
"INSERT INTO {} (customer_id, name, processor_id, {price}, quantity, status, \
current_period_start, current_period_end, trial_ends_at, ends_at, metadata, {data}, {}, updated_at) VALUES (",
tables.subscriptions,
tables.inserted_at,
price = tables.price,
data = tables.data,
));
push_values(
&mut sql,
vec![
Value::Int(customer_id),
Value::Text("default".to_owned()),
Value::Text(processor_id.clone()),
Value::Text(price.clone()),
Value::Int(quantity),
Value::Text(status.clone()),
time(period_start),
time(period_end),
time(&object["trial_end"]),
time(&ends_at),
Value::Json(object["metadata"].clone()),
Value::Json(object.clone()),
Value::Timestamp(now),
Value::Timestamp(now),
],
);
sql.push(&format!(
") ON CONFLICT (customer_id, processor_id) DO UPDATE SET {price} = excluded.{price}, \
quantity = excluded.quantity, status = excluded.status, current_period_start = excluded.current_period_start, \
current_period_end = excluded.current_period_end, trial_ends_at = excluded.trial_ends_at, \
ends_at = excluded.ends_at, metadata = excluded.metadata, {data} = excluded.{data}, \
updated_at = excluded.updated_at RETURNING id",
price = tables.price,
data = tables.data,
));
let rows = db::current()?.fetch_all(&sql).await?;
let id = id_of(rows.first().ok_or_else(|| Error::internal("no subscription id"))?, "id")?;
let synced = Synced {
record: Subscription {
id,
customer_id,
processor_id: processor_id.clone(),
price: price.clone(),
quantity,
status: status.clone(),
current_period_end: timestamp(period_end),
ends_at: timestamp(&ends_at),
metadata: object["metadata"].clone(),
},
created: previous.is_none(),
previous_status: previous.clone(),
};
if previous.as_deref() != Some(status.as_str())
&& let Some(hook) = &billing.on_subscription
{
hook(synced.clone()).await?;
}
Ok(synced)
})
.await
}
fn timestamp(value: &Json) -> Option<Timestamp> {
value
.as_i64()
.and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0))
}
async fn previous_status(
tables: Tables,
customer_id: i64,
processor_id: &str,
) -> Result<Option<String>> {
let mut sql = Sql::new();
sql.push(&format!(
"SELECT status FROM {} WHERE customer_id = ",
tables.subscriptions
));
sql.push_value(Value::Int(customer_id));
sql.push(" AND processor_id = ");
sql.push_value(Value::Text(processor_id.to_owned()));
let rows = db::current()?.fetch_all(&sql).await?;
rows.first()
.map(|row| row.get::<String>("status"))
.transpose()
}
async fn sync_charge_object(billing: &Billing, object: &Json) -> Result<Synced<Charge>> {
let customer = object["customer"]
.as_str()
.or_else(|| object["customer"]["id"].as_str())
.unwrap_or_default();
let customer_id = customer_id_for(billing, customer).await?;
let processor_id = object["id"].as_str().unwrap_or_default().to_owned();
let amount = object["amount"].as_i64().unwrap_or_default();
let refunded = object["amount_refunded"].as_i64().unwrap_or_default();
let currency = object["currency"].as_str().unwrap_or("usd").to_owned();
db::transaction(async {
let mut sql = Sql::new();
let tables = billing.tables;
sql.push(&format!(
"SELECT amount_refunded FROM {} WHERE customer_id = ",
tables.charges
));
sql.push_value(Value::Int(customer_id));
sql.push(" AND processor_id = ");
sql.push_value(Value::Text(processor_id.clone()));
let existing = db::current()?.fetch_all(&sql).await?;
let before: Option<i64> = match existing.first() {
Some(row) => Some(row.get::<Option<i64>>("amount_refunded").or_else(|_| {
row.get::<Option<i32>>("amount_refunded").map(|n| n.map(i64::from))
})?.unwrap_or_default()),
None => None,
};
let now = crate::time::now();
let mut sql = Sql::new();
sql.push(&format!(
"INSERT INTO {} (customer_id, processor_id, amount, currency, amount_refunded, metadata, {}, \
{}, updated_at) VALUES (",
tables.charges, tables.data, tables.inserted_at
));
push_values(
&mut sql,
vec![
Value::Int(customer_id),
Value::Text(processor_id.clone()),
Value::Int(amount),
Value::Text(currency.clone()),
Value::Int(refunded),
Value::Json(object["metadata"].clone()),
Value::Json(object.clone()),
Value::Timestamp(now),
Value::Timestamp(now),
],
);
sql.push(&format!(
") ON CONFLICT (customer_id, processor_id) DO UPDATE SET amount_refunded = excluded.amount_refunded, \
metadata = excluded.metadata, {data} = excluded.{data}, updated_at = excluded.updated_at RETURNING id",
data = tables.data,
));
let rows = db::current()?.fetch_all(&sql).await?;
let id = id_of(rows.first().ok_or_else(|| Error::internal("no charge id"))?, "id")?;
let synced = Synced {
record: Charge {
id,
customer_id,
subscription_id: None,
processor_id: processor_id.clone(),
amount,
currency: currency.clone(),
amount_refunded: refunded,
metadata: object["metadata"].clone(),
},
created: before.is_none(),
previous_status: None,
};
if before != Some(refunded)
&& let Some(hook) = &billing.on_charge
{
hook(synced.clone()).await?;
}
Ok(synced)
})
.await
}
fn push_values(sql: &mut Sql, values: Vec<Value>) {
for (i, value) in values.into_iter().enumerate() {
if i > 0 {
sql.push(", ");
}
sql.push_value(value);
}
}
fn id_of(row: &db::Row, column: &str) -> Result<i64> {
row.get::<i64>(column)
.or_else(|_| row.get::<i32>(column).map(i64::from))
}
pub(crate) fn form_pairs(value: &Json, prefix: &str, out: &mut Vec<(String, String)>) {
match value {
Json::Object(map) => {
for (key, value) in map {
let name = if prefix.is_empty() {
key.clone()
} else {
format!("{prefix}[{key}]")
};
form_pairs(value, &name, out);
}
}
Json::Array(items) => {
for (i, value) in items.iter().enumerate() {
form_pairs(value, &format!("{prefix}[{i}]"), out);
}
}
Json::Null => {}
Json::String(text) => out.push((prefix.to_owned(), text.clone())),
other => out.push((prefix.to_owned(), other.to_string())),
}
}
pub(crate) fn checkout_params(customer: &str, checkout: &Checkout) -> Vec<(String, String)> {
let metadata: serde_json::Map<String, Json> = checkout
.metadata
.iter()
.map(|(k, v)| (k.clone(), json!(v)))
.collect();
let mut body = json!({
"customer": customer,
"mode": checkout.mode,
"line_items": [{"price": checkout.price, "quantity": checkout.quantity}],
"success_url": checkout.success_url_with_id(),
"cancel_url": checkout.cancel_url,
"metadata": metadata,
});
if checkout.allow_promotion_codes {
body["allow_promotion_codes"] = json!(true);
}
let carrier = if checkout.mode == "subscription" {
"subscription_data"
} else {
"payment_intent_data"
};
body[carrier] = json!({ "metadata": metadata });
let mut pairs = Vec::new();
form_pairs(&body, "", &mut pairs);
pairs
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encodes_checkouts_as_stripe_does() {
let checkout = Checkout::payment("price_1", "https://x.com/return", "https://x.com/p")
.metadata("user_id", 7)
.allow_promotion_codes();
let pairs = checkout_params("cus_1", &checkout);
let get = |k: &str| {
pairs
.iter()
.find(|(name, _)| name == k)
.map(|(_, v)| v.as_str())
};
assert_eq!(get("line_items[0][price]"), Some("price_1"));
assert_eq!(get("line_items[0][quantity]"), Some("1"));
assert_eq!(get("metadata[user_id]"), Some("7"));
assert_eq!(get("payment_intent_data[metadata][user_id]"), Some("7"));
assert_eq!(
get("success_url"),
Some("https://x.com/return?session_id={CHECKOUT_SESSION_ID}")
);
assert_eq!(get("allow_promotion_codes"), Some("true"));
}
}