最近在一个项目需要支持人民币支付,并且客户要求希望能够收完款后的结算是用美元,所以就想到了去年 Stripe 宣布已经跟支付宝达成合作意向,所以经过一番咨询跟集成,终于把 Stripe 集成进来,并且启用了支付宝收款。这篇文章介绍功能申请以及集成的完整过程。

假设支付页面上有个开始支付按钮,其 html 代码为:
<button id='pay'>支付</button>
请在 html 代码里合适的地方(比如<body>标签的底部)加载 stripe.js:
<script src="https://checkout.stripe.com/checkout.js"></script>
在脚本中初始化 stripe.js,并且注册支付按钮的事件监听函数:
$(function(){
  var stripeHandler = StripeCheckout.configure({
    key: 'pk_test_xxxxxxxxxxxxxxxxxxxxx',  // 可以查看 https://dashboard.stripe.com/account/apikeys
    image: 'https://placehold.it/200x200',    // 显示在支付对话框的图片,可自己指定
    alipay: true,                             // 启用支付宝支付
    token: function(token){                   // 用户填写完资料并且 Stripe 校验成功后的回调函数
      // 此时应该提交 token.id 到后台,比如 http://example.com/orders/1?stripeToken={token.id}
    }
  })
  $('#pay').click(function(){
    stripeHandler.open({
      name: 'Business Name',                  // 收款方或商家名称,比如 Beansmile
      description: "商品描述内容",              // 待支付商品的描述
      amount: 50 * 100,                       // 支付金额,单位是“分”
      opened: function(){                     // 支付对话框打开后的回调函数
        // Do something
      }
    });
  });
});
服务器端是 Ruby on Rails 实现,所以在 Gemfile 中引入 Stripe 官方的 Ruby SDK(具体配置方法请自行查阅其 README):
# Gemfile
# Stripe Ruby bindings
# https://github.com/stripe/stripe-ruby
gem "stripe", "~> 1.20.1"
然后在 Controller action 中添加处理逻辑:
# app/controllers/orders_controller.rb
class OrdersController < ApplicationController
  # PUT /orders/:id
  #
  # params:
  #   id: 订单的 id
  #   stripeToken: 客户端完成支付流程,在脚本的回调函数中会得到 `token.id`,
  #                将其上传到 `stripeToken` 参数,服务器端用此 token 请求收款
  #
  def pay
    response = Stripe::Charge.create  amount: order.amount_in_cents,
                                      currency: 'USD',
                                      source: params[:stripeToken],
                                      description: "订单描述"
    order.update_attribute :state, :paid
    redirect_to order
  rescue Stripe::InvalidRequestError => error
    flash[:error] = "由于#{error.message},支付失败!"
    redirect_to order
  end
end

There is no token with ID atok_xxxxxxxxxxxxxxxxxxxxxxxx