Home > other >  how to send email to user after purchase on STRIPE with ruby ​on rails
how to send email to user after purchase on STRIPE with ruby ​on rails

Time:06-21

I would like to know how to send an email to the user after successful checkout

My Webhook controller:

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
    end
  
    render json: { message: 'success' }
  end
end

CodePudding user response:

If you are creating the payment intent with the Ruby SDK you can add the receipt_email field to add a customers email.(see ther Stripe PaymentIntent docs)

Stripe.api_key = 'API_KEY'

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

If you are creating the checkout session server side you can preconfigure the properties/settings like for the checkout page per the Stripe Checkout Docs

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',
})

This is the note on the customer email field per Stripe docs :

If provided, this value will be used when the Customer object is created. If not provided, customers will be asked to enter their email address. Use this parameter to prefill customer data if you already have an email on file. To access information about the customer once a session is complete, use the customer field.

  • Related