# Stripe + Ruby入門 - 本文是簡短翻譯自kamiさん在Simplie Post的技術文章。 - 內容主要是如何透過Stripe做訂閱制的服務金流部分 - [連結在此](http://post.simplie.jp/posts/94) - 本人日文渣,如有翻錯,那就是錯。 ## 定期扣款 ### Flow 1. Plan - 可以根據不同plan設定不同費用 - ex. basic, premium 2. 購買流程 1. user輸入信用卡資訊 2. 將信用卡資訊提交給stripe,並取得返回token。 3. 用token建立user資訊 4. user subscribe plan 5. 設定有效期限 3. 更新有效期限 - 每個月扣款完成透過webhook通知該用戶新的期限 4. 取消訂閱 - 結算&對用戶的一些資料操作 - 這個好像看各家實作方案(RayWay) ### GEM #### Stripe Object - Stripe::Token - 用戶第一次輸入付款資訊後,會將付款資訊以token的形式提交。 - token只能使用一次,如果要重複扣款要為該用戶建立Customer。 - Stripe::Customer - 可以將Customer訂閱到某個plan藉以重複扣款。 - Stripe::Plan - 定義商品費用以及有效期限。 - Stripe::Subscription - 串連Customer以及Plan的物件,用來定期對用戶扣款。 - Stripe::Invoice - 毫無疑問就是收據 - Subscription定期產生Invoice - Stripe::Event - 可以藉由event去trigger webhook - ex. 定期扣款結束後觸發 `customer.subscription.updated` 事件,再通知應用程式有效期限的更新。 ### Token取得的方法 1. [Checkout](https://stripe.com/checkout) - stripe出的套件,從付款頁面到token取得一次包好。 2. [stripe.js](https://stripe.com/docs/stripe.js) - 刻到死 ### Customer建立 - 一個token只能使用一次,token可以拿來建立Customer。 - 詳見[API doc](https://stripe.com/docs/api/ruby#create_customer) - 若要儲存customer額外資訊要透過metadata - key-value ```ruby # example customer = Stripe::Customer.create( source: params[:stripeToken], description: 'Example customer' ) ``` ### Plan建立 - 建立訂閱方案 - 也可以由stripe,Dashboard建立。 - 參數請參照 [doc](https://stripe.com/docs/subscriptions/plans) ```ruby Stripe::Plan.create( amount: 2000, interval: 'month', name: 'Basic', currency: 'jpy', id: 'basic' ) ``` ### 用戶訂閱方案 - `subscription.current_period_end`: 訂閱期限timestamp ```ruby subscription = Stripe::Subscription.create( customer: '<CUSTOMER_ID>', plan: 'basic' ) ``` ### Rails + Stripe實戰範例 - [看code比較快](http://post.simplie.jp/posts/97)