Stripe Checkout Beta:避免为每次付款创建新客户

时间:2019-03-14 15:01:08

标签: ruby-on-rails stripe-payments

我正在使用Stripe Checkout Beta构建Rails应用程序。为此,我要在服务器上创建一个Stripe::Checkout::Session,在前端使用redirectToCheckout,然后等待类型为checkout_beta.session_succeeded的Webhook告诉我已完成付款。效果很好,但是:

对于每笔付款,Stripe都会创建一个客户-这不是我想要的。如果现有客户第二次付款,Stripe不应创建新客户,新付款应链接到现有客户。

如何在重定向到Checkout之前设置客户ID?

这是我的Ruby 控制器代码:

# app/controllers/payments_controller.rb

def new
  @session = Stripe::Checkout::Session.create(
    success_url: "https://shop.example.test/success",
    cancel_url: "https://shop.example.test/cancelled",
    payment_method_types: ["card"],
    line_items: cart_items.map do |cart_item|
      {
        name: cart_item.name,
        quantity: 1,
        amount: cart_item.name.price.cents,
        currency: 'eur'
      }
    end,
    customer_email: current_user.email
  )
end

HTML 代码(使用Slim):

# app/views/payments/new.html.slim

= content_tag :div, nil, data: { \
    controller: 'stripe',
    stripe_public_key: ENV['STRIPE_PUBLIC_KEY'],
    stripe_session_id: @session.id }

JavaScript 代码(使用Stimulus.js):

// app/javascripts/controllers/stripe_controller.js

import { Controller } from 'stimulus'

export default class extends Controller {
  connect() {
    this.stripe = window.Stripe(this.data.get('public-key'), {
      betas: ['checkout_beta_4']
    })

    this.stripe.redirectToCheckout({
      paymentIntentId: this.data.get('session-id')
    }).then((result) => {
      console.log(result)
    })
  }
}

Ruby webhook 代码(使用宝石stripe_event):

# config/initializer/stripe.rb

Stripe.api_key = Rails.configuration.x.stripe.private_key
Stripe.api_version = '2019-02-19; checkout_sessions_beta=v4'
StripeEvent.signing_secret = Rails.configuration.x.stripe.webhook_secret

class RecordSessions
  def call(event)
    session = event.data.object

    Payment.create!(
      stripe_charge_token: session.payment_intent
    )
  end
end

StripeEvent.configure do |events|
  events.subscribe 'checkout_beta.session_succeeded', RecordSessions.new
end

1 个答案:

答案 0 :(得分:0)

Stripe::Checkout::Session.create的API允许添加一个引用Stripe客户ID的customer密钥。这样,付款便会添加到您的现有客户中。

  

您可以指定现有的Customer对象供Checkout在以下情况下使用   一次性付款或订阅。如果这样做,任何条纹   Checkout创建的对象与该客户相关联。

     
session = Stripe::Checkout::Session.create(
  customer: 'cus_123',
  payment_method_types: ['card'],
  line_items: [{
    name: 'T-shirt',
    description: 'Comfortable cotton t-shirt',
    images: ['https://example.com/t-shirt.png'],
    amount: 500,
    currency: 'eur',
    quantity: 1,
  }],
  success_url: 'https://example.com/success',
  cancel_url: 'https://example.com/cancel',
)

请参阅:https://stripe.com/docs/payments/checkout/server#using-existing-customers