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.
@@ -9,17 +9,42 @@ module Belt
9
9
  # Handles API key management and provides the Stripe-specific implementations
10
10
  # that the generic Belt::Pay API delegates to.
11
11
  class Stripe
12
+ # A real webhook signing secret. Anything else is refused, above all the
13
+ # whsec_PLACEHOLDER older generated Terraform seeded the secret with: it is
14
+ # public, so anyone could sign an event with it.
15
+ WEBHOOK_SECRET_FORMAT = /\Awhsec_(?!PLACEHOLDER\z).+\z/
16
+
17
+ # The API key older generated Terraform seeded (sk_test_PLACEHOLDER).
18
+ API_KEY_PLACEHOLDER = /_PLACEHOLDER\z/i
19
+
12
20
  # Ensure the Stripe API key is set for the current request.
13
21
  # Reads from Secrets Manager via the configured secret name.
22
+ # @raise [ConfigurationError] when there is no key, or it is still the placeholder
14
23
  def ensure_api_key!
15
- ::Stripe.api_key ||= fetch_api_key
16
- raise ConfigurationError, 'Stripe API key not configured' unless ::Stripe.api_key
24
+ key = ::Stripe.api_key
25
+ fetched = blank?(key)
26
+ key = fetch_api_key if fetched
27
+ raise ConfigurationError, 'Stripe API key not configured' if blank?(key)
28
+
29
+ if API_KEY_PLACEHOLDER.match?(key)
30
+ raise ConfigurationError,
31
+ 'Stripe API key is still the placeholder; run `belt pay:setup <env>` to store a real key'
32
+ end
33
+
34
+ ::Stripe.api_key = key if fetched
17
35
  end
18
36
 
19
- # Get the webhook signing secret for signature verification.
20
- # @return [String]
37
+ # Get the webhook signing secret for signature verification. Only a usable
38
+ # secret is remembered, so a warm Lambda picks up the real one after
39
+ # `belt pay:setup` replaces a missing or placeholder value.
40
+ # @return [String, nil]
21
41
  def webhook_signing_secret
22
- @webhook_signing_secret ||= fetch_webhook_secret
42
+ return @webhook_signing_secret if @webhook_signing_secret
43
+
44
+ secret = fetch_webhook_secret
45
+ secret = secret.strip if secret.is_a?(String)
46
+ @webhook_signing_secret = secret if usable_webhook_secret?(secret)
47
+ secret
23
48
  end
24
49
 
25
50
  # Create a Stripe customer for the given user.
@@ -162,6 +187,14 @@ module Belt
162
187
  false
163
188
  end
164
189
 
190
+ # The subscription as Stripe holds it now.
191
+ # @param subscription_id [String] Stripe subscription ID
192
+ # @return [Stripe::Subscription]
193
+ def retrieve_subscription(subscription_id)
194
+ ensure_api_key!
195
+ ::Stripe::Subscription.retrieve(subscription_id)
196
+ end
197
+
165
198
  # Generate a billing portal session URL.
166
199
  # @param pay_customer_id [String] Stripe customer ID
167
200
  # @param return_url [String]
@@ -202,8 +235,28 @@ module Belt
202
235
  # @param payload [String] Raw request body
203
236
  # @param signature [String] Stripe-Signature header
204
237
  # @return [Stripe::Event]
238
+ # @raise [ConfigurationError] when the signing secret is missing, blank or the
239
+ # placeholder. Nothing is verified against a secret that isn't one.
205
240
  def verify_webhook(payload, signature)
206
- ::Stripe::Webhook.construct_event(payload, signature, webhook_signing_secret)
241
+ secret = webhook_signing_secret
242
+ unless usable_webhook_secret?(secret)
243
+ raise ConfigurationError,
244
+ 'Stripe webhook signing secret is missing or still the placeholder; ' \
245
+ 'run `belt pay:setup <env>` to store the endpoint\'s whsec_ secret'
246
+ end
247
+
248
+ ::Stripe::Webhook.construct_event(payload, signature, secret)
249
+ end
250
+
251
+ # The id of the Checkout Session a payment was made through, or nil when the
252
+ # payment didn't come from Checkout. Refunds and disputes name only the payment.
253
+ # Stripe errors are raised, so the webhook fails and Stripe sends the event again.
254
+ # @param payment_intent_id [String]
255
+ # @return [String, nil]
256
+ def checkout_session_id_for(payment_intent_id)
257
+ ensure_api_key!
258
+ sessions = ::Stripe::Checkout::Session.list({ payment_intent: payment_intent_id, limit: 1 })
259
+ sessions.data.first&.id
207
260
  end
