Class: Pay::Stripe::Subscription
- Inherits:
-
Pay::Subscription
- Object
- ApplicationRecord
- Pay::Subscription
- Pay::Stripe::Subscription
- Defined in:
- app/models/pay/stripe/subscription.rb
Constant Summary
Constants inherited from Pay::Subscription
Instance Attribute Summary collapse
Class Method Summary collapse
-
.expand_options ⇒ Object
Common expand options for all requests that create, retrieve, or update a Stripe Subscription.
- .sync(subscription_id, object: nil, name: nil, stripe_account: nil, try: 0, retries: 1) ⇒ Object
- .sync_from_checkout_session(session_id, stripe_account: nil) ⇒ Object
Instance Method Summary collapse
-
#cancel(**options) ⇒ Object
Marks a subscription to cancel at period end.
-
#cancel_now!(**options) ⇒ Object
Cancels a subscription immediately.
-
#change_quantity(quantity, **options) ⇒ Object
This updates a SubscriptionItem’s quantity in Stripe.
-
#client_secret ⇒ Object
Returns a SetupIntent or PaymentIntent client secret for the subscription.
-
#create_usage_record(**options) ⇒ Object
Creates a metered billing usage record.
- #latest_payment ⇒ Object
-
#metered_subscription_item ⇒ Object
Returns the first metered subscription item.
- #on_grace_period? ⇒ Boolean
-
#pause(**options) ⇒ Object
Pauses a Stripe subscription.
- #pause_active? ⇒ Boolean
- #paused? ⇒ Boolean
-
#pay_open_invoices ⇒ Object
Looks up open invoices for a subscription and attempts to pay them.
- #resumable? ⇒ Boolean
- #resume ⇒ Object
-
#retry_failed_payment(payment_intent_id: nil) ⇒ Object
Retries the latest invoice for a Past Due subscription and attempts to pay it.
- #swap(plan, **options) ⇒ Object
-
#unpause ⇒ Object
Unpauses a subscription.
-
#upcoming_invoice(**options) ⇒ Object
Returns an upcoming invoice for a subscription.
-
#update_payment_method(id) ⇒ Object
Sets the default_payment_method on a subscription Pass an empty string to unset.
-
#usage_record_summaries(**options) ⇒ Object
Returns usage record summaries for a subscription item.
- #will_pause? ⇒ Boolean
Methods inherited from Pay::Subscription
#active?, #canceled?, #cancelled?, #ended?, find_by_processor_and_id, #generic_trial?, #has_incomplete_payment?, #has_trial?, #incomplete?, #no_prorate, #on_trial?, #past_due?, #skip_trial, #swap_and_invoice, #sync!, #trial_ended?, #unpaid?
Instance Attribute Details
#api_record(**options) ⇒ Object
134 135 136 |
# File 'app/models/pay/stripe/subscription.rb', line 134 def api_record(**) @api_record ||= ::Stripe::Subscription.retrieve(.with_defaults(id: processor_id).merge(), {stripe_account: stripe_account}.compact) end |
Class Method Details
.expand_options ⇒ Object
Common expand options for all requests that create, retrieve, or update a Stripe Subscription
121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'app/models/pay/stripe/subscription.rb', line 121 def self. { expand: [ "default_payment_method", "pending_setup_intent", "latest_invoice.payment_intent", "latest_invoice.charge", "latest_invoice.total_discount_amounts.discount", "latest_invoice.total_tax_amounts.tax_rate" ] } end |
.sync(subscription_id, object: nil, name: nil, stripe_account: nil, try: 0, retries: 1) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
# File 'app/models/pay/stripe/subscription.rb', line 11 def self.sync(subscription_id, object: nil, name: nil, stripe_account: nil, try: 0, retries: 1) # Skip loading the latest subscription details from the API if we already have it object ||= ::Stripe::Subscription.retrieve({id: subscription_id}.merge(), {stripe_account: stripe_account}.compact) if object.customer.blank? Rails.logger.debug "Stripe Subscription #{object.id} does not have a customer" return end pay_customer = Pay::Customer.find_by(processor: :stripe, processor_id: object.customer) if pay_customer.blank? Rails.logger.debug "Pay::Customer #{object.customer} is not in the database while syncing Stripe Subscription #{object.id}" return end attributes = { application_fee_percent: object.application_fee_percent, created_at: Time.at(object.created), processor_plan: object.items.first.price.id, quantity: object.items.first.try(:quantity) || 0, status: object.status, stripe_account: pay_customer.stripe_account, metadata: object., subscription_items: [], metered: false, pause_behavior: object.pause_collection&.behavior, pause_resumes_at: (object.pause_collection&.resumes_at ? Time.at(object.pause_collection&.resumes_at) : nil), current_period_start: (object.current_period_start ? Time.at(object.current_period_start) : nil), current_period_end: (object.current_period_end ? Time.at(object.current_period_end) : nil) } # Subscriptions that have ended should have their trial ended at the # same time if they were still on trial (if you cancel a # subscription, your are cancelling your trial as well at the same # instant). This avoids canceled subscriptions responding `true` # to #on_trial? due to the `trial_ends_at` being left set in the # future. if object.trial_end trial_ended_at = [object.ended_at, object.trial_end].compact.min attributes[:trial_ends_at] = Time.at(trial_ended_at) end # Record subscription items to db object.items.auto_paging_each do |subscription_item| if !attributes[:metered] && (subscription_item.to_hash.dig(:price, :recurring, :usage_type) == "metered") attributes[:metered] = true end attributes[:subscription_items] << subscription_item.to_hash.slice(:id, :price, :metadata, :quantity) end attributes[:ends_at] = if object.ended_at # Fully cancelled subscription Time.at(object.ended_at) elsif object.cancel_at # subscription cancelling in the future Time.at(object.cancel_at) elsif object.cancel_at_period_end # Subscriptions cancelling in the future Time.at(object.current_period_end) end # Sync payment method if directly attached to subscription if object.default_payment_method if object.default_payment_method.is_a? String Pay::Stripe::PaymentMethod.sync(object.default_payment_method) attributes[:payment_method_id] = object.default_payment_method else Pay::Stripe::PaymentMethod.sync(object.default_payment_method.id, object: object.default_payment_method) attributes[:payment_method_id] = object.default_payment_method.id end end # Update or create the subscription pay_subscription = pay_customer.subscriptions.find_by(processor_id: object.id) if pay_subscription # If pause behavior is changing to `void`, record the pause start date # Any other pause status (or no pause at all) should have nil for start if pay_subscription.pause_behavior != attributes[:pause_behavior] attributes[:pause_starts_at] = if attributes[:pause_behavior] == "void" Time.at(object.current_period_end) end end pay_subscription.with_lock { pay_subscription.update!(attributes) } else # Allow setting the subscription name in metadata, otherwise use the default name ||= object.["pay_name"] || Pay.default_product_name pay_subscription = pay_customer.subscriptions.create!(attributes.merge(name: name, processor_id: object.id)) end # Cache the Stripe subscription on the Pay::Subscription that we return pay_subscription.api_record = object # Sync the latest charge if we already have it loaded (like during subscrbe), otherwise, let webhooks take care of creating it if (charge = object.try(:latest_invoice).try(:charge)) && charge.try(:status) == "succeeded" Pay::Stripe::Charge.sync(charge.id, stripe_account: pay_subscription.stripe_account) end pay_subscription rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique try += 1 if try <= retries sleep 0.1 retry else raise end end |
.sync_from_checkout_session(session_id, stripe_account: nil) ⇒ Object
6 7 8 9 |
# File 'app/models/pay/stripe/subscription.rb', line 6 def self.sync_from_checkout_session(session_id, stripe_account: nil) checkout_session = ::Stripe::Checkout::Session.retrieve({id: session_id}, {stripe_account: stripe_account}.compact) sync(checkout_session.subscription) end |
Instance Method Details
#cancel(**options) ⇒ Object
Marks a subscription to cancel at period end
If subscription is already past_due, the subscription will be cancelled immediately To disable this, pass past_due_cancel_now: false
156 157 158 159 160 161 162 163 164 165 166 167 |
# File 'app/models/pay/stripe/subscription.rb', line 156 def cancel(**) return if canceled? if past_due? && .fetch(:past_due_cancel_now, true) cancel_now! else @api_record = ::Stripe::Subscription.update(processor_id, {cancel_at_period_end: true}.merge(), ) update(ends_at: (on_trial? ? trial_ends_at : Time.at(@api_record.current_period_end))) end rescue ::Stripe::StripeError => e raise Pay::Stripe::Error, e end |
#cancel_now!(**options) ⇒ Object
Cancels a subscription immediately
cancel_now!(prorate: true) cancel_now!(invoice_now: true)
173 174 175 176 177 178 179 180 |
# File 'app/models/pay/stripe/subscription.rb', line 173 def cancel_now!(**) return if canceled? && ends_at.past? @api_record = ::Stripe::Subscription.cancel(processor_id, .merge(), ) update(trial_ends_at: Time.current, ends_at: Time.current, status: :canceled) rescue ::Stripe::StripeError => e raise Pay::Stripe::Error, e end |
#change_quantity(quantity, **options) ⇒ Object
This updates a SubscriptionItem’s quantity in Stripe
For a subscription with a single item, we can update the subscription directly if no SubscriptionItem ID is available Otherwise a SubscriptionItem ID is required so Stripe knows which entry to update
186 187 188 189 190 191 192 193 194 195 196 197 |
# File 'app/models/pay/stripe/subscription.rb', line 186 def change_quantity(quantity, **) subscription_item_id = .delete(:subscription_item_id) || subscription_items&.first&.dig("id") if subscription_item_id ::Stripe::SubscriptionItem.update(subscription_item_id, .merge(quantity: quantity), ) @api_record = nil else @api_record = ::Stripe::Subscription.update(processor_id, .merge(quantity: quantity).merge(), ) end update(quantity: quantity) rescue ::Stripe::StripeError => e raise Pay::Stripe::Error, e end |
#client_secret ⇒ Object
Returns a SetupIntent or PaymentIntent client secret for the subscription
139 140 141 |
# File 'app/models/pay/stripe/subscription.rb', line 139 def client_secret api_record&.pending_setup_intent&.client_secret || api_record&.latest_invoice&.payment_intent&.client_secret end |
#create_usage_record(**options) ⇒ Object
Creates a metered billing usage record
Uses the first subscription_item ID unless ‘subscription_item_id: “si_1234”` is passed
create_usage_record(quantity: 4, action: :increment) create_usage_record(subscription_item_id: “si_1234”, quantity: 100, action: :set)
310 311 312 313 |
# File 'app/models/pay/stripe/subscription.rb', line 310 def create_usage_record(**) subscription_item_id = .delete(:subscription_item_id) || metered_subscription_item&.dig("id") ::Stripe::SubscriptionItem.create_usage_record(subscription_item_id, , ) end |
#latest_payment ⇒ Object
355 356 357 |
# File 'app/models/pay/stripe/subscription.rb', line 355 def latest_payment api_record(expand: ["latest_invoice.payment_intent"]).latest_invoice.payment_intent end |
#metered_subscription_item ⇒ Object
Returns the first metered subscription item
322 323 324 325 326 |
# File 'app/models/pay/stripe/subscription.rb', line 322 def metered_subscription_item subscription_items.find do |subscription_item| subscription_item.dig("price", "recurring", "usage_type") == "metered" end end |
#on_grace_period? ⇒ Boolean
199 200 201 |
# File 'app/models/pay/stripe/subscription.rb', line 199 def on_grace_period? (ends_at? && ends_at > Time.current) || (paused? && will_pause?) end |
#pause(**options) ⇒ Object
Pauses a Stripe subscription
pause(behavior: “mark_uncollectible”) pause(behavior: “keep_as_draft”) pause(behavior: “void”) pause(behavior: “mark_uncollectible”, resumes_at: 1.month.from_now)
‘void` - If you can’t provide your services for a certain period of time, you can void invoices that are created by your subscriptions so that your customers aren’t charged. `keep_as_draft` - If you want to temporarily offer your services for free and collect payments later `mark_uncollectible` - If you want to offer your services for free
pause_behavior of ‘void` is considered active until the end of the current period and not active after that. The current_period_end is stored as `pause_starts_at` Other pause_behaviors do not set `pause_starts_at` because they are used for offering free services
230 231 232 233 234 235 236 237 238 239 |
# File 'app/models/pay/stripe/subscription.rb', line 230 def pause(**) attributes = {pause_collection: .reverse_merge(behavior: "void")} @api_record = ::Stripe::Subscription.update(processor_id, attributes.merge(), ) behavior = @api_record.pause_collection&.behavior update( pause_behavior: behavior, pause_resumes_at: (@api_record.pause_collection&.resumes_at ? Time.at(@api_record.pause_collection&.resumes_at) : nil), pause_starts_at: ((behavior == "void") ? Time.at(@api_record.current_period_end) : nil) ) end |
#pause_active? ⇒ Boolean
203 204 205 |
# File 'app/models/pay/stripe/subscription.rb', line 203 def pause_active? paused? && (pause_starts_at.nil? || Time.current.after?(pause_starts_at)) end |
#paused? ⇒ Boolean
211 212 213 |
# File 'app/models/pay/stripe/subscription.rb', line 211 def paused? pause_behavior == "void" end |
#pay_open_invoices ⇒ Object
Looks up open invoices for a subscription and attempts to pay them
349 350 351 352 353 |
# File 'app/models/pay/stripe/subscription.rb', line 349 def pay_open_invoices ::Stripe::Invoice.list({subscription: processor_id, status: :open}, ).auto_paging_each do |invoice| retry_failed_payment(payment_intent_id: invoice.payment_intent) end end |
#resumable? ⇒ Boolean
253 254 255 |
# File 'app/models/pay/stripe/subscription.rb', line 253 def resumable? on_grace_period? || paused? end |
#resume ⇒ Object
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
# File 'app/models/pay/stripe/subscription.rb', line 257 def resume unless resumable? raise Error, "You can only resume subscriptions within their grace period." end if paused? unpause else @api_record = ::Stripe::Subscription.update(processor_id, { plan: processor_plan, trial_end: (on_trial? ? trial_ends_at.to_i : "now"), cancel_at_period_end: false }.merge(), ) end update(ends_at: nil, status: :active) rescue ::Stripe::StripeError => e raise Pay::Stripe::Error, e end |
#retry_failed_payment(payment_intent_id: nil) ⇒ Object
Retries the latest invoice for a Past Due subscription and attempts to pay it
334 335 336 337 338 339 340 341 342 343 344 345 346 |
# File 'app/models/pay/stripe/subscription.rb', line 334 def retry_failed_payment(payment_intent_id: nil) payment_intent_id ||= api_record.latest_invoice.payment_intent.id payment_intent = ::Stripe::PaymentIntent.retrieve({id: payment_intent_id}, ) payment_intent = if payment_intent.status == "requires_payment_method" ::Stripe::PaymentIntent.confirm(payment_intent_id, {payment_method: customer.default_payment_method.processor_id}, ) else ::Stripe::PaymentIntent.confirm(payment_intent_id, ) end Pay::Payment.new(payment_intent).validate rescue ::Stripe::StripeError => e raise Pay::Stripe::Error, e end |
#swap(plan, **options) ⇒ Object
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 |
# File 'app/models/pay/stripe/subscription.rb', line 277 def swap(plan, **) raise ArgumentError, "plan must be a string" unless plan.is_a?(String) proration_behavior = .delete(:proration_behavior) || (prorate ? "always_invoice" : "none") @api_record = ::Stripe::Subscription.update( processor_id, { cancel_at_period_end: false, plan: plan, proration_behavior: proration_behavior, trial_end: (on_trial? ? trial_ends_at.to_i : "now"), quantity: quantity }.merge().merge(), ) # Validate that swap was successful and handle SCA if needed if (payment_intent = @api_record.latest_invoice.payment_intent) Pay::Payment.new(payment_intent).validate end sync!(object: @api_record) rescue ::Stripe::StripeError => e raise Pay::Stripe::Error, e end |
#unpause ⇒ Object
Unpauses a subscription
docs.stripe.com/billing/subscriptions/pause-payment#unpausing
244 245 246 247 248 249 250 251 |
# File 'app/models/pay/stripe/subscription.rb', line 244 def unpause @api_record = ::Stripe::Subscription.update(processor_id, {pause_collection: ""}.merge(), ) update( pause_behavior: nil, pause_resumes_at: nil, pause_starts_at: nil ) end |
#upcoming_invoice(**options) ⇒ Object
Returns an upcoming invoice for a subscription
329 330 331 |
# File 'app/models/pay/stripe/subscription.rb', line 329 def upcoming_invoice(**) ::Stripe::Invoice.upcoming(.merge(subscription: processor_id), ) end |
#update_payment_method(id) ⇒ Object
Sets the default_payment_method on a subscription Pass an empty string to unset
145 146 147 148 149 150 |
# File 'app/models/pay/stripe/subscription.rb', line 145 def update_payment_method(id) @api_record = ::Stripe::Subscription.update(processor_id, {default_payment_method: id}.merge(), ) update(payment_method_id: @api_record.default_payment_method&.id) rescue ::Stripe::StripeError => e raise Pay::Stripe::Error, e end |
#usage_record_summaries(**options) ⇒ Object
Returns usage record summaries for a subscription item
316 317 318 319 |
# File 'app/models/pay/stripe/subscription.rb', line 316 def usage_record_summaries(**) subscription_item_id = .delete(:subscription_item_id) || metered_subscription_item&.dig("id") ::Stripe::SubscriptionItem.list_usage_record_summaries(subscription_item_id, , ) end |
#will_pause? ⇒ Boolean
207 208 209 |
# File 'app/models/pay/stripe/subscription.rb', line 207 def will_pause? pause_starts_at? && Time.current < pause_starts_at end |