Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a charge and a customer in Stripe (Rails)

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. However, only tokens are being created, not charges and customers. So the forms goes through successfully, but in the Stripe dashboard, test charges and a customers don't exist. Here is my controller:

class SubscribersController < ApplicationController
  before_filter :authenticate_user!

  def new
  end

  def update
    token = params[:stripeToken]

    customer = Stripe::Customer.create(
      card: token,
      plan: 1212,
      email: current_user.email
    )

    Stripe::Charge.create(
      :amount => 8999,
      :currency => "usd",
      :source => token,
      :description => "Example charge"
    )

    current_user.subscribed = true
    current_user.stripeid = customer.id
    current_user.save

    redirect_to profiles_user_path
  end
end
like image 452
Marko I. Avatar asked May 15 '16 19:05

Marko I.


People also ask

How do Stripe charges work?

With this charge type: You create a charge on your platform’s account so the payment appears as a charge on your account. Then, you determine whether some or all of those funds are transferred to the connected account. Your account balance will be debited for the cost of the Stripe fees, refunds, and chargebacks.

What types of accounts can be charged directly from stripe?

Only connected accounts with the card_payments capability can be directly charged. When using Express or Custom accounts, Stripe recommends that you create destination charges. With this charge type: You create a charge on your platform’s account so the payment appears as a charge on your account.

Can I pass my stripe fees on to my customers?

You can pass your Stripe fees on to your customers by including the fee into the final charge amount. It is important to ensure that this action complies with any applicable laws that pertain to your business. If you are unsure whether such laws apply, consult with your legal counsel. How to calculate the payment amount to include the Stripe fee

How do I add additional sources of payment to stripe?

If you want to add additional sources instead of replacing the existing default, use the card creation API. Whenever you attach a card to a customer, Stripe will automatically validate the card.


1 Answers

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.

Setup Stripe in your Application

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

Add a Migration to Add Stripe Customer ID to Customer

class AddUserStripeCustomerId < ActiveRecord::Migration
  def change
    change_table :users do |t|
      t.string :stripe_customer_id, limit: 50, null: true
    end
  end
end

Create a Customer

When you're ready to begin the billing process for a customer, do this:

if [email protected]_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.

Create a Default Source

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)

Make a One-off Charge

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.

Create a Subscription Plan

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.

Create a Subscription for the Customer

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"
)

Set up a Web Hook Receiver

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.

Collect a Regular Payment

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.

like image 174
Michael Gaskill Avatar answered Oct 21 '22 05:10

Michael Gaskill