208
261
 
209
262
  private
@@ -222,11 +275,7 @@ module Belt
222
275
  end
223
276
 
224
277
  def fetch_api_key
225
- secret_name = Belt::Pay.configuration.secret_name
226
- return nil unless secret_name
227
-
228
- require_secrets_helper
229
- SecretsHelper.get_secret(secret_name: secret_name, key: 'stripe_secret_key', required: true)
278
+ read_secret(Belt::Pay.configuration.secret_name, 'stripe_secret_key')
230
279
  rescue StandardError => e
231
280
  Belt::Pay.log(:error, 'Failed to fetch Stripe API key', error: e.message)
232
281
  nil
@@ -234,19 +283,33 @@ module Belt
234
283
 
235
284
  def fetch_webhook_secret
236
285
  secret_name = Belt::Pay.configuration.webhook_secret_name || Belt::Pay.configuration.secret_name
237
- return nil unless secret_name
238
-
239
- require_secrets_helper
240
- SecretsHelper.get_secret(secret_name: secret_name, key: 'stripe_webhook_secret', required: true)
286
+ read_secret(secret_name, 'stripe_webhook_secret')
241
287
  rescue StandardError => e
242
288
  Belt::Pay.log(:error, 'Failed to fetch Stripe webhook secret', error: e.message)
243
289
  nil
244
290
  end
245
291
 
246
- def require_secrets_helper
247
- require 'belt/secrets_helper' if defined?(Belt::SecretsHelper)
248
- rescue LoadError
249
- # SecretsHelper not available — key must be set via Stripe.api_key directly
292
+ # Read one key of the JSON secret `belt pay:setup` writes. An app-defined
293
+ # ::SecretsHelper is used when there is one; otherwise Secrets Manager is read
294
+ # directly. Nothing is cached here: callers keep a value once it is usable.
295
+ def read_secret(secret_name, key)
296
+ return nil if blank?(secret_name)
297
+ if defined?(::SecretsHelper)
298
+ return ::SecretsHelper.get_secret(secret_name: secret_name, key: key, required: true)
299
+ end
300
+
301
+ require 'aws-sdk-secretsmanager'
302
+ require 'json'
303
+ response = Aws::SecretsManager::Client.new.get_secret_value(secret_id: secret_name)
304
+ JSON.parse(response.secret_string)[key]
305
+ end
306
+
307
+ def usable_webhook_secret?(secret)
308
+ secret.is_a?(String) && WEBHOOK_SECRET_FORMAT.match?(secret)
309
+ end
310
+
311
+ def blank?(value)
312
+ value.nil? || value.to_s.strip.empty?
250
313
  end
251
314
  end
252
315
  end
@@ -4,6 +4,13 @@ module Belt
4
4
  module Pay
5
5
  # Manages subscriptions — create, cancel, check status.
6
6
  module Subscription
7
+ # Stripe subscription statuses that entitle the customer to the plan.
8
+ ACTIVE_STATUSES = %w[active trialing].freeze
9
+
10
+ # Statuses that mean the plan is no longer paid for. `past_due` is neither:
11
+ # Stripe is still retrying the payment, and ends it as one of these.
12
+ ENDED_STATUSES = %w[canceled unpaid incomplete_expired].freeze
13
+
7
14
  class << self
8
15
  # Create a subscription for a customer.
9
16
  # @param customer [Object] App model with Billable included
@@ -19,11 +26,13 @@ module Belt
19
26
  metadata: metadata.merge(app_customer_id: customer.id)
20
27
  )
21
28
 
22
- # Record the transaction
29
+ # Record the transaction. A subscription that still needs its first
30
+ # payment is pending; the webhook completes it once Stripe says active.
23
31
  Transaction.record_subscription(
24
32
  customer_id: customer.id,
25
33
  subscription_id: result[:subscription_id],
26
34
  amount_cents: 0, # Amount comes from invoice.paid webhook
35
+ status: ACTIVE_STATUSES.include?(result[:status].to_s) ? 'completed' : 'pending',
27
36
  metadata: metadata.merge(price_id: price_id)
28
37
  )
29
38
 
@@ -17,9 +17,10 @@ module <%= ns %>Controllers
17
17
  # result
18
18
  # end
19
19
 
20
- # Add custom event handlers by overriding the webhook handler:
20
+ # To act on an event, a hook is usually enough (no controller needed). It runs
21
+ # after the gem's bookkeeping, on every delivery, with the transaction it touched:
21
22
  #
22
- # Belt::Pay::WebhookHandler.define_method(:handle_custom_event) do |event_data|
23
+ # Belt::Pay.on('charge.refunded') do |event, transaction|
23
24
  # # Your custom logic here
24
25
  # end
25
26
  end
@@ -37,7 +37,8 @@ resource "aws_secretsmanager_secret" "stripe" {
37
37
  })
38
38
  }
39
39
 
40
- # Initial secret value — update manually or via CI after creation
40
+ # The secret starts empty: Belt Pay refuses to run with a missing key or signing
41
+ # secret, and nothing guessable is ever stored. `belt pay:setup <env>` fills it in.
41
42
  resource "aws_secretsmanager_secret_version" "stripe" {
42
43
  secret_id = aws_secretsmanager_secret.stripe.id
43
44
  secret_string = jsonencode({
@@ -9,15 +9,15 @@ variable "environment" {
9
9
  }
10
10
 
11
11
  variable "stripe_secret_key" {
12
- description = "Stripe secret API key (initial value — update via console/CI)"
12
+ description = "Stripe secret API key. Leave empty and store it with `belt pay:setup <env>`"
13
13
  type = string
14
- default = "sk_test_PLACEHOLDER"
14
+ default = ""
15
15
  sensitive = true
16
16
  }
17
17
 
18
18
  variable "stripe_webhook_secret" {
19
- description = "Stripe webhook signing secret (initial value — update via console/CI)"
19
+ description = "Stripe webhook signing secret. Leave empty and store it with `belt pay:setup <env>`"
20
20
  type = string
21
- default = "whsec_PLACEHOLDER"
21
+ default = ""
22
22
  sensitive = true
23
23
  }
@@ -16,7 +16,7 @@ module Belt
16
16
 
17
17
  attr_accessor :id, :customer_id, :provider, :provider_customer_id,
18
18
  :provider_session_id, :provider_subscription_id, :provider_payment_intent_id,
19
- :type, :status, :amount_cents, :currency, :description,
19
+ :type, :status, :amount_cents, :amount_refunded_cents, :currency, :description,
20
20
  :metadata, :created_at, :updated_at
21
21
 
22
22
  validates :customer_id, presence: true
@@ -30,33 +30,44 @@ module Belt
30
30
  # Transaction types
31
31
  TYPES = %w[checkout subscription subscription_renewal refund payment_method_update].freeze
32
32
 
33
- # Transaction statuses
34
- STATUSES = %w[pending completed failed refunded canceled].freeze
33
+ # Transaction statuses. Only `completed` means the money is in: `pending` has
34
+ # not been paid (yet), `refunded` and `disputed` mean it went back or may.
35
+ STATUSES = %w[pending completed failed refunded disputed canceled].freeze
35
36
 
36
37
  class << self
37
- # Record a checkout completion
38
- def record_checkout(customer_id:, session_id:, amount_cents:, currency: 'usd', metadata: {})
39
- create!(
38
+ # Record a checkout seen first by the webhook (no pending row). The row's id
39
+ # is the session id, so a second delivery of the event cannot add another.
40
+ # @return [Transaction, nil] nil when the session is already recorded
41
+ def record_checkout(customer_id:, session_id:, amount_cents:, currency: 'usd', status: 'completed',
42
+ payment_intent_id: nil, metadata: {})
43
+ create_once!(
44
+ id: session_id,
40
45
  customer_id: customer_id,
41
46
  provider: Belt::Pay.configuration.provider.to_s,
42
47
  provider_session_id: session_id,
48
+ provider_payment_intent_id: payment_intent_id,
43
49
  type: 'checkout',
44
- status: 'completed',
50
+ status: status,
45
51
  amount_cents: amount_cents,
46
52
  currency: currency,
47
- description: 'Checkout session completed',
53
+ description: status == 'completed' ? 'Checkout session completed' : 'Checkout session awaiting payment',
48
54
  metadata: metadata
49
55
  )
50
56
  end
51
57
 
52
- # Record a subscription creation
53
- def record_subscription(customer_id:, subscription_id:, amount_cents:, currency: 'usd', metadata: {})
54
- create!(
58
+ # Record a subscription creation. `completed` only once the subscription is
59
+ # active; one that still needs its first payment is `pending`. The row's id is
60
+ # the subscription id, so the webhook can find it.
61
+ # @return [Transaction, nil] nil when the subscription is already recorded
62
+ def record_subscription(customer_id:, subscription_id:, amount_cents:, currency: 'usd', status: 'completed',
63
+ metadata: {})
64
+ create_once!(
65
+ id: subscription_id,
55
66
  customer_id: customer_id,
56
67
  provider: Belt::Pay.configuration.provider.to_s,
57
68
  provider_subscription_id: subscription_id,
58
69
  type: 'subscription',
59
- status: 'completed',
70
+ status: status,
60
71
  amount_cents: amount_cents,
61
72
  currency: currency,
62
73
  description: 'Subscription created',
@@ -64,9 +75,12 @@ module Belt
64
75
  )
65
76
  end
66
77
 
67
- # Record a subscription renewal (invoice paid)
68
- def record_renewal(customer_id:, subscription_id:, amount_cents:, currency: 'usd', metadata: {})
69
- create!(
78
+ # Record a subscription renewal (invoice paid). Pass the invoice id as `id`
79
+ # so a second delivery of the same invoice cannot add another row.
80
+ # @return [Transaction, nil] nil when the invoice is already recorded
81
+ def record_renewal(customer_id:, subscription_id:, amount_cents:, currency: 'usd', id: nil, metadata: {})
82
+ create_once!(
83
+ id: id,
70
84
  customer_id: customer_id,
71
85
  provider: Belt::Pay.configuration.provider.to_s,
72
86
  provider_subscription_id: subscription_id,
@@ -97,6 +111,36 @@ module Belt
97
111
  def for_customer(customer_id)
98
112
  where(customer_id: customer_id, index: 'CustomerIndex')
99
113
  end
114
+
115
+ # The transaction of a Checkout Session: the pending row Checkout.create
116
+ # wrote, or one the webhook recorded under the session id.
117
+ # @return [Transaction, nil]
118
+ def for_session(session_id)
119
+ return nil if session_id.to_s.empty?
120
+
121
+ where(provider_session_id: session_id, index: 'ProviderSessionIndex').first || lookup(session_id)
122
+ end
123
+
124
+ # Find by primary key; nil when there is no such row.
125
+ # @return [Transaction, nil]
126
+ def lookup(id)
127
+ return nil if id.to_s.empty?
128
+
129
+ find(id)
130
+ rescue ActiveItem::RecordNotFound
131
+ nil
132
+ end
133
+
134
+ # Create a row unless one with the same id exists (a conditional put), which
135
+ # is what makes a redelivered webhook event harmless.
136
+ # @return [Transaction, nil] nil when a row with that id already exists
137
+ def create_once!(attributes)
138
+ create!(attributes.compact)
139
+ rescue ActiveItem::RecordInvalid => e
140
+ raise unless e.record && e.record.errors[:id].include?('already exists')
141
+
142
+ nil
143
+ end
100
144
  end
101
145
  end
102
146
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Belt
4
4
  module Pay
5
- VERSION = '0.0.6'
5
+ VERSION = '0.0.7'
6
6
  end
7
7
  end