Set up a Stripe webhook:

  • Log in to your Stripe dashboard.
  • Navigate to “Developers” > “Webhooks” in the left sidebar.
  • Click the “Add endpoint” button to create a new webhook endpoint.
  • Enter the URL of your Rails application where you’ll receive Stripe webhook events (e.g., https://your-app.com/webhooks/stripe).
  • Select the events you want to listen to, such as “checkout.session.completed” for successful payments.
  • Save the webhook endpoint.

In the app/controllers/webhooks_controller.rb file, create an action to handle the webhook events:

To send email to user after purchase:

1. In the webhooks controller, you can send an email to the user after a checkout is completed. To obtain the user’s email address for sending the email, you can retrieve it from the event object.

class WebhooksController < ApplicationController
  skip_before_action :verify_authenticity_token
  def create
    payload = request.body.read
    sig_header = request.env['HTTP_STRIPE_SIGNATURE']
    event = nil
    begin
      event = Stripe::Webhook.construct_event(
      payload, sig_header,Rails.application.credentials[:stripe][:webhook]
     )
    rescue JSON::ParserError => e
      status 400
      return
    rescue Stripe::SignatureVerificationError => e
      # Invalid signature
      puts "Signature error"
      return
    end
    # Handle the event
    case event.type
    when 'checkout.session.completed'
      session = event.data.object
      session_with_expand = Stripe::Checkout::Session.retrieve({id:     session.id, expand: ["line_items"] })
      session_with_expand.line_items.data.each do |line_item|
      product = Product.find_by(stripe_product_id: line_item.price.product)
      product.increment!(:sales_count)
    end
      #Send email to user after successful payment
      user_id = event.data.object.client_reference_id
      User = User.find_by(id: user_id)
      if user
        UserMailer.payment_success_email(user).deliver_now
      end
    end
    render json: { message: 'success' }
  end
end

2. If you are creating the payment intent with the Ruby SDK you can add the receipt_email field to add a customers email.

Stripe.api_key = 'API_KEY'


intent = Stripe::PaymentIntent.create({
  amount: 1099,
  currency: 'cad',
  payment_method_types: ['card'],
  receipt_email: '[email protected]',
})

3. If you are creating the checkout session server side you can preconfigure the properties/settings like for the checkout page.

require 'stripe'
Stripe.api_key ='API_KEY'

Stripe::Checkout::Session.create({
  success_url: 'https://example.com/success',
  cancel_url: 'https://example.com/cancel',
  customer_email:'email',
  line_items: [
    {price: 'price_H5ggYwtDq4fbrJ', quantity: 2},
  ],
  mode: 'payment',
})

 

Support On Demand!

                                         
Ruby on Rails