pay 13.6.0 → 13.7.0

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 56a7e3f3ba69b0d4cd0c4b6b115d3e32910313151d0faf48beff1e21f24d77dc
4
- data.tar.gz: 30c33a24385e8b2dbec3bd36c7243f5ed3f8fa4afa174be96caab8cfa98d4983
3
+ metadata.gz: 0f547e6a76567091f1604e00459d7ecc342cc11c7270c0d5bb40faecababe3a7
4
+ data.tar.gz: 41ff3bf03a44ff777a066eaab056de57bae4072c9fe0c6d229ecfe37ce5fbea0
5
5
  SHA512:
6
- metadata.gz: 37e9fd91dda3293f99543a9301e545ff930921ab8807b67da02525cdddefb05af1812e658030b286eff80302e164ef141f58a44f30d8c869a3a10d31282c8b24
7
- data.tar.gz: 1a5a5badf6f4e3e54f155fede115d8457ce1e44ebd65925e966fdd1a2e910dfa7f7be39112c7bcda5644caa33eaddddc4d6c24166d52b514b6dd56bf4646998e
6
+ metadata.gz: e575a0057130d59fb6f09da9a099aa1dfb441409402c44848dd0324d6ad882fb8b1e10194f9930ff18e3430d8c4381cf25aa701843729a6bb6da5d318d9697ed
7
+ data.tar.gz: 7f98d1dd2d86173ee64ceecd5663f6f8febf5e5827841d70c398bb99a516e2c3ba109edb145fdf012f9910bd3defa4f5903f603b56b0d7f139a5bfc5dfd52108
@@ -90,11 +90,20 @@ module Pay
90
90
  if data["stripe_invoice"].present?
91
91
  description = options.delete(:description) || I18n.t("pay.refund")
92
92
  lines = [{type: :custom_line_item, description: description, quantity: 1, unit_amount: amount_to_refund}]
93
- credit_note!(**options.merge(refund_amount: amount_to_refund, lines: lines))
93
+ credit_note = credit_note!(
94
+ **options.with_defaults(lines: lines),
95
+ refund_amount: amount_to_refund,
96
+ expand: ["refunds.refund.charge"]
97
+ )
98
+ refunded = credit_note.refunds.first.refund.charge.amount_refunded
94
99
  else
95
- stripe_client.v1.refunds.create(options.merge(charge: processor_id, amount: amount_to_refund), stripe_options)
100
+ refund = stripe_client.v1.refunds.create(
101
+ options.merge(charge: processor_id, amount: amount_to_refund, expand: ["charge"]),
102
+ stripe_options
103
+ )
104
+ refunded = refund.charge.amount_refunded
96
105
  end
97
- update!(amount_refunded: amount_refunded + amount_to_refund)
106
+ update!(amount_refunded: refunded)
98
107
  rescue ::Stripe::StripeError => e
99
108
  raise Pay::Stripe::Error, e
100
109
  end
@@ -134,7 +143,7 @@ module Pay
134
143
 
135
144
  def stripe_object
136
145
  sync! if object.nil?
137
- ::Stripe::Charge.construct_from(object)
146
+ Pay::Stripe.construct_from(::Stripe::Charge, object, customer: customer, stripe_account: stripe_account)
138
147
  end
139
148
 
140
149
  def sync!(**options)
@@ -24,14 +24,17 @@ module Pay
24
24
  end
25
25
 
26
26
  def api_record(expand: ["tax", "invoice_credit_balance"])
27
- with_lock do
28
- if processor_id?
29
- stripe_client.v1.customers.retrieve(processor_id, {expand: expand}, stripe_options)
30
- else
31
- stripe_client.v1.customers.create(api_record_attributes.merge(expand: expand), stripe_options).tap do |customer|
32
- update!(processor_id: customer.id, stripe_account: stripe_account)
27
+ if processor_id?
28
+ stripe_client.v1.customers.retrieve(processor_id, {expand: expand}, stripe_options)
29
+ else
30
+ created = with_lock do
31
+ unless processor_id?
32
+ stripe_client.v1.customers.create(api_record_attributes.merge(expand: expand), stripe_options).tap do |customer|
33
+ update!(processor_id: customer.id)
34
+ end
33
35
  end
