Skip to content

Commit e2d606f

Browse files
Update subscription.rb (#1168)
Fix: Handle empty payments array in Stripe subscription swap **Problem:** A `NoMethodError: undefined method 'payment' for nil:NilClass` was occurring in `Pay::Stripe::Subscription#swap` when a user changed their subscription plan, and the change resulted in a credit or a $0 invoice (e.g., due to proration). **Root Cause:** When a Stripe subscription update results in a credit or a $0 invoice, the `latest_invoice` object returned by the Stripe API has an empty `payments` array. This is because no actual payment is processed, and therefore no `payment_intent` is generated for such invoices. The existing code was attempting to access `payments.first.payment.payment_intent` without checking if `payments.first` was `nil`. **Solution:** This commit updates the `swap` method to use safe navigation operators (`&.`) when accessing `latest_invoice.payments.first.payment.payment_intent`. ```ruby # Before # if (payment_intent_id = @api_record.latest_invoice.payments.first.payment.payment_intent) # After if (payment_intent_id = @api_record.latest_invoice.payments.first&.payment&.payment_intent)
1 parent f8203b0 commit e2d606f

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

app/models/pay/stripe/subscription.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,7 @@ def swap(plan, **options)
297297
)
298298

299299
# Validate that swap was successful and handle SCA if needed
300-
if (payment_intent_id = @api_record.latest_invoice.payments.first.payment.payment_intent)
300+
if (payment_intent_id = @api_record.latest_invoice.payments.first&.payment&.payment_intent)
301301
Pay::Payment.from_id(payment_intent_id).validate
302302
end
303303

0 commit comments

Comments
 (0)