I\'m building a subscription-based app, and I want to charge customers through Stripe subscriptions. I\'m trying to create a customer and a charge after submitting the form
All of this can be found in the excellent Ruby API Docs. There are a few steps involved, but it's not so hard. It may take a little experimentation to get it working in your application.
It looks as though you're trying to set the customer up on a Subscription Plan (use of plan: 1212
), so I'll explain how Subscription works. I'll also explain simple one-off charges, as well, in case that's what you were looking for.
Add Stripe keys to your config/secrets.yml
file:
development:
stripe_private_key: <%= ENV["STRIPE_PRIVATE_KEY"] %>
stripe_public_key: <%= ENV["STRIPE_PUBLIC_KEY"] %>
You can keep the STRIPE_PRIVATE_KEY and STRIPE_PUBLIC_KEY in your environment. Test and production environments would require similar configuration settings.
Next, add this code to your BillingController
, or wherever you plan to use the Stripe API:
require "stripe"
Stripe.api_key = Rails.application.secrets.stripe_private_key
class AddUserStripeCustomerId < ActiveRecord::Migration
def change
change_table :users do |t|
t.string :stripe_customer_id, limit: 50, null: true
end
end
end
When you're ready to begin the billing process for a customer, do this:
if !@user.stripe_customer_id
@user.stripe_customer_id = Stripe::Customer.create(
account_balance: 0,
email: @user.email_canonical
)
end
Make sure to save the customer ID in your User model. You'll need to make sure that you don't keep creating and overwriting your customer ID for a user, because this is your tie-in to the Stripe payments system for that user.
The customer must have a default source assigned for subscription charges to be made. This can be created from a token, like so:
customer.sources.create({source: token_id})
or assigned from a customer's existing cards, if you've already assigned cards to the user:
customer.default_source = customer.sources.retrieve(card_id)
You can charge the customer one time, without recurring, and you do that with this:
Stripe::Charge.create(
:amount => 1395, # <== Currency in 'cents'
:currency => "usd",
:source => customer.default_source, # <== from previous section
:description => "Fuzzy eyeglasses"
)
You should capture the charge ID, but you can always retrieve that from Stripe if you happen to need it later.
You can easily create the Subscription Plan on the Stripe console, since this is typically a one-time activity; building out a UI to manage Subscription Plans is almost certainly overkill unless you have admin users that can manage subscription plans, but shouldn't have access to the Stripe console.
To programmatically create a Subscription Plan, try this:
Stripe::Plan.create(
:amount => 4200, #<== Amount is in cents, not dollars
:interval => "month",
:name => "Purple Plan",
:currency => "usd",
:id => "purple"
)
You can create as many plans as you like, and can subscribe the user to any that they like.
At this point, you can create the subscription on the customer, and this will initiate the billing process.
Stripe::Subscription.create(
:customer => customer,
:plan => "purple"
)
For some reason, this documentation is in a different location (see Webhooks), but it's a very necessary part of the process. This will keep your application advised of the
def PaymentController
protect_from_forgery :except => :webhook
def webhook
# Capture the event information from the webhook params
event_id = params[:event]
# Verify that the event isn't forged to your Stripe account
event = Stripe::Event.retrieve(event_id)
# Record the event
PaymentEvents.create!(event)
# Handle the event in terms of your application
#...
end
end
The types of events sent from Stripe are documented at Types of Events. You may choose to capture and handle some, while letting others pass. However, in my applications, I've found it's better to capture and log all events, and then handle them as you need. This way, if you missed handling an event that later becomes important to have handled, you have the event to refer to and can deal with it post hoc.
This is the easy part, and may best be done with your favorite cold beverage. All you need to do from this point is monitor the Stripe console and your bank account. No additional action required, because Stripe takes care of the rest.