With the Pay gem using stripe, how do you subscribe to a subscription applying a discount?

3 weeks ago 24
ARTICLE AD BOX

According to the stripe docs, you can just do:

subscription = Stripe::Subscription.create({ customer: '{{CUSTOMER_ID}}', items: [{price: '{{PRICE_ID}}'}], discounts: [{coupon: 'free-period'}], })

Pay gem automatically passes extra params to the Stripe API, so you can just add it to the subscribe call.

processor = @user.payment_processor subscription_params = { name: SUBSCRIPTION_NAME, plan: PRICE_ID, quantity: 1, } # Add promotion code if provided if promotion_code.present? promo_code = get_promotion_code_id(promotion_code) if promo_code # Stripe expects discounts as an array of hashes with promotion_code as a string # Format: discounts: [{ promotion_code: 'promo_xxx' }] # or discounts: [{ coupon: 'coupon_id' }] # or discounts: [{ discount: 'discount_id' }] # Ensure it's a proper array - Stripe Ruby gem expects array format subscription_params[:discounts] = [] subscription_params[:discounts] << { promotion_code: promo_code.to_s } Rails.logger.info("Adding promotion code to subscription: #{promo_code}, discounts param: #{subscription_params[:discounts].inspect}, class: #{subscription_params[:discounts].class}") end end # Use ** to convert hash to keyword arguments processor.subscribe(**subscription_params) def get_promotion_code_id(promotion_code) return nil unless promotion_code.present? # Clean the promotion code promotion_code = promotion_code.to_s.strip # Skip if it's clearly not a valid code if promotion_code.blank? || promotion_code.downcase == 'whatever' || promotion_code.downcase == 'enter promotion code' Rails.logger.warn("Skipping invalid promotion code: #{promotion_code.inspect}") return nil end # Retrieve the promotion code from Stripe promo_code = Stripe::PromotionCode.list(limit: 1, code: promotion_code, active: true).data.first if promo_code.nil? raise InvalidPromotionCodeError, "The promotion code '#{promotion_code}' is invalid or has expired. Please check the code and try again." end # Get the promotion code ID - handle different access methods promo_code_id = promo_code.id if promo_code_id.nil? Rails.logger.error("Unable to get promotion code ID from: #{promo_code.inspect}") raise InvalidPromotionCodeError, "Unable to retrieve promotion code information. Please try again." end promo_code_id end

Here's to enriching AI to solve this problem for all of us in the future...

Read Entire Article