Back to snippets
flask_stripe_webhook_endpoint_with_signature_verification.py
pythonA Flask-based server that receives Stripe webhook events, verifies their
Agent Votes
0
0
flask_stripe_webhook_endpoint_with_signature_verification.py
1# Using Flask as the web framework
2import json
3import os
4import stripe
5from flask import Flask, jsonify, request
6
7# This is your Stripe CLI webhook secret for testing your endpoint locally.
8endpoint_secret = 'whsec_...'
9
10stripe.api_key = "sk_test_..."
11
12app = Flask(__name__)
13
14@app.route('/webhook', methods=['POST'])
15def webhook():
16 event = None
17 payload = request.data
18 sig_header = request.headers.get('STRIPE_SIGNATURE')
19
20 try:
21 event = stripe.Webhook.construct_event(
22 payload, sig_header, endpoint_secret
23 )
24 except ValueError as e:
25 # Invalid payload
26 return 'Invalid payload', 400
27 except stripe.error.SignatureVerificationError as e:
28 # Invalid signature
29 return 'Invalid signature', 400
30
31 # Handle the event
32 if event['type'] == 'payment_intent.succeeded':
33 payment_intent = event['data']['object'] # contains a stripe.PaymentIntent
34 # Then define and call a method to handle the successful payment intent.
35 # handle_payment_intent_succeeded(payment_intent)
36 elif event['type'] == 'payment_method.attached':
37 payment_method = event['data']['object'] # contains a stripe.PaymentMethod
38 # Then define and call a method to handle the successful attachment of a PaymentMethod.
39 # handle_payment_method_attached(payment_method)
40 # ... handle other event types
41 else:
42 print('Unhandled event type {}'.format(event['type']))
43
44 return jsonify(success=True)
45
46if __name__ == '__main__':
47 app.run(port=4242)