2017-02-19 62 views
2

我創建了一個Flask簡單的表單並在Stripe.com上創建了一個Plan,它工作得很好。我可以訂閱開發模式的計劃,它反映了對Stripe的付款。現在我需要進一步與Stripe站點實時同步以獲得計劃過期和其他事件。我明白,爲了這個目的,我需要創建一個回調函數來獲取stripe id並將其保存到數據庫。我寧願將它保存到數據庫而不是會話。請告知如何創建一個回調路由並將JSON api的值保存到數據庫。以下是我的代碼來訂閱,我需要顯示過期和其他事件。條紋瓶的請求/響應方法

def yearly_charged(): 
    #Need to save customer stripe ID to DB model 
    amount = 1450 

    customer = stripe.Customer.create(
     email='[email protected]', 
     source=request.form['stripeToken'] 
    ) 
    try: 
     charge = stripe.Charge.create(
      customer=customer.id, 
      capture='true', 
      amount=amount, 
      currency='usd', 
      description='standard', 
     ) 
     data="$" + str(float(amount)/100) + " " + charge.currency.upper() 
    except stripe.error.CardError as e: 
     # The card has been declined 
     body = e.json_body 
     err = body['error'] 
     print 
     "Status is: %s" % e.http_status 
     print 
     "Type is: %s" % err['type'] 
     print 
     "Code is: %s" % err['code'] 
     print 
     "Message is: %s" % err['message'] 


    return render_template('/profile/charge.html', data=data, charge=charge) 

模板:

<form action="/charged" method="post"> 
      <div class="form-group"> 
       <label for="email">Amount is 14.95 USD </label> 
       <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" 
        data-key="{{ key }}" 
        data-description="Yearly recurring billing" 
        data-name="yearly" 
        data-amount="1495" 
        data-image="https://stripe.com/img/documentation/checkout/marketplace.png" 
        data-locale="auto"> 
       </script> 
      </div> 
     </form> 

型號:

class Students(db.Model): 
    __tablename__='students' 
    ....... 
    student_strip_id = db.Column(db.String(45)) 
    ....... 

需要幫助制定以下功能,所以我可以設置的方法得到適當的方式以dB爲單位保存的響應。

@app.route('/oauth/callback/, methods=['POST']) 
    # This is where I guess I have to define callback function to get API data 
    return redirect('/') 

此處的目標是從條帶API對象中提取條紋ID,過期事件和其他訂閱通知以保存在Flask模型中。

回答

1

首先,請注意,您分享的代碼只是creates a one-off charge,而非訂閱(即重複收費)。如果您想創建自動重複收費,您應該查看documentation for subscriptions

如果我正確理解您的問題,您希望使用webhooks通知成功的訂閱付款。將爲每次成功的付款創建一個invoice.payment_succeeded事件。 (參看here有關訂閱事件的詳細信息)

隨着瓶,一個網絡掛接處理程序將類似於此:

import json 
import stripe 
from flask import Flask, request 

app = Flask(__name__) 

@app.route('/webhook', methods=['POST']) 
def webhook(): 
    event_json = json.loads(request.data) 
    event = stripe.Event.retrieve(event_json['id']) 

    if event.type == 'invoice.payment_succeeded': 
     invoice = event.data.object 
     # Do something with invoice 
+0

謝謝你一直有很大的幫助。 –