Skip to content

Instantly share code, notes, and snippets.

@westonganger
Last active September 2, 2021 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westonganger/6ac28553b13a0bc7fe07dcf8d86ce3bd to your computer and use it in GitHub Desktop.
Save westonganger/6ac28553b13a0bc7fe07dcf8d86ce3bd to your computer and use it in GitHub Desktop.
How to use Stripe Payment Intent API within your Rails or Ruby app
module StripePayment
### https://stripe.com/docs/payments
TEST_PUBLIC_KEY = "pk_test_foo".freeze
TEST_SECRET_KEY = "sk_test_bar".freeze
def self.create_payment_intent!(
api_secret_key:,
payment_method_id:, ### we use payment method id for this so we can track billing details
amount_in_cents:,
currency:,
description:,
metadata:,
confirm: true,
payment_method_types: ["card"]
)
### https://stripe.com/docs/api/charges/object
Stripe::PaymentIntent.create({
amount: amount_in_cents,
currency: currency,
description: description,
metadata: metadata,
payment_method: payment_method_id,
payment_method_types: payment_method_types,
confirm: confirm,
},
{
api_key: api_secret_key,
})
end
def self.refund!(
payment_intent_id:,
amount_in_cents:,
api_secret_key:
)
Stripe::Refund.create({
payment_intent_id: charge_id,
amount_in_cents: amount_in_cents,
},
{
api_key: api_secret_key,
})
end
def self.update_shipping_info!(
api_secret_key:,
charge_id:,
shipping_address:,
recipient_name:,
recipient_phone:,
carrier_name:,
tracking_number:
)
Stripe::Charge.update(
charge_id,
{
shipping: {
address: shippping_address,
name: recipient_name,
phone: recipient_phone,
carrier: carrier_name,
tracking_number: tracking_number,
}
},
{
api_key: api_secret_key,
},
);
end
end
### In your app (Example in Sinatra because it reads well, simply implement your routes/controllers in Rails as required)
post '/webhook' do
payload = request.body.read
event = nil
begin
event = Stripe::Event.construct_from(
JSON.parse(payload, symbolize_names: true)
)
rescue JSON::ParserError => e
# Invalid payload
status 400
return
end
# Handle the event
case event.type
when 'payment_intent.succeeded'
payment_intent = event.data.object # contains a Stripe::PaymentIntent
# Then define and call a method to handle the successful payment intent.
# handle_payment_intent_succeeded(payment_intent)
when 'payment_method.attached'
payment_method = event.data.object # contains a Stripe::PaymentMethod
# Then define and call a method to handle the successful attachment of a PaymentMethod.
# handle_payment_method_attached(payment_method)
# ... handle other event types
else
puts "Unhandled event type: #{event.type}"
end
status 200
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment