[Python] Stripe payment webhook is not working with python

Discussão em 'Python' iniciado por Stack, Maio 15, 2025.

  1. Stack

    Stack Membro Participativo

    I am succesfully listening stripe and payment_intent.succeeded is working, but when i try to take it with my code to update user_status my webhook function is not working. Code is below, do you have any idea?

    import os
    from flask import Flask, request, Blueprint
    import stripe
    from extensions import csrf
    import logging


    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    payment_bp = Blueprint('payment', __name__)

    stripe.api_key = os.environ.get('STRIPE_SECRET_KEY')
    webhook_secret = os.environ.get('STRIPE_WEBHOOK_SECRET')


    @payment_bp.route('/webhook', methods=['POST'])
    @csrf.exempt
    def webhook():
    logger.info(f"STRIPE_SECRET_KEY loaded: {'Yes' if stripe.api_key else 'No'}")
    logger.info(f"STRIPE_WEBHOOK_SECRET loaded: {'Yes' if webhook_secret else 'No'}")
    logger.info("Webhook endpoint hit by a request.")

    payload = request.data
    sig_header = request.headers.get('Stripe-Signature')

    if not webhook_secret:
    logger.error("Stripe webhook secret is not set. Cannot process webhook.")
    return "Webhook secret not configured", 500

    try:
    event = stripe.Webhook.construct_event(
    payload, sig_header, webhook_secret
    )
    logger.info(f"Stripe event constructed successfully: {event['type']}")
    except ValueError as e:
    # Invalid payload
    logger.error(f"Invalid payload: {e}")
    return '', 400
    except stripe.error.SignatureVerificationError as e:
    # Invalid signature
    logger.error(f"Invalid signature: {e}")
    return '', 400
    except Exception as e:
    logger.error(f"An unexpected error occurred in webhook: {e}")
    return '', 500

    if event['type'] == 'payment_intent.succeeded':
    logger.info("PaymentIntent succeeded event received.")

    return '', 200``

    Continue reading...

Compartilhe esta Página