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

后端 未结 1 401
自闭症患者
自闭症患者 2021-01-01 01:39

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

相关标签:
1条回答
  • 2021-01-01 02:44

    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 !@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.

    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.

    0 讨论(0)
提交回复
热议问题