Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
1,498 linesCodeBlameRaw
1//! The card processor, behind the calls billing needs: start a payment
2//! page, save and verify a card, ask whether a payment was made, and start,
3//! read or end the monthly plan. Stripe speaks form-encoded requests and
4//! JSON answers.
5//!
6//! Every Stripe object billing needs beyond customers and their payments
7//! (the plan's product, the billing page's settings) is made the first time
8//! it is needed, and found again by its `metadata[g1t]` after that.
9//!
10//! Every request names the API version it is written for
11//! (`STRIPE_VERSION`). Without it Stripe answers at the account's default,
12//! which for an account made today is a newer version than this code reads:
13//! invoices no longer carry `subscription`, charges no longer carry
14//! `invoice`, and parameters this code sends can be refused. A failure is
15//! never shown raw: `friendly` turns it into a sentence for the page.
16
17use serde::Deserialize;
18use worker::{Error, Fetch, Headers, Method, Request, RequestInit, Result};
19
20const API: &str = "https://api.stripe.com/v1";
21
22/// The Stripe API version billing is written against. Changing it is a
23/// code change: read Stripe's upgrade notes for every field billing reads.
24pub(crate) const STRIPE_VERSION: &str = "2025-02-24.acacia";
25
26/// Stripe Tax's code for what g1t sells, on every product, price and
27/// invoice line: software as a service, for business use.
28pub(crate) const TAX_CODE: &str = "txcd_10103001";
29
30/// What every payment page (payment or subscription mode) asks of Stripe
31/// Tax: tax worked out on top of the price shown, from a billing address
32/// it always collects, with the buyer's tax ID if they have one. With a
33/// customer already, what was entered is saved on it, so invoices and
34/// off-session charges later find the address too. Checkout refuses
35/// `automatic_tax` for a customer with no address unless it may save one
36/// (`customer_update[address]`), and `tax_id_collection` unless it may save
37/// the name (`customer_update[name]`).
38pub(crate) fn checkout_tax_fields(customer: Option<&str>) -> Vec<(&'static str, String)> {
39 let mut fields = vec![
40 ("automatic_tax[enabled]", "true".to_owned()),
41 ("billing_address_collection", "required".to_owned()),
42 ("tax_id_collection[enabled]", "true".to_owned()),
43 ];
44 if customer.is_some() {
45 fields.extend([("customer_update[address]", "auto".to_owned()), ("customer_update[name]", "auto".to_owned())]);
46 }
47 fields
48}
49
50/// Whether Stripe refused because it could not tell where the customer is
51/// for tax: no address, or not enough of one.
52pub(crate) fn is_tax_location_error(error: &Error) -> bool {
53 let text = error.to_string();
54 text.contains("customer_tax_location_invalid") || text.contains("requires_location_inputs")
55}
56
57/// Whether an address is enough for Stripe Tax to place the customer: a
58/// country, and in the United States a postal code (in Canada a postal
59/// code or a province).
60pub(crate) fn address_places_customer(address: &serde_json::Value) -> bool {
61 let text = |key: &str| address[key].as_str().map(str::trim).unwrap_or_default().to_owned();
62 match text("country").to_uppercase().as_str() {
63 "" => false,
64 "US" => !text("postal_code").is_empty(),
65 "CA" => !text("postal_code").is_empty() || !text("state").is_empty(),
66 _ => true,
67 }
68}
69
70/// What a Stripe failure says, for the person on the page: Stripe's own
71/// message when it gave one (never the request or any key), else that it
72/// could not be reached.
73pub(crate) fn friendly(error: &Error) -> String {
74 let text = error.to_string();
75 let message = text
76 .split_once(": ")
77 .and_then(|(_, body)| serde_json::from_str::<serde_json::Value>(body).ok())
78 .and_then(|body| body["error"]["message"].as_str().map(str::to_owned));
79 match message {
80 Some(message) => format!("Stripe refused it: {}", message.trim_end_matches('.').to_owned() + "."),
81 None if text.contains("the card processor answered") => "Stripe refused it. Try again in a minute; if it keeps happening, write to support@g1t.sh.".to_owned(),
82 None => "Stripe could not be reached. Try again in a minute.".to_owned(),
83 }
84}
85
86pub struct Stripe {
87 key: String,
88}
89
90/// A payment page, and the payment made through it.
91#[derive(Deserialize)]
92pub struct Session {
93 pub id: String,
94 /// Where to send the person. Absent once the page has been used.
95 pub url: Option<String>,
96 /// `paid` once the money has been taken.
97 pub payment_status: String,
98 /// What was paid, in cents, tax included.
99 pub amount_total: Option<u32>,
100 /// What the lines came to before tax, in cents.
101 #[serde(default)]
102 pub amount_subtotal: Option<u32>,
103 /// The tax Stripe added (`amount_tax`), among other totals.
104 #[serde(default)]
105 pub total_details: Option<TotalDetails>,
106 /// For a payment page: the payment that took the money.
107 #[serde(default)]
108 pub payment_intent: Option<String>,
109 pub customer: Option<String>,
110 /// For a plan's page: the subscription it started.
111 #[serde(default)]
112 pub subscription: Option<String>,
113 /// For a card check's page: the setup that saved and verified the card.
114 #[serde(default)]
115 pub setup_intent: Option<String>,
116}
117
118#[derive(Default, Deserialize)]
119pub struct TotalDetails {
120 #[serde(default)]
121 pub amount_tax: i64,
122}
123
124impl Session {
125 /// The tax Stripe added on the page, in cents.
126 pub fn tax_cents(&self) -> i64 {
127 self.total_details.as_ref().map_or(0, |t| t.amount_tax.max(0))
128 }
129
130 /// What the page's lines came to before tax, in cents: the total less
131 /// the tax when Stripe gives no subtotal.
132 pub fn before_tax_cents(&self) -> i64 {
133 match self.amount_subtotal {
134 Some(subtotal) => i64::from(subtotal),
135 None => (i64::from(self.amount_total.unwrap_or(0)) - self.tax_cents()).max(0),
136 }
137 }
138}
139
140/// A card saved and verified: what a card check found.
141#[derive(Debug, Deserialize)]
142pub struct CheckedCard {
143 pub payment_method: String,
144 pub fingerprint: Option<String>,
145 pub brand: Option<String>,
146 pub last4: Option<String>,
147 /// `credit`, `debit`, `prepaid` or `unknown`.
148 pub funding: Option<String>,
149 pub country: Option<String>,
150 /// The billing address entered with the card, as Stripe keeps it.
151 #[serde(default)]
152 pub address: Option<serde_json::Value>,
153}
154
155/// g1t's settings for Stripe's hosted billing page.
156#[derive(Debug, Deserialize)]
157pub struct PortalConfiguration {
158 pub id: String,
159 #[serde(default)]
160 pub active: bool,
161 #[serde(default)]
162 pub login_page: Option<LoginPage>,
163 #[serde(default)]
164 pub metadata: Option<std::collections::HashMap<String, String>>,
165}
166
167#[derive(Debug, Deserialize)]
168pub struct LoginPage {
169 pub url: Option<String>,
170}
171
172/// A monthly plan.
173#[derive(Deserialize)]
174pub struct StripeSubscription {
175 pub id: String,
176 #[serde(default)]
177 pub latest_invoice: Option<String>,
178 /// `active`, `trialing`, `past_due`, `unpaid`, `canceled`, `incomplete`…
179 pub status: String,
180 #[serde(default)]
181 pub cancel_at_period_end: bool,
182 /// Unix seconds. Older API versions carry it here…
183 #[serde(default)]
184 pub current_period_end: Option<i64>,
185 /// …newer ones on each item.
186 #[serde(default)]
187 pub items: Option<Items>,
188 /// A change waiting on its payment (`payment_behavior=pending_if_incomplete`):
189 /// until it is paid the subscription keeps its items.
190 #[serde(default)]
191 pub pending_update: Option<serde_json::Value>,
192 #[serde(default)]
193 pub metadata: Option<std::collections::HashMap<String, String>>,
194}
195
196#[derive(Deserialize)]
197pub struct Items {
198 pub data: Vec<Item>,
199}
200
201#[derive(Deserialize)]
202pub struct Item {
203 #[serde(default)]
204 pub id: Option<String>,
205 #[serde(default)]
206 pub current_period_end: Option<i64>,
207 #[serde(default)]
208 pub price: Option<ItemPrice>,
209}
210
211#[derive(Deserialize)]
212pub struct ItemPrice {
213 pub id: String,
214 #[serde(default)]
215 pub unit_amount: Option<i64>,
216}
217
218impl StripeSubscription {
219 /// The subscription's only item, as complimentary enrollment makes it.
220 pub fn first_item(&self) -> Option<&Item> {
221 self.items.as_ref().and_then(|items| items.data.first())
222 }
223
224 /// When the period paid for ends, in Unix seconds.
225 pub fn period_end(&self) -> Option<i64> {
226 self.current_period_end.or_else(|| {
227 self.items
228 .as_ref()
229 .and_then(|items| items.data.iter().filter_map(|item| item.current_period_end).max())
230 })
231 }
232}
233
234/// Percent-encodes a form value.
235fn encode(value: &str) -> String {
236 let mut encoded = String::with_capacity(value.len());
237 for byte in value.bytes() {
238 match byte {
239 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
240 encoded.push(byte as char);
241 }
242 _ => encoded.push_str(&format!("%{byte:02X}")),
243 }
244 }
245 encoded
246}
247
248/// `name=value` pairs as a form body.
249/// Requests that carry `automatic_tax`: payment pages, invoices and
250/// subscriptions. When Stripe Tax is not active for the key's mode (a test
251/// account where it was never turned on), Stripe refuses them outright, so
252/// in test mode the field is left out and the payment goes through untaxed;
253/// with a live key the request is refused instead (`untaxed_body`).
254pub(crate) fn taxed_path(path: &str) -> bool {
255 path == "/checkout/sessions" || path == "/invoices" || path == "/subscriptions" || path.starts_with("/subscriptions/")
256}
257
258/// A form body without its `automatic_tax[…]` fields.
259pub(crate) fn without_automatic_tax(body: &str) -> String {
260 body.split('&').filter(|pair| !pair.starts_with("automatic_tax")).collect::<Vec<_>>().join("&")
261}
262
263/// What a request asking for tax becomes when Stripe Tax is not active.
264/// In test mode, the body without `automatic_tax`: the payment goes through
265/// untaxed. With a live key, nothing is sent: charging real money without
266/// the tax owed on it would under-collect, so the charge, page or invoice
267/// is refused, loudly, until Stripe Tax is turned on.
268pub(crate) fn untaxed_body(live: bool, body: &str) -> Result<String> {
269 if live {
270 return Err(Error::RustError(format!(
271 "the card processor answered 400: {}",
272 serde_json::json!({ "error": { "type": "g1t_tax_not_active", "message": "Payments are paused while g1t sets up sales tax. Try again later" } })
273 )));
274 }
275 Ok(without_automatic_tax(body))
276}
277
278/// How long whether Stripe Tax is active is believed, in milliseconds.
279const TAX_ACTIVE_FOR_MS: u64 = 10 * 60 * 1000;
280
281thread_local! {
282 /// Whether Stripe Tax is active for the key, and when that was read.
283 static TAX_ACTIVE: std::cell::Cell<Option<(bool, u64)>> = const { std::cell::Cell::new(None) };
284 /// When g1t's portal configuration was last brought in line with
285 /// `portal_fields` in this isolate.
286 static PORTAL_SYNCED: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
287}
288
289/// How long a portal configuration brought in line is taken to stay so.
290const PORTAL_SYNCED_FOR_MS: u64 = 60 * 60 * 1000;
291
292/// The `metadata[g1t]` of the portal configuration billing makes.
293pub(crate) const PORTAL_TAG: &str = "billing";
294
295/// Why a customer can end a plan on Stripe's page: Stripe asks for the
296/// list whenever it asks for a reason.
297const CANCELLATION_REASONS: [&str; 8] =
298 ["too_expensive", "missing_features", "switched_service", "unused", "customer_service", "too_complex", "low_quality", "other"];
299
300/// g1t's settings for Stripe's hosted billing page (the customer portal),
301/// where every card, billing detail, tax ID, invoice and receipt is
302/// managed, and the plan ended: the customer's details (email, address,
303/// name, tax IDs, phone), the card, the invoice history, and ending the
304/// plan at the end of the period with a reason. Never changing the plan
305/// there: g1t has one.
306pub(crate) fn portal_fields() -> Vec<(&'static str, String)> {
307 let mut fields = vec![
308 ("business_profile[headline]", "g1t billing: your card, billing details, tax IDs and invoices".to_owned()),
309 ("business_profile[privacy_policy_url]", "https://g1t.sh/policies/privacy".to_owned()),
310 ("business_profile[terms_of_service_url]", "https://g1t.sh/policies/terms".to_owned()),
311 ("features[customer_update][enabled]", "true".to_owned()),
312 ("features[customer_update][allowed_updates][0]", "email".to_owned()),
313 ("features[customer_update][allowed_updates][1]", "address".to_owned()),
314 ("features[customer_update][allowed_updates][2]", "name".to_owned()),
315 ("features[customer_update][allowed_updates][3]", "tax_id".to_owned()),
316 ("features[customer_update][allowed_updates][4]", "phone".to_owned()),
317 ("features[payment_method_update][enabled]", "true".to_owned()),
318 ("features[invoice_history][enabled]", "true".to_owned()),
319 ("features[subscription_cancel][enabled]", "true".to_owned()),
320 ("features[subscription_cancel][mode]", "at_period_end".to_owned()),
321 ("features[subscription_cancel][cancellation_reason][enabled]", "true".to_owned()),
322 ("features[subscription_update][enabled]", "false".to_owned()),
323 ("login_page[enabled]", "true".to_owned()),
324 ("metadata[g1t]", PORTAL_TAG.to_owned()),
325 ];
326 const OPTION_KEYS: [&str; 8] = [
327 "features[subscription_cancel][cancellation_reason][options][0]",
328 "features[subscription_cancel][cancellation_reason][options][1]",
329 "features[subscription_cancel][cancellation_reason][options][2]",
330 "features[subscription_cancel][cancellation_reason][options][3]",
331 "features[subscription_cancel][cancellation_reason][options][4]",
332 "features[subscription_cancel][cancellation_reason][options][5]",
333 "features[subscription_cancel][cancellation_reason][options][6]",
334 "features[subscription_cancel][cancellation_reason][options][7]",
335 ];
336 fields.extend(OPTION_KEYS.iter().zip(CANCELLATION_REASONS).map(|(key, reason)| (*key, reason.to_owned())));
337 fields
338}
339
340/// g1t's portal configuration among Stripe's, by its tag: an active one
341/// first.
342pub(crate) fn ours(configurations: Vec<PortalConfiguration>) -> Option<PortalConfiguration> {
343 let mut tagged: Vec<PortalConfiguration> = configurations
344 .into_iter()
345 .filter(|c| c.metadata.as_ref().and_then(|m| m.get("g1t")).map(String::as_str) == Some(PORTAL_TAG))
346 .collect();
347 tagged.sort_by_key(|c| !c.active);
348 tagged.into_iter().next()
349}
350
351/// Stripe Tax's settings, for the go-live checklist: `active` once it can
352/// collect tax, else `pending` with what is missing (`head_office`, …).
353#[derive(Debug, Default, Deserialize)]
354pub struct TaxSettings {
355 #[serde(default)]
356 pub status: String,
357 #[serde(default)]
358 pub status_details: TaxStatusDetails,
359}
360
361#[derive(Debug, Default, Deserialize)]
362pub struct TaxStatusDetails {
363 #[serde(default)]
364 pub pending: Option<TaxPending>,
365}
366
367#[derive(Debug, Default, Deserialize)]
368pub struct TaxPending {
369 #[serde(default)]
370 pub missing_fields: Option<Vec<String>>,
371}
372
373pub(crate) fn form(fields: &[(&str, String)]) -> String {
374 fields
375 .iter()
376 .map(|(name, value)| format!("{}={}", encode(name), encode(value)))
377 .collect::<Vec<_>>()
378 .join("&")
379}
380
381/// The idempotency key for starting a plan on a saved card: the same
382/// workspace, plan and card within the same ten minutes is one subscription,
383/// however many times it is asked for (a double click, two tabs), so a
384/// workspace is never billed twice for one plan. A different card is a new
385/// attempt, as Stripe refuses a key reused with other fields.
386pub(crate) fn plan_key(workspace: &str, feature: &str, payment_method: &str, now_ms: u64) -> String {
387 format!("plan/{workspace}/{feature}/{payment_method}/{}", now_ms / 600_000)
388}
389
390impl Stripe {
391 pub fn new(key: String) -> Self {
392 Stripe { key }
393 }
394
395 /// Whether the key is for real cards, not Stripe's test mode.
396 pub fn live(&self) -> bool {
397 is_live(&self.key)
398 }
399
400 /// A GET of any Stripe resource, for the webhook handlers.
401 pub(crate) async fn get<T: for<'a> Deserialize<'a>>(&self, path: &str) -> Result<T> {
402 self.call(Method::Get, path, None).await
403 }
404
405 /// A DELETE of any Stripe resource.
406 pub(crate) async fn delete<T: for<'a> Deserialize<'a>>(&self, path: &str) -> Result<T> {
407 self.call(Method::Delete, path, None).await
408 }
409
410 /// A form POST to any Stripe resource.
411 pub(crate) async fn post<T: for<'a> Deserialize<'a>>(&self, path: &str, fields: &[(&str, String)]) -> Result<T> {
412 self.call(Method::Post, path, Some(form(fields))).await
413 }
414
415 /// A form POST that Stripe does at most once for `key`, however often
416 /// it is sent.
417 pub(crate) async fn post_idempotent<T: for<'a> Deserialize<'a>>(
418 &self,
419 path: &str,
420 fields: &[(&str, String)],
421 key: &str,
422 ) -> Result<T> {
423 self.send(Method::Post, path, Some(form(fields)), Some(key)).await
424 }
425
426 async fn call<T: for<'a> Deserialize<'a>>(
427 &self,
428 method: Method,
429 path: &str,
430 body: Option<String>,
431 ) -> Result<T> {
432 self.send(method, path, body, None).await
433 }
434
435 async fn send<T: for<'a> Deserialize<'a>>(
436 &self,
437 method: Method,
438 path: &str,
439 body: Option<String>,
440 idempotency_key: Option<&str>,
441 ) -> Result<T> {
442 let body = match body {
443 Some(body) if matches!(method, Method::Post) && taxed_path(path) && body.contains("automatic_tax") && !self.tax_active().await => {
444 if self.live() {
445 worker::console_error!(
446 "STRIPE TAX IS NOT ACTIVE for the live key: refused {path} rather than charge without tax. Turn it on in Stripe (Tax → Settings)."
447 );
448 }
449 Some(untaxed_body(self.live(), &body)?)
450 }
451 body => body,
452 };
453 self.send_raw(method, path, body, idempotency_key).await
454 }
455
456 /// The request itself, as given: `send` without the Stripe Tax check.
457 async fn send_raw<T: for<'a> Deserialize<'a>>(
458 &self,
459 method: Method,
460 path: &str,
461 body: Option<String>,
462 idempotency_key: Option<&str>,
463 ) -> Result<T> {
464 let headers = Headers::new();
465 headers.set("authorization", &format!("Bearer {}", self.key))?;
466 headers.set("stripe-version", STRIPE_VERSION)?;
467 if let Some(key) = idempotency_key {
468 headers.set("idempotency-key", key)?;
469 }
470 if body.is_some() {
471 headers.set("content-type", "application/x-www-form-urlencoded")?;
472 }
473 let deleting = matches!(method, Method::Delete);
474 let mut init = RequestInit::new();
475 init.with_method(method).with_headers(headers);
476 if let Some(body) = body {
477 init.with_body(Some(body.into()));
478 }
479 let request = Request::new_with_init(&format!("{API}{path}"), &init)?;
480 let mut response = Fetch::Request(request).send().await?;
481 if response.status_code() != 200 {
482 return Err(Error::RustError(format!(
483 "the card processor answered {}: {}",
484 response.status_code(),
485 response.text().await.unwrap_or_default()
486 )));
487 }
488 let found: serde_json::Value = response.json().await?;
489 // A deleted customer is read back with a 200 and `deleted: true`:
490 // as good as missing, so every caller that forgets a missing
491 // customer forgets this one too.
492 if !deleting && is_deleted_customer(&found) {
493 return Err(Error::RustError(DELETED_CUSTOMER.to_owned()));
494 }
495 serde_json::from_value(found).map_err(|error| Error::RustError(format!("the card processor's answer to {path} was unexpected: {error}")))
496 }
497
498 /// Whether Stripe Tax is active for this key's mode (`GET /tax/settings`,
499 /// `status` `active`), read at most every ten minutes. When it cannot be
500 /// read, it is taken as active: asking for tax and being refused says
501 /// why, where leaving it out would undercharge without a word.
502 pub async fn tax_active(&self) -> bool {
503 let now = crate::now_ms();
504 if let Some((active, at)) = TAX_ACTIVE.with(|cell| cell.get())
505 && now.saturating_sub(at) < TAX_ACTIVE_FOR_MS
506 {
507 return active;
508 }
509 #[derive(Deserialize)]
510 struct Settings {
511 status: String,
512 }
513 let active = match self.send_raw::<Settings>(Method::Get, "/tax/settings", None, None).await {
514 Ok(settings) => settings.status == "active",
515 Err(error) => {
516 worker::console_error!("Stripe Tax settings could not be read; asking for tax anyway: {error}");
517 true
518 }
519 };
520 TAX_ACTIVE.with(|cell| cell.set(Some((active, now))));
521 active
522 }
523
524 /// A customer for a workspace that has none yet, with the email its
525 /// receipts go to and the billing page signs in with. Two asking at once
526 /// make one customer (`customer_key`).
527 pub async fn create_customer(&self, workspace: &str, email: Option<&str>) -> Result<String> {
528 #[derive(Deserialize)]
529 struct Customer {
530 id: String,
531 }
532 let fields = customer_fields(workspace, email);
533 let key = customer_key(workspace, email, g1t_kit::now_ms());
534 let customer: Customer = self.send(Method::Post, "/customers", Some(form(&fields)), Some(&key)).await?;
535 Ok(customer.id)
536 }
537
538 /// A session on Stripe's hosted billing page (the customer portal) for
539 /// the customer, coming back to `return_url`.
540 pub async fn portal_session(&self, customer: &str, return_url: &str) -> Result<String> {
541 #[derive(Deserialize)]
542 struct Portal {
543 url: String,
544 }
545 let configuration = self.portal_configuration().await?;
546 let fields = [
547 ("customer", customer.to_owned()),
548 ("return_url", return_url.to_owned()),
549 ("configuration", configuration.id),
550 ];
551 let portal: Portal = self.call(Method::Post, "/billing_portal/sessions", Some(form(&fields))).await?;
552 Ok(portal.url)
553 }
554
555 /// g1t's billing page settings at Stripe (`portal_fields`), made the
556 /// first time they are needed, and an existing one (`metadata[g1t]` =
557 /// `billing`) brought in line with them rather than a second made: at
558 /// most once an hour in an isolate.
559 pub async fn portal_configuration(&self) -> Result<PortalConfiguration> {
560 let now = crate::now_ms();
561 let existing = self.our_portal().await?;
562 let fresh = PORTAL_SYNCED.with(|cell| cell.get()).is_some_and(|at| now.saturating_sub(at) < PORTAL_SYNCED_FOR_MS);
563 let configuration: PortalConfiguration = match existing {
564 Some(existing) if fresh && existing.active => existing,
565 Some(existing) => {
566 let mut fields = portal_fields();
567 fields.push(("active", "true".to_owned()));
568 self.call(Method::Post, &format!("/billing_portal/configurations/{}", encode(&existing.id)), Some(form(&fields))).await?
569 }
570 None => self.call(Method::Post, "/billing_portal/configurations", Some(form(&portal_fields()))).await?,
571 };
572 PORTAL_SYNCED.with(|cell| cell.set(Some(now)));
573 Ok(configuration)
574 }
575
576 /// g1t's portal configuration as Stripe has it, without making or
577 /// changing it. None when there is none yet.
578 pub async fn our_portal(&self) -> Result<Option<PortalConfiguration>> {
579 #[derive(Deserialize)]
580 struct List {
581 data: Vec<PortalConfiguration>,
582 }
583 let list: List = self.call(Method::Get, "/billing_portal/configurations?limit=100", None).await?;
584 Ok(ours(list.data))
585 }
586
587 /// Stripe Tax's settings for this key's mode, read now.
588 pub async fn tax_settings(&self) -> Result<TaxSettings> {
589 self.send_raw(Method::Get, "/tax/settings", None, None).await
590 }
591
592 /// The customer's email at Stripe, if they gave one.
593 pub async fn customer_email(&self, customer: &str) -> Result<Option<String>> {
594 #[derive(Deserialize)]
595 struct Customer {
596 email: Option<String>,
597 }
598 let found: Customer = self.call(Method::Get, &format!("/customers/{}", encode(customer)), None).await?;
599 Ok(found.email)
600 }
601
602 /// Starts a page on which `amount_cents` is paid in advance: by card,
603 /// with 3-D Secure asked for wherever the card supports it, the card
604 /// kept for later charges; or, with `bank_transfer` and a customer, by
605 /// bank transfer to the account details Stripe gives, counted when the
606 /// money arrives.
607 pub async fn start_checkout(
608 &self,
609 workspace: &str,
610 amount_cents: u32,
611 customer: Option<&str>,
612 return_url: &str,
613 bank_transfer: bool,
614 ) -> Result<Session> {
615 let fields = prepay_fields(workspace, amount_cents, customer, return_url, bank_transfer);
616 let key = page_key(
617 "prepay",
618 workspace,
619 &format!("{amount_cents}/{bank_transfer}/{}", customer.unwrap_or("new")),
620 g1t_kit::now_ms(),
621 );
622 self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await
623 }
624
625 /// Starts a page on which a feature's monthly plan is paid for by card,
626 /// at its price and nothing more, tax added where it applies.
627 pub async fn start_subscription(
628 &self,
629 workspace: &str,
630 feature: &str,
631 title: &str,
632 monthly_cents: u32,
633 customer: Option<&str>,
634 return_url: &str,
635 ) -> Result<Session> {
636 let fields = subscription_fields(workspace, feature, title, monthly_cents, customer, return_url);
637 let key = page_key(
638 "plan",
639 workspace,
640 &format!("{feature}/{monthly_cents}/{}", customer.unwrap_or("new")),
641 g1t_kit::now_ms(),
642 );
643 self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await
644 }
645
646 /// Starts a page that saves and verifies a card, with 3-D Secure asked
647 /// for wherever the card supports it. Nothing is charged: the card's
648 /// bank sees at most a $0 or $1 authorization that is never captured.
649 pub async fn start_card_check(&self, workspace: &str, customer: &str, return_url: &str) -> Result<Session> {
650 let fields = card_check_fields(workspace, customer, return_url);
651 let key = page_key("card_check", workspace, customer, g1t_kit::now_ms());
652 self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await
653 }
654
655 /// The customer's default payment method: the one its invoices are
656 /// charged to, else its newest card. None when it has none.
657 pub async fn default_payment_method(&self, customer: &str) -> Result<Option<SavedMethod>> {
658 let found: serde_json::Value = self
659 .call(
660 Method::Get,
661 &format!("/customers/{}?expand[]=invoice_settings.default_payment_method", encode(customer)),
662 None,
663 )
664 .await?;
665 if let Some(method) = SavedMethod::from_json(&found["invoice_settings"]["default_payment_method"]) {
666 return Ok(Some(method));
667 }
668 let list: serde_json::Value = self
669 .call(Method::Get, &format!("/payment_methods?customer={}&type=card&limit=1", encode(customer)), None)
670 .await?;
671 Ok(list["data"].as_array().and_then(|data| data.first()).and_then(SavedMethod::from_json))
672 }
673
674 /// The customer as Stripe keeps it, with its tax ids.
675 pub async fn customer(&self, customer: &str) -> Result<serde_json::Value> {
676 self.call(Method::Get, &format!("/customers/{}?expand[]=tax_ids", encode(customer)), None).await
677 }
678
679 /// The customer's invoices, newest first.
680 pub async fn invoices(&self, customer: &str) -> Result<Vec<serde_json::Value>> {
681 let list: serde_json::Value = self.call(Method::Get, &format!("/invoices?customer={}&limit=24", encode(customer)), None).await?;
682 Ok(list["data"].as_array().cloned().unwrap_or_default())
683 }
684
685 /// Reverses a tax transaction in part for a refund: `refunded_cents` of
686 /// the payment, tax included, taken back across all of it.
687 pub async fn reverse_tax(&self, transaction: &str, reference: &str, refunded_cents: i64) -> Result<()> {
688 let _: serde_json::Value = self
689 .send(
690 Method::Post,
691 "/tax/transactions/create_reversal",
692 Some(form(&reversal_fields(transaction, reference, refunded_cents))),
693 Some(&format!("tax-reversal/{reference}")),
694 )
695 .await?;
696 Ok(())
697 }
698
699 /// Copies the billing address entered with a card onto the customer
700 /// when the customer has none Stripe Tax can use, so later invoices and
701 /// charges can be taxed. Never replaces an address an owner gave.
702 pub async fn fill_address(&self, customer: &str, address: &serde_json::Value) -> Result<bool> {
703 if !address_places_customer(address) {
704 return Ok(false);
705 }
706 let found = self.customer(customer).await?;
707 if address_places_customer(&found["address"]) {
708 return Ok(false);
709 }
710 let _: serde_json::Value = self.post(&format!("/customers/{}", encode(customer)), &address_fields(address)).await?;
711 Ok(true)
712 }
713
714 /// Whether the customer's address is enough for Stripe Tax.
715 pub async fn customer_placed(&self, customer: &str) -> Result<bool> {
716 let found = self.customer(customer).await?;
717 Ok(address_places_customer(&found["address"]) || address_places_customer(&found["shipping"]["address"]))
718 }
719}
720
721/// A customer's address from an address Stripe gave.
722pub(crate) fn address_fields(address: &serde_json::Value) -> Vec<(&'static str, String)> {
723 let text = |key: &str| address[key].as_str().unwrap_or_default().to_owned();
724 vec![
725 ("address[line1]", text("line1")),
726 ("address[line2]", text("line2")),
727 ("address[city]", text("city")),
728 ("address[state]", text("state")),
729 ("address[postal_code]", text("postal_code")),
730 ("address[country]", text("country")),
731 ]
732}
733
734/// A refund's tax reversal: a part of the payment, as a negative amount.
735pub(crate) fn reversal_fields(transaction: &str, reference: &str, refunded_cents: i64) -> Vec<(&'static str, String)> {
736 vec![
737 ("mode", "partial".to_owned()),
738 ("original_transaction", transaction.to_owned()),
739 ("reference", reference.to_owned()),
740 ("flat_amount", (-refunded_cents.abs()).to_string()),
741 ]
742}
743
744/// A saved way to pay, as far as it is safe to show.
745#[derive(Clone, Debug, PartialEq)]
746pub struct SavedMethod {
747 pub id: String,
748 pub kind: String,
749 pub brand: Option<String>,
750 pub last4: Option<String>,
751 pub exp_month: Option<u32>,
752 pub exp_year: Option<u32>,
753}
754
755impl SavedMethod {
756 fn from_json(method: &serde_json::Value) -> Option<SavedMethod> {
757 let id = method["id"].as_str()?.to_owned();
758 let kind = method["type"].as_str().unwrap_or("card").to_owned();
759 let details = &method[kind.as_str()];
760 Some(SavedMethod {
761 id,
762 brand: details["brand"].as_str().or_else(|| details["bank_name"].as_str()).map(str::to_owned),
763 last4: details["last4"].as_str().map(str::to_owned),
764 exp_month: details["exp_month"].as_u64().map(|m| m as u32),
765 exp_year: details["exp_year"].as_u64().map(|y| y as u32),
766 kind,
767 })
768 }
769}
770
771/// A new customer's fields: the workspace, and the email receipts go to
772/// when there is one.
773pub(crate) fn customer_fields(workspace: &str, email: Option<&str>) -> Vec<(&'static str, String)> {
774 let mut fields = vec![("name", workspace.to_owned()), ("metadata[workspace]", workspace.to_owned())];
775 if let Some(email) = email.map(str::trim).filter(|e| e.contains('@')) {
776 fields.push(("email", email.to_owned()));
777 }
778 fields
779}
780
781/// The idempotency key for a workspace's customer: one per workspace in ten
782/// minutes, however many pages ask at once. Ten minutes, not for ever: a
783/// customer deleted at Stripe is forgotten (`forget_customer`), and the
784/// next must be new. The email is part of it, as Stripe refuses a key
785/// reused with other fields.
786pub(crate) fn customer_key(workspace: &str, email: Option<&str>, now_ms: u64) -> String {
787 format!("customer/{workspace}/{}/{}", email.map_or("-", str::trim), now_ms / 600_000)
788}
789
790/// The idempotency key for a payment page: the same workspace, purpose and
791/// details within ten minutes is one page, however often it is asked for (a
792/// double click, two tabs).
793pub(crate) fn page_key(purpose: &str, workspace: &str, details: &str, now_ms: u64) -> String {
794 format!("page/{purpose}/{workspace}/{details}/{}", now_ms / 600_000)
795}
796
797/// Where Stripe sends the person back, with the page's id under `name`.
798fn back_to(return_url: &str, name: &str) -> String {
799 let separator = if return_url.contains('?') { '&' } else { '?' };
800 // Stripe fills in the page's id.
801 format!("{return_url}{separator}{name}={{CHECKOUT_SESSION_ID}}")
802}
803
804/// The name of the card fee's line on payments from before the fee was
805/// folded into g1t's prices. Nothing new carries it; paid invoices that do
806/// still have it counted apart by this name (`invoice_split`).
807pub(crate) const CARD_FEE_LINE: &str = "Card processing fee";
808
809/// The form keys of the one line on a payment page: what is bought.
810const LINE_KEYS: [&str; 8] = [
811 "line_items[0][quantity]",
812 "line_items[0][price_data][currency]",
813 "line_items[0][price_data][unit_amount]",
814 "line_items[0][price_data][tax_behavior]",
815 "line_items[0][price_data][product_data][name]",
816 "line_items[0][price_data][product_data][tax_code]",
817 "line_items[0][price_data][product_data][description]",
818 "line_items[0][price_data][recurring][interval]",
819];
820
821/// The one line on a payment page at g1t's tax code, its price excluding
822/// tax; monthly when `monthly`. g1t's prices include Stripe's fee, so there
823/// is never a second line for it.
824fn page_line(cents: u32, name: String, description: Option<String>, monthly: bool) -> Vec<(&'static str, String)> {
825 let keys = LINE_KEYS;
826 let mut fields = vec![
827 (keys[0], "1".to_owned()),
828 (keys[1], "usd".to_owned()),
829 (keys[2], cents.to_string()),
830 (keys[3], "exclusive".to_owned()),
831 (keys[4], name),
832 (keys[5], TAX_CODE.to_owned()),
833 ];
834 if let Some(description) = description {
835 fields.push((keys[6], description));
836 }
837 if monthly {
838 fields.push((keys[7], "month".to_owned()));
839 }
840 fields
841}
842
843/// A prepayment page's fields: the amount prepaid as the one line, by card
844/// or by bank transfer alike, tax added where it applies.
845pub(crate) fn prepay_fields(
846 workspace: &str,
847 amount_cents: u32,
848 customer: Option<&str>,
849 return_url: &str,
850 bank_transfer: bool,
851) -> Vec<(&'static str, String)> {
852 let mut fields = vec![("mode", "payment".to_owned())];
853 if bank_transfer {
854 fields.extend([
855 ("payment_method_types[0]", "customer_balance".to_owned()),
856 ("payment_method_options[customer_balance][funding_type]", "bank_transfer".to_owned()),
857 ("payment_method_options[customer_balance][bank_transfer][type]", "us_bank_transfer".to_owned()),
858 ]);
859 } else {
860 fields.extend([
861 ("payment_method_types[0]", "card".to_owned()),
862 ("payment_method_options[card][request_three_d_secure]", "any".to_owned()),
863 ("payment_intent_data[setup_future_usage]", "off_session".to_owned()),
864 ]);
865 }
866 fields.extend([
867 ("success_url", back_to(return_url, "session")),
868 ("cancel_url", return_url.to_owned()),
869 ("client_reference_id", workspace.to_owned()),
870 ("metadata[workspace]", workspace.to_owned()),
871 ]);
872 fields.extend(page_line(amount_cents, format!("g1t usage paid in advance for {workspace}"), None, false));
873 fields.extend(checkout_tax_fields(customer));
874 match customer {
875 Some(customer) => fields.push(("customer", customer.to_owned())),
876 None => fields.push(("customer_creation", "always".to_owned())),
877 }
878 fields
879}
880
881/// A plan's page's fields: the plan at its price, as its only line. In
882/// subscription mode Stripe makes the customer itself when
883/// there is none; `customer_creation` is for payment mode only. The
884/// subscription it starts keeps `automatic_tax`, so every renewal is taxed.
885pub(crate) fn subscription_fields(
886 workspace: &str,
887 feature: &str,
888 title: &str,
889 monthly_cents: u32,
890 customer: Option<&str>,
891 return_url: &str,
892) -> Vec<(&'static str, String)> {
893 let mut fields = vec![
894 ("mode", "subscription".to_owned()),
895 ("payment_method_types[0]", "card".to_owned()),
896 ("success_url", back_to(return_url, "session")),
897 ("cancel_url", return_url.to_owned()),
898 ("client_reference_id", workspace.to_owned()),
899 ("metadata[workspace]", workspace.to_owned()),
900 ("metadata[feature]", feature.to_owned()),
901 ("subscription_data[metadata][workspace]", workspace.to_owned()),
902 ("subscription_data[metadata][feature]", feature.to_owned()),
903 ];
904 fields.extend(page_line(monthly_cents, format!("g1t {title} for {workspace}"), None, true));
905 fields.extend(checkout_tax_fields(customer));
906 if let Some(customer) = customer {
907 fields.push(("customer", customer.to_owned()));
908 }
909 fields
910}
911
912/// A card check's page's fields: setup mode, nothing charged, so nothing
913/// to tax. Setup mode takes no line items and no amount. The billing
914/// address is asked for all the same, and copied onto the customer once
915/// the card is checked (`fill_address`), so the plan and invoices that
916/// follow can be taxed.
917pub(crate) fn card_check_fields(workspace: &str, customer: &str, return_url: &str) -> Vec<(&'static str, String)> {
918 vec![
919 ("mode", "setup".to_owned()),
920 ("customer", customer.to_owned()),
921 ("payment_method_types[0]", "card".to_owned()),
922 ("payment_method_options[card][request_three_d_secure]", "any".to_owned()),
923 ("billing_address_collection", "required".to_owned()),
924 ("success_url", back_to(return_url, "card_check")),
925 ("cancel_url", return_url.to_owned()),
926 ("client_reference_id", workspace.to_owned()),
927 ("metadata[workspace]", workspace.to_owned()),
928 ("metadata[purpose]", "card_check".to_owned()),
929 ("setup_intent_data[metadata][workspace]", workspace.to_owned()),
930 ("setup_intent_data[description]", format!("Card check for g1t workspace {workspace}; never charged")),
931 ]
932}
933
934/// A Stripe invoice's tax settings, for every invoice g1t makes: worked out
935/// by Stripe Tax.
936pub(crate) fn invoice_tax_fields() -> Vec<(&'static str, String)> {
937 vec![("automatic_tax[enabled]", "true".to_owned())]
938}
939
940/// An invoice item's tax settings: g1t's tax code, the amount excluding tax.
941pub(crate) fn item_tax_fields() -> Vec<(&'static str, String)> {
942 vec![("tax_behavior", "exclusive".to_owned()), ("tax_code", TAX_CODE.to_owned())]
943}
944
945/// What a paid Stripe invoice comes to, as billing counts it: the tax
946/// (`tax`, in this API version), any card fee (its lines, by name, on
947/// invoices from before the fee was folded into prices), and what is left
948/// for what was sold, all in cents.
949#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
950pub(crate) struct InvoiceSplit {
951 pub tax_cents: i64,
952 pub fee_cents: i64,
953 pub net_cents: i64,
954}
955
956/// A plan started on a saved card, as its subscription needs it.
957pub(crate) struct SavedPlan<'a> {
958 pub workspace: &'a str,
959 pub feature: &'a str,
960 pub title: &'a str,
961 pub monthly_cents: u32,
962 pub customer: &'a str,
963 pub payment_method: &'a str,
964}
965
966/// A subscription's fields, started on a saved card: the plan as its only
967/// item, excluding tax, and Stripe Tax on.
968pub(crate) fn saved_subscription_fields(p: &SavedPlan<'_>, product: &str) -> Vec<(&'static str, String)> {
969 vec![
970 ("customer", p.customer.to_owned()),
971 ("default_payment_method", p.payment_method.to_owned()),
972 ("payment_behavior", "error_if_incomplete".to_owned()),
973 ("automatic_tax[enabled]", "true".to_owned()),
974 ("items[0][price_data][currency]", "usd".to_owned()),
975 ("items[0][price_data][product]", product.to_owned()),
976 ("items[0][price_data][unit_amount]", p.monthly_cents.to_string()),
977 ("items[0][price_data][recurring][interval]", "month".to_owned()),
978 ("items[0][price_data][tax_behavior]", "exclusive".to_owned()),
979 ("metadata[workspace]", p.workspace.to_owned()),
980 ("metadata[feature]", p.feature.to_owned()),
981 ("description", format!("{} plan for {}", p.title, p.workspace)),
982 ]
983}
984
985pub(crate) fn invoice_split(invoice: &serde_json::Value, amount_paid: i64) -> InvoiceSplit {
986 let tax_cents = invoice["tax"].as_i64().unwrap_or(0).max(0);
987 let fee_cents: i64 = invoice["lines"]["data"]
988 .as_array()
989 .map(|lines| {
990 lines
991 .iter()
992 .filter(|line| line["description"].as_str().is_some_and(|d| d.contains(CARD_FEE_LINE)))
993 .map(|line| line["amount"].as_i64().unwrap_or(0))
994 .sum()
995 })
996 .unwrap_or(0);
997 let fee_cents = fee_cents.max(0);
998 InvoiceSplit { tax_cents, fee_cents, net_cents: (amount_paid - tax_cents - fee_cents).max(0) }
999}
1000
1001impl Stripe {
1002 /// What a card check's setup found, once it succeeded.
1003 pub async fn checked_card(&self, setup_intent: &str) -> Result<Option<CheckedCard>> {
1004 #[derive(Deserialize)]
1005 struct Setup {
1006 status: String,
1007 payment_method: Option<String>,
1008 }
1009 #[derive(Deserialize)]
1010 struct Card {
1011 fingerprint: Option<String>,
1012 brand: Option<String>,
1013 last4: Option<String>,
1014 funding: Option<String>,
1015 country: Option<String>,
1016 }
1017 #[derive(Deserialize)]
1018 struct Billing {
1019 #[serde(default)]
1020 address: Option<serde_json::Value>,
1021 }
1022 #[derive(Deserialize)]
1023 struct PaymentMethod {
1024 card: Option<Card>,
1025 #[serde(default)]
1026 billing_details: Option<Billing>,
1027 }
1028 let setup: Setup = self.call(Method::Get, &format!("/setup_intents/{}", encode(setup_intent)), None).await?;
1029 let (true, Some(method)) = (setup.status == "succeeded", setup.payment_method) else { return Ok(None) };
1030 let found: PaymentMethod = self.call(Method::Get, &format!("/payment_methods/{}", encode(&method)), None).await?;
1031 let card = found.card;
1032 let address = found.billing_details.and_then(|b| b.address).filter(|a| a.is_object());
1033 Ok(Some(CheckedCard {
1034 address,
1035 payment_method: method,
1036 fingerprint: card.as_ref().and_then(|c| c.fingerprint.clone()),
1037 brand: card.as_ref().and_then(|c| c.brand.clone()),
1038 last4: card.as_ref().and_then(|c| c.last4.clone()),
1039 funding: card.as_ref().and_then(|c| c.funding.clone()),
1040 country: card.as_ref().and_then(|c| c.country.clone()),
1041 }))
1042 }
1043
1044 /// Makes `payment_method` the card the customer's invoices are charged to.
1045 pub async fn set_default_card(&self, customer: &str, payment_method: &str) -> Result<()> {
1046 let _: serde_json::Value = self
1047 .call(
1048 Method::Post,
1049 &format!("/customers/{}", encode(customer)),
1050 Some(form(&[("invoice_settings[default_payment_method]", payment_method.to_owned())])),
1051 )
1052 .await?;
1053 Ok(())
1054 }
1055
1056 /// One of g1t's products at Stripe, tagged `metadata[g1t]` (the plan's
1057 /// is `plan`), made the first time it is
1058 /// needed, with g1t's tax code. One made before Stripe Tax was on is
1059 /// given the code when it is found.
1060 pub(crate) async fn product(&self, tag: &str, name: &str) -> Result<String> {
1061 #[derive(Deserialize)]
1062 struct Product {
1063 id: String,
1064 #[serde(default)]
1065 metadata: Option<std::collections::HashMap<String, String>>,
1066 #[serde(default)]
1067 tax_code: Option<serde_json::Value>,
1068 }
1069 #[derive(Deserialize)]
1070 struct List {
1071 data: Vec<Product>,
1072 }
1073 let list: List = self.call(Method::Get, "/products?active=true&limit=100", None).await?;
1074 let ours = |p: &Product| p.metadata.as_ref().and_then(|m| m.get("g1t")).map(String::as_str) == Some(tag);
1075 if let Some(found) = list.data.into_iter().find(ours) {
1076 let coded = found.tax_code.as_ref().is_some_and(|code| code.as_str() == Some(TAX_CODE) || code["id"].as_str() == Some(TAX_CODE));
1077 if !coded {
1078 let _: serde_json::Value = self
1079 .call(Method::Post, &format!("/products/{}", encode(&found.id)), Some(form(&[("tax_code", TAX_CODE.to_owned())])))
1080 .await?;
1081 }
1082 return Ok(found.id);
1083 }
1084 let created: Product = self
1085 .call(
1086 Method::Post,
1087 "/products",
1088 Some(form(&[("name", name.to_owned()), ("metadata[g1t]", tag.to_owned()), ("tax_code", TAX_CODE.to_owned())])),
1089 )
1090 .await?;
1091 Ok(created.id)
1092 }
1093
1094 /// Archives one of g1t's products (by its `metadata[g1t]` tag), so it
1095 /// is never sold again; past invoices keep pointing at it. Nothing to
1096 /// do when there is no such active product.
1097 pub async fn archive_product(&self, tag: &str) -> Result<()> {
1098 #[derive(Deserialize)]
1099 struct Product {
1100 id: String,
1101 #[serde(default)]
1102 metadata: Option<std::collections::HashMap<String, String>>,
1103 }
1104 #[derive(Deserialize)]
1105 struct List {
1106 data: Vec<Product>,
1107 }
1108 let list: List = self.call(Method::Get, "/products?active=true&limit=100", None).await?;
1109 for product in list.data.into_iter().filter(|p| p.metadata.as_ref().and_then(|m| m.get("g1t")).map(String::as_str) == Some(tag)) {
1110 let _: serde_json::Value = self
1111 .call(Method::Post, &format!("/products/{}", encode(&product.id)), Some(form(&[("active", "false".to_owned())])))
1112 .await?;
1113 }
1114 Ok(())
1115 }
1116
1117 /// Starts the monthly plan on a saved card, at once, at its price with
1118 /// tax worked out by Stripe Tax on every invoice. Fails rather than leaving it half-started when the card's
1119 /// bank wants the person again, or when Stripe Tax cannot place the
1120 /// customer (no billing address yet); the caller then sends them to
1121 /// Stripe's page, which asks for the address.
1122 #[allow(clippy::too_many_arguments)]
1123 pub async fn subscribe_with_card(
1124 &self,
1125 workspace: &str,
1126 feature: &str,
1127 title: &str,
1128 monthly_cents: u32,
1129 customer: &str,
1130 payment_method: &str,
1131 ) -> Result<StripeSubscription> {
1132 let product = self.product(feature, &format!("{title} plan")).await?;
1133 let plan = SavedPlan { workspace, feature, title, monthly_cents, customer, payment_method };
1134 let fields = saved_subscription_fields(&plan, &product);
1135 let key = plan_key(workspace, feature, &format!("{payment_method}/{monthly_cents}"), g1t_kit::now_ms());
1136 self.send(Method::Post, "/subscriptions", Some(form(&fields)), Some(&key)).await
1137 }
1138
1139
1140 /// Ends a subscription now: one that never started properly.
1141 pub async fn cancel_now(&self, id: &str) -> Result<StripeSubscription> {
1142 self.call(Method::Delete, &format!("/subscriptions/{}", encode(id)), None).await
1143 }
1144
1145 pub async fn subscription(&self, id: &str) -> Result<StripeSubscription> {
1146 self.call(Method::Get, &format!("/subscriptions/{}", encode(id)), None)
1147 .await
1148 }
1149
1150 /// Ends a plan when its period does (`cancel` true), or takes that back.
1151 pub async fn cancel_at_period_end(&self, id: &str, cancel: bool) -> Result<StripeSubscription> {
1152 self.call(
1153 Method::Post,
1154 &format!("/subscriptions/{}", encode(id)),
1155 Some(form(&[("cancel_at_period_end", cancel.to_string())])),
1156 )
1157 .await
1158 }
1159
1160 pub async fn session(&self, id: &str) -> Result<Session> {
1161 self.call(
1162 Method::Get,
1163 &format!("/checkout/sessions/{}", encode(id)),
1164 None,
1165 )
1166 .await
1167 }
1168}
1169
1170/// Whether the processor said an id it was given does not exist, as when
1171/// g1t moves to another Stripe account and ids saved from the old one stay
1172/// behind, or the customer was deleted there.
1173pub(crate) fn is_missing(error: &Error) -> bool {
1174 error.to_string().contains("resource_missing")
1175}
1176
1177/// What reading a deleted customer comes to: Stripe's own shape for an id
1178/// it does not have, so `is_missing` and `friendly` read it as one.
1179const DELETED_CUSTOMER: &str = r#"the card processor answered 404: {"error": {"type": "invalid_request_error", "code": "resource_missing", "message": "The customer was deleted at Stripe."}}"#;
1180
1181/// Whether Stripe answered with a deleted customer (`{"id": "cus_…",
1182/// "object": "customer", "deleted": true}`), which it does with a 200.
1183pub(crate) fn is_deleted_customer(found: &serde_json::Value) -> bool {
1184 found["deleted"].as_bool() == Some(true) && found["object"].as_str() == Some("customer")
1185}
1186
1187pub(crate) fn is_live(key: &str) -> bool {
1188 key.starts_with("sk_live_") || key.starts_with("rk_live_")
1189}
1190
1191#[cfg(test)]
1192mod tax_mode_tests {
1193 use super::*;
1194
1195 #[test]
1196 fn untaxed_requests_lose_only_automatic_tax() {
1197 let body = form(&[("mode", "payment".to_owned()), ("automatic_tax[enabled]", "true".to_owned()), ("tax_id_collection[enabled]", "true".to_owned())]);
1198 assert_eq!(without_automatic_tax(&body), form(&[("mode", "payment".to_owned()), ("tax_id_collection[enabled]", "true".to_owned())]));
1199 assert!(taxed_path("/checkout/sessions") && taxed_path("/invoices") && taxed_path("/subscriptions"));
1200 // An enrollment converting to the plan turns tax on by updating it.
1201 assert!(taxed_path("/subscriptions/sub_1") && taxed_path("/subscriptions/sub_1?expand[]=latest_invoice"));
1202 assert!(!taxed_path("/invoices/in_1/finalize") && !taxed_path("/payment_intents"));
1203 }
1204
1205 #[test]
1206 fn without_stripe_tax_a_live_key_charges_nothing_and_test_mode_goes_untaxed() {
1207 let body = form(&[("mode", "payment".to_owned()), ("automatic_tax[enabled]", "true".to_owned())]);
1208 assert_eq!(untaxed_body(false, &body).unwrap(), form(&[("mode", "payment".to_owned())]));
1209 let refused = untaxed_body(true, &body).unwrap_err();
1210 // Refused as Stripe would, never a decline, with a sentence for the page.
1211 assert!(friendly(&refused).contains("sales tax"));
1212 assert!(!crate::invoices::is_decline(&refused.to_string()));
1213 }
1214
1215 #[test]
1216 fn a_workspace_gets_one_customer_with_its_owners_email() {
1217 let fields = customer_fields("acme", Some(" ana@acme.test "));
1218 assert!(fields.contains(&("email", "ana@acme.test".to_owned())));
1219 assert!(customer_fields("acme", None).iter().all(|(name, _)| *name != "email"));
1220 assert!(customer_fields("acme", Some("not an email")).iter().all(|(name, _)| *name != "email"));
1221 let at = 1_791_000_000_000;
1222 // Two asking at once make one; another workspace, or later, another.
1223 assert_eq!(customer_key("acme", Some("a@b.c"), at), customer_key("acme", Some("a@b.c"), at + 1_000));
1224 assert_ne!(customer_key("acme", Some("a@b.c"), at), customer_key("other", Some("a@b.c"), at));
1225 assert_ne!(customer_key("acme", Some("a@b.c"), at), customer_key("acme", Some("a@b.c"), at + 600_000));
1226 }
1227}
1228
1229#[cfg(test)]
1230mod tests {
1231 use super::*;
1232
1233 #[test]
1234 fn asking_twice_for_a_plan_starts_one() {
1235 let at = 1_791_000_000_000;
1236 assert_eq!(plan_key("acme", "plan", "pm_1", at), plan_key("acme", "plan", "pm_1", at + 1_000));
1237 assert_ne!(plan_key("acme", "plan", "pm_1", at), plan_key("acme", "plan", "pm_2", at));
1238 assert_ne!(plan_key("acme", "plan", "pm_1", at), plan_key("other", "plan", "pm_1", at));
1239 }
1240
1241 #[test]
1242 fn form_values_are_percent_encoded() {
1243 assert_eq!(
1244 form(&[
1245 (
1246 "success_url",
1247 "https://g1t.sh/a/-/billing?session={ID}".to_owned()
1248 ),
1249 ("line_items[0][quantity]", "1".to_owned()),
1250 ]),
1251 "success_url=https%3A%2F%2Fg1t.sh%2Fa%2F-%2Fbilling%3Fsession%3D%7BID%7D&line_items%5B0%5D%5Bquantity%5D=1"
1252 );
1253 }
1254
1255 #[test]
1256 fn test_keys_are_not_live() {
1257 assert!(is_live("sk_live_abc"));
1258 assert!(!is_live("sk_test_abc"));
1259 assert!(!is_live(""));
1260 }
1261
1262 fn has(fields: &[(&str, String)], name: &str) -> Option<String> {
1263 fields.iter().find(|(n, _)| *n == name).map(|(_, v)| v.clone())
1264 }
1265
1266 #[test]
1267 fn every_request_names_the_api_version_it_is_written_for() {
1268 // Without it a new Stripe account answers at its newest version, and
1269 // invoices, charges and pages read differently from what billing
1270 // expects.
1271 assert!(STRIPE_VERSION.starts_with("2025-02-24"));
1272 let source = include_str!("stripe.rs");
1273 assert!(source.contains(concat!("headers.set(\"stripe-", "version\", STRIPE_VERSION)")));
1274 }
1275
1276 #[test]
1277 fn the_plans_page_is_a_subscription_without_payment_mode_fields() {
1278 let url = "https://g1t.sh/acme/-/billing?plan=plan";
1279 for customer in [None, Some("cus_1")] {
1280 let fields = subscription_fields("acme", "plan", "g1t", 2_100, customer, url);
1281 assert_eq!(has(&fields, "mode").as_deref(), Some("subscription"));
1282 // customer_creation is for payment mode; Stripe refuses it here.
1283 assert!(has(&fields, "customer_creation").is_none());
1284 assert!(has(&fields, "payment_intent_data[setup_future_usage]").is_none());
1285 assert_eq!(has(&fields, "customer").as_deref(), customer);
1286 assert_eq!(has(&fields, "success_url").unwrap(), "https://g1t.sh/acme/-/billing?plan=plan&session={CHECKOUT_SESSION_ID}");
1287 assert_eq!(has(&fields, "line_items[0][price_data][recurring][interval]").as_deref(), Some("month"));
1288 // The plan at its price is the only line: no card fee.
1289 assert_eq!(has(&fields, "line_items[0][price_data][unit_amount]").as_deref(), Some("2100"));
1290 assert!(has(&fields, "line_items[1][quantity]").is_none());
1291 }
1292 }
1293
1294 /// Every field a page must carry for Stripe Tax: tax on top of the
1295 /// price, an address always asked for, the buyer's tax ID, and each
1296 /// line at g1t's tax code, excluding tax. With a customer, what is
1297 /// entered is saved on it (Checkout refuses `automatic_tax` and
1298 /// `tax_id_collection` for a customer otherwise).
1299 fn assert_taxed_page(fields: &[(&str, String)], customer: Option<&str>) {
1300 assert_eq!(has(fields, "automatic_tax[enabled]").as_deref(), Some("true"));
1301 assert_eq!(has(fields, "billing_address_collection").as_deref(), Some("required"));
1302 assert_eq!(has(fields, "tax_id_collection[enabled]").as_deref(), Some("true"));
1303 let saved = if customer.is_some() { Some("auto") } else { None };
1304 assert_eq!(has(fields, "customer_update[address]").as_deref(), saved);
1305 assert_eq!(has(fields, "customer_update[name]").as_deref(), saved);
1306 assert_eq!(has(fields, LINE_KEYS[3]).as_deref(), Some("exclusive"));
1307 assert_eq!(has(fields, LINE_KEYS[5]).as_deref(), Some(TAX_CODE));
1308 // One line, never a second for a card fee.
1309 assert!(fields.iter().all(|(n, _)| !n.starts_with("line_items[1]")));
1310 // No key twice: Stripe takes the last, silently.
1311 let mut names: Vec<&str> = fields.iter().map(|(n, _)| *n).collect();
1312 names.sort_unstable();
1313 let count = names.len();
1314 names.dedup();
1315 assert_eq!(names.len(), count);
1316 }
1317
1318 #[test]
1319 fn every_payment_page_is_taxed_by_stripe_tax() {
1320 let url = "https://g1t.sh/acme/-/billing";
1321 for customer in [None, Some("cus_1")] {
1322 // The plan and Security and quality.
1323 assert_taxed_page(&subscription_fields("acme", "plan", "g1t", 2_100, customer, url), customer);
1324 assert_taxed_page(&subscription_fields("acme", "security", "Security and quality", 1_000, customer, url), customer);
1325 // Prepaying by card and by bank transfer alike.
1326 assert_taxed_page(&prepay_fields("acme", 5_000, customer, url, false), customer);
1327 assert_taxed_page(&prepay_fields("acme", 100_000, customer, url, true), customer);
1328 }
1329 // tax_id_collection and customer_update are for payment and
1330 // subscription mode; a card check charges nothing, so it is not
1331 // taxed, but it asks for the address the plan will be taxed at.
1332 let check = card_check_fields("acme", "cus_1", url);
1333 assert!(has(&check, "automatic_tax[enabled]").is_none());
1334 assert_eq!(has(&check, "billing_address_collection").as_deref(), Some("required"));
1335 }
1336
1337 #[test]
1338 fn the_portal_manages_details_cards_invoices_and_ending_the_plan() {
1339 let fields = portal_fields();
1340 let updates: Vec<&str> =
1341 fields.iter().filter(|(n, _)| n.starts_with("features[customer_update][allowed_updates]")).map(|(_, v)| v.as_str()).collect();
1342 assert_eq!(updates, ["email", "address", "name", "tax_id", "phone"]);
1343 for (name, value) in [
1344 ("features[customer_update][enabled]", "true"),
1345 ("features[payment_method_update][enabled]", "true"),
1346 ("features[invoice_history][enabled]", "true"),
1347 ("features[subscription_cancel][enabled]", "true"),
1348 ("features[subscription_cancel][mode]", "at_period_end"),
1349 ("features[subscription_cancel][cancellation_reason][enabled]", "true"),
1350 ("features[subscription_update][enabled]", "false"),
1351 ("business_profile[privacy_policy_url]", "https://g1t.sh/policies/privacy"),
1352 ("business_profile[terms_of_service_url]", "https://g1t.sh/policies/terms"),
1353 ("metadata[g1t]", "billing"),
1354 ] {
1355 assert_eq!(has(&fields, name).as_deref(), Some(value), "{name}");
1356 }
1357 assert!(has(&fields, "business_profile[headline]").is_some());
1358 // Stripe wants the reasons whenever it asks for one.
1359 assert_eq!(has(&fields, "features[subscription_cancel][cancellation_reason][options][7]").as_deref(), Some("other"));
1360 let mut names: Vec<&str> = fields.iter().map(|(n, _)| *n).collect();
1361 names.sort_unstable();
1362 let count = names.len();
1363 names.dedup();
1364 assert_eq!(names.len(), count);
1365 }
1366
1367 #[test]
1368 fn our_portal_configuration_is_found_by_its_tag_not_made_twice() {
1369 let config = |id: &str, active: bool, tag: Option<&str>| PortalConfiguration {
1370 id: id.to_owned(),
1371 active,
1372 login_page: None,
1373 metadata: tag.map(|t| std::collections::HashMap::from([("g1t".to_owned(), t.to_owned())])),
1374 };
1375 assert_eq!(ours(vec![config("a", true, None), config("b", false, Some("billing")), config("c", true, Some("billing"))]).map(|c| c.id).as_deref(), Some("c"));
1376 assert_eq!(ours(vec![config("b", false, Some("billing"))]).map(|c| c.id).as_deref(), Some("b"));
1377 assert!(ours(vec![config("a", true, None), config("d", true, Some("other"))]).is_none());
1378 }
1379
1380 #[test]
1381 fn stripe_taxs_settings_say_what_is_missing() {
1382 let settings: TaxSettings =
1383 serde_json::from_value(serde_json::json!({ "status": "pending", "status_details": { "pending": { "missing_fields": ["head_office"] } } })).unwrap();
1384 assert_eq!(settings.status, "pending");
1385 assert_eq!(settings.status_details.pending.and_then(|p| p.missing_fields), Some(vec!["head_office".to_owned()]));
1386 let active: TaxSettings = serde_json::from_value(serde_json::json!({ "status": "active", "status_details": { "active": {} } })).unwrap();
1387 assert!(active.status_details.pending.is_none());
1388 }
1389
1390 #[test]
1391 fn a_deleted_customer_reads_as_missing() {
1392 let deleted = serde_json::json!({ "id": "cus_1", "object": "customer", "deleted": true });
1393 assert!(is_deleted_customer(&deleted));
1394 assert!(is_missing(&Error::RustError(DELETED_CUSTOMER.to_owned())));
1395 assert_eq!(friendly(&Error::RustError(DELETED_CUSTOMER.to_owned())), "Stripe refused it: The customer was deleted at Stripe.");
1396 // A customer as usual, and a deleted thing that is not a customer.
1397 assert!(!is_deleted_customer(&serde_json::json!({ "id": "cus_1", "object": "customer", "email": null })));
1398 assert!(!is_deleted_customer(&serde_json::json!({ "id": "txi_1", "object": "tax_id", "deleted": true })));
1399 }
1400
1401 #[test]
1402 fn no_prepayment_has_a_card_fee_line() {
1403 for bank_transfer in [true, false] {
1404 let fields = prepay_fields("acme", 5_000, Some("cus_1"), "https://g1t.sh/acme/-/billing", bank_transfer);
1405 assert_eq!(has(&fields, "line_items[0][price_data][unit_amount]").as_deref(), Some("5000"));
1406 assert!(has(&fields, "line_items[1][quantity]").is_none());
1407 assert!(fields.iter().all(|(_, v)| !v.contains(CARD_FEE_LINE)));
1408 }
1409 }
1410
1411 #[test]
1412 fn a_plan_on_a_saved_card_is_taxed_at_its_price_alone() {
1413 let plan = SavedPlan { workspace: "acme", feature: "plan", title: "g1t", monthly_cents: 2_100, customer: "cus_1", payment_method: "pm_1" };
1414 let fields = saved_subscription_fields(&plan, "prod_plan");
1415 assert_eq!(has(&fields, "automatic_tax[enabled]").as_deref(), Some("true"));
1416 assert_eq!(has(&fields, "items[0][price_data][tax_behavior]").as_deref(), Some("exclusive"));
1417 assert_eq!(has(&fields, "items[0][price_data][unit_amount]").as_deref(), Some("2100"));
1418 assert!(fields.iter().all(|(n, _)| !n.starts_with("items[1]")));
1419 }
1420
1421 #[test]
1422 fn invoices_and_their_lines_are_taxed() {
1423 assert_eq!(has(&invoice_tax_fields(), "automatic_tax[enabled]").as_deref(), Some("true"));
1424 let item = item_tax_fields();
1425 assert_eq!(has(&item, "tax_behavior").as_deref(), Some("exclusive"));
1426 assert_eq!(has(&item, "tax_code").as_deref(), Some(TAX_CODE));
1427 }
1428
1429 #[test]
1430 fn a_refund_reverses_part_of_its_tax() {
1431 let reversal = reversal_fields("tax_1", "pi_1/re_1", 500);
1432 assert_eq!(has(&reversal, "flat_amount").as_deref(), Some("-500"));
1433 assert_eq!(has(&reversal, "mode").as_deref(), Some("partial"));
1434 }
1435
1436 #[test]
1437 fn a_paid_invoice_splits_into_tax_card_fee_and_what_was_sold() {
1438 let invoice = serde_json::json!({
1439 "tax": 180,
1440 "lines": { "data": [
1441 { "description": "1 × g1t plan (at $20.00 / month)", "amount": 2000 },
1442 { "description": "1 × Card processing fee (at $0.92 / month)", "amount": 92 },
1443 ] }
1444 });
1445 assert_eq!(invoice_split(&invoice, 2_272), InvoiceSplit { tax_cents: 180, fee_cents: 92, net_cents: 2_000 });
1446 // Before Stripe Tax: no tax, no fee, all of it sold.
1447 assert_eq!(invoice_split(&serde_json::json!({ "tax": null }), 2_000).net_cents, 2_000);
1448 // A page's tax and what came before it.
1449 let session: Session = serde_json::from_value(serde_json::json!({
1450 "id": "cs_1", "payment_status": "paid", "amount_total": 5_585, "amount_subtotal": 5_185,
1451 "total_details": { "amount_tax": 400 }, "customer": "cus_1", "payment_intent": "pi_1"
1452 }))
1453 .unwrap();
1454 assert_eq!((session.tax_cents(), session.before_tax_cents()), (400, 5_185));
1455 }
1456
1457 #[test]
1458 fn an_address_places_a_customer_for_tax() {
1459 use serde_json::json;
1460 assert!(address_places_customer(&json!({ "country": "DE" })));
1461 assert!(address_places_customer(&json!({ "country": "US", "postal_code": "94107" })));
1462 assert!(!address_places_customer(&json!({ "country": "US", "postal_code": "" })));
1463 assert!(address_places_customer(&json!({ "country": "CA", "state": "ON" })));
1464 assert!(!address_places_customer(&json!({ "country": "" })));
1465 assert!(!address_places_customer(&serde_json::Value::Null));
1466 let error = Error::RustError(r#"the card processor answered 400: {"error":{"code":"customer_tax_location_invalid","message":"x"}}"#.into());
1467 assert!(is_tax_location_error(&error));
1468 }
1469
1470 #[test]
1471 fn a_card_check_is_a_setup_page_with_no_amount() {
1472 let fields = card_check_fields("acme", "cus_1", "https://g1t.sh/acme/-/billing");
1473 assert_eq!(has(&fields, "mode").as_deref(), Some("setup"));
1474 assert!(fields.iter().all(|(n, _)| !n.starts_with("line_items")));
1475 assert_eq!(has(&fields, "success_url").unwrap(), "https://g1t.sh/acme/-/billing?card_check={CHECKOUT_SESSION_ID}");
1476 assert_eq!(has(&fields, "customer").as_deref(), Some("cus_1"));
1477 }
1478
1479 #[test]
1480 fn a_page_asked_for_twice_is_one_page() {
1481 let at = 1_791_000_000_000;
1482 assert_eq!(page_key("plan", "acme", "plan/2000", at), page_key("plan", "acme", "plan/2000", at + 60_000));
1483 assert_ne!(page_key("plan", "acme", "plan/2000", at), page_key("prepay", "acme", "plan/2000", at));
1484 }
1485
1486 #[test]
1487 fn a_stripe_failure_reads_as_a_sentence_never_raw() {
1488 let refused = Error::RustError(
1489 r#"the card processor answered 400: {"error":{"message":"You may only specify one of these parameters: customer, customer_creation.","type":"invalid_request_error"}}"#.into(),
1490 );
1491 assert_eq!(friendly(&refused), "Stripe refused it: You may only specify one of these parameters: customer, customer_creation.");
1492 assert!(!friendly(&refused).contains("invalid_request_error"));
1493 let odd = Error::RustError("the card processor answered 502: <html>".into());
1494 assert!(friendly(&odd).starts_with("Stripe refused it. Try again"));
1495 let down = Error::RustError("network connection lost".into());
1496 assert_eq!(friendly(&down), "Stripe could not be reached. Try again in a minute.");
1497 }
1498}