34
36
  end
37
+ created || api_record(expand: expand)
35
38
  end
36
39
  rescue ::Stripe::StripeError => e
37
40
  raise Pay::Stripe::Error, e
@@ -66,7 +69,7 @@ module Pay
66
69
  opts[:customer] = stripe_customer_id
67
70
 
68
71
  # Create subscription on Stripe
69
- stripe_sub = stripe_client.v1.subscriptions.create(opts.merge(Pay::Stripe::Subscription.expand_options), stripe_options)
72
+ stripe_sub = stripe_client.v1.subscriptions.create(Pay::Stripe::Subscription.expand_options(opts), stripe_options)
70
73
 
71
74
  # Save Pay::Subscription
72
75
  subscription = Pay::Stripe::Subscription.sync(stripe_sub.id, object: stripe_sub, name: name, customer: self)
@@ -157,8 +160,11 @@ module Pay
157
160
  # Syncs a customer's subscriptions from Stripe to the database.
158
161
  # Note that by default canceled subscriptions are NOT returned by Stripe. In order to include them, use `sync_subscriptions(status: "all")`.
159
162
  def sync_subscriptions(**options)
160
- subscriptions = stripe_client.v1.subscriptions.list(options.with_defaults(customer: processor_id), stripe_options)
161
- subscriptions.map do |subscription|
163
+ options[:customer] ||= processor_id
164
+ return [] if options[:customer].blank?
165
+
166
+ subscriptions = stripe_client.v1.subscriptions.list(options.with_defaults(limit: 100), stripe_options)
167
+ subscriptions.auto_paging_each.map do |subscription|
162
168
  Pay::Stripe::Subscription.sync(subscription.id, stripe_account: stripe_account, customer: self)
163
169
  end
164
170
  rescue ::Stripe::StripeError => e
@@ -24,14 +24,13 @@ module Pay
24
24
  end
25
25
 
26
26
  # Syncs PaymentMethod objects from Stripe
27
- def self.sync(id, object: nil, stripe_account: nil, customer: nil, retries: 1)
27
+ def self.sync(id, object: nil, stripe_account: nil, customer: nil, default: nil, retries: 1)
28
28
  sync_with_retries(retries: retries) do
29
29
  payment_method = object || Pay::Stripe.client(customer: customer).v1.payment_methods.retrieve(id, {}, {stripe_account: stripe_account}.compact)
30
30
  return unless (pay_customer = find_pay_customer(payment_method.customer, customer: customer))
31
31
  stripe_account ||= pay_customer.stripe_account
32
32
 
33
- default_payment_method_id = pay_customer.api_record.invoice_settings&.default_payment_method
34
- default = (id == default_payment_method_id)
33
+ default = (id == pay_customer.api_record.invoice_settings&.default_payment_method) if default.nil?
35
34
 
36
35
  attributes = extract_attributes(payment_method).merge(default: default, stripe_account: stripe_account)
37
36
 
@@ -75,15 +75,11 @@ module Pay
75
75
 
76
76
  # Update or create the subscription
77
77
  pay_subscription = find_by(customer: pay_customer, processor_id: subscription.id)
78
- if pay_subscription
79
- # If pause behavior is changing to `void`, record the pause start date
80
- # Any other pause status (or no pause at all) should have nil for start
81
- if pay_subscription.pause_behavior != attributes[:pause_behavior]
82
- attributes[:pause_starts_at] = if attributes[:pause_behavior] == "void"
83
- Time.at(subscription.items.first.current_period_end)
84
- end
85
- end
78
+ if pay_subscription&.pause_behavior != attributes[:pause_behavior]
79
+ attributes[:pause_starts_at] = (Time.at(subscription.items.first.current_period_end) if attributes[:pause_behavior] == "void")
80
+ end
86
81
 
82
+ if pay_subscription
87
83
  pay_subscription.with_lock { pay_subscription.update!(attributes) }
