Skip to main content
 首页 » 编程设计

python之Stripe Flask 请求/响应方法

2025年02月15日11oomusou

我已经创建了一个 Flask 简单表单并在 Stripe.com 上创建了一个计划,它工作得很好。我可以在开发模式下订阅计划,它反射(reflect)了 Stripe 上的付款。现在进一步,我需要与 Stripe 站点实时同步以获取计划到期和其他事件。我知道为此我需要创建一个回调函数来获取 strip ID 并将其保存到数据库中。我宁愿将它保存到数据库而不是 session 。请告知如何创建回调路由并将值从 JSON api 保存到数据库。以下是我的订阅代码,我需要显示过期和其他事件。

def yearly_charged(): 
    #Need to save customer stripe ID to DB model   
    amount = 1450 
 
    customer = stripe.Customer.create( 
        email='test@test.com', 
        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)) 
    ....... 

需要帮助来设计以下功能,以便我可以设置方法以正确的方式获取响应以保存在数据库中。

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

这里的目标是从 stripe API 对象中提取 Stripe id、过期事件和其他订阅通知,以保存在 Flask 模型中。

请您参考如下方法:

首先,请注意您分享的代码很简单 creates a one-off charge ,而不是订阅(即经常性费用)。你应该看看 documentation for subscriptions如果您想自动创建经常性费用。

如果我正确理解你的问题,你想使用 webhooks收到订阅付款成功的通知。一个invoice.payment_succeeded将为每次成功的付款创建事件。 (有关订阅事件的更多信息,请参见 here。)

使用 Flask,webhook 处理程序看起来类似于:

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