如何在 Stripe (Rails) 中创建费用和客户 [英] How to create a charge and a customer in Stripe (Rails)

查看:57
本文介绍了如何在 Stripe (Rails) 中创建费用和客户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个基于订阅的应用,我想通过 Stripe 订阅向客户收费.我正在尝试在提交表单后创建客户和费用.但是,只会创建代币,而不是费用和客户.所以表单成功通过,但在 Stripe 仪表板中,测试费用和客户不存在.这是我的控制器:

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

推荐答案

所有这些都可以在优秀的 Ruby API 文档.有几个步骤,但并不难.可能需要进行一些实验才能让它在您的应用程序中运行.

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.

看起来好像您正在尝试为客户设置订阅计划(使用 plan: 1212),因此我将解释订阅的工作原理.我还将解释简单的一次性费用,以防万一,这正是您所需要的.

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.

将 Stripe 密钥添加到您的 config/secrets.yml 文件:

Add Stripe keys to your config/secrets.yml file:

development:
  stripe_private_key: <%= ENV["STRIPE_PRIVATE_KEY"] %>
  stripe_public_key: <%= ENV["STRIPE_PUBLIC_KEY"] %>

您可以在您的环境中保留 STRIPE_PRIVATE_KEY 和 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.

接下来,将此代码添加到您的 BillingController 或您计划使用 Stripe API 的任何位置:

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

添加迁移以将 Stripe 客户 ID 添加到客户

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

确保在您的用户模型中保存客户 ID.您需要确保不会继续为用户创建和覆盖您的客户 ID,因为这是您与该用户的 Stripe 支付系统的搭档.

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)

一次性收费

您可以一次性向客户收费,无需重复,您可以这样做:

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

您应该获取费用 ID,但如果您以后碰巧需要,您可以随时从 Stripe 中检索它.

You should capture the charge ID, but you can always retrieve that from Stripe if you happen to need it later.

您可以在 Stripe 控制台上轻松创建订阅计划,因为这通常是一次性活动;除非您拥有可以管理订阅计划但不应该访问 Stripe 控制台的管理员用户,否则构建用于管理订阅计划的 UI 几乎肯定是矫枉过正.

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

设置 Web Hook 接收器

出于某种原因,此文档位于不同的位置(请参阅 Webhooks),但它非常过程的必要部分.这将使您的应用程序被告知

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

从 Stripe 发送的事件类型记录在事件类型.您可以选择捕获并处理一些,而让其他人通过.但是,在我的应用程序中,我发现最好捕获和记录所有事件,然后根据需要处理它们.这样,如果您错过了处理后来变得很重要的事件,您可以参考该事件并可以事后处理.

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.

这是比较简单的部分,最好用您最喜欢的冷饮来完成.从这一点开始,您需要做的就是监控 Stripe 控制台和您的银行账户.不需要额外的操作,因为 Stripe 会处理剩下的事情.

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.

这篇关于如何在 Stripe (Rails) 中创建费用和客户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