Skip to content

Instantly share code, notes, and snippets.

@adam-stripe
Created February 24, 2017 17:16
Show Gist options
  • Save adam-stripe/72cadb71a60fdfbe7b416eec43944560 to your computer and use it in GitHub Desktop.
Save adam-stripe/72cadb71a60fdfbe7b416eec43944560 to your computer and use it in GitHub Desktop.
Generic Stripe receipt webhook with Sinatra and Mailgun
# A simple text-based email receipt webhook, written for Sinatra. Sends email receipts for one-off charges.
# See https://github.com/adamjstevenson/stripe-ruby-webhook-receipts for more specifics
require 'sinatra'
require 'stripe'
require 'mailgun-ruby'
# Set your Stripe secret key as an environment variable: https://dashboard.stripe.com/account/apikeys
Stripe.api_key = ENV['STRIPE_KEY']
# Set mailgun API key and domain: https://mailgun.com/app/domains
mg_client = Mailgun::Client.new ENV['MAILGUN_KEY']
mg_domain = ENV['MAILGUN_DOMAIN']
# Listen for a POST to the /webhook endpoint
post "/webhook" do
# Retrieve the request's body and parse it as JSON
event_json = JSON.parse(request.body.read)
# Retrieve the event from Stripe
event = Stripe::Event.retrieve(event_json['id'])
# Only respond to `charge.succeeded` events with an email address available
if event.type.eql?('charge.succeeded') && event.data.object.metadata.email
# Send an email receipt
message_params = {
from: "postmaster@#{mg_domain}", # Your domain or Mailgun Sandbox domain
to: event.data.object.metadata.email, # Email address for the charge, storing in metadata here
subject: 'Your SITE-NAME.COM email receipt',
text: text_email(event)
}
result = mg_client.send_message(mg_domain, message_params).to_h!
puts result
else
# Nothing to see here, return a 200
status 200
end
end
# Text email
def text_email(event)
<<-EOF
Hi there,
Thank you for your purchase: here's your payment receipt!
Questions? Please contact [email protected].
=================================================================
SITE-NAME RECEIPT - Payment for #{event.data.object.description}
Total: #{format_amount(event.data.object.amount)} #{event.data.object.currency}
Charged to: #{event.data.object.source.brand} ending in #{event.data.object.source.last4}
Payment ID: #{event.data.object.id}
Date: #{Time.now.strftime("%m/%d/%Y")}
SITE-NAME.COM
3180 18th Street
San Francisco, CA 94110
=================================================================
EOF
end
def format_amount(amount)
sprintf('$%0.2f', amount.to_f / 100.0).gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1,")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment