pay 12.5.0 → 13.0.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: 618d06be256f138854df0025d396ec8a3eb19ba19d2bc1892ba5c7ac147f832c
4
- data.tar.gz: 4d8fec94d382dd451e3e5c0a2e82292c45559b320645a649edecf6cc358f24e3
3
+ metadata.gz: e070a8068ea85e41632ddea4d3934d471ae2be7c795c6532d965fe93aa809544
4
+ data.tar.gz: 9df7a081c6ade23f9b2f146d20ca991556195ffbddb1cc9396098132adb1f6bd
5
5
  SHA512:
6
- metadata.gz: 1010542511e8d58d0e077d7a1b0e006cc7c2935ded4d5e1b499724d9e1214b55e4cf730b07eb6c02a28fbb0772f024d6ce47d26d8806bca644f58cb19f15fe6e
7
- data.tar.gz: 48f66dca21dcf2120a5136d3b723418835097a4b45a2da50a03847227f4bb763178272d757fb698d68d374ec22dc7fee65fa9399b5ab2e07b1f5e744d651442c
6
+ metadata.gz: 43cec09eceb32a4f8c3f6bb8df73a220d83452ffc202e297377b615ea418555f8ef91c8da01583e2d29cbd51ed56a20287d1126a2c66e3ab196811a4935af29d
7
+ data.tar.gz: 50172d9ddc1ec9e97f0286fe7c9727ae2b33d91f76d32eee5b598f90c381ee237cae8489854e4e22ffabf97842197e3a71996a8c53b75d5dda46fe625b90f909
data/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  [![Build Status](https://github.com/pay-rails/pay/workflows/Tests/badge.svg)](https://github.com/pay-rails/pay/actions) [![Gem Version](https://badge.fury.io/rb/pay.svg)](https://badge.fury.io/rb/pay) <img src="docs/images/stripe_partner_badge.svg" height="26px">
6
6
 
7
- Pay is a payments engine for Ruby on Rails 6.0 and higher.
7
+ Pay is a payments engine for Ruby on Rails 7.1 and higher.
8
8
 
9
9
  > [!TIP]
10
10
  > Check out [Jumpstart](https://jumpstartrails.com) for Rails Starter Kit with Pay already integrated!
@@ -1,9 +1,11 @@
1
1
  module Pay
2
2
  class CustomerSyncJob < ApplicationJob
3
3
  def perform(pay_customer_id)
4
- Pay::Customer.find(pay_customer_id).update_api_record
5
- rescue ActiveRecord::RecordNotFound
6
- Rails.logger.info "Couldn't find a Pay::Customer with ID = #{pay_customer_id}"
4
+ if (pay_customer = Pay::Customer.active.find_by(id: pay_customer_id))
5
+ pay_customer.update_api_record
6
+ else
7
+ Rails.logger.info "Couldn't find an active Pay::Customer with ID = #{pay_customer_id}"
8
+ end
7
9
  end
8
10
  end
9
11
  end
@@ -10,17 +10,17 @@ module Pay
10
10
  store_accessor :data, :stripe_invoice
11
11
  store_accessor :data, :stripe_receipt_url
12
12
 
13
- def self.sync_payment_intent(id, stripe_account: nil)
14
- payment_intent = ::Stripe::PaymentIntent.retrieve({id: id}, {stripe_account: stripe_account}.compact)
15
- sync(payment_intent.latest_charge, stripe_account: stripe_account)
13
+ def self.sync_payment_intent(id, stripe_account: nil, customer: nil)
14
+ payment_intent = Pay::Stripe.client(customer: customer).v1.payment_intents.retrieve(id, {}, {stripe_account: stripe_account}.compact)
15
+ sync(payment_intent.latest_charge, stripe_account: stripe_account, customer: customer)
16
16
  rescue ::Stripe::StripeError => e
17
17
  raise Pay::Stripe::Error, e
18
18
  end
19
19
 
20
- def self.sync(charge_id, object: nil, stripe_account: nil, retries: 1)
20
+ def self.sync(charge_id, object: nil, stripe_account: nil, customer: nil, retries: 1)
21
21
  sync_with_retries(retries: retries) do
22
- charge = object || ::Stripe::Charge.retrieve({id: charge_id, expand: EXPAND}, {stripe_account: stripe_account}.compact)
23
- return unless (pay_customer = find_pay_customer(charge.customer))
22
+ charge = object || Pay::Stripe.client(customer: customer).v1.charges.retrieve(charge_id, {expand: EXPAND}, {stripe_account: stripe_account}.compact)
23
+ return unless (pay_customer = find_pay_customer(charge.customer, customer: customer))
24
24
  stripe_account ||= pay_customer.stripe_account
25
25
 
26
26
  payment_method = charge.payment_method_details.try(charge.payment_method_details.type)
@@ -44,9 +44,10 @@ module Pay
44
44
 
45
45
  # Associate charge with subscription if we can
46
46
  if charge.payment_intent.present?
47
- invoice_payments = ::Stripe::InvoicePayment.list({payment: {type: :payment_intent, payment_intent: charge.payment_intent}, status: :paid}, {stripe_account: stripe_account}.compact)
47
+ client = Pay::Stripe.client(customer: pay_customer)
48
+ invoice_payments = client.v1.invoice_payments.list({payment: {type: :payment_intent, payment_intent: charge.payment_intent}, status: :paid}, {stripe_account: stripe_account}.compact)
48
49
  if invoice_payments.any?
49
- invoice = ::Stripe::Invoice.retrieve({id: invoice_payments.first.invoice, expand: ["total_discount_amounts.discount.source.coupon"]}, {stripe_account: stripe_account}.compact)
50
+ invoice = client.v1.invoices.retrieve(invoice_payments.first.invoice, {expand: ["total_discount_amounts.discount.source.coupon"]}, {stripe_account: stripe_account}.compact)
50
51
  attrs[:stripe_invoice] = invoice.to_hash
51
52
  attrs[:subtotal] = invoice.subtotal
52
53
  attrs[:tax] = invoice.total - invoice.total_excluding_tax.to_i
@@ -69,7 +70,7 @@ module Pay
69
70
  end
70
71
 
71
72
  def api_record
72
- ::Stripe::Charge.retrieve({id: processor_id, expand: EXPAND}, stripe_options)
73
+ stripe_client.v1.charges.retrieve(processor_id, {expand: EXPAND}, stripe_options)
73
74
  rescue ::Stripe::StripeError => e
74
75
  raise Pay::Stripe::Error, e
75
76
  end
@@ -86,12 +87,12 @@ module Pay
86
87
  def refund!(amount_to_refund = nil, **options)
87
88
  amount_to_refund ||= amount
88
89
 
89
- if stripe_invoice.present?
90
+ if data["stripe_invoice"].present?
90
91
  description = options.delete(:description) || I18n.t("pay.refund")
91
92
  lines = [{type: :custom_line_item, description: description, quantity: 1, unit_amount: amount_to_refund}]
92
93
  credit_note!(**options.merge(refund_amount: amount_to_refund, lines: lines))
93
94
  else
94
- ::Stripe::Refund.create(options.merge(charge: processor_id, amount: amount_to_refund), stripe_options)
95
+ stripe_client.v1.refunds.create(options.merge(charge: processor_id, amount: amount_to_refund), stripe_options)
95
96
  end
96
97
  update!(amount_refunded: amount_refunded + amount_to_refund)
97
98
  rescue ::Stripe::StripeError => e
@@ -100,9 +101,10 @@ module Pay
100
101
 
101
102
  # Adds a credit note to a Stripe Invoice
102
103
  def credit_note!(**options)
103
- raise Pay::Stripe::Error, "no Stripe Invoice on Pay::Charge" if stripe_invoice.blank?
104
+ invoice_id = data.dig("stripe_invoice", "id")
105
+ raise Pay::Stripe::Error, "no Stripe Invoice on Pay::Charge" if invoice_id.blank?
104
106
 
105
- ::Stripe::CreditNote.create({invoice: stripe_invoice.id}.merge(options), stripe_options)
107
+ stripe_client.v1.credit_notes.create({invoice: invoice_id}.merge(options), stripe_options)
106
108
  rescue ::Stripe::StripeError => e
107
109
  raise Pay::Stripe::Error, e
108
110
  end
@@ -114,8 +116,8 @@ module Pay
114
116
  def capture(**options)
115
117
  raise Pay::Stripe::Error, "no payment_intent on charge" unless payment_intent.present?
116
118
  payment_intent_id = payment_intent.is_a?(::Stripe::PaymentIntent) ? payment_intent.id : payment_intent
117
- ::Stripe::PaymentIntent.capture(payment_intent_id, options, stripe_options)
118
- self.class.sync(processor_id, stripe_account: stripe_account)
119
+ stripe_client.v1.payment_intents.capture(payment_intent_id, options, stripe_options)
120
+ self.class.sync(processor_id, stripe_account: stripe_account, customer: customer)
119
121
  rescue ::Stripe::StripeError => e
120
122
  raise Pay::Stripe::Error, e
121
123
  end
@@ -126,7 +128,7 @@ module Pay
126
128
 
127
129
  def stripe_invoice
128
130
  if (value = data.dig("stripe_invoice"))
129
- ::Stripe::Invoice.construct_from(value)
131
+ Pay::Stripe.construct_from(::Stripe::Invoice, value, customer: customer, stripe_account: stripe_account)
130
132
  end
131
133
  end
132
134
 
@@ -136,12 +138,15 @@ module Pay
136
138
  end
137
139
 
138
140
  def sync!(**options)
139
- super(**options.with_defaults(stripe_account: stripe_account))
141
+ super(**options.with_defaults(stripe_account: stripe_account, customer: customer))
140
142
  end
141
143
 
142
144
  private
143
145
 
144
- # Options for Stripe requests
146
+ def stripe_client
147
+ Pay::Stripe.client(customer: customer)
148
+ end
149
+
145
150
  def stripe_options
146
151
  {stripe_account: stripe_account}.compact
147
152
  end
@@ -26,9 +26,9 @@ module Pay
26
26
  def api_record(expand: ["tax", "invoice_credit_balance"])
27
27
  with_lock do
28
28
  if processor_id?
29
- ::Stripe::Customer.retrieve({id: processor_id, expand: expand}, stripe_options)
29
+ stripe_client.v1.customers.retrieve(processor_id, {expand: expand}, stripe_options)
30
30
  else
31
- ::Stripe::Customer.create(api_record_attributes.merge(expand: expand), stripe_options).tap do |customer|
31
+ stripe_client.v1.customers.create(api_record_attributes.merge(expand: expand), stripe_options).tap do |customer|
32
32
  update!(processor_id: customer.id, stripe_account: stripe_account)
33
33
  end
34
34
  end
@@ -38,7 +38,7 @@ module Pay
38
38
  end
39
39
 
40
40
  def update_api_record(**attributes)
41
- ::Stripe::Customer.update(stripe_customer_id, api_record_attributes.merge(attributes), stripe_options)
41
+ stripe_client.v1.customers.update(stripe_customer_id, api_record_attributes.merge(attributes), stripe_options)
42
42
  rescue ::Stripe::StripeError => e
43
43
  raise Pay::Stripe::Error, e
44
44
  end
@@ -48,10 +48,10 @@ module Pay
48
48
  args = {confirm: true, payment_method: default_payment_method&.processor_id}.merge(options)
49
49
  payment_intent = create_payment_intent(amount, args)
50
50
 
51
- Pay::Payment.new(payment_intent).validate
51
+ Pay::Payment.new(payment_intent, stripe_account: stripe_account).validate
52
52
 
53
53
  charge = payment_intent.latest_charge
54
- Pay::Stripe::Charge.sync(charge.id, object: charge, stripe_account: stripe_account)
54
+ Pay::Stripe::Charge.sync(charge.id, object: charge, stripe_account: stripe_account, customer: self)
55
55
  rescue ::Stripe::StripeError => e
56
56
  raise Pay::Stripe::Error, e
57
57
  end
@@ -66,15 +66,15 @@ module Pay
66
66
  opts[:customer] = stripe_customer_id
67
67
 
68
68
  # Create subscription on Stripe
69
- stripe_sub = ::Stripe::Subscription.create(opts.merge(Pay::Stripe::Subscription.expand_options), stripe_options)
69
+ stripe_sub = stripe_client.v1.subscriptions.create(opts.merge(Pay::Stripe::Subscription.expand_options), stripe_options)
70
70
 
71
71
  # Save Pay::Subscription
72
- subscription = Pay::Stripe::Subscription.sync(stripe_sub.id, object: stripe_sub, name: name)
72
+ subscription = Pay::Stripe::Subscription.sync(stripe_sub.id, object: stripe_sub, name: name, customer: self)
73
73
 
74
74
  # No trial, payment method requires SCA
75
75
  if options[:payment_behavior].to_s != "default_incomplete" && subscription.incomplete?
76
76
  payment_intent_id = stripe_sub.latest_invoice.payments.first.payment.payment_intent
77
- Pay::Payment.from_id(payment_intent_id, stripe_account: stripe_account).validate
77
+ Pay::Payment.from_id(payment_intent_id, stripe_account: stripe_account, customer: self).validate
78
78
  end
79
79
 
80
80
  subscription
@@ -83,10 +83,10 @@ module Pay
83
83
  end
84
84
 
85
85
  def add_payment_method(payment_method_id, default: false)
86
- payment_method = ::Stripe::PaymentMethod.attach(payment_method_id, {customer: stripe_customer_id}, stripe_options)
86
+ payment_method = stripe_client.v1.payment_methods.attach(payment_method_id, {customer: stripe_customer_id}, stripe_options)
87
87
 
88
88
  if default
89
- ::Stripe::Customer.update(stripe_customer_id, {
89
+ stripe_client.v1.customers.update(stripe_customer_id, {
90
90
  invoice_settings: {
91
91
  default_payment_method: payment_method.id
92
92
  }
@@ -126,7 +126,7 @@ module Pay
126
126
  return_url: root_url
127
127
  }.merge(options)
128
128
 
129
- ::Stripe::PaymentIntent.create(args, stripe_options)
129
+ stripe_client.v1.payment_intents.create(args, stripe_options)
130
130
  rescue ::Stripe::StripeError => e
131
131
  raise Pay::Stripe::Error, e
132
132
  end
@@ -137,19 +137,19 @@ module Pay
137
137
  end
138
138
 
139
139
  def create_setup_intent(options = {})
140
- ::Stripe::SetupIntent.create({customer: stripe_customer_id, usage: :off_session}.merge(options), stripe_options)
140
+ stripe_client.v1.setup_intents.create({customer: stripe_customer_id, usage: :off_session}.merge(options), stripe_options)
141
141
  rescue ::Stripe::StripeError => e
142
142
  raise Pay::Stripe::Error, e
143
143
  end
144
144
 
145
145
  def invoice!(options = {})
146
- ::Stripe::Invoice.create(options.merge(customer: stripe_customer_id), stripe_options).pay
146
+ stripe_client.v1.invoices.create(options.merge(customer: stripe_customer_id), stripe_options).pay
147
147
  rescue ::Stripe::StripeError => e
148
148
  raise Pay::Stripe::Error, e
149
149
  end
150
150
 
151
151
  def preview_invoice(**options)
152
- ::Stripe::Invoice.create_preview(options.merge(customer: stripe_customer_id), stripe_options)
152
+ stripe_client.v1.invoices.create_preview(options.merge(customer: stripe_customer_id), stripe_options)
153
153
  rescue ::Stripe::StripeError => e
154
154
  raise Pay::Stripe::Error, e
155
155
  end
@@ -157,9 +157,9 @@ module Pay
157
157
  # Syncs a customer's subscriptions from Stripe to the database.
158
158
  # Note that by default canceled subscriptions are NOT returned by Stripe. In order to include them, use `sync_subscriptions(status: "all")`.
159
159
  def sync_subscriptions(**options)
160
- subscriptions = ::Stripe::Subscription.list(options.with_defaults(customer: processor_id), stripe_options)
160
+ subscriptions = stripe_client.v1.subscriptions.list(options.with_defaults(customer: processor_id), stripe_options)
161
161
  subscriptions.map do |subscription|
162
- Pay::Stripe::Subscription.sync(subscription.id, stripe_account: stripe_account)
162
+ Pay::Stripe::Subscription.sync(subscription.id, stripe_account: stripe_account, customer: self)
163
163
  end
164
164
  rescue ::Stripe::StripeError => e
165
165
  raise Pay::Stripe::Error, e
@@ -207,7 +207,7 @@ module Pay
207
207
  }
208
208
  end
209
209
 
210
- ::Stripe::Checkout::Session.create(args.merge(options), stripe_options)
210
+ stripe_client.v1.checkout.sessions.create(args.merge(options), stripe_options)
211
211
  rescue ::Stripe::StripeError => e
212
212
  raise Pay::Stripe::Error, e
213
213
  end
@@ -236,14 +236,14 @@ module Pay
236
236
  customer: stripe_customer_id,
237
237
  return_url: options.delete(:return_url) || root_url
238
238
  }
239
- ::Stripe::BillingPortal::Session.create(args.merge(options), stripe_options)
239
+ stripe_client.v1.billing_portal.sessions.create(args.merge(options), stripe_options)
240
240
  rescue ::Stripe::StripeError => e
241
241
  raise Pay::Stripe::Error, e
242
242
  end
243
243
 
244
244
  def customer_session(**options)
245
245
  args = {customer: stripe_customer_id}
246
- ::Stripe::CustomerSession.create(args.merge(options), stripe_options)
246
+ stripe_client.v1.customer_sessions.create(args.merge(options), stripe_options)
247
247
  rescue ::Stripe::StripeError => e
248
248
  raise Pay::Stripe::Error, e
249
249
  end
@@ -263,7 +263,7 @@ module Pay
263
263
  # create_meter_event(:api_request, value: 1)
264
264
  # create_meter_event(:api_request, token: 7)
265
265
  def create_meter_event(event_name, payload: {}, **options)
266
- ::Stripe::Billing::MeterEvent.create({
266
+ stripe_client.v1.billing.meter_events.create({
267
267
  event_name: event_name,
268
268
  payload: {stripe_customer_id: stripe_customer_id}.merge(payload)
269
269
  }.merge(options), stripe_options)
@@ -278,7 +278,10 @@ module Pay
278
278
  processor_id || api_record.id
279
279
  end
280
280
 
281
- # Options for Stripe requests
281
+ def stripe_client
282
+ Pay::Stripe.client(customer: self)
283
+ end
284
+
282
285
  def stripe_options
283
286
  {stripe_account: stripe_account}.compact
284
287
  end
@@ -2,7 +2,7 @@ module Pay
2
2
  module Stripe
3
3
  class Merchant < Pay::Merchant
4
4
  def create_account(**options)
5
- stripe_account = ::Stripe::Account.create(options)
5
+ stripe_account = Pay::Stripe.client.v1.accounts.create(options)
6
6
  update(processor_id: stripe_account.id)
7
7
  stripe_account
8
8
  rescue ::Stripe::StripeError => e
@@ -10,13 +10,13 @@ module Pay
10
10
  end
11
11
 
12
12
  def account
13
- ::Stripe::Account.retrieve(processor_id)
13
+ Pay::Stripe.client.v1.accounts.retrieve(processor_id)
14
14
  rescue ::Stripe::StripeError => e
15
15
  raise Pay::Stripe::Error, e
16
16
  end
17
17
 
18
18
  def account_link(refresh_url:, return_url:, type: "account_onboarding", **options)
19
- ::Stripe::AccountLink.create({
19
+ Pay::Stripe.client.v1.account_links.create({
20
20
  account: processor_id,
21
21
  refresh_url: refresh_url,
22
22
  return_url: return_url,
@@ -28,7 +28,7 @@ module Pay
28
28
 
29
29
  # A single-use login link for Express accounts to access their Stripe dashboard
30
30
  def login_link(**options)
31
- ::Stripe::Account.create_login_link(processor_id, options)
31
+ Pay::Stripe.client.v1.accounts.login_links.create(processor_id, options)
32
32
  rescue ::Stripe::StripeError => e
33
33
  raise Pay::Stripe::Error, e
34
34
  end
@@ -36,7 +36,7 @@ module Pay
36
36
  # Transfer money from the platform to this connected account
37
37
  # https://stripe.com/docs/connect/charges-transfers#transfer-availability
38
38
  def transfer(amount:, currency: "usd", **options)
39
- ::Stripe::Transfer.create({
39
+ Pay::Stripe.client.v1.transfers.create({
40
40
  amount: amount,
41
41
  currency: currency,
42
42
  destination: processor_id
@@ -4,30 +4,30 @@ module Pay
4
4
  extend Pay::Sync
5
5
 
6
6
  # Syncs a PaymentIntent's payment method to the database
7
- def self.sync_payment_intent(id, stripe_account: nil)
8
- payment_intent = ::Stripe::PaymentIntent.retrieve({id: id, expand: ["payment_method"]}, {stripe_account: stripe_account}.compact)
7
+ def self.sync_payment_intent(id, stripe_account: nil, customer: nil)
8
+ payment_intent = Pay::Stripe.client(customer: customer).v1.payment_intents.retrieve(id, {expand: ["payment_method"]}, {stripe_account: stripe_account}.compact)
9
9
  payment_method = payment_intent.payment_method
10
10
  return unless payment_method
11
- Pay::Stripe::PaymentMethod.sync(payment_method.id, object: payment_method, stripe_account: stripe_account)
11
+ Pay::Stripe::PaymentMethod.sync(payment_method.id, object: payment_method, stripe_account: stripe_account, customer: customer)
12
12
  rescue ::Stripe::StripeError => e
13
13
  raise Pay::Stripe::Error, e
14
14
  end
15
15
 
16
16
  # Syncs a SetupIntent's payment method to the database
17
- def self.sync_setup_intent(id, stripe_account: nil)
18
- setup_intent = ::Stripe::SetupIntent.retrieve({id: id, expand: ["payment_method"]}, {stripe_account: stripe_account}.compact)
17
+ def self.sync_setup_intent(id, stripe_account: nil, customer: nil)
18
+ setup_intent = Pay::Stripe.client(customer: customer).v1.setup_intents.retrieve(id, {expand: ["payment_method"]}, {stripe_account: stripe_account}.compact)
19
19
  payment_method = setup_intent.payment_method
20
20
  return unless payment_method
21
- Pay::Stripe::PaymentMethod.sync(payment_method.id, object: payment_method, stripe_account: stripe_account)
21
+ Pay::Stripe::PaymentMethod.sync(payment_method.id, object: payment_method, stripe_account: stripe_account, customer: customer)
22
22
  rescue ::Stripe::StripeError => e
23
23
  raise Pay::Stripe::Error, e
24
24
  end
25
25
 
26
26
  # Syncs PaymentMethod objects from Stripe
27
- def self.sync(id, object: nil, stripe_account: nil, retries: 1)
27
+ def self.sync(id, object: nil, stripe_account: nil, customer: nil, retries: 1)
28
28
  sync_with_retries(retries: retries) do
29
- payment_method = object || ::Stripe::PaymentMethod.retrieve(id, {stripe_account: stripe_account}.compact)
30
- return unless (pay_customer = find_pay_customer(payment_method.customer))
29
+ payment_method = object || Pay::Stripe.client(customer: customer).v1.payment_methods.retrieve(id, {}, {stripe_account: stripe_account}.compact)
30
+ return unless (pay_customer = find_pay_customer(payment_method.customer, customer: customer))
31
31
  stripe_account ||= pay_customer.stripe_account
32
32
 
33
33
  default_payment_method_id = pay_customer.api_record.invoice_settings&.default_payment_method
@@ -63,7 +63,7 @@ module Pay
63
63
  def make_default!
64
64
  return if default?
65
65
 
66
- ::Stripe::Customer.update(customer.processor_id, {invoice_settings: {default_payment_method: processor_id}}, stripe_options)
66
+ stripe_client.v1.customers.update(customer.processor_id, {invoice_settings: {default_payment_method: processor_id}}, stripe_options)
67
67
 
68
68
  customer.payment_methods.update_all(default: false)
69
69
  update!(default: true)
@@ -73,14 +73,17 @@ module Pay
73
73
 
74
74
  # Remove payment method
75
75
  def detach
76
- ::Stripe::PaymentMethod.detach(processor_id, {}, stripe_options)
76
+ stripe_client.v1.payment_methods.detach(processor_id, {}, stripe_options)
77
77
  rescue ::Stripe::StripeError => e
78
78
  raise Pay::Stripe::Error, e
79
79
  end
80
80
 
81
81
  private
82
82
 
83
- # Options for Stripe requests
83
+ def stripe_client
84
+ Pay::Stripe.client(customer: customer)
85
+ end
86
+
84
87
  def stripe_options
85
88
  {stripe_account: customer.stripe_account}.compact
86
89
  end
@@ -10,10 +10,10 @@ module Pay
10
10
  Pay::Stripe.sync_checkout_session(session_id, stripe_account: stripe_account)
11
11
  end
12
12
 
13
- def self.sync(subscription_id, object: nil, name: nil, stripe_account: nil, retries: 1)
13
+ def self.sync(subscription_id, object: nil, name: nil, stripe_account: nil, customer: nil, retries: 1)
14
14
  sync_with_retries(retries: retries) do
15
- subscription = object || ::Stripe::Subscription.retrieve({id: subscription_id}.merge(expand_options), {stripe_account: stripe_account}.compact)
16
- return unless (pay_customer = find_pay_customer(subscription.customer))
15
+ subscription = object || Pay::Stripe.client(customer: customer).v1.subscriptions.retrieve(subscription_id, expand_options, {stripe_account: stripe_account}.compact)
16
+ return unless (pay_customer = find_pay_customer(subscription.customer, customer: customer))
17
17
  stripe_account ||= pay_customer.stripe_account
18
18
 
19
19
  attributes = {
@@ -64,10 +64,10 @@ module Pay
64
64
  # Sync payment method if directly attached to subscription
65
65
  if subscription.default_payment_method
66
66
  if subscription.default_payment_method.is_a? String
67
- Pay::Stripe::PaymentMethod.sync(subscription.default_payment_method, stripe_account: stripe_account)
67
+ Pay::Stripe::PaymentMethod.sync(subscription.default_payment_method, stripe_account: stripe_account, customer: pay_customer)
68
68
  attributes[:payment_method_id] = subscription.default_payment_method
69
69
  else
70
- Pay::Stripe::PaymentMethod.sync(subscription.default_payment_method.id, object: subscription.default_payment_method, stripe_account: stripe_account)
70
+ Pay::Stripe::PaymentMethod.sync(subscription.default_payment_method.id, object: subscription.default_payment_method, stripe_account: stripe_account, customer: pay_customer)
71
71
  attributes[:payment_method_id] = subscription.default_payment_method.id
72
72
  end
73
73
  end
@@ -100,9 +100,9 @@ module Pay
100
100
 
101
101
  case invoice_payment.payment.type
102
102
  when "payment_intent"
103
- Pay::Stripe::Charge.sync_payment_intent(invoice_payment.payment.payment_intent, stripe_account: stripe_account)
103
+ Pay::Stripe::Charge.sync_payment_intent(invoice_payment.payment.payment_intent, stripe_account: stripe_account, customer: pay_customer)
104
104
  when "charge"
105
- Pay::Stripe::Charge.sync(invoice_payment.payment.charge, stripe_account: stripe_account)
105
+ Pay::Stripe::Charge.sync(invoice_payment.payment.charge, stripe_account: stripe_account, customer: pay_customer)
106
106
  end
107
107
  end
108
108
  end
@@ -130,15 +130,15 @@ module Pay
130
130
 
131
131
  def stripe_object
132
132
  sync! if object.nil?
133
- ::Stripe::Subscription.construct_from(object)
133
+ Pay::Stripe.construct_from(::Stripe::Subscription, object, customer: customer, stripe_account: stripe_account)
134
134
  end
135
135
 
136
136
  def sync!(**options)
137
- super(**options.with_defaults(stripe_account: stripe_account))
137
+ super(**options.with_defaults(stripe_account: stripe_account, customer: customer))
138
138
  end
139
139
 
140
- def api_record(**options)
141
- @api_record ||= ::Stripe::Subscription.retrieve(options.with_defaults(id: processor_id).merge(expand_options), {stripe_account: stripe_account}.compact)
140
+ def api_record(id: processor_id, **options)
141
+ @api_record ||= stripe_client.v1.subscriptions.retrieve(id, options.merge(expand_options), stripe_options)
142
142
  rescue ::Stripe::StripeError => e
143
143
  raise Pay::Stripe::Error, e
144
144
  end
@@ -151,7 +151,7 @@ module Pay
151
151
  # Sets the default_payment_method on a subscription
152
152
  # Pass an empty string to unset
153
153
  def update_payment_method(id)
154
- @api_record = ::Stripe::Subscription.update(processor_id, {default_payment_method: id}.merge(expand_options), stripe_options)
154
+ @api_record = stripe_client.v1.subscriptions.update(processor_id, {default_payment_method: id}.merge(expand_options), stripe_options)
155
155
  update(payment_method_id: @api_record.default_payment_method&.id)
156
156
  rescue ::Stripe::StripeError => e
157
157
  raise Pay::Stripe::Error, e
@@ -167,7 +167,7 @@ module Pay
167
167
  if past_due? && options.fetch(:past_due_cancel_now, true)
168
168
  cancel_now!
169
169
  else
170
- @api_record = ::Stripe::Subscription.update(processor_id, {cancel_at_period_end: true}.merge(expand_options), stripe_options)
170
+ @api_record = stripe_client.v1.subscriptions.update(processor_id, {cancel_at_period_end: true}.merge(expand_options), stripe_options)
171
171
  update(ends_at: Time.at(@api_record.cancel_at))
172
172
  end
173
173
  rescue ::Stripe::StripeError => e
@@ -181,7 +181,7 @@ module Pay
181
181
  def cancel_now!(**options)
182
182
  return if canceled? && ends_at.past?
183
183
 
184
- @api_record = ::Stripe::Subscription.cancel(processor_id, options.merge(expand_options), stripe_options)
184
+ @api_record = stripe_client.v1.subscriptions.cancel(processor_id, options.merge(expand_options), stripe_options)
185
185
  update(
186
186
  trial_ends_at: (@api_record.trial_end ? Time.at(@api_record.trial_end) : nil),
187
187
  ends_at: Time.at(@api_record.ended_at),
@@ -197,7 +197,7 @@ module Pay
197
197
  # (Stripe no longer accepts a top-level quantity on the subscription itself)
198
198
  def change_quantity(quantity, **options)
199
199
  subscription_item_id = options.delete(:subscription_item_id) || subscription_items.first.id
200
- ::Stripe::SubscriptionItem.update(subscription_item_id, options.merge(quantity: quantity), stripe_options)
200
+ stripe_client.v1.subscription_items.update(subscription_item_id, options.merge(quantity: quantity), stripe_options)
201
201
  @api_record = nil
202
202
  update(quantity: quantity)
203
203
  rescue ::Stripe::StripeError => e
@@ -237,7 +237,7 @@ module Pay
237
237
  # https://docs.stripe.com/billing/subscriptions/pause-payment
238
238
  def pause(**options)
239
239
  attributes = {pause_collection: options.reverse_merge(behavior: "void")}
240
- @api_record = ::Stripe::Subscription.update(processor_id, attributes.merge(expand_options), stripe_options)
240
+ @api_record = stripe_client.v1.subscriptions.update(processor_id, attributes.merge(expand_options), stripe_options)
241
241
  behavior = @api_record.pause_collection&.behavior
242
242
  update(
243
243
  pause_behavior: behavior,
@@ -252,7 +252,7 @@ module Pay
252
252
  #
253
253
  # https://docs.stripe.com/billing/subscriptions/pause-payment#unpausing
254
254
  def unpause
255
- @api_record = ::Stripe::Subscription.update(processor_id, {pause_collection: ""}.merge(expand_options), stripe_options)
255
+ @api_record = stripe_client.v1.subscriptions.update(processor_id, {pause_collection: ""}.merge(expand_options), stripe_options)
256
256
  update(
257
257
  pause_behavior: nil,
258
258
  pause_resumes_at: nil,
@@ -280,15 +280,14 @@ module Pay
280
280
  end
281
281
 
282
282
  if status_paused?
283
- @api_record = ::Stripe::Subscription.resume(processor_id, options.merge(expand_options), stripe_options)
283
+ @api_record = stripe_client.v1.subscriptions.resume(processor_id, options.merge(expand_options), stripe_options)
284
284
  elsif paused?
285
285
  unpause
286
286
  else
287
- @api_record = ::Stripe::Subscription.update(processor_id, {
287
+ @api_record = stripe_client.v1.subscriptions.update(processor_id, {
288
288
  trial_end: (on_trial? ? trial_ends_at.to_i : "now"),
289
289
  cancel_at_period_end: false
290
- }.merge(expand_options),
291
- stripe_options)
290
+ }.merge(expand_options), stripe_options)
292
291
  end
293
292
  update(ends_at: nil, status: @api_record.status)
294
293
 
@@ -310,15 +309,14 @@ module Pay
310
309
  options[:billing_cycle_anchor] = {type: options[:billing_cycle_anchor].to_s}
311
310
  end
312
311
 
313
- @api_record = ::Stripe::Subscription.update(
312
+ @api_record = stripe_client.v1.subscriptions.update(
314
313
  processor_id,
315
314
  {
316
315
  cancel_at_period_end: false,
317
316
  items: [{id: subscription_items.first.id, plan: plan, quantity: quantity}],
318
317
  proration_behavior: proration_behavior,
319
318
  trial_end: (on_trial? ? trial_ends_at.to_i : "now")
320
- }.merge(expand_options).merge(options),
321
- stripe_options
319
+ }.merge(expand_options).merge(options), stripe_options
322
320
  )
323
321
 
324
322
  # Validate that swap was successful and handle SCA if needed
@@ -341,7 +339,7 @@ module Pay
341
339
  end
342
340
 
343
341
  def preview_invoice(**options)
344
- ::Stripe::Invoice.create_preview(options.merge(subscription: processor_id), stripe_options)
342
+ stripe_client.v1.invoices.create_preview(options.merge(subscription: processor_id), stripe_options)
345
343
  rescue ::Stripe::StripeError => e
346
344
  raise Pay::Stripe::Error, e
347
345
  end
@@ -349,17 +347,17 @@ module Pay
349
347
  # Retries the latest invoice for a Past Due subscription and attempts to pay it
350
348
  def retry_failed_payment(payment_intent_id: nil)
351
349
  payment_intent_id ||= api_record.latest_invoice.payments.first.payment.payment_intent
352
- payment_intent = ::Stripe::PaymentIntent.retrieve({id: payment_intent_id}, stripe_options)
350
+ payment_intent = stripe_client.v1.payment_intents.retrieve(payment_intent_id, {}, stripe_options)
353
351
 
354
352
  payment_intent = if payment_intent.status == "requires_payment_method"
355
353
  payment_method = customer.default_payment_method
356
354
  raise Pay::Stripe::Error, "no default payment method to retry the payment with" if payment_method.nil?
357
355
 
358
- ::Stripe::PaymentIntent.confirm(payment_intent_id, {payment_method: payment_method.processor_id}, stripe_options)
356
+ stripe_client.v1.payment_intents.confirm(payment_intent_id, {payment_method: payment_method.processor_id}, stripe_options)
359
357
  else
360
- ::Stripe::PaymentIntent.confirm(payment_intent_id, {}, stripe_options)
358
+ stripe_client.v1.payment_intents.confirm(payment_intent_id, {}, stripe_options)
361
359
  end
362
- Pay::Payment.new(payment_intent).validate
360
+ Pay::Payment.new(payment_intent, stripe_account: stripe_account).validate
363
361
  rescue ::Stripe::StripeError => e
364
362
  raise Pay::Stripe::Error, e
365
363
  end
@@ -368,7 +366,7 @@ module Pay
368
366
  #
369
367
  # Invoices no longer expose a `payment_intent` directly, so the PaymentIntent is looked up through the invoice's payments
370
368
  def pay_open_invoices
371
- ::Stripe::Invoice.list({subscription: processor_id, status: :open, expand: ["data.payments"]}, stripe_options).auto_paging_each do |invoice|
369
+ stripe_client.v1.invoices.list({subscription: processor_id, status: :open, expand: ["data.payments"]}, stripe_options).auto_paging_each do |invoice|
372
370
  payment_intent_id = invoice.payments.first&.payment&.payment_intent
373
371
  retry_failed_payment(payment_intent_id: payment_intent_id) if payment_intent_id
374
372
  end
@@ -379,7 +377,7 @@ module Pay
379
377
  # Returns the Stripe::PaymentIntent for the latest invoice, if there is one
380
378
  def latest_payment
381
379
  payment_intent_id = api_record.latest_invoice&.payments&.first&.payment&.payment_intent
382
- ::Stripe::PaymentIntent.retrieve({id: payment_intent_id}, stripe_options) if payment_intent_id
380
+ stripe_client.v1.payment_intents.retrieve(payment_intent_id, {}, stripe_options) if payment_intent_id
383
381
  rescue ::Stripe::StripeError => e
384
382
  raise Pay::Stripe::Error, e
385
383
  end
@@ -403,7 +401,10 @@ module Pay
403
401
  end
404
402
  end
405
403
 
406
- # Options for Stripe requests
404
+ def stripe_client
405
+ Pay::Stripe.client(customer: customer)
406
+ end
407
+
407
408
  def stripe_options
408
409
  {stripe_account: stripe_account}.compact
409
410
  end
@@ -24,7 +24,7 @@ module Pay
24
24
  when "lemon_squeezy"
25
25
  Pay::LemonSqueezy.construct_from_webhook_event(event)
26
26
  when "stripe"
27
- ::Stripe::Event.construct_from(event)
27
+ Pay::Stripe.construct_from_webhook_event(event)
28
28
  else
29
29
  event
30
30
  end
data/lib/pay/adapter.rb CHANGED
@@ -3,11 +3,7 @@ module Pay
3
3
  extend ActiveSupport::Concern
4
4
 
5
5
  def self.current_adapter
6
- if ActiveRecord::Base.respond_to?(:connection_db_config)
7
- ActiveRecord::Base.connection_db_config.adapter
8
- else
9
- ActiveRecord::Base.connection_config[:adapter]
10
- end
6
+ ActiveRecord::Base.connection_db_config.adapter
11
7
  end
12
8
 
13
9
  def self.json_column_type
@@ -8,7 +8,7 @@ module Pay
8
8
  extend ActiveSupport::Concern
9
9
 
10
10
  included do
11
- after_update_commit :enqeue_customer_sync_job, if: :pay_should_sync_customer?
11
+ after_update_commit :enqueue_customer_sync_job, if: :pay_should_sync_customer?
12
12
  end
13
13
 
14
14
  def pay_should_sync_customer?
@@ -17,13 +17,8 @@ module Pay
17
17
 
18
18
  private
19
19
 
20
- def enqeue_customer_sync_job
21
- if pay_should_sync_customer?
22
- # Queue job to update each payment processor for this customer
23
- pay_customers.pluck(:id).each do |pay_customer_id|
24
- CustomerSyncJob.perform_later(pay_customer_id)
25
- end
26
- end
20
+ def enqueue_customer_sync_job
21
+ ActiveJob.perform_all_later(pay_customers.active.ids.map { |id| CustomerSyncJob.new(id) })
27
22
  end
28
23
  end
29
24
  end
data/lib/pay/engine.rb CHANGED
@@ -20,7 +20,7 @@ module Pay
20
20
  end
21
21
 
22
22
  initializer "pay.deprecator" do |app|
23
- app.deprecators[:pay] = Pay.deprecator if app.respond_to?(:deprecators)
23
+ app.deprecators[:pay] = Pay.deprecator
24
24
  end
25
25
 
26
26
  RECEIPTS_VERSION = [">= 2", "< 4"].freeze
data/lib/pay/payment.rb CHANGED
@@ -6,9 +6,10 @@ module Pay
6
6
 
7
7
  delegate :id, :amount, :client_secret, :currency, :customer, :status, :confirm, to: :intent
8
8
 
9
- def self.from_id(id, stripe_account: nil)
10
- options = {stripe_account: stripe_account}.compact
11
- intent = id.start_with?("seti_") ? ::Stripe::SetupIntent.retrieve(id, options) : ::Stripe::PaymentIntent.retrieve(id, options)
9
+ def self.from_id(id, stripe_account: nil, customer: nil)
10
+ v1 = Pay::Stripe.client(customer: customer).v1
11
+ service = id.start_with?("seti_") ? v1.setup_intents : v1.payment_intents
12
+ intent = service.retrieve(id, {}, {stripe_account: stripe_account}.compact)
12
13
  new(intent, stripe_account: stripe_account)
13
14
  rescue ::Stripe::StripeError => e
14
15
  raise Pay::Stripe::Error, e
data/lib/pay/receipts.rb CHANGED
@@ -30,7 +30,10 @@ module Pay
30
30
  ]
31
31
  ]
32
32
 
33
- if try(:stripe_invoice)
33
+ # Rebuilt once, since each call rebuilds the invoice and runs Pay::Stripe.client_options
34
+ stripe_invoice = try(:stripe_invoice)
35
+
36
+ if stripe_invoice
34
37
  stripe_invoice.lines.auto_paging_each do |line|
35
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)]
36
39
 
@@ -44,21 +47,21 @@ module Pay
44
47
  end
45
48
 
46
49
  # If no subtotal, we will display the total
47
- items << [nil, nil, I18n.t("pay.line_items.subtotal"), Pay::Currency.format(try(:stripe_invoice)&.subtotal || amount, currency: currency)]
50
+ items << [nil, nil, I18n.t("pay.line_items.subtotal"), Pay::Currency.format(stripe_invoice&.subtotal || amount, currency: currency)]
48
51
 
49
52
  # Discounts on the invoice
50
- try(:stripe_invoice)&.discounts&.each do |discount_id|
53
+ stripe_invoice&.discounts&.each do |discount_id|
51
54
  discount = stripe_invoice.total_discount_amounts.find { |d| d.discount.id == discount_id }
52
55
  items << [nil, nil, discount_description(discount), Pay::Currency.format(-discount.amount, currency: currency)]
53
56
  end
54
57
 
55
58
  # Total excluding tax
56
- if try(:stripe_invoice)
59
+ if stripe_invoice
57
60
  items << [nil, nil, I18n.t("pay.line_items.total"), Pay::Currency.format(stripe_invoice.total_excluding_tax, currency: currency)]
58
61
  end
59
62
 
60
63
  # Tax rates
61
- try(:stripe_invoice)&.total_taxes&.each do |tax|
64
+ stripe_invoice&.total_taxes&.each do |tax|
62
65
  next if tax.amount.zero?
63
66
  # tax_rate = ::Stripe::TaxRate.retrieve(tax.tax_rate_details.tax_rate)
64
67
  items << [nil, nil, I18n.t("pay.line_items.tax"), Pay::Currency.format(tax.amount, currency: currency)]
@@ -3,7 +3,7 @@ module Pay
3
3
  module Webhooks
4
4
  class ChargeRefunded
5
5
  def call(event)
6
- pay_charge = Pay::Stripe::Charge.sync(event.data.object.id, stripe_account: event.try(:account))
6
+ pay_charge = Pay::Stripe::Charge.sync(event.data.object.id, stripe_account: event.try(:account), customer: Pay::Stripe.find_pay_customer(event.data.object.customer))
7
7
 
8
8
  if pay_charge && Pay.send_email?(:refund, pay_charge)
9
9
  Pay.mailer.with(pay_customer: pay_charge.customer, pay_charge: pay_charge).refund.deliver_later
@@ -3,7 +3,7 @@ module Pay
3
3
  module Webhooks
4
4
  class ChargeSucceeded
5
5
  def call(event)
6
- pay_charge = Pay::Stripe::Charge.sync(event.data.object.id, stripe_account: event.try(:account))
6
+ pay_charge = Pay::Stripe::Charge.sync(event.data.object.id, stripe_account: event.try(:account), customer: Pay::Stripe.find_pay_customer(event.data.object.customer))
7
7
 
8
8
  if pay_charge && Pay.send_email?(:receipt, pay_charge)
9
9
  Pay.mailer.with(pay_customer: pay_charge.customer, pay_charge: pay_charge).receipt.deliver_later
@@ -3,7 +3,7 @@ module Pay
3
3
  module Webhooks
4
4
  class ChargeUpdated
5
5
  def call(event)
6
- Pay::Stripe::Charge.sync(event.data.object.id, stripe_account: event.try(:account))
6
+ Pay::Stripe::Charge.sync(event.data.object.id, stripe_account: event.try(:account), customer: Pay::Stripe.find_pay_customer(event.data.object.customer))
7
7
  end
8
8
  end
9
9
  end
@@ -3,22 +3,23 @@ module Pay
3
3
  module Webhooks
4
4
  class CheckoutSessionCompleted
5
5
  def call(event)
6
- locate_owner(event.data.object, stripe_account: event.try(:account))
6
+ customer = locate_owner(event.data.object, stripe_account: event.try(:account)) || Pay::Stripe.find_pay_customer(event.data.object.customer)
7
7
 
8
8
  # By the time CheckoutSessionCompleted is fired, we probably missed the original events
9
9
  # Instead, we can sync the payment intent or subscription during this event to ensure they're in the database
10
10
 
11
11
  if (payment_intent_id = event.data.object.payment_intent)
12
- payment_intent = ::Stripe::PaymentIntent.retrieve({id: payment_intent_id}, {stripe_account: event.try(:account)}.compact)
13
- Pay::Stripe::Charge.sync(payment_intent.latest_charge, stripe_account: event.try(:account)) if payment_intent.latest_charge
12
+ payment_intent = Pay::Stripe.client(customer: customer).v1.payment_intents.retrieve(payment_intent_id, {}, {stripe_account: event.try(:account)}.compact)
13
+ Pay::Stripe::Charge.sync(payment_intent.latest_charge, stripe_account: event.try(:account), customer: customer) if payment_intent.latest_charge
14
14
  end
15
15
 
16
16
  if (subscription_id = event.data.object.subscription)
17
- Pay::Stripe::Subscription.sync(subscription_id, stripe_account: event.try(:account))
17
+ Pay::Stripe::Subscription.sync(subscription_id, stripe_account: event.try(:account), customer: customer)
18
18
  end
19
19
  end
20
20
 
21
21
  # Associates the Stripe customer from the session with the record referenced by client_reference_id
22
+ # and returns its Pay::Customer
22
23
  #
23
24
  # Sessions in payment or setup mode don't always create a Stripe customer (for example Payment Links with
24
25
  # customer_creation: if_required), so skip those rather than clearing an existing processor_id
@@ -4,7 +4,7 @@ module Pay
4
4
  class CustomerDeleted
5
5
  def call(event)
6
6
  object = event.data.object
7
- pay_customer = Pay::Customer.find_by(processor: :stripe, processor_id: object.id)
7
+ pay_customer = Pay::Stripe.find_pay_customer(object.id)
8
8
 
9
9
  # Skip processing if this customer is not in the database
10
10
  return unless pay_customer
@@ -4,7 +4,7 @@ module Pay
4
4
  class CustomerUpdated
5
5
  def call(event)
6
6
  object = event.data.object
7
- pay_customer = Pay::Customer.find_by(processor: :stripe, processor_id: object.id)
7
+ pay_customer = Pay::Stripe.find_pay_customer(object.id)
8
8
 
9
9
  # Couldn't find user, we can skip
10
10
  return unless pay_customer.present?
@@ -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))
28
+ Pay::Stripe::PaymentMethod.sync(payment_method_id, stripe_account: event.try(:account), customer: pay_customer)
29
29
 
30
30
  else
31
31
  # No default payment method set
@@ -26,7 +26,7 @@ module Pay
26
26
 
27
27
  # Compare the local invoice id to the event invoice id and sync if they are the same
28
28
  if latest_invoice_id.to_s == invoice.id.to_s
29
- Pay::Stripe::Subscription.sync(subscription_id, stripe_account: event.try(:account))
29
+ Pay::Stripe::Subscription.sync(subscription_id, stripe_account: event.try(:account), customer: subscription.customer)
30
30
  end
31
31
  rescue ::Stripe::StripeError => e
32
32
  Rails.logger.error "Stripe Webhook Error (InvoiceUpdated): #{e.message}"
@@ -13,7 +13,7 @@ module Pay
13
13
  pay_subscription = Pay::Subscription.find_by_processor_and_id(:stripe, subscription_id)
14
14
  return if pay_subscription.nil? || pay_subscription.status == "incomplete"
15
15
 
16
- invoice_payment = ::Stripe::InvoicePayment.list({invoice: invoice.id, status: :open}, {stripe_account: event.try(:account)}.compact).first
16
+ invoice_payment = Pay::Stripe.client(customer: pay_subscription.customer).v1.invoice_payments.list({invoice: invoice.id, status: :open}, {stripe_account: event.try(:account)}.compact).first
17
17
 
18
18
  if invoice_payment && Pay.send_email?(:payment_action_required, pay_subscription)
19
19
  Pay.mailer.with(
@@ -9,8 +9,7 @@ module Pay
9
9
 
10
10
  def call(event)
11
11
  object = event.data.object
12
- payment_intent = ::Stripe::PaymentIntent.retrieve({id: object.id}, {stripe_account: event.try(:account)}.compact)
13
- Pay::Stripe::Charge.sync(payment_intent.latest_charge, stripe_account: event.try(:account))
12
+ Pay::Stripe::Charge.sync_payment_intent(object.id, stripe_account: event.try(:account), customer: Pay::Stripe.find_pay_customer(object.customer))
14
13
  end
15
14
  end
16
15
  end
@@ -4,7 +4,7 @@ module Pay
4
4
  class PaymentMethodAttached
5
5
  def call(event)
6
6
  object = event.data.object
7
- Pay::Stripe::PaymentMethod.sync(object.id, stripe_account: event.try(:account))
7
+ Pay::Stripe::PaymentMethod.sync(object.id, stripe_account: event.try(:account), customer: Pay::Stripe.find_pay_customer(object.customer))
8
8
  end
9
9
  end
10
10
  end
@@ -5,7 +5,7 @@ module Pay
5
5
  def call(event)
6
6
  object = event.data.object
7
7
  if object.customer
8
- Pay::Stripe::PaymentMethod.sync(object.id, stripe_account: event.try(:account))
8
+ Pay::Stripe::PaymentMethod.sync(object.id, stripe_account: event.try(:account), customer: Pay::Stripe.find_pay_customer(object.customer))
9
9
  else
10
10
  # If customer was removed, we should delete the payment method if it exists
11
11
  Pay::PaymentMethod.find_by_processor_and_id(:stripe, object.id)&.destroy
@@ -15,7 +15,7 @@ module Pay
15
15
  return unless pay_subscription
16
16
 
17
17
  # Stripe subscription items all have the same interval
18
- price = ::Stripe::Price.retrieve({id: invoice.lines.first.pricing.price_details.price}, {stripe_account: event.try(:account)}.compact)
18
+ price = Pay::Stripe.client(customer: pay_subscription.customer).v1.prices.retrieve(invoice.lines.first.pricing.price_details.price, {}, {stripe_account: event.try(:account)}.compact)
19
19
 
20
20
  # For collection_method=send_invoice, Stripe will send an email and next_payment_attempt will be null
21
21
  # https://docs.stripe.com/api/invoices/object#invoice_object-collection_method
@@ -3,7 +3,7 @@ module Pay
3
3
  module Webhooks
4
4
  class SubscriptionUpdated
5
5
  def call(event)
6
- Pay::Stripe::Subscription.sync(event.data.object.id, stripe_account: event.try(:account))
6
+ Pay::Stripe::Subscription.sync(event.data.object.id, stripe_account: event.try(:account), customer: Pay::Stripe.find_pay_customer(event.data.object.customer))
7
7
  end
8
8
  end
9
9
  end
data/lib/pay/stripe.rb CHANGED
@@ -43,6 +43,79 @@ module Pay
43
43
  end
44
44
  self.model_names = Set.new
45
45
 
46
+ # An optional callable returning Stripe::StripeClient options (api_key:, stripe_version:, etc.) for apps with more
47
+ # than one Stripe account. They're merged over the global Stripe configuration; returning nil uses it unchanged.
48
+ # Pay sets the Connect account itself, so the options can't include stripe_account.
49
+ # A callable that takes keywords is passed the Pay::Customer the request is for, which is nil when Pay doesn't know it yet.
50
+ #
51
+ # Pay::Stripe.client_options = -> { {api_key: Current.brand.stripe_api_key} if Current.brand }
52
+ # Pay::Stripe.client_options = ->(customer: nil, **) { ... }
53
+ class << self
54
+ attr_accessor :client_options
55
+ end
56
+
57
+ # The Stripe::StripeClient for a Stripe API request. Building a client is cheap, so one is created per request
58
+ # instead of being shared across threads and Ractors.
59
+ #
60
+ # Pay passes the Connect account with each request ({stripe_account: "acct_..."}) rather than setting it on the
61
+ # client: stripe-ruby keeps one HTTP connection pool per client configuration, so a client per connected account
62
+ # would open a new connection for every account.
63
+ def self.client(customer: nil)
64
+ options = default_client_options.merge(app_client_options(customer) || {})
65
+ ::Stripe::StripeClient.new(options.delete(:api_key), **options)
66
+ end
67
+
68
+ # Rebuilds a Stripe object from JSON Pay stored or received in a webhook, with the customer's API key and the
69
+ # Connect account, so requests it makes (like paging through a list) go to the same account.
70
+ # Stripe objects only keep api_key and stripe_account; their requests use the global configuration for the rest.
71
+ def self.construct_from(klass, data, customer: nil, stripe_account: nil)
72
+ klass.construct_from(data, {api_key: app_client_options(customer)&.dig(:api_key), stripe_account: stripe_account}.compact)
73
+ end
74
+
75
+ # Objects in the event make requests, like paging through a list, with the customer's API key on the Connect account that sent it
76
+ def self.construct_from_webhook_event(event)
77
+ # customer.* events carry the customer itself, other objects reference it
78
+ object = event.dig("data", "object") || {}
79
+ customer_id = (object["object"] == "customer") ? object["id"] : object["customer"]
80
+ construct_from(::Stripe::Event, event, customer: find_pay_customer(customer_id), stripe_account: event["account"])
81
+ end
82
+
83
+ def self.app_client_options(customer)
84
+ return unless client_options
85
+
86
+ options = if client_options.respond_to?(:arity) && client_options.arity.zero?
87
+ client_options.call
88
+ else
89
+ client_options.call(customer: customer)
90
+ end
91
+
92
+ # Otherwise platform requests, like Merchant transfers, would be sent as the connected account
93
+ if options&.key?(:stripe_account)
94
+ raise ArgumentError, "Pay::Stripe.client_options can't set stripe_account. Pay sets the Connect account from the customer, charge or subscription."
95
+ end
96
+
97
+ options
98
+ end
99
+ private_class_method :app_client_options
100
+
101
+ # StripeClient doesn't read the global client options (API base, version, etc.) itself, so copy them over
102
+ # so requests match what the legacy class methods sent.
103
+ def self.default_client_options
104
+ config = ::Stripe.config
105
+ {
106
+ api_key: config.api_key,
107
+ stripe_account: config.stripe_account,
108
+ stripe_context: config.stripe_context,
109
+ stripe_version: config.api_version,
110
+ api_base: config.api_base,
111
+ uploads_base: config.uploads_base,
112
+ connect_base: config.connect_base,
113
+ meter_events_base: config.meter_events_base,
114
+ client_id: config.client_id
115
+ }
116
+ end
117
+ private_class_method :default_client_options
118
+
46
119
  def self.enabled?
47
120
  return false unless Pay.enabled_processors.include?(:stripe) && defined?(::Stripe)
48
121
 
@@ -153,9 +226,15 @@ module Pay
153
226
  nil
154
227
  end
155
228
 
229
+ # The Pay::Customer for a Stripe customer ID, or nil when it's blank or Pay doesn't have it.
230
+ # Stripe customer IDs are unique across Stripe accounts, so this finds the customer whichever account sent a webhook.
231
+ def self.find_pay_customer(customer_id)
232
+ Pay::Customer.find_by(processor: :stripe, processor_id: customer_id) if customer_id.present?
233
+ end
234
+
156
235
  # Subscriptions aren't always immediately associated, so we want to retry by default
157
236
  def self.sync_checkout_session(session_id, stripe_account: nil, try: 0, retries: 5)
158
- checkout_session = ::Stripe::Checkout::Session.retrieve({id: session_id, expand: ["payment_intent.latest_charge"]}, {stripe_account: stripe_account}.compact)
237
+ checkout_session = Pay::Stripe.client.v1.checkout.sessions.retrieve(session_id, {expand: ["payment_intent.latest_charge"]}, {stripe_account: stripe_account}.compact)
159
238
  case checkout_session.mode
160
239
  when "payment"
161
240
  if (id = checkout_session.payment_intent.try(:latest_charge)&.id)
data/lib/pay/sync.rb CHANGED
@@ -16,9 +16,13 @@ module Pay
16
16
  end
17
17
  end
18
18
 
19
- # The Pay::Customer for this processor, or nil when the ID is blank or the customer isn't in the database
20
- def find_pay_customer(processor_id)
21
- Pay::Customer.find_by(processor: pay_processor, processor_id: processor_id) if processor_id.present?
19
+ # The Pay::Customer for this processor, or nil when the ID is blank or the customer isn't in the database.
20
+ # Returns the caller's customer without a query when it's the one the ID refers to.
21
+ def find_pay_customer(processor_id, customer: nil)
22
+ return if processor_id.blank?
23
+ return customer if customer&.processor_id == processor_id
24
+
25
+ Pay::Customer.find_by(processor: pay_processor, processor_id: processor_id)
22
26
  end
23
27
 
24
28
  # "stripe" for Pay::Stripe::Charge, "paddle_billing" for Pay::PaddleBilling::Subscription, and so on
data/lib/pay/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Pay
4
- VERSION = "12.5.0"
4
+ VERSION = "13.0.0"
5
5
  end
data/lib/pay.rb CHANGED
@@ -98,14 +98,7 @@ module Pay
98
98
 
99
99
  # Should return String or Array of email recipients
100
100
  self.mail_to = -> {
101
- if ::ActionMailer::Base.respond_to?(:email_address_with_name)
102
- ::ActionMailer::Base.email_address_with_name(params[:pay_customer].email, params[:pay_customer].customer_name)
103
- else
104
- ::Mail::Address.new.tap do |builder|
105
- builder.address = params[:pay_customer].email
106
- builder.display_name = params[:pay_customer].customer_name.presence
107
- end.to_s
108
- end
101
+ ::ActionMailer::Base.email_address_with_name(params[:pay_customer].email, params[:pay_customer].customer_name)
109
102
  }
110
103
 
111
104
  def self.setup
@@ -165,6 +158,7 @@ module Pay
165
158
  self.mail_to = shareable_callable(mail_to)
166
159
  self.mail_arguments = shareable_callable(mail_arguments)
167
160
  emails.transform_values! { |option| shareable_callable(option) }
161
+ Stripe.client_options = shareable_callable(Stripe.client_options)
168
162
  end
169
163
 
170
164
  def self.share_customer_model_options
@@ -182,7 +176,7 @@ module Pay
182
176
  model_parent_class, application_name, business_address, business_name, business_logo, support_email,
183
177
  automount_routes, routes_path, default_product_name, default_plan_name, enabled_processors,
184
178
  send_emails, emails, attach_invoice_to_receipt, @mailer, parent_mailer, mail_arguments, mail_to,
185
- Stripe.model_names, Currency.all, Webhooks.delegator, deprecator
179
+ Stripe.model_names, Stripe.client_options, Currency.all, Webhooks.delegator, deprecator
186
180
  ]
187
181
  end
188
182
  private_class_method :share_callable_options, :share_customer_model_options, :shareable_configuration
data/lib/tasks/pay.rake CHANGED
@@ -19,7 +19,7 @@ def sync_default_payment_method(pay_customer, retries: 2)
19
19
  Pay::Braintree::PaymentMethod.sync(payment_method.token, object: payment_method) if payment_method
20
20
  when "stripe"
21
21
  payment_method_id = pay_customer.api_record.invoice_settings.default_payment_method
22
- Pay::Stripe::PaymentMethod.sync(payment_method_id) if payment_method_id
22
+ Pay::Stripe::PaymentMethod.sync(payment_method_id, stripe_account: pay_customer.stripe_account, customer: pay_customer) if payment_method_id
23
23
  when "paddle_classic"
24
24
  Pay::PaddleClassic::PaymentMethod.sync(pay_customer: pay_customer)
25
25
  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: 12.5.0
4
+ version: 13.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jason Charnes
@@ -17,14 +17,14 @@ dependencies:
17
17
  requirements:
18
18
  - - ">="
19
19
  - !ruby/object:Gem::Version
20
- version: 7.0.0
20
+ version: 7.1.0
21
21
  type: :runtime
22
22
  prerelease: false
23
23
  version_requirements: !ruby/object:Gem::Requirement
24
24
  requirements:
25
25
  - - ">="
26
26
  - !ruby/object:Gem::Version
27
- version: 7.0.0
27
+ version: 7.1.0
28
28
  description: Stripe, Paddle, and Braintree payments for Ruby on Rails apps
29
29
  email:
30
30
  - jason@thecharnes.com