How to integrate with Stripe
suggest changeAdd Stripe gem to our Gemfile
gem 'stripe'
Add config/initializers/stripe.rb with the keys for your Stripe account:
Rails.configuration.stripe = {
publishable_key: ENV["STRIPE_PUBLISHABLE_KEY"],
secret_key: ENV["STRIPE_SECRET_KEY"]
}
Stripe.api_key = Rails.configuration.stripe[:secret_key]
How to create a new customer to Stripe
Stripe::Customer.create(email: email, source: payment_token)
This code creates a new customer on Stripe with given email address and source.
payment_token is the token given from the client-side that contains a payment method like a credit card or bank account. More info: Stripe.js client-side
How to retrieve a plan from Stripe
Stripe::Plan.retrieve(stripe_plan_id)
This code retrieves a plan from Stripe by its id.
How to create a subscription
When we have a customer and a plan we can create a new subscription on Stripe.
Stripe::Subscription.create(customer: customer.id, plan: plan.id)
It will create a new subscription and will charge our User. It’s important to know what really happens on Stripe when we subscribe a user to a plan, you will find more info here: Stripe Subscription lifecycle.
How to charge a user with a single payment
To charge once, instead of starting a subscription:
Stripe::Charge.create(amount: amount, customer: customer.id, currency: currency)
customer here is the Stripe customer object from Stripe::Customer.create, so the charge uses customer.id.
Common errors:
- Send
amountas an integer in the currency's smallest unit. For two-decimal currencies such as USD,2000is 20.00. Stripe's charge docs show the rule, including zero-decimal currencies. - A Stripe customer is locked to the currency of the first charge. A customer charged in EUR cannot later be charged in USD.
- You cannot charge a customer who has no payment source.