API e Integración Acceso Libre 20 Feb, 2026

Script: Verificación de Stripe webhooks en Python

Implementación completa de verificación de webhooks de Stripe con manejo de replay attacks, logging y procesamiento de eventos comunes.

#stripe #webhooks #pagos #seguridad #python

Contenido

Stripe Webhooks: Implementación Segura

Verificación de firma

import stripe
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import logging

logger = logging.getLogger(__name__)
stripe.api_key = settings.STRIPE_SECRET_KEY

@csrf_exempt
def stripe_webhook(request):
    payload = request.body
    sig_header = request.META.get('HTTP_STRIPE_SIGNATURE', '')

    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, settings.STRIPE_WEBHOOK_SECRET
        )
    except ValueError:
        logger.error("Invalid payload")
        return HttpResponse(status=400)
    except stripe.error.SignatureVerificationError:
        logger.error("Invalid signature")
        return HttpResponse(status=400)

    # Procesar eventos
    handlers = {
        'checkout.session.completed': handle_checkout,
        'customer.subscription.created': handle_subscription_created,
        'customer.subscription.updated': handle_subscription_updated,
        'customer.subscription.deleted': handle_subscription_deleted,
        'invoice.payment_failed': handle_payment_failed,
    }

    handler = handlers.get(event['type'])
    if handler:
        try:
            handler(event['data']['object'])
        except Exception as e:
            logger.exception(f"Error handling {event['type']}: {e}")
            return HttpResponse(status=500)
    else:
        logger.info(f"Unhandled event type: {event['type']}")

    return HttpResponse(status=200)

def handle_checkout(session):
    user_id = session['metadata'].get('user_id')
    subscription_id = session.get('subscription')
    customer_id = session.get('customer')
    logger.info(f"Checkout completed for user {user_id}")

Testing con Stripe CLI

stripe listen --forward-to localhost:8000/webhook/
stripe trigger checkout.session.completed

Recurso Externo

Este recurso incluye un enlace externo. Regístrate para acceder.

Inicia Sesión para Acceder

Únete a la Comunidad

Regístrate gratis para descargar archivos, guardar recursos en favoritos, ganar XP y acceder a cursos y el foro de la comunidad.

¿Ya tienes cuenta? Inicia sesión

Erik Taveras

Autor

Erik Taveras

Recursos Relacionados