'Flask database not updated after stripe webhook completed

this is my first time writing a flask project and I find it easy to understand. I am working on a subscription base project and I stumbled a problem that I cannot get my head around.

I really appreciate it if anyone can help. Thanks so much. Looking forward to your response.

@payments.route('/webhook', methods=['POST'])
def webhook_received():
    # You can use webhooks to receive information about asynchronous payment events.
    # For more about our webhook events check out https://stripe.com/docs/webhooks.
    webhook_secret = os.getenv('STRIPE_WEBHOOK_SECRET')
    request_data = json.loads(request.data)

    if webhook_secret:
        # Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
        signature = request.headers.get('stripe-signature')
        try:
            event = stripe.Webhook.construct_event(
                payload=request.data, sig_header=signature, secret=webhook_secret)
            data = event['data']
        except Exception as e:
            return e
        # Get the type of webhook event sent - used to check the status of PaymentIntents.
        event_type = event['type']
    else:
        data = request_data['data']
        event_type = request_data['type']
    data_object = data['object']

    print('event ' + event_type)

    if event_type == 'checkout.session.completed':
        # Handle the checkout.session.completed event
        session = data['data']['object']

        #find and update the user's subscription
        user = UserMixin.query.filter_by(username=current_user.username).first()
        user.subscriptionStatus = True
        user.stripe_customer_id = session['customer']
        user.subscriptionItem = session['subscription_items'][0]['price']['lookup_key']
        user.price = session['subscription_items'][0]['plan']['amount']
        if user.subscriptionItem == 'Starter':
            user.num_words = 20000
        elif user.subscriptionItem == 'Professional':   
            user.num_words = 50000
        db.session.commit()
        print('🔔 Payment succeeded!')

    return jsonify({'status': 'success'})


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source