最近在一個項目須要支持人民幣支付,而且客戶要求但願可以收完款後的結算是用美圓,因此就想到了去年 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