glacier-web-cli 0.5.0

Command-line tool for creating and running Glacier applications.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
---
title: Billing
description: Taking payments with Stripe Checkout, one-off and subscriptions: customers, checkout, the return URL, syncing charges and subscriptions from Stripe and its webhooks, hooks that grant what was bought, a fake for development and tests, and production config.
category: Going Further
order: 9
---

`glacier::billing` takes payments through
[Stripe Checkout](https://docs.stripe.com/payments/checkout), for one-off
prices and for subscriptions. The app asks for a checkout and sends the
buyer to Stripe's page. When they come back, and again when Stripe's
webhooks arrive, Glacier fetches what the checkout made from Stripe and
saves it: a charge, or a subscription. Hooks the app gives run as each
one is saved for the first time, or changes, and that's where the app
grants what was bought. In development and tests, a fake stands in for
Stripe, so the whole purchase runs without an account or a network.

After reading this guide, you will know:

- Which tables billing keeps, and how to make them.
- How to set up billing on the app, with Stripe or the fake.
- How to make a customer for a user, and start a checkout.
- What the return URL does, and why both it and the webhooks sync from
  Stripe.
- How to write the hooks that grant and take away access.
- How to test a purchase with the fake, and against Stripe's API,
  stubbed.
- How to configure billing in production.
- What isn't built yet.

The examples come from `shop`, an app made with `glacier new shop`,
`glacier generate authentication`, and a mailer. It sells two products,
a Field Guide for £12 and the Glacier Club for £5 a month. A signed-in
user who buys one gets a `License` for it, and a receipt by email:

```glacier
# A user's right to a product, granted when a payment syncs: by a charge
# for a one-off price, or by a subscription for as long as it's active.
module License do
  implements Model

  belongs_to :user
  belongs_to :product
  # The Stripe charge or subscription that pays for it.
  field charge_id: Option<String>
  field subscription_id: Option<String>
  field active: bool

  # The licence a charge pays for, made the first time it's asked for.
  def for_charge(user_id: i64, product_id: i64, charge_id: &str) -> License do
    found = License.where(user_id: user_id, product_id: product_id, charge_id: charge_id).first()!
    case found do
      Some(license) -> license
      None ->
        license = License.new(user_id: user_id, product_id: product_id, charge_id: Some(charge_id.to_owned()), active: true)
        license.save()!
        license
    end
  end

  # The licence a subscription pays for, made the first time.
  def for_subscription(user_id: i64, product_id: i64, subscription_id: &str) -> License do
    found = License.where(user_id: user_id, product_id: product_id, subscription_id: subscription_id).first()!
    case found do
      Some(license) -> license
      None ->
        license = License.new(user_id: user_id, product_id: product_id, subscription_id: Some(subscription_id.to_owned()), active: true)
        license.save()!
        license
    end
  end

  # Whether the user has an active licence for the product.
  def held(user_id: i64, product_id: i64) -> bool do
    License.where(user_id: user_id, product_id: product_id, active: true).exists()!
  end
end
```

A licence for a subscription stays active only while the subscription
is.

## The Tables

### Glacier's Tables

Billing keeps three tables:

| Table | One row per |
| --- | --- |
| `billing_customers` | Customer: an app record (`owner_type`, `owner_id`) and its Stripe id (`processor_id`, `cus_…`) |
| `billing_charges` | One-off payment: its `amount` and `amount_refunded`, in the currency's smallest unit, its `currency` and its `metadata` |
| `billing_subscriptions` | Subscription: its `price`, `quantity`, `status`, `current_period_end`, `ends_at` and `metadata` |

Charges and subscriptions also keep Stripe's whole object, as JSON, in
`data`. Each is unique by its customer and its Stripe id, so saving one
again updates it rather than adding a row.

### The Migration

`glacier::billing::create_tables` makes the three tables, in a migration
of the app's own:

```console
$ glacier generate migration create_billing_tables
      create  db/migrations/m20261005033750_create_billing_tables.glacier
```

```glacier
# The pay gem's tables: customers, subscriptions and charges.
migration do
  up do
    glacier::billing::create_tables(s)
  end

  down do
    drop_table :billing_charges
    drop_table :billing_subscriptions
    drop_table :billing_customers
  end
end
```

### Coming from the pay Gem

A Rails app that bills with the pay gem has its records in `pay_customers`,
`pay_charges` and `pay_subscriptions`. A Glacier app reaching that data
has two ways:

- **Move it across once.** A migration that calls
  `glacier::billing::create_tables(s)` and then
  `glacier::billing::copy_from_pay(s)` copies every customer, charge and
  subscription into Glacier's tables. Ids are kept, so the app's own
  references to them (a licence's charge id, say) still point at the
  right rows, and on Postgres the tables' id sequences move past the
  copied ids. pay's tables are left as they were; drop them in a later
  migration once nothing reads them.
- **Use pay's tables where they are**, while the app shares its database
  with the Rails app: `pay_tables` in `billing do` (after `stripe`;
  `Billing::stripe(&key).pay_tables()` in Rust) reads and writes them
  instead of Glacier's, with pay's column names
  (`processor_plan` for the price, `object` for Stripe's object,
  `created_at`). Tests make them with
  `glacier::billing::create_pay_tables(s)`; in the Rails app's database,
  its migrations made them already.

Webhooks are handled in [background jobs](background_jobs.html), and the
receipts are sent with `deliver_later`, so the app also has the jobs
table and the webhook tables, as
[Calling Other Services](calling_other_services.html#generating-a-provider)
describes; `glacier generate webhook stripe` writes migrations for both.

## Setting Up Billing

### Stripe or the Fake

Billing is a processor and the app's hooks, set up in
`src/billing.glacier`. `stripe secret(…)` makes it Stripe when the config
has a secret key, and it's the stand-in, the fake, when it doesn't, which
is in development and tests:

```glacier
# Stripe when a secret key is set, as it is in production: the config's
# `billing.stripe_secret_key` (or `GLACIER__BILLING__STRIPE_SECRET_KEY`),
# else `STRIPE_SECRET_KEY`. Otherwise the fake, so development and tests
# need no Stripe account.
billing do
  alias Store.Purchases
  stripe secret("billing.stripe_secret_key", "STRIPE_SECRET_KEY")
  # What the shop does as payments sync.
  on_charge Purchases.charged
  on_subscription Purchases.subscription_changed
end
```

`billing do` compiles to `billing::from_config(&config)`, and an app
with a `src/billing.glacier` uses it (`App::billing`) by itself, as it
does `src/webhooks.glacier`'s providers (`App::webhooks`). `provider
:billing` makes the provider for Stripe's webhooks:

```glacier
# Payments (src/billing.glacier) and Stripe's webhooks
# (src/webhooks.glacier), handled in jobs, are added for you.
```

```glacier
# Stripe's webhooks, verified with the signing secret from the config's
# `billing.stripe_webhook_secret` (or `GLACIER__BILLING__STRIPE_WEBHOOK_SECRET`),
# else `STRIPE_WEBHOOK_SECRET`, and handled by syncing what each names
# from Stripe, which runs the hooks in src/billing.glacier.
webhooks do
  provider :billing, secret: secret("billing.stripe_webhook_secret", "STRIPE_WEBHOOK_SECRET")
end
```

In Rust, `Billing::stripe(secret_key)` is Stripe, `Billing::fake()` the
stand-in, and `billing.stripe_webhooks(&[secret])` the provider.

The route is the one every provider uses, in a scope with no pipeline,
since a webhook is checked by its signature rather than a CSRF token:

```glacier
# Webhooks: no CSRF, as they're signed instead.
scope "/" do
  post "/webhooks/:provider", glacier.webhooks.receive
end
```

### Turning Payments Off

Without a Stripe key, an app has the fake, which takes payments that
never happen. An app that shouldn't, such as one deployed before its
Stripe account is ready, says so in its config:

```toml
[billing]
fake = false
```

Billing is then off: a checkout fails with `422` and "Payments are not
enabled.", and `glacier::billing::enabled()` is `false`, for a page that
offers a checkout only when it can. A Stripe key, when one is set, still
wins over `fake = false`. The `shop` app checks both:

```glacier
test "the fake without a key, unless the config turns payments off" do
  fake = Config.from_toml(Env.Test, "")?
  assert from_config(&fake)?.is_enabled()
  off = Config.from_toml(Env.Test, "[billing]\nfake = false\n")?
  assert not from_config(&off)?.is_enabled()
end
```

`Billing::off()` is the same in Rust, and `Billing::without_key(&config)`
the fake or off, as the config says.

### One Billing per Process

`App::billing` sets the billing for the whole process, not only for that
`App`: `glacier::billing::checkout` and the rest find it there, from
actions, jobs and webhook handlers alike. Each `#[glacier::test]` has a
billing of its own, so tests running side by side, each building an app
with its own `Billing::fake()`, never see each other's checkouts.

## Customers

A customer is an app record with a Stripe customer.
`glacier::billing::customer(owner_type, owner_id, email)` finds the
customer for a record, or, the first time, makes one at Stripe and saves
it in `billing_customers`. It returns a `glacier::billing::Customer`, with
the row's `id` and the Stripe `processor_id`. `owner_type` is the
record's model name, here `"User"`, as pay writes it.

## Checkout

### Starting a Checkout

`glacier::billing::Checkout::payment(price, success_url, cancel_url)`
describes a one-off payment for a Stripe price, and
`Checkout::subscription(…)` a subscription. `metadata(key, value)` adds
to what the checkout carries through to the charge or subscription it
makes, and `allow_promotion_codes()` lets the buyer enter a code.
`glacier::billing::checkout(&customer, checkout)` starts it at Stripe and
returns a `CheckoutSession`, with its `id` and the `url` to send the
buyer to. `Products::buy` does all three:

```glacier
# Sends the signed-in user to Stripe Checkout to pay for the product.
def buy(ctx) do
  product = Product.find(params[:id])!
  user = Auth.signed_in_user(&ctx)?
  customer = glacier::billing::customer("User", user.id, &user.email_address)!
  shop: String = ctx.state::<Config>()?.get("shop.url")?
  success_url = format!("{}{}", shop, purchased_product_path(product.id))
  cancel_url = format!("{}{}", shop, product_path(product.id))
  checkout = if product.recurring do
    glacier::billing::Checkout::subscription(&product.price_id, &success_url, &cancel_url)
  else
    glacier::billing::Checkout::payment(&product.price_id, &success_url, &cancel_url)
  end
  # For the hooks in src/billing.rs: who bought what.
  checkout = checkout.metadata("user_id", user.id).metadata("product_id", product.id)
  session = glacier::billing::checkout(&customer, checkout)!
  redirect session.url
end
```

The buy and return routes are for signed-in users only:

```glacier
scope "/", through: [:browser, :authenticated] do
  post "/products/:id/buy", ProductsController.buy, as: :buy_product
  # Where Stripe sends the buyer back.
  get "/products/:id/purchased", ProductsController.purchased, as: :purchased_product
end
```

`shop.url` is the address Stripe sends the buyer back to, set for each
environment:

```toml
[shop]
# Where Stripe sends buyers back to.
url = "http://127.0.0.1:4000"
```

### Metadata

Stripe keeps a checkout's metadata on the charge or subscription it
makes (Glacier sends it as `payment_intent_data[metadata]` or
`subscription_data[metadata]` too), so the hooks can tell who bought
what. Values are text: `metadata("user_id", user.id)` arrives as
`"7"`.

## The Return URL

### Syncing the Checkout

Stripe sends the buyer to the success URL with the session's id added,
as `?session_id=cs_…`; a success URL that already has
`{CHECKOUT_SESSION_ID}` in it has that replaced instead.
`glacier::billing::sync_checkout(id)` fetches the session from Stripe,
and when it's complete, saves the subscription or the charge it made,
running the hooks. It returns a `glacier::billing::Purchase`:
`Purchase::Charge(synced)`, `Purchase::Subscription(synced)`, or
`Purchase::Nothing` for a session that isn't complete, or made nothing
to save:

```glacier
# Where Stripe sends the buyer back, with `?session_id=cs_…`: syncs what
# the checkout made, which runs the hooks, rather than waiting for the
# webhook. Both can happen, in either order; the second changes nothing.
def purchased(ctx) do
  product = Product.find(params[:id])!
  user = Auth.signed_in_user(&ctx)?
  if let Some(session_id) = params.get("session_id") do
    glacier::billing::sync_checkout(session_id)!
  end
  owned = License.held(user.id, product.id)!
  title = product.name.clone()
  render product, owned: owned, title: title
end
```

### Sync from the Source

The return URL and the webhooks do the same thing: each takes an id,
fetches the object as Stripe has it now, and saves that. Neither trusts
what it was sent. So it doesn't matter which comes first, how often
either happens, or whether a webhook arrives late: the rows end up as
Stripe has them, and a hook runs only when a row is new or has changed.
The buyer sees their purchase as soon as they're back, without waiting
for the webhook, and a buyer who closes the tab before coming back is
still served by the webhook.

## Webhooks

`stripe_webhooks(secrets)` verifies each event with the endpoint's
signing secrets (list the old and the new while rotating one) and
handles these events, each by syncing the object it names:

| Event | Syncs |
| --- | --- |
| `checkout.session.completed` | The session, with `sync_checkout` |
| `customer.subscription.created`, `.updated`, `.deleted` | The subscription, with `glacier::billing::sync_subscription` |
| `charge.succeeded`, `charge.refunded` | The charge, with `glacier::billing::sync_charge` |

Events are stored once and handled in jobs, retried if they fail, as
[Calling Other Services](calling_other_services.html#what-happens-to-a-request)
describes. Point Stripe's webhook endpoint at
`https://<your host>/webhooks/stripe`, with those events. A charge or
subscription made in Stripe's dashboard, for a customer the app hasn't
seen, gets a `billing_customers` row with no owner.

## Hooks

### `on_charge` and `on_subscription`

`on_charge` names a function that runs after a charge is saved, when
it's new or its refunded amount has changed. `on_subscription` names one
that runs after a subscription is saved, when it's new or its `status`
has changed. Each gets a `glacier::billing::Synced`, with the `record` (a
`Charge` or `Subscription`), `created`, which is true the first time,
and, for subscriptions, `previous_status`:

```glacier
# What the shop does as payments sync.
on_charge Purchases.charged
on_subscription Purchases.subscription_changed
```

A hook runs in the same transaction as the sync that saved the row, so
if it fails, the row isn't saved either, and the next sync (a webhook's
retry, or the buyer reloading the return page) runs it again. Mail sent
with `deliver_later` inside it is queued in that transaction too.

### Granting and Revoking

The `shop` app's hooks find the user and product the checkout named,
then make or update the licence. A charge grants a licence the first
time, and a refund in full takes it away. A subscription's licence is
active while `Subscription::is_active()` is true: when its status is
`active` or `trialing`, or it's cancelled but paid up to its `ends_at`.
A receipt goes out only the first time:

```glacier
# A one-off payment: a licence and a receipt the first time it syncs.
# A charge refunded in full takes the licence away again.
def charged(synced: Synced<Charge>) do
  charge = synced.record
  if let Some((user, product)) = buyer(&charge.metadata)! do
    license = License.for_charge(user.id, product.id, &charge.processor_id)!
    paid = charge.amount_refunded < charge.amount
    if license.active != paid do
      license.active = paid
      license.save()!
    end
    if synced.created do
      ReceiptMailer.purchased(&user, &product).deliver_later()!
    end
  end
end

# A subscription: a licence for as long as it's active (or cancelled
# but paid up), and a receipt when it starts.
def subscription_changed(synced: Synced<Subscription>) do
  subscription = synced.record
  if let Some((user, product)) = buyer(&subscription.metadata)! do
    license = License.for_subscription(user.id, product.id, &subscription.processor_id)!
    license.active = subscription.is_active()
    license.save()!
    if synced.created && license.active do
      ReceiptMailer.purchased(&user, &product).deliver_later()!
    end
  end
end
```

`License::for_charge` and `License::for_subscription` find the licence
or make it, so a hook that runs again changes nothing. A hook also sees
charges and subscriptions that didn't come from the app's checkout, such
as a subscription's monthly payment, which carries no metadata, so
`buyer` returns `None` for those, and the hooks leave them alone:

```glacier
# Who bought what, from the metadata `Products.buy` gave the checkout.
# `None` for a payment that didn't start there, such as one made in
# Stripe's dashboard.
defp buyer(metadata: &JsonValue) -> Option<(User, Product)> do
  id = fn key -> metadata[key].as_str().and_then(fn id -> id.parse::<i64>().ok() end) end
  case (id("user_id"), id("product_id")) do
    (Some(user_id), Some(product_id)) -> Some((User.find(user_id)!, Product.find(product_id)!))
    _ -> None
  end
end
```

## The Fake

`Billing::fake()` makes no requests. A checkout is paid at once: its
`url` is the success URL, with the session's id in it, so the buyer goes
straight back to the app, and `sync_checkout` finds a complete session
with a charge or an active subscription in Stripe's shapes, carrying the
checkout's metadata. Its ids look like Stripe's, with `_fake_` in them:
`cus_fake_1`, `cs_fake_2`, `sub_fake_3`. Every charge is for 1,000 (in
the smallest unit) times the quantity, in `usd`, whatever the price.

The fake keeps what it made in memory, so it forgets it all when the
process stops, and only syncs from the return URL; it sends no webhooks.

Here the `shop` app ran in development with `glacier server`, on another
port as `GLACIER__SERVER__PORT=4107` and
`GLACIER__SHOP__URL=http://127.0.0.1:4107`. A new user signed up, then
bought the Field Guide. The buy went straight to the return URL, which
showed "Field Guide is yours", and the receipt was in the development
inbox at `/dev/mail`. The server logged:

```text
2026-10-05T04:10:47.041195Z  INFO glacier: GET /registration/new -> 200 in 341.4µs
2026-10-05T04:10:47.296135Z  INFO glacier: POST /registration -> 303 in 242.0ms
2026-10-05T04:10:47.308196Z  INFO glacier: GET /products/1 -> 200 in 757.0µs
2026-10-05T04:10:47.319202Z  INFO glacier: POST /products/1/buy -> 303 in 1.1ms
2026-10-05T04:10:50.816086Z  INFO glacier: GET /products/1/purchased -> 200 in 4.0ms
```

## Testing

### With the Fake

`config/test.toml` sets no Stripe key, so tests use the fake, and a test
can buy as a browser would, end to end. It sets the webhook secret, for
tests that sign webhooks:

```toml
# No Stripe key, so the fake; webhooks are signed with this in tests.
[billing]
stripe_webhook_secret = "whsec_test"
```

The receipt is queued, so `perform_jobs()` sends it. Coming back to the
return URL a second time syncs again but changes nothing:

```glacier
test "buying grants a licence and sends a receipt, once" do
  user = sign_in()
  product = insert(Product)
  res = post buy_product_path(product.id)
  # The fake sends the buyer straight back, paid.
  assert res.location =~ format!("{}?session_id=cs_fake_", purchased_product_path(product.id))
  return_path = path_of(&res.location)

  res = get &return_path
  assert res.body =~ "Field Guide is yours"
  assert License.held(user.id, product.id)!
  assert perform_jobs()! == 1
  assert delivered_mail()[0].subject == "Your receipt for Field Guide"

  # Back again, or the webhook: synced again, but nothing new.
  get &return_path
  assert License.count()! == 1
  assert perform_jobs()! == 0
  assert delivered_mail().len() == 1
  assert get(product_path(product.id)).body =~ "It's yours."
end
```

```console
$ glacier test controllers::products
running 5 tests
test controllers::products_controller::shows_a_product ... ok
test controllers::products_controller::buying_needs_a_signed_in_user ... ok
test controllers::products_controller::a_return_without_a_session_id_waits_for_the_webhook ... ok
test controllers::products_controller::subscribing_grants_a_licence_while_the_subscription_is_active ... ok
test controllers::products_controller::buying_grants_a_licence_and_sends_a_receipt_once ... ok

test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 13 filtered out; finished in 0.94s
```

### Against Stripe, Stubbed

`Billing::stripe` calls Stripe's API through `glacier::client`, so a
test stubs `https://api.stripe.com/v1/…` with `stub_request`, as in
[Testing Calls](calling_other_services.html#stubs), and no request
leaves the process. Since billing is the whole process's, a test that
uses Stripe goes in a file of its own, `tests/stripe_billing.rs`, a
test binary of its own, so it never shares the process with tests that
use the fake. It runs the app with Stripe in place of the fake:

```rust
/// The shop, with Stripe in place of the fake.
fn stripe_app(config: Config, repo: Repo) -> glacier::Result<App> {
    Ok(shop::app(config, repo)?.billing(shop::billing::with_hooks(Billing::stripe("sk_test_1"))))
}
```

with helpers for Stripe's answer and a signed webhook:

```rust
/// Stripe's answer for `GET /v1/subscriptions/sub_1`, in a `status`.
fn subscription(status: &str, user_id: i64, product_id: i64) -> serde_json::Value {
    json!({
        "id": "sub_1", "object": "subscription", "customer": "cus_1", "status": status,
        "cancel_at_period_end": false,
        "metadata": {"user_id": user_id.to_string(), "product_id": product_id.to_string()},
        "items": {"data": [{"price": {"id": "price_club"}, "quantity": 1,
                            "current_period_start": 1790000000, "current_period_end": 1792600000}]}
    })
}

/// Posts `event` to /webhooks/stripe, signed as Stripe would sign it.
async fn deliver(event: String) -> glacier::testing::TestResponse {
    let t = glacier::time::now().timestamp();
    let signature = glacier::webhooks::sign_hex("whsec_test", format!("{t}.{event}").as_bytes());
    glacier::testing::header("stripe-signature", format!("t={t},v1={signature}"));
    post_json("/webhooks/stripe", event).await
}
```

The test buys a subscription, comes back from Stripe, and is then told
by a webhook that the subscription was cancelled. The handler fetches the
subscription again, and the hook takes the licence away:

```rust
let mut product = Product::new();
product.name = "Glacier Club".into();
product.description = "A new route every month.".into();
product.price_id = "price_club".into();
product.price = "£5 a month".into();
product.recurring = true;
product.save().await.unwrap();
get("/registration/new").await;
let form: Form = [
    ("email_address", "ada@example.com"),
    ("password", "a long password"),
]
.into_iter()
.collect();
post("/registration", form).await;
let user = User::authenticate_by("ada@example.com", "a long password")
    .await
    .unwrap()
    .unwrap();

// Buying makes a customer and a session at Stripe, and goes there.
stub_request(
    "POST",
    "https://api.stripe.com/v1/customers",
    200,
    json!({"id": "cus_1"}),
);
stub_request(
    "POST",
    "https://api.stripe.com/v1/checkout/sessions",
    200,
    json!({"id": "cs_1", "url": "https://checkout.stripe.com/c/pay/cs_1"}),
);
get(format!("/products/{}", product.id)).await;
let res = post(format!("/products/{}/buy", product.id), ()).await;
assert_eq!(res.location, "https://checkout.stripe.com/c/pay/cs_1");
let form = String::from_utf8(requests()[1].body.to_vec()).unwrap();
assert!(form.contains("mode=subscription"), "{form}");
assert!(
    form.contains("subscription_data%5Bmetadata%5D%5Bproduct_id%5D"),
    "{form}"
);

// Back from Stripe, paid: the return URL syncs the session.
stub_request(
    "GET",
    "https://api.stripe.com/v1/checkout/sessions/cs_1",
    200,
    json!({"id": "cs_1", "status": "complete",
           "subscription": subscription("active", user.id, product.id)}),
);
let res = get(format!(
    "/products/{}/purchased?session_id=cs_1",
    product.id
))
.await;
assert!(res.body.contains("Glacier Club is yours"), "{}", res.body);
assert!(License::held(user.id, product.id).await.unwrap());

// Later, Stripe says it was cancelled. The handler fetches it again.
stub_request(
    "GET",
    "https://api.stripe.com/v1/subscriptions/sub_1",
    200,
    subscription("canceled", user.id, product.id),
);
let event = json!({"id": "evt_1", "type": "customer.subscription.deleted",
                   "data": {"object": {"id": "sub_1"}}});
let res = deliver(event.to_string()).await;
assert_eq!(res.body, "ok");
perform_jobs().await.unwrap();
assert!(!License::held(user.id, product.id).await.unwrap());
assert!(
    get(format!("/products/{}", product.id))
        .await
        .body
        .contains("Buy")
);
```

```console
$ glacier test --test stripe_billing
running 1 test
test a_cancelled_subscription_takes_the_licence_away ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.49s
```

## Production

In production, set the secret key and the webhook endpoint's signing
secret through the environment, never in a config file you commit. The
`shop` app reads them with `config.secret`, as
[Calling Other Services](calling_other_services.html#secrets) describes:
`GLACIER__BILLING__STRIPE_SECRET_KEY` (or the config's
`billing.stripe_secret_key`), else Stripe's own `STRIPE_SECRET_KEY`, and
likewise `billing.stripe_webhook_secret` or `STRIPE_WEBHOOK_SECRET`:

```toml
#     GLACIER__BILLING__STRIPE_SECRET_KEY=sk_live_…
#     GLACIER__BILLING__STRIPE_WEBHOOK_SECRET=whsec_…
```

`Billing::stripe` sends the key as a bearer token. It retries a `GET`
that fails to connect, times out, or is answered `429`, `502`, `503` or
`504`, twice; it sends each `POST`, which makes a customer or a session,
once. Use a `sk_test_…` key with Stripe's test mode
before a live one.

## What Isn't Built Yet

Glacier's billing doesn't yet have these, which are planned for 0.7:

- **Other processors**: only Stripe, and one processor per app.
- **A customer portal**, for buyers to change their card or cancel;
  link to Stripe's own for now.
- **Invoices and receipts as PDFs**: the app sends its own receipts.
- **Seats**: a subscription's `quantity` is synced, but nothing manages
  who has a seat.

Nor can an app yet swap, pause or cancel a subscription, or refund a
charge, through Glacier: do that in Stripe, and the change arrives by
webhook.