88
84
  else
89
85
  # Allow setting the subscription name in metadata, otherwise use the default
@@ -114,19 +110,19 @@ module Pay
114
110
  raise Pay::Stripe::Error, e
115
111
  end
116
112
 
113
+ EXPAND = Pay.make_shareable([
114
+ "default_payment_method",
115
+ "discounts",
116
+ "latest_invoice.confirmation_secret",
117
+ "latest_invoice.payments",
118
+ "latest_invoice.total_discount_amounts.discount",
119
+ "pending_setup_intent",
120
+ "schedule"
121
+ ])
122
+
117
123
  # Common expand options for all requests that create, retrieve, or update a Stripe Subscription
118
- def self.expand_options
119
- {
120
- expand: [
121
- "default_payment_method",
122
- "discounts",
123
- "latest_invoice.confirmation_secret",
124
- "latest_invoice.payments",
125
- "latest_invoice.total_discount_amounts.discount",
126
- "pending_setup_intent",
127
- "schedule"
128
- ]
129
- }
124
+ def self.expand_options(params = {})
125
+ params.merge(expand: Array(params[:expand]) | EXPAND)
130
126
  end
131
127
 
132
128
  def stripe_object
@@ -139,7 +135,7 @@ module Pay
139
135
  end
140
136
 
141
137
  def api_record(id: processor_id, **options)
142
- @api_record ||= stripe_client.v1.subscriptions.retrieve(id, options.merge(expand_options), stripe_options)
138
+ @api_record ||= stripe_client.v1.subscriptions.retrieve(id, expand_options(options), stripe_options)
143
139
  rescue ::Stripe::StripeError => e
144
140
  raise Pay::Stripe::Error, e
145
141
  end
@@ -182,7 +178,7 @@ module Pay
182
178
  def cancel_now!(**options)
183
179
  return if canceled? && ends_at.past?
184
180
 
185
- @api_record = stripe_client.v1.subscriptions.cancel(processor_id, options.merge(expand_options), stripe_options)
181
+ @api_record = stripe_client.v1.subscriptions.cancel(processor_id, expand_options(options), stripe_options)
186
182
  update(
187
183
  trial_ends_at: (@api_record.trial_end ? Time.at(@api_record.trial_end) : nil),
188
184
  ends_at: Time.at(@api_record.ended_at),
@@ -252,8 +248,8 @@ module Pay
252
248
  # Unpauses a subscription
253
249
  #
254
250
  # https://docs.stripe.com/billing/subscriptions/pause-payment#unpausing
255
- def unpause
256
- @api_record = stripe_client.v1.subscriptions.update(processor_id, {pause_collection: ""}.merge(expand_options), stripe_options)
251
+ def unpause(**options)
252
+ @api_record = stripe_client.v1.subscriptions.update(processor_id, expand_options({pause_collection: ""}.merge(options)), stripe_options)
257
253
  update(
258
254
  pause_behavior: nil,
259
255
  pause_resumes_at: nil,
@@ -281,14 +277,14 @@ module Pay
281
277
  end
282
278
 
283
279
  if status_paused?
284
- @api_record = stripe_client.v1.subscriptions.resume(processor_id, options.merge(expand_options), stripe_options)
280
+ @api_record = stripe_client.v1.subscriptions.resume(processor_id, expand_options(options), stripe_options)
285
281
  elsif paused?
286
- unpause
282
+ unpause(**options, **(canceled? ? {cancel_at_period_end: false} : {}))
287
283
  else
288
- @api_record = stripe_client.v1.subscriptions.update(processor_id, {
284
+ @api_record = stripe_client.v1.subscriptions.update(processor_id, expand_options({
289
285
  trial_end: (on_trial? ? trial_ends_at.to_i : "now"),
290
286
  cancel_at_period_end: false
291
- }.merge(expand_options), stripe_options)
287
+ }.merge(options)), stripe_options)
292
288
  end
293
289
  update(ends_at: nil, status: @api_record.status)
294
290
 
@@ -318,18 +314,20 @@ module Pay
318
314
 
319
315
  @api_record = stripe_client.v1.subscriptions.update(
320
316
  processor_id,
321
- {
317
+ expand_options({
322
318
  cancel_at_period_end: false,
323
319
  items: [{id: subscription_items.first.id, plan: plan, quantity: quantity}],
324
320
  proration_behavior: proration_behavior,
325
321
  trial_end: (on_trial? ? trial_ends_at.to_i : "now")
326
- }.merge(expand_options).merge(options), stripe_options
322
+ }.merge(options)), stripe_options
327
323
  )
328
324
 
325
+ sync!(object: @api_record)
326
+
329
327
  # Validate that swap was successful and handle SCA if needed
330
328
  validate_latest_payment
331
329
 
332
- sync!(object: @api_record)
330
+ self
333
331
  rescue ::Stripe::StripeError => e
334
332
  raise Pay::Stripe::Error, e
335
333
  end
@@ -369,13 +367,12 @@ module Pay
369
367
  raise Pay::Stripe::Error, e
370
368
  end
371
369
 
372
- # Looks up open invoices for a subscription and attempts to pay them
373
- #
374
- # Invoices no longer expose a `payment_intent` directly, so the PaymentIntent is looked up through the invoice's payments
370
+ # Looks up open invoices for a subscription and attempts to pay them off-session
375
371
  def pay_open_invoices
376
- stripe_client.v1.invoices.list({subscription: processor_id, status: :open, expand: ["data.payments"]}, stripe_options).auto_paging_each do |invoice|
377
- payment_intent_id = invoice.payments.first&.payment&.payment_intent
378
- retry_failed_payment(payment_intent_id: payment_intent_id) if payment_intent_id
372
+ stripe_client.v1.invoices.list({subscription: processor_id, status: :open}, stripe_options).auto_paging_each do |invoice|
373
+ stripe_client.v1.invoices.pay(invoice.id, {off_session: true}, stripe_options)
374
+ rescue ::Stripe::CardError => e
375
+ Rails.logger.info "Retrying open invoice #{invoice.id} for #{processor_id} failed: #{e.message}"
379
376
  end
380
377
  rescue ::Stripe::StripeError => e
381
378
  raise Pay::Stripe::Error, e
@@ -416,8 +413,8 @@ module Pay
416
413
  {stripe_account: stripe_account}.compact
417
414
  end
418
415
 
419
- def expand_options
420
- self.class.expand_options
416
+ def expand_options(params = {})
417
+ self.class.expand_options(params)
421
418
  end
422
419
 
423
420
  def interval_changes?(plan)
@@ -115,8 +115,8 @@ module Pay
115
115
  end
116
116
 
117
117
  def swap_and_invoice(plan)
118
+ Pay.deprecator.warn "Pay::Subscription#swap_and_invoice is deprecated, use swap instead"
118
119
  swap(plan)
119
- customer.invoice!(subscription: processor_id)
120
120
  end
121
121
 
122
122
  private
@@ -6,7 +6,17 @@
6
6
  <title>Payment Confirmation - <%= Pay.business_name %></title>
7
7
  <%= csrf_meta_tags %>
8
8
 
9
- <link href="https://unpkg.com/tailwindcss@^2.2/dist/tailwind.min.css" rel="stylesheet">
9
+ <link href="https://unpkg.com/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet" integrity="sha384-HtMZLkYo+pR5/u7zCzXxMJP6QoNnQJt1qkHM0EaOPvGDIzaVZbmYr/TlvUZ/sKAg" crossorigin="anonymous">
10
+ <script type="importmap">
11
+ {
12
+ "imports": {
13
+ "@hotwired/stimulus": "https://unpkg.com/@hotwired/stimulus@3.2.2/dist/stimulus.js"
14
+ },
15
+ "integrity": {
16
+ "https://unpkg.com/@hotwired/stimulus@3.2.2/dist/stimulus.js": "sha384-Z9ISq680E84zQ7uFT7Pw8g/TlnoyCUECFycQz5aZs9IlrNFR56FhXoVi5U7bVi+l"
17
+ }
18
+ }
19
+ </script>
10
20
  <script src="https://js.stripe.com/v3"></script>
11
21
  </head>
12
22
  <body class="font-sans text-gray-600 bg-gray-100 leading-normal p-4 h-full">
@@ -6,8 +6,6 @@
6
6
  data-payment-intent-client-secret-value="<%= @payment.client_secret %>"
7
7
  data-payment-intent-status-value="<%= @payment.status %>"
8
8
  data-payment-intent-setup-intent-value="<%= @payment.setup_intent? %>"
9
- data-payment-intent-customer-value="<%= @payment.customer %>"
10
- data-payment-intent-name-missing-message-value="<%= t("pay.requires_action.name_missing") %>"
11
9
  data-payment-intent-confirmed-message-value="<%= t("requires_action.success", scope: scope) %>"
12
10
  class="h-screen md:flex md:justify-center md:items-center">
13
11
  <div class="w-full max-w-lg">
@@ -44,13 +42,7 @@
44
42
  <p class="mb-6"><%=t "requires_action.description", scope: scope %></p>
45
43
 
46
44
  <div data-payment-intent-target="cardFields" class="hidden">
47
- <!-- Name -->
48
- <label for="cardholder-name" class="inline-block text-sm text-gray-700 font-semibold mb-2"><%=t "pay.requires_action.full_name" %></label>
49
- <input data-payment-intent-target="name" id="cardholder-name" type="text" placeholder="Jane Doe" required autofocus class="mt-1 mb-6 block w-full px-3 py-2 rounded-md border border-gray-300 shadow-sm focus:outline-none focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50">
50
-
51
- <!-- Card -->
52
- <label for="card-element" class="inline-block text-sm text-gray-700 font-semibold mb-2"><%=t "pay.requires_action.card" %></label>
53
- <div data-payment-intent-target="card" id="card-element" class="mt-1 mb-6 block w-full px-3 py-4 rounded-md border border-gray-300 shadow-sm focus:outline-none focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"></div>
45
+ <div data-payment-intent-target="card" class="mt-1 mb-6 block w-full px-3 py-4 rounded-md border border-gray-300 shadow-sm focus:outline-none focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"></div>
54
46
  </div>
55
47
 
56
48
  <!-- Pay Button -->
@@ -70,19 +62,17 @@
70
62
  </div>
71
63
 
72
64
  <script type="module">
73
- import { Application, Controller } from 'https://unpkg.com/@hotwired/stimulus/dist/stimulus.js'
65
+ import { Application, Controller } from '@hotwired/stimulus'
74
66
  const application = Application.start()
75
67
 
76
68
  application.register('payment-intent', class extends Controller {
77
- static targets = ["error", "errorMessage", "success", "successMessage", "form", "button", "name", "card", "cardFields"]
69
+ static targets = ["error", "errorMessage", "success", "successMessage", "form", "button", "card", "cardFields"]
78
70
  static values = {
79
71
  publicKey: String,
80
72
  stripeAccount: String,
81
73
  clientSecret: String,
82
- customer: String,
83
74
  status: String,
84
75
  setupIntent: Boolean,
85
- nameMissingMessage: String,
86
76
  confirmedMessage: String,
87
77
  errorMessage: String,
88
78
  successMessage: String,
@@ -98,8 +88,7 @@
98
88
  connect() {
99
89
  if (this.hasCardTarget) {
100
90
  this.elements = this.stripe.elements({clientSecret: this.clientSecretValue})
101
- this.payment = this.elements.create('payment')
102
- this.payment.mount(this.cardTarget)
91
+ this.elements.create('payment').mount(this.cardTarget)
103
92
  }
104
93
  }
105
94
 
@@ -107,39 +96,37 @@
107
96
  switch(this.statusValue) {
108
97
  case "requires_action":
109
98
  this.processingValue = true
110
- this.confirm({clientSecret: this.clientSecretValue})
99
+ this.stripe.handleNextAction({clientSecret: this.clientSecretValue}).then(this.handleConfirmResult.bind(this))
111
100
  break
112
101
  case "requires_payment_method":
113
102
  this.cardFieldsTarget.classList.toggle("hidden", false)
114
103
  break
104
+ case "succeeded":
105
+ case "processing":
106
+ if (this.hasFormTarget) {
107
+ this.completeValue = true
108
+ this.successMessageValue = this.confirmedMessageValue
109
+ }
110
+ break
115
111
  }
116
112
  }
117
113
 
118
114
  confirmPayment() {
119
115
  this.processingValue = true
120
- this.confirm({elements: this.elements})
121
- }
122
-
123
- // SetupIntents (saving a payment method) and PaymentIntents confirm through different Stripe.js methods
124
- confirm(options) {
125
- const params = {...options, confirmParams: { return_url: document.location.href }}
116
+ const params = {elements: this.elements, confirmParams: {return_url: document.location.href}}
126
117
  const result = this.setupIntentValue ? this.stripe.confirmSetup(params) : this.stripe.confirmPayment(params)
127
118
  result.then(this.handleConfirmResult.bind(this))
128
119
  }
129
120
 
130
121
  handleConfirmResult(result) {
131
122
  this.processingValue = false
123
+ const intent = result.error ? (result.error.payment_intent || result.error.setup_intent) : (result.paymentIntent || result.setupIntent)
124
+ const lastError = intent && (intent.last_payment_error || intent.last_setup_error)
125
+ this.errorMessageValue = result.error?.message || lastError?.message || ""
132
126
 
133
- if (result.error) {
134
- if (result.error.code === 'parameter_invalid_empty' &&
135
- result.error.param === 'payment_method_data[billing_details][name]') {
136
- this.errorMessageValue = this.nameMissingMessageValue
137
- } else {
138
- this.errorMessageValue = result.error.message
139
- const intent = result.error.payment_intent || result.error.setup_intent
140
- if (intent) { this.statusValue = intent.status }
141
- }
142
- } else {
127
+ if (intent) {
128
+ this.statusValue = intent.status
129
+ } else if (!result.error) {
143
130
  this.completeValue = true
144
131
  this.successMessageValue = this.confirmedMessageValue
145
132
  }
@@ -36,7 +36,7 @@ en:
36
36
  subtotal: "Subtotal"
37
37
  discount: "Discount"
38
38
  tax: "Tax"
39
- total: "Total excluding tax"
39
+ total_excluding_tax: "Total excluding tax"
40
40
  total: "Total"
41
41
  unit_price: "Unit Price"
42
42
  percent_discount: "%{name} (%{percent}% off)"
data/lib/pay/env.rb CHANGED
@@ -37,9 +37,13 @@ module Pay
37
37
  def find_value_by_name(name)
38
38
  return @frozen_credentials.fetch(name) if @frozen_credentials
39
39
 
40
- ENV["#{credential_scope.upcase}_#{name.upcase}"] ||
41
- credentials&.dig(env, credential_scope, name) ||
40
+ value = ENV["#{credential_scope.upcase}_#{name.upcase}"]
41
+ return value unless value.nil?
42
+
43
+ [
44
+ credentials&.dig(env, credential_scope, name),
42
45
  credentials&.dig(credential_scope, name)
46
+ ].compact.first
43
47
  rescue ActiveSupport::MessageEncryptor::InvalidMessage
44
48
  Rails.logger.error <<~MESSAGE
45
49
  Rails was unable to decrypt credentials. Pay checks the Rails credentials to look for API keys for payment processors.
data/lib/pay/receipts.rb CHANGED
@@ -34,11 +34,15 @@ module Pay
34
34
  stripe_invoice = try(:stripe_invoice)
35
35
 
36
36
  if stripe_invoice
37
+ discounts_by_id = stripe_invoice.total_discount_amounts.index_by { |d| d.discount.try(:id) }
38
+
37
39
  stripe_invoice.lines.auto_paging_each do |line|
38
- items << [line.description, line.quantity, Pay::Currency.format(line.pricing.unit_amount_decimal, currency: line.currency), Pay::Currency.format(line.amount, currency: line.currency)]
40
+ unit_price = line.pricing&.unit_amount_decimal
41
+ items << [line.description, line.quantity, (Pay::Currency.format(unit_price, currency: line.currency) if unit_price), Pay::Currency.format(line.amount, currency: line.currency)]
39
42
 
40
43
  line.discounts.each do |discount_id|
41
- discount = stripe_invoice.total_discount_amounts.find { |d| d.discount.id == discount_id }
44
+ next unless (discount = discounts_by_id[discount_id])
45
+
42
46
  items << [discount_description(discount), nil, nil, Pay::Currency.format(-discount.amount, currency: currency)]
43
47
  end
44
48
  end
@@ -51,13 +55,14 @@ module Pay
51
55
 
52
56
  # Discounts on the invoice
53
57
  stripe_invoice&.discounts&.each do |discount_id|
54
- discount = stripe_invoice.total_discount_amounts.find { |d| d.discount.id == discount_id }
58
+ next unless (discount = discounts_by_id[discount_id])
59
+
55
60
  items << [nil, nil, discount_description(discount), Pay::Currency.format(-discount.amount, currency: currency)]
56
61
  end
57
62
 
58
63
  # Total excluding tax
59
64
  if stripe_invoice
60
- items << [nil, nil, I18n.t("pay.line_items.total"), Pay::Currency.format(stripe_invoice.total_excluding_tax, currency: currency)]
65
+ items << [nil, nil, I18n.t("pay.line_items.total_excluding_tax"), Pay::Currency.format(stripe_invoice.total_excluding_tax, currency: currency)]
61
66
  end
62
67
 
63
68
  # Tax rates
@@ -22,12 +22,24 @@ module Pay
22
22
  # and returns its Pay::Customer
23
23
  #
24
24
  # Sessions in payment or setup mode don't always create a Stripe customer (for example Payment Links with
25
- # customer_creation: if_required), so skip those rather than clearing an existing processor_id
25
+ # customer_creation: if_required), so skip those rather than clearing an existing processor_id.
26
+ # Also refuse to overwrite an existing different processor_id, since client_reference_id on Payment Links
27
+ # is client-supplied and replacing processor_id would orphan webhooks for the existing Stripe customer
28
+ # (returning nil here lets `call` fall back to `find_pay_customer`).
26
29
  def locate_owner(object, stripe_account: nil)
27
30
  return if object.client_reference_id.nil? || object.customer.nil?
28
31
 
29
32
  owner = Pay::Stripe.find_by_client_reference_id(object.client_reference_id)
30
- owner&.add_payment_processor(:stripe, processor_id: object.customer, stripe_account: stripe_account)
33
+ existing = owner&.pay_customers&.active&.find_by(processor: :stripe, stripe_account: stripe_account)
34
+
35
+ if existing&.processor_id.blank?
36
+ owner&.add_payment_processor(:stripe, processor_id: object.customer, stripe_account: stripe_account)
37
+ elsif existing.processor_id == object.customer
38
+ existing
39
+ else
40
+ Rails.logger.error "[Pay] Skipping client_reference_id #{object.client_reference_id}: already linked to #{existing.processor_id} (session has #{object.customer})"
41
+ nil
42
+ end
31
43
  end
32
44
  end
33
45
  end
@@ -25,7 +25,7 @@ module Pay
25
25
 
26
26
  # Sync default card
27
27
  if (payment_method_id = stripe_customer.invoice_settings.default_payment_method)
28
- Pay::Stripe::PaymentMethod.sync(payment_method_id, stripe_account: event.try(:account), customer: pay_customer)
28
+ Pay::Stripe::PaymentMethod.sync(payment_method_id, stripe_account: event.try(:account), customer: pay_customer, default: true)
29
29
  retry_open_invoices(pay_customer) if default_payment_method_changed?(event)
30
30
  else
31
31
  # No default payment method set
@@ -36,7 +36,7 @@ module Pay
36
36
  private
37
37
 
38
38
  def default_payment_method_changed?(event)
39
- event.data.try(:previous_attributes)&.to_hash&.dig(:invoice_settings)&.key?(:default_payment_method)
39
+ event.data.previous_attributes.to_hash[:invoice_settings]&.key?(:default_payment_method)
40
40
  end
41
41
 
42
42
  # Retry past due invoices as soon as a new default payment method is set,
@@ -28,8 +28,6 @@ module Pay
28
28
  if latest_invoice_id.to_s == invoice.id.to_s
29
29
  Pay::Stripe::Subscription.sync(subscription_id, stripe_account: event.try(:account), customer: subscription.customer)
30
30
  end
31
- rescue ::Stripe::StripeError => e
32
- Rails.logger.error "Stripe Webhook Error (InvoiceUpdated): #{e.message}"
33
31
  end
34
32
  end
35
33
  end
data/lib/pay/stripe.rb CHANGED
@@ -144,8 +144,7 @@ module Pay
144
144
  end
145
145
 
146
146
  def self.webhook_receive_test_events
147
- value = super
148
- value.blank? || ActiveModel::Type::Boolean.new.cast(value)
147
+ ActiveModel::Type::Boolean.new.cast(super) != false
149
148
  end
150
149
 
151
150
  def self.configure_webhooks
@@ -233,23 +232,33 @@ module Pay
233
232
  end
234
233
 
235
234
  # Subscriptions aren't always immediately associated, so we want to retry by default
236
- def self.sync_checkout_session(session_id, stripe_account: nil, try: 0, retries: 5)
237
- checkout_session = Pay::Stripe.client.v1.checkout.sessions.retrieve(session_id, {expand: ["payment_intent.latest_charge"]}, {stripe_account: stripe_account}.compact)
235
+ def self.sync_checkout_session(session_id, stripe_account: nil, customer: nil, try: 0, retries: 5)
236
+ checkout_session ||= Pay::Stripe.client(customer: customer).v1.checkout.sessions.retrieve(session_id, {expand: ["payment_intent.latest_charge"]}, {stripe_account: stripe_account}.compact)
237
+ pay_customer ||= customer || find_pay_customer(checkout_session.customer)
238
+
238
239
  case checkout_session.mode
239
240
  when "payment"
240
241
  if (id = checkout_session.payment_intent.try(:latest_charge)&.id)
241
- Pay::Stripe::Charge.sync(id, stripe_account: stripe_account, retries: 5)
242
+ Pay::Stripe::Charge.sync(id, stripe_account: stripe_account, customer: pay_customer, retries: 5)
242
243
  end
243
244
  when "subscription"
244
- Pay::Stripe::Subscription.sync(checkout_session.subscription, stripe_account: stripe_account)
245
+ if (id = checkout_session.subscription)
246
+ Pay::Stripe::Subscription.sync(id, stripe_account: stripe_account, customer: pay_customer)
247
+ end
248
+ when "setup"
249
+ if (id = checkout_session.setup_intent)
250
+ Pay::Stripe::PaymentMethod.sync_setup_intent(id, stripe_account: stripe_account, customer: pay_customer)
251
+ end
245
252
  end
246
- rescue ::Stripe::InvalidRequestError => e
247
- if try > retries
248
- raise Pay::Stripe::Error, e
249
- else
250
- try += 1
253
+ rescue ::Stripe::StripeError, Pay::Stripe::Error => e
254
+ try += 1
255
+ if [e, e.cause].any?(::Stripe::InvalidRequestError) && try <= retries
251
256
  sleep 0.15 * try
252
257
  retry
258
+ elsif e.is_a?(Pay::Stripe::Error)
259
+ raise
260
+ else
261
+ raise Pay::Stripe::Error, e
253
262
  end
254
263
  end
255
264
  end
data/lib/pay/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Pay
4
- VERSION = "13.6.0"
4
+ VERSION = "13.7.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: pay
3
3
  version: !ruby/object:Gem::Version
4
- version: 13.6.0
4
+ version: 13.7.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jason Charnes