最近在一个项目须要支持人民币支付,而且客户要求但愿可以收完款后的结算是用美圆,因此就想到了去年 Stripe 宣布已经跟支付宝达成合做意向,因此通过一番咨询跟集成,终于把 Stripe 集成进来,而且启用了支付宝收款。这篇文章介绍功能申请以及集成的完整过程。
html
假设支付页面上有个开始支付按钮,其 html 代码为:git
html<button id='pay'>支付</button>
请在 html 代码里合适的地方(好比<body>
标签的底部)加载 stripe.js:github
html<script src="https://checkout.stripe.com/checkout.js"></script>
在脚本中初始化 stripe.js,而且注册支付按钮的事件监听函数:web
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):api
ruby# Gemfile # Stripe Ruby bindings # https://github.com/stripe/stripe-ruby gem "stripe", "~> 1.20.1"
而后在 Controller action 中添加处理逻辑:ruby
ruby# 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