belt-pay 0.0.6 → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +156 -0
- data/README.md +97 -16
- data/lib/belt/pay/billable.rb +13 -4
- data/lib/belt/pay/checkout.rb +15 -1
- data/lib/belt/pay/cli.rb +35 -2
- data/lib/belt/pay/configuration.rb +13 -1
- data/lib/belt/pay/controllers/webhooks_controller.rb +4 -2
- data/lib/belt/pay/providers/stripe.rb +82 -19
- data/lib/belt/pay/subscription.rb +10 -1
- data/lib/belt/pay/templates/controllers/pay_webhooks_controller.rb.erb +3 -2
- data/lib/belt/pay/templates/terraform/main.tf.erb +2 -1
- data/lib/belt/pay/templates/terraform/variables.tf.erb +4 -4
- data/lib/belt/pay/transaction.rb +59 -15
- data/lib/belt/pay/version.rb +1 -1
- data/lib/belt/pay/webhook_handler.rb +341 -76
- data/lib/belt/pay.rb +43 -0
- metadata +1 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 75e20f3be237db3416278e50e6ab37a8ba716f03c93a8e6d7b5b45ece3e2b740
|
|
4
|
+
data.tar.gz: '093835f36169b61cc8e24486946ecd249e537f9ece9fbf3127bcd80c9b8baf83'
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: aedef9e1ac18d26b57e7d43e62609a642ef6f117c69aefbcd469d032f9990646ad5488dc87853e9c05536311fd4a8c6a8c795aef991464546ac8074562c71b31
|
|
7
|
+
data.tar.gz: 7bda16104e9beefd25990383ae0b5c27369faf9a38267cb1ea79cd74ac8172bf53602a771dc6c7edcbd23040a98c1832fffc708b4170eeab9e1e8179d2776bdb
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,161 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.0.7 — 2026-11-15
|
|
4
|
+
|
|
5
|
+
Security release for the Stripe webhook. **Read "Upgrading from 0.0.6 or earlier" below
|
|
6
|
+
before deploying**: the steps marked Required are not optional.
|
|
7
|
+
|
|
8
|
+
### Fixed
|
|
9
|
+
|
|
10
|
+
- **The webhook no longer accepts events signed with the placeholder secret.** The
|
|
11
|
+
generated Terraform seeded the secret with `whsec_PLACEHOLDER` / `sk_test_PLACEHOLDER`,
|
|
12
|
+
and the webhook verified against whatever it found, so on a deploy whose secret was
|
|
13
|
+
never replaced anyone could sign a made-up event. `verify_webhook` now raises
|
|
14
|
+
`Belt::Pay::ConfigurationError` unless the signing secret is a real `whsec_` secret,
|
|
15
|
+
`ensure_api_key!` refuses a missing or placeholder API key, and the Terraform template
|
|
16
|
+
creates the secret empty. `belt pay:setup` warns while either value is unset.
|
|
17
|
+
- **`checkout.session.completed` no longer means paid.** A transaction is completed only
|
|
18
|
+
when the session's `payment_status` is `paid` or `no_payment_required`. A session paid
|
|
19
|
+
by a delayed method (bank debit, voucher) stays `pending` until
|
|
20
|
+
`checkout.session.async_payment_succeeded` completes it or `_failed` fails it.
|
|
21
|
+
- **Refunds and disputes reach the transaction.** `charge.refunded` records
|
|
22
|
+
`amount_refunded_cents` and marks a fully refunded transaction `refunded`;
|
|
23
|
+
`charge.dispute.created` marks it `disputed`; `charge.dispute.closed` returns it to
|
|
24
|
+
`completed` (won) or `refunded` (lost).
|
|
25
|
+
- **A redelivered event changes nothing.** Rows the webhook creates are keyed on the
|
|
26
|
+
Checkout Session / invoice id with a conditional put, and only a `pending` transaction
|
|
27
|
+
can be completed, so Stripe's retries and Dashboard resends no longer add duplicate
|
|
28
|
+
rows or revive a refunded purchase.
|
|
29
|
+
- **`Billable#subscribe!` no longer grants the plan before anything is paid.** `pay_plan`
|
|
30
|
+
is recorded only when the subscription is `active` or `trialing`. The webhook sets it
|
|
31
|
+
when Stripe reports the subscription active and clears it when the subscription is
|
|
32
|
+
`canceled`, `unpaid` or `incomplete_expired` (it asks Stripe for the subscription's
|
|
33
|
+
current status rather than trusting the event). This needs the new
|
|
34
|
+
`Belt::Pay.configuration.customer_class`. The subscription's own transaction is
|
|
35
|
+
`pending` until active. `cancel_subscription!(immediately: true)` clears `pay_plan`
|
|
36
|
+
along with the subscription id.
|
|
37
|
+
- **Events missing a field no longer crash the webhook.** Stripe objects raise on a
|
|
38
|
+
field the event doesn't carry (for example metadata without `app_customer_id`, or
|
|
39
|
+
`invoice.subscription` on API versions from 2025-03-31), which made such events fail
|
|
40
|
+
with a 500 on every retry. Fields are now read defensively.
|
|
41
|
+
- **Secrets are read without an app patch.** `fetch_api_key` / `fetch_webhook_secret`
|
|
42
|
+
relied on a `SecretsHelper` Belt doesn't ship and returned nil without one. They now
|
|
43
|
+
read the configured secret from AWS Secrets Manager directly (a `::SecretsHelper`
|
|
44
|
+
defined by the app is still used when present).
|
|
45
|
+
- The webhook controller decodes a base64-encoded body (`isBase64Encoded`). Belt itself
|
|
46
|
+
still rejects such a body before the controller runs, so this only takes effect once
|
|
47
|
+
Belt passes it through.
|
|
48
|
+
- `Checkout.create` no longer records every pending transaction as `usd`: the currency
|
|
49
|
+
comes from the request when it names one, and from the session when it is paid.
|
|
50
|
+
|
|
51
|
+
### Added
|
|
52
|
+
|
|
53
|
+
- **`Belt::Pay.on(*event_types) { |event, transaction| ... }`** runs your code when the
|
|
54
|
+
webhook receives an event, after the gem's bookkeeping. See "Acting on Events" in the
|
|
55
|
+
README.
|
|
56
|
+
- `Belt::Pay::WebhookHandler::EVENTS` gains `checkout.session.async_payment_succeeded`,
|
|
57
|
+
`checkout.session.async_payment_failed`, `customer.subscription.created`,
|
|
58
|
+
`charge.refunded`, `charge.dispute.created` and `charge.dispute.closed`.
|
|
59
|
+
- `belt pay:setup` offers to add missing events to an existing Stripe endpoint in place,
|
|
60
|
+
keeping its signing secret.
|
|
61
|
+
- `Belt::Pay.configuration.customer_class`, transaction status `disputed`, and the
|
|
62
|
+
transaction fields `amount_refunded_cents` and `provider_payment_intent_id` (now filled
|
|
63
|
+
in). No table or index change is needed.
|
|
64
|
+
|
|
65
|
+
### Known limits
|
|
66
|
+
|
|
67
|
+
- A refund or dispute is matched to a checkout through its Checkout Session, and to a
|
|
68
|
+
renewal through the charge's `invoice`. Stripe API versions from 2025-03-31 no longer
|
|
69
|
+
put `invoice` on a charge, so on an endpoint using one of those a refunded renewal is
|
|
70
|
+
not marked; use a `Belt::Pay.on('charge.refunded')` hook for those.
|
|
71
|
+
- A part refund has no row of its own: the running total is `amount_refunded_cents` on
|
|
72
|
+
the original transaction.
|
|
73
|
+
|
|
74
|
+
### Upgrading from 0.0.6 or earlier
|
|
75
|
+
|
|
76
|
+
Do these in order, for every environment (`dev`, `prod`, ...).
|
|
77
|
+
|
|
78
|
+
1. **Bump the gem.** In the app's `Gemfile` (and `lambda/Gemfile` if it has one) allow
|
|
79
|
+
`belt-pay` 0.0.7 (`gem 'belt-pay', '~> 0.0.7'`), then `bundle update belt-pay`.
|
|
80
|
+
|
|
81
|
+
2. **Required: run `belt 'pay:setup[<env>]'` once per environment.** It does two things
|
|
82
|
+
this release needs: it subscribes the existing Stripe endpoint to the new events, and
|
|
83
|
+
it tells you if the stored secret is still unset. Do not use `pay:show` for this; it
|
|
84
|
+
prints live credentials. Answer the prompts in this order:
|
|
85
|
+
|
|
86
|
+
| Prompt | Answer |
|
|
87
|
+
|--------|--------|
|
|
88
|
+
| `Stripe secret key [blank keeps existing]` | blank (Enter) |
|
|
89
|
+
| `Create the <mode>-mode webhook endpoint in Stripe now? [y/N]` | `y` |
|
|
90
|
+
| `Stripe <mode> secret key, or restricted key with Webhook Endpoints write [not stored]` | Only appears when the stored key is a restricted key that can't manage endpoints. Needs a person: paste an `sk_` key or a restricted key with Webhook Endpoints: Write. It is used once and not stored |
|
|
91
|
+
| `Add them to this endpoint? (its signing secret stays the same) [Y/n]` | `y` |
|
|
92
|
+
| `Replace it? [y/N]` | `n` |
|
|
93
|
+
| `Stripe webhook signing secret [blank keeps existing]` | blank (Enter) |
|
|
94
|
+
|
|
95
|
+
The output should include `Endpoint we_... now receives 12 events.` (Or do this part
|
|
96
|
+
in the Stripe Dashboard: Developers -> Webhooks -> the endpoint -> add the six events
|
|
97
|
+
listed under "Added".) **Do not skip this**: once this version is deployed, a checkout
|
|
98
|
+
paid by a delayed method stays `pending` until
|
|
99
|
+
`checkout.session.async_payment_succeeded` arrives, and refunds and disputes are only
|
|
100
|
+
seen if the endpoint sends them.
|
|
101
|
+
|
|
102
|
+
3. **Required: if that run printed `Warning: ... not set in <secret>`**, or said
|
|
103
|
+
`No Stripe secret key stored yet`, the environment still holds the placeholder (or
|
|
104
|
+
nothing). Run `belt 'pay:setup[<env>]'` again and this time give it the real Stripe
|
|
105
|
+
key and let it create the endpoint. Until then, by design, that environment answers
|
|
106
|
+
every webhook with 500 and refuses Stripe calls.
|
|
107
|
+
|
|
108
|
+
4. **Required if the app uses `subscribe!(plan:)` or reads `pay_plan` / `plan` /
|
|
109
|
+
`plan_allows?` / `within_limit?`:** set the customer model where the app and the
|
|
110
|
+
webhook Lambda boot, and make sure that model is loaded in the webhook Lambda
|
|
111
|
+
(`lambda/pay_webhooks.rb`):
|
|
112
|
+
|
|
113
|
+
```ruby
|
|
114
|
+
Belt::Pay.configure { |config| config.customer_class = 'Customer' } # your Billable model
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Without it `pay_plan` is never set for a subscription that starts unpaid (the webhook
|
|
118
|
+
logs `customer_class is not configured` on each subscription event). Code that relied
|
|
119
|
+
on `pay_plan` being set immediately after `subscribe!` must wait for the webhook, or
|
|
120
|
+
check `result[:status]`.
|
|
121
|
+
|
|
122
|
+
5. **Check what the webhook Lambda is allowed to do.** Belt Pay does not generate this
|
|
123
|
+
IAM; it is in the app's Terraform (look for the policy attached to the `pay_webhooks`
|
|
124
|
+
Lambda). A missing permission makes the affected events answer 500.
|
|
125
|
+
- On the `<app>-<env>-pay-transactions` table and its indexes: `dynamodb:GetItem`,
|
|
126
|
+
`dynamodb:Query`, `dynamodb:PutItem` and `dynamodb:UpdateItem`. `GetItem` is new in
|
|
127
|
+
this release.
|
|
128
|
+
- If you set `customer_class` (step 4): `dynamodb:GetItem`, `dynamodb:PutItem` and
|
|
129
|
+
`dynamodb:UpdateItem` on that model's table.
|
|
130
|
+
- `secretsmanager:GetSecretValue` on the Stripe secret (the generated
|
|
131
|
+
`read_secrets_policy_arn`).
|
|
132
|
+
- If the runtime Stripe key is a restricted key (`rk_`): at least Read on Checkout
|
|
133
|
+
Sessions (to find the purchase behind a refund or dispute) and on Subscriptions.
|
|
134
|
+
|
|
135
|
+
6. **Check code that reads transactions.** `checkout`/`subscription` rows can now be
|
|
136
|
+
`pending` after checkout completes, and `refunded` or `disputed` later. Treat only
|
|
137
|
+
`status == 'completed'` as paid. Rows written by the webhook use the Stripe id
|
|
138
|
+
(`cs_...`, `in_...`, `sub_...`) as `id` instead of a UUID. `Transaction.record_checkout`,
|
|
139
|
+
`record_subscription` and `record_renewal` return nil when the row already exists.
|
|
140
|
+
|
|
141
|
+
7. **Remove app patches this release replaces** (optional, they keep working): a
|
|
142
|
+
`prepend` over `fetch_api_key` / `fetch_webhook_secret` that reads Secrets Manager,
|
|
143
|
+
and controller overrides that only check `payment_status`, refuse the placeholder
|
|
144
|
+
secret or de-duplicate events. An overridden controller that calls
|
|
145
|
+
`Belt::Pay.provider.verify_webhook` and `WebhookHandler.send(:dispatch, event)` keeps
|
|
146
|
+
working; `dispatch` now also runs `Belt::Pay.on` hooks.
|
|
147
|
+
|
|
148
|
+
8. **Stop seeding placeholders in Terraform (optional hygiene).** In the app's generated
|
|
149
|
+
`infrastructure/modules/pay/variables.tf`, change the defaults of `stripe_secret_key`
|
|
150
|
+
and `stripe_webhook_secret` from `"sk_test_PLACEHOLDER"` / `"whsec_PLACEHOLDER"` to
|
|
151
|
+
`""`. Edit those two lines by hand; do not regenerate with `belt g pay --force`,
|
|
152
|
+
which would also overwrite `lambda/pay_webhooks.rb` and the Lambda config. Existing
|
|
153
|
+
secrets are not touched (`ignore_changes`); this only affects environments created
|
|
154
|
+
later.
|
|
155
|
+
|
|
156
|
+
9. Deploy (`belt apply <env>` / your usual deploy), then send a test event from the
|
|
157
|
+
Stripe Dashboard and confirm the endpoint answers 200.
|
|
158
|
+
|
|
3
159
|
## 0.0.6 — 2026-11-02
|
|
4
160
|
|
|
5
161
|
- **`pay:setup` works with a restricted runtime key.** The stored key is what the app
|
data/README.md
CHANGED
|
@@ -59,7 +59,9 @@ Belt::Pay.plans.paid # => [pro, ...]
|
|
|
59
59
|
Belt::Pay.plans.featured # => the :pro plan
|
|
60
60
|
Belt::Pay.plans.to_a # => [{ key:, name:, prices:, limits:, ... }] for your frontend
|
|
61
61
|
|
|
62
|
-
# Gate features and enforce limits
|
|
62
|
+
# Gate features and enforce limits. The plan is granted once Stripe reports the
|
|
63
|
+
# subscription active (or trialing) and taken back when it ends; see
|
|
64
|
+
# "Plans follow the subscription" below.
|
|
63
65
|
customer.on_plan?(:pro) # => true
|
|
64
66
|
customer.plan_allows?(:sso) # => true
|
|
65
67
|
customer.within_limit?(:projects, current_count) # => false once the ceiling is hit
|
|
@@ -165,9 +167,28 @@ Belt::Pay.configure do |config|
|
|
|
165
167
|
config.provider = :stripe # Only :stripe for now
|
|
166
168
|
config.secret_name = 'myapp-prod-stripe' # Secrets Manager secret
|
|
167
169
|
config.table_name_prefix = 'myapp-prod' # DynamoDB table prefix
|
|
170
|
+
config.customer_class = 'Customer' # Your Billable model (class or name)
|
|
168
171
|
end
|
|
169
172
|
```
|
|
170
173
|
|
|
174
|
+
#### Plans follow the subscription
|
|
175
|
+
|
|
176
|
+
`customer_class` is the model that includes `Belt::Pay::Billable`. Set it wherever the
|
|
177
|
+
webhook Lambda boots (the model must be loadable there). The webhook uses it to find the
|
|
178
|
+
customer named by a subscription's `app_customer_id` and keep `pay_plan` /
|
|
179
|
+
`pay_subscription_id` in step with Stripe:
|
|
180
|
+
|
|
181
|
+
- `subscribe!(plan:)` records `pay_plan` only if the subscription is already `active` or
|
|
182
|
+
`trialing`. One that still needs its first payment (`incomplete`, the usual case)
|
|
183
|
+
grants nothing yet.
|
|
184
|
+
- When Stripe reports the subscription `active` or `trialing`, the webhook sets
|
|
185
|
+
`pay_plan` (the plan declared for the subscription's price, else its `plan` metadata).
|
|
186
|
+
- When it becomes `canceled`, `unpaid` or `incomplete_expired`, the webhook clears
|
|
187
|
+
`pay_plan`. `past_due` keeps it while Stripe retries the payment.
|
|
188
|
+
|
|
189
|
+
Without `customer_class` the webhook cannot do any of this: it logs an error on each
|
|
190
|
+
subscription event and `pay_plan` is never set for a subscription that starts unpaid.
|
|
191
|
+
|
|
171
192
|
### Secrets Manager Format
|
|
172
193
|
|
|
173
194
|
The Stripe secret should contain:
|
|
@@ -179,6 +200,14 @@ The Stripe secret should contain:
|
|
|
179
200
|
}
|
|
180
201
|
```
|
|
181
202
|
|
|
203
|
+
Belt Pay reads it straight from Secrets Manager (the webhook and API Lambdas need
|
|
204
|
+
`secretsmanager:GetSecretValue` on it, which the generated `read_secrets_policy_arn`
|
|
205
|
+
grants). The generated Terraform creates the secret with both values empty, and Belt Pay
|
|
206
|
+
refuses to work with a value that is missing or a placeholder: `verify_webhook` raises
|
|
207
|
+
`Belt::Pay::ConfigurationError` (the webhook answers 500) unless the signing secret is a
|
|
208
|
+
real `whsec_` secret, and no Stripe call is made without a real API key. Nothing is ever
|
|
209
|
+
verified against a secret someone else could know.
|
|
210
|
+
|
|
182
211
|
### Setting Up and Managing Secrets
|
|
183
212
|
|
|
184
213
|
Belt Pay hooks into Belt through its standard gem-provided Rake task mechanism. The
|
|
@@ -200,9 +229,16 @@ either prompt blank to preserve its existing value. Use `--webhook-url` /
|
|
|
200
229
|
`BELT_PAY_WEBHOOK_URL` or `--webhook-events` / `BELT_PAY_WEBHOOK_EVENTS` to override the
|
|
201
230
|
defaults. Test (`sk_test_`) and live (`sk_live_`) keys get separate endpoints and secrets.
|
|
202
231
|
|
|
232
|
+
If Stripe already has an endpoint for the URL and it lacks some handled events (one
|
|
233
|
+
created by an older Belt Pay, say), setup offers to add them to it in place, which keeps
|
|
234
|
+
its signing secret. Setup also warns when the key or signing secret is still unset.
|
|
235
|
+
|
|
203
236
|
Prefer a [restricted key](https://docs.stripe.com/keys#limit-access) (`rk_`) as the
|
|
204
237
|
stored key, scoped to what your app calls at runtime (typically Customers, Checkout
|
|
205
|
-
Sessions, Customer portal and Subscriptions).
|
|
238
|
+
Sessions, Customer portal and Subscriptions). The webhook reads Checkout Sessions (to
|
|
239
|
+
find the purchase a refund or dispute belongs to) and Subscriptions (to check a
|
|
240
|
+
subscription's current status), so give those at least Read. It doesn't need Webhook
|
|
241
|
+
Endpoints access:
|
|
206
242
|
when Stripe refuses it for the endpoint step, setup asks once for a key that can manage
|
|
207
243
|
endpoints (your `sk_` secret key, or a restricted key with Webhook Endpoints: Write),
|
|
208
244
|
uses it for that step only, and doesn't store it.
|
|
@@ -313,26 +349,63 @@ end
|
|
|
313
349
|
|
|
314
350
|
## Webhook Events
|
|
315
351
|
|
|
316
|
-
The gem automatically handles these Stripe webhook events
|
|
352
|
+
The gem automatically handles these Stripe webhook events
|
|
353
|
+
(`Belt::Pay::WebhookHandler::EVENTS`, which is what `belt pay:setup` subscribes the
|
|
354
|
+
endpoint to):
|
|
317
355
|
|
|
318
356
|
| Event | Behavior |
|
|
319
357
|
|-------|----------|
|
|
320
|
-
| `checkout.session.completed` |
|
|
321
|
-
| `checkout.session.
|
|
322
|
-
| `
|
|
358
|
+
| `checkout.session.completed` | Completes the transaction if the session is paid (`payment_status` `paid` or `no_payment_required`). A session paid by a delayed method (bank debit, voucher) stays `pending` |
|
|
359
|
+
| `checkout.session.async_payment_succeeded` | Completes the pending transaction of a delayed payment |
|
|
360
|
+
| `checkout.session.async_payment_failed` | Marks it `failed` |
|
|
361
|
+
| `checkout.session.expired` | Marks pending transaction as `failed` |
|
|
362
|
+
| `invoice.paid` | Records a subscription renewal transaction (once per invoice) |
|
|
323
363
|
| `invoice.payment_failed` | Logs payment failure |
|
|
324
|
-
| `customer.subscription.deleted` |
|
|
325
|
-
| `
|
|
364
|
+
| `customer.subscription.created` / `.updated` / `.deleted` | Sets or clears the customer's `pay_plan` to match the subscription (see [Plans follow the subscription](#plans-follow-the-subscription)) and settles the subscription's transaction |
|
|
365
|
+
| `charge.refunded` | Records `amount_refunded_cents`; a full refund marks the transaction `refunded` |
|
|
366
|
+
| `charge.dispute.created` | Marks the transaction `disputed` |
|
|
367
|
+
| `charge.dispute.closed` | Won: `completed` again. Lost: `refunded` |
|
|
368
|
+
|
|
369
|
+
Stripe delivers events at least once, and anyone with Dashboard access can send one
|
|
370
|
+
again. Handling is safe to repeat: rows the webhook creates are keyed on the Checkout
|
|
371
|
+
Session or invoice id, and only a `pending` transaction can become `completed`, so a
|
|
372
|
+
redelivered event never adds a row or revives a refunded purchase.
|
|
373
|
+
|
|
374
|
+
**Only `completed` means the customer has paid.** If your app decides what someone owns
|
|
375
|
+
from `customer.transactions`, check `status == 'completed'`.
|
|
376
|
+
|
|
377
|
+
### Acting on Events
|
|
378
|
+
|
|
379
|
+
Register a hook to run your own code when an event arrives, after the gem's bookkeeping.
|
|
380
|
+
The block gets the Stripe event and the `Belt::Pay::Transaction` it touched (`nil` when
|
|
381
|
+
the event has none):
|
|
382
|
+
|
|
383
|
+
```ruby
|
|
384
|
+
# Wherever the webhook Lambda boots
|
|
385
|
+
Belt::Pay.on('checkout.session.completed', 'checkout.session.async_payment_succeeded') do |event, transaction|
|
|
386
|
+
Orders.fulfil(transaction) if transaction&.status == 'completed'
|
|
387
|
+
end
|
|
388
|
+
|
|
389
|
+
Belt::Pay.on('charge.refunded', 'charge.dispute.created', 'charge.dispute.closed') do |event, transaction|
|
|
390
|
+
Orders.revoke(transaction) if transaction && transaction.status != 'completed'
|
|
391
|
+
end
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
Hooks run on every delivery, including repeats, so make them safe to run twice and go by
|
|
395
|
+
`transaction.status` rather than the event alone. A hook that raises fails the webhook
|
|
396
|
+
(HTTP 500) and Stripe sends the event again later. A hook can be registered for any
|
|
397
|
+
event type, including ones the gem does nothing with; add those to the endpoint with
|
|
398
|
+
`--webhook-events` or in the Dashboard.
|
|
326
399
|
|
|
327
400
|
### Customizing Webhook Behavior
|
|
328
401
|
|
|
329
|
-
|
|
402
|
+
For anything a hook can't do, override the webhook controller:
|
|
330
403
|
|
|
331
404
|
```bash
|
|
332
405
|
belt g pay --controllers
|
|
333
406
|
```
|
|
334
407
|
|
|
335
|
-
This generates a controller in your app that inherits from the gem's default.
|
|
408
|
+
This generates a controller in your app that inherits from the gem's default.
|
|
336
409
|
|
|
337
410
|
## Transaction Model
|
|
338
411
|
|
|
@@ -350,14 +423,16 @@ end
|
|
|
350
423
|
|
|
351
424
|
| Field | Description |
|
|
352
425
|
|-------|-------------|
|
|
353
|
-
| `id` | UUID
|
|
426
|
+
| `id` | Primary key: a UUID, or the Stripe id (Checkout Session, invoice, subscription) for rows that must exist only once |
|
|
354
427
|
| `customer_id` | Your app's customer/user ID |
|
|
355
428
|
| `provider` | Payment provider (`stripe`) |
|
|
356
429
|
| `provider_session_id` | Stripe checkout session ID |
|
|
357
430
|
| `provider_subscription_id` | Stripe subscription ID |
|
|
431
|
+
| `provider_payment_intent_id` | Stripe PaymentIntent ID of a paid checkout |
|
|
358
432
|
| `type` | `checkout`, `subscription`, `subscription_renewal`, `refund` |
|
|
359
|
-
| `status` | `pending
|
|
433
|
+
| `status` | `pending` (not paid yet), `completed` (paid), `failed`, `refunded`, `disputed`, `canceled` |
|
|
360
434
|
| `amount_cents` | Amount in cents |
|
|
435
|
+
| `amount_refunded_cents` | How much of it has been refunded, if any |
|
|
361
436
|
| `currency` | ISO currency code |
|
|
362
437
|
| `metadata` | Free-form JSON metadata |
|
|
363
438
|
| `created_at` | ISO 8601 timestamp |
|
|
@@ -372,12 +447,12 @@ module "pay" {
|
|
|
372
447
|
app_name = var.app_name
|
|
373
448
|
environment = var.environment
|
|
374
449
|
|
|
375
|
-
# Set these or update secrets manually after apply
|
|
376
|
-
# stripe_secret_key = var.stripe_secret_key
|
|
377
|
-
# stripe_webhook_secret = var.stripe_webhook_secret
|
|
378
450
|
}
|
|
379
451
|
```
|
|
380
452
|
|
|
453
|
+
The secret is created empty. Store the real values with `belt pay:setup <env>` after
|
|
454
|
+
`belt apply`; until then Belt Pay refuses to call Stripe or accept a webhook.
|
|
455
|
+
|
|
381
456
|
## Stripe Dashboard Setup
|
|
382
457
|
|
|
383
458
|
`BELT_ENV=<env> belt pay:setup` creates the webhook endpoint and stores its signing
|
|
@@ -387,11 +462,17 @@ secret for you. To do it by hand instead:
|
|
|
387
462
|
2. Add endpoint: `https://<your-api-domain>/pay/webhooks`
|
|
388
463
|
3. Select events:
|
|
389
464
|
- `checkout.session.completed`
|
|
465
|
+
- `checkout.session.async_payment_succeeded`
|
|
466
|
+
- `checkout.session.async_payment_failed`
|
|
390
467
|
- `checkout.session.expired`
|
|
391
468
|
- `invoice.paid`
|
|
392
469
|
- `invoice.payment_failed`
|
|
393
|
-
- `customer.subscription.
|
|
470
|
+
- `customer.subscription.created`
|
|
394
471
|
- `customer.subscription.updated`
|
|
472
|
+
- `customer.subscription.deleted`
|
|
473
|
+
- `charge.refunded`
|
|
474
|
+
- `charge.dispute.created`
|
|
475
|
+
- `charge.dispute.closed`
|
|
395
476
|
4. Copy the signing secret into your Secrets Manager secret
|
|
396
477
|
|
|
397
478
|
## Removing
|
data/lib/belt/pay/billable.rb
CHANGED
|
@@ -48,7 +48,11 @@ module Belt
|
|
|
48
48
|
#
|
|
49
49
|
# Pass either a declared plan key (`plan:`) or a raw `price_id:`.
|
|
50
50
|
# When a plan key is given, the customer's `pay_plan` is recorded so
|
|
51
|
-
# limits/features can be checked later without a Stripe round-trip
|
|
51
|
+
# limits/features can be checked later without a Stripe round-trip, but only
|
|
52
|
+
# once the subscription is active or trialing. A subscription that still needs
|
|
53
|
+
# its first payment (the usual case: status `incomplete`) grants nothing here;
|
|
54
|
+
# the webhook sets `pay_plan` when Stripe reports it active, and takes it back
|
|
55
|
+
# when the subscription ends. That needs `Belt::Pay.configuration.customer_class`.
|
|
52
56
|
#
|
|
53
57
|
# @param plan [Symbol, String, nil] A declared plan key (see Belt::Pay.plans)
|
|
54
58
|
# @param price_id [String, nil] Provider price ID (overrides plan lookup)
|
|
@@ -59,7 +63,7 @@ module Belt
|
|
|
59
63
|
result = Belt::Pay.subscribe(self, plan: plan, price_id: price_id,
|
|
60
64
|
interval: interval, metadata: metadata)
|
|
61
65
|
self.pay_subscription_id = result[:subscription_id]
|
|
62
|
-
self.pay_plan = plan.to_s if plan
|
|
66
|
+
self.pay_plan = plan.to_s if plan && Subscription::ACTIVE_STATUSES.include?(result[:status].to_s)
|
|
63
67
|
save(validate: false)
|
|
64
68
|
result
|
|
65
69
|
end
|
|
@@ -111,8 +115,13 @@ module Belt
|
|
|
111
115
|
# @param immediately [Boolean] Cancel now (true) or at period end (false, default)
|
|
112
116
|
def cancel_subscription!(immediately: false)
|
|
113
117
|
Belt::Pay.cancel_subscription(self, immediately: immediately)
|
|
114
|
-
|
|
115
|
-
|
|
118
|
+
return unless immediately
|
|
119
|
+
|
|
120
|
+
# The plan goes with the subscription. At period end it stays until Stripe
|
|
121
|
+
# deletes the subscription and the webhook takes it back.
|
|
122
|
+
self.pay_subscription_id = nil
|
|
123
|
+
self.pay_plan = nil
|
|
124
|
+
save(validate: false)
|
|
116
125
|
end
|
|
117
126
|
|
|
118
127
|
# Generate a billing portal URL for self-service management.
|
data/lib/belt/pay/checkout.rb
CHANGED
|
@@ -37,7 +37,7 @@ module Belt
|
|
|
37
37
|
provider_session_id: result[:session_id],
|
|
38
38
|
type: mode == 'subscription' ? 'subscription' : 'checkout',
|
|
39
39
|
status: 'pending',
|
|
40
|
-
currency:
|
|
40
|
+
currency: checkout_currency(line_items, options),
|
|
41
41
|
description: "Checkout session created (#{mode})",
|
|
42
42
|
metadata: metadata
|
|
43
43
|
)
|
|
@@ -47,6 +47,20 @@ module Belt
|
|
|
47
47
|
|
|
48
48
|
result
|
|
49
49
|
end
|
|
50
|
+
|
|
51
|
+
private
|
|
52
|
+
|
|
53
|
+
# The currency the session will charge in, when the request says: the
|
|
54
|
+
# session's `currency:` or the first line item's inline price. A session
|
|
55
|
+
# sold by price id doesn't say, so the pending row has none and the webhook
|
|
56
|
+
# fills it in from the paid session.
|
|
57
|
+
def checkout_currency(line_items, options)
|
|
58
|
+
first = Array(line_items).first
|
|
59
|
+
price_data = first.is_a?(Hash) ? (first[:price_data] || first['price_data']) : nil
|
|
60
|
+
inline = price_data.is_a?(Hash) ? (price_data[:currency] || price_data['currency']) : nil
|
|
61
|
+
currency = options[:currency] || inline
|
|
62
|
+
currency&.to_s&.downcase
|
|
63
|
+
end
|
|
50
64
|
end
|
|
51
65
|
end
|
|
52
66
|
end
|
data/lib/belt/pay/cli.rb
CHANGED
|
@@ -129,13 +129,29 @@ module Belt
|
|
|
129
129
|
|
|
130
130
|
update_secret(response, original, updated)
|
|
131
131
|
delete_replaced_endpoints(replaced)
|
|
132
|
+
warn_unset(updated)
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
# Belt Pay refuses to call Stripe or verify a webhook with a value that is
|
|
136
|
+
# missing or still a placeholder, so say so while the operator is here.
|
|
137
|
+
def warn_unset(secret)
|
|
138
|
+
unset = %w[stripe_secret_key stripe_webhook_secret].select { |key| unset?(secret[key]) }
|
|
139
|
+
return if unset.empty?
|
|
140
|
+
|
|
141
|
+
@out.puts "Warning: #{unset.join(' and ')} #{unset.size == 1 ? 'is' : 'are'} not set in #{@secret_name}."
|
|
142
|
+
@out.puts 'Payments and webhooks are refused until a real value is stored; run this command again to set it.'
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
# Blank, or the placeholder older generated Terraform seeded the secret with.
|
|
146
|
+
def unset?(value)
|
|
147
|
+
blank?(value) || value.strip.match?(/_PLACEHOLDER\z/i)
|
|
132
148
|
end
|
|
133
149
|
|
|
134
150
|
# Returns [signing_secret, endpoints_to_delete]. Offers to create the Stripe
|
|
135
151
|
# webhook endpoint (Stripe only returns a signing secret at creation time);
|
|
136
152
|
# otherwise prints Dashboard instructions and prompts for the secret.
|
|
137
153
|
def webhook_secret_for(api_key, existing_secret)
|
|
138
|
-
if
|
|
154
|
+
if unset?(api_key)
|
|
139
155
|
@out.puts 'No Stripe secret key stored yet, so the webhook endpoint cannot be created for you.'
|
|
140
156
|
return [manual_webhook_secret(nil), []]
|
|
141
157
|
end
|
|
@@ -145,12 +161,13 @@ module Belt
|
|
|
145
161
|
@out.puts "Stripe account mode: #{mode}"
|
|
146
162
|
@out.puts "Webhook endpoint URL: #{url || '(unknown; run `belt apply` first or pass --webhook-url)'}"
|
|
147
163
|
|
|
148
|
-
create = !url.nil? && confirm("Create the #{mode}-mode webhook endpoint in Stripe now?", default:
|
|
164
|
+
create = !url.nil? && confirm("Create the #{mode}-mode webhook endpoint in Stripe now?", default: unset?(existing_secret))
|
|
149
165
|
return [manual_webhook_secret(url, mode: mode), []] unless create
|
|
150
166
|
|
|
151
167
|
@endpoint_key = api_key
|
|
152
168
|
existing = with_endpoint_key(mode) { |key| stripe_endpoints(key) }.select { |endpoint| endpoint.url == url }
|
|
153
169
|
if existing.any?
|
|
170
|
+
existing.each { |endpoint| add_missing_events(endpoint, mode) }
|
|
154
171
|
ids = existing.map(&:id).join(', ')
|
|
155
172
|
@out.puts "Stripe already has an endpoint for this URL (#{ids}). Stripe never re-sends a signing secret,"
|
|
156
173
|
@out.puts 'so setup can only replace it with a new endpoint (the old secret stops working).'
|
|
@@ -173,6 +190,22 @@ module Belt
|
|
|
173
190
|
[manual_webhook_secret(url, mode: mode), []]
|
|
174
191
|
end
|
|
175
192
|
|
|
193
|
+
# An endpoint made by an older Belt Pay is subscribed to fewer events than the
|
|
194
|
+
# handler now acts on. Adding them in place keeps the endpoint's signing secret.
|
|
195
|
+
def add_missing_events(endpoint, mode)
|
|
196
|
+
current = Array(endpoint.enabled_events)
|
|
197
|
+
missing = webhook_events - current
|
|
198
|
+
return if current.include?('*') || missing.empty?
|
|
199
|
+
|
|
200
|
+
@out.puts "Endpoint #{endpoint.id} is not subscribed to: #{missing.join(', ')}"
|
|
201
|
+
return unless confirm('Add them to this endpoint? (its signing secret stays the same)', default: true)
|
|
202
|
+
|
|
203
|
+
with_endpoint_key(mode) do |key|
|
|
204
|
+
::Stripe::WebhookEndpoint.update(endpoint.id, { enabled_events: current | webhook_events }, { api_key: key })
|
|
205
|
+
end
|
|
206
|
+
@out.puts "Endpoint #{endpoint.id} now receives #{(current | webhook_events).size} events."
|
|
207
|
+
end
|
|
208
|
+
|
|
176
209
|
def manual_webhook_secret(url, mode: nil)
|
|
177
210
|
@out.puts <<~STEPS
|
|
178
211
|
|
|
@@ -4,7 +4,7 @@ module Belt
|
|
|
4
4
|
module Pay
|
|
5
5
|
class Configuration
|
|
6
6
|
attr_accessor :provider, :secret_name, :webhook_secret_name,
|
|
7
|
-
:table_name_prefix, :logger, :test_mode
|
|
7
|
+
:table_name_prefix, :logger, :test_mode, :customer_class
|
|
8
8
|
|
|
9
9
|
def initialize
|
|
10
10
|
@provider = :stripe
|
|
@@ -13,6 +13,18 @@ module Belt
|
|
|
13
13
|
@table_name_prefix = "#{ENV['APP_NAME']}-#{ENV['ENVIRONMENT']}"
|
|
14
14
|
@logger = nil
|
|
15
15
|
@test_mode = ENV['BELT_PAY_MODE'] != 'live'
|
|
16
|
+
@customer_class = nil
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# The app model that includes Belt::Pay::Billable, as set in `customer_class`
|
|
20
|
+
# (the class, or its name as a String so it need not be loaded yet). The
|
|
21
|
+
# webhook finds customers through it to keep `pay_plan` in step with the
|
|
22
|
+
# subscription. Nil when not configured.
|
|
23
|
+
# @return [Class, nil]
|
|
24
|
+
def customer_model
|
|
25
|
+
return nil if customer_class.nil?
|
|
26
|
+
|
|
27
|
+
customer_class.is_a?(String) ? Object.const_get(customer_class) : customer_class
|
|
16
28
|
end
|
|
17
29
|
|
|
18
30
|
def transactions_table_name
|
|
@@ -31,9 +31,11 @@ module Belt
|
|
|
31
31
|
private
|
|
32
32
|
|
|
33
33
|
# Get the raw request body for signature verification.
|
|
34
|
-
# Stripe requires the exact raw body — not parsed JSON.
|
|
34
|
+
# Stripe requires the exact raw body — not parsed JSON. API Gateway sends
|
|
35
|
+
# it base64-encoded when isBase64Encoded is set.
|
|
35
36
|
def raw_body
|
|
36
|
-
event.dig('body') || ''
|
|
37
|
+
body = event.dig('body') || ''
|
|
38
|
+
event.dig('isBase64Encoded') ? body.unpack1('m') : body
|
|
37
39
|
end
|
|
38
40
|
|
|
39
41
|
def headers
|