简体   繁体   English

如何在条带中分离订阅和普通结帐 webhook?

[英]How to separate subscription and common checkout webhook in stripe?

I have made a webhook (flask) for stripe.我为条纹制作了一个 webhook(烧瓶)。

My app has both one time payment and subscription.我的应用程序有一次性付款和订阅。

I would like to know how can I detect if it's normal checkout or subscription?我想知道如何检测它是正常结帐还是订阅?

This is how I am separating now, but I think it's not recommended way.这就是我现在分开的方式,但我认为不推荐这种方式。

I am checking stripe_subscription_id and if exist, I considered it as subscription.我正在检查 stripe_subscription_id,如果存在,我将其视为订阅。

(charge.succeeded is called for subscription succeeded also) (charge.succeeded 也被称为订阅成功)

@api.route('/stripe/webhook', methods=['GET', 'POST'])
def webhook():
    event = None
    payload = request.data

    try:
        event = json.loads(payload)
    except Exception as e:
        print('Webhook error while parsing basic request.' + str(e))
    if not event:
        return jsonify({'status': 'failed'}), 400

    # one time payout
    if event['type'] == 'charge.succeeded':
        event_intent = event['data']['object']
        payment_intent = event_intent['payment_intent']
    # payment
    if event['type'] == 'checkout.session.completed':
        checkout_session = event['data']['object']

        stripe_subscription_id = checkout_session['subscription']
        # customer_email = checkout_session['customer_email']
        if stripe_subscription_id:
            # Create a new subscription and mark it as paid this month.
            customer_subscription_mark_paid(checkout_session['id'], stripe_subscription_id)
    elif event['type'] == 'invoice.paid':
        invoice = event['data']['object']
        stripe_subscription_id = invoice['subscription']
        if stripe_subscription_id:
            # Check if this is the first invoice or a later invoice in the
            # subscription lifecycle.
            first_invoice = invoice['billing_reason'] == 'subscription_create'

            # You already handle marking the first invoice as paid in the
            # `checkout.session.completed` handler.
            # Only use this for the 2nd invoice and later, so it doesn't conflict.
            if not first_invoice:
                # Mark the subscription as paid.
                customer_subscription_mark_paid(None, stripe_subscription_id)
    elif event['type'] == 'invoice.payment_failed':

        invoice = event['data']['object']
        stripe_subscription_id = invoice['subscription']

        if stripe_subscription_id:
            customer_subscription_mark_past_due(None, stripe_subscription_id)

Checking to see if the subscription field is filled is fine, but to be extra sure you can check the contents of the mode field .检查subscription字段是否已填写很好,但要特别确保您可以检查mode 字段的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM