'Python Flask request.data returned different types when testing Stripe Webhook
I have the following code from Stripe Webhook test application:
@app.route('/webhook', methods=['POST'])
def webhook_received():
webhook_secret = 'whsec_...' # this is the "signing secret" of your webhook
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']
if event_type == 'checkout.session.completed':
print('🔔 Payment succeeded!')
return jsonify({'status': 'success'})
I am testing this using Stripe Cli on my localhost.
In the test application (Flask == 1.0.3, requests == 2.60.0, localhost:4242), the code works, and request.data is <class 'bytes'>. The json.loads(request.data) made it <class 'dict'>
However, in my application (Flask == 1.1.2, requests == 2.25.1, localhost:5000), request.data is <class 'dict'>. The stripe.Webhook.construct_event requires payload to be raw data, but when I tried to get the raw request body using request.get_data(), it threw a 400 error.
I literally copied and pasted the codes. the signing secret are the same in both applications.
This is driving me crazy. Has anyone ever had similar problem before? Any help would be greatly appreciated. Thank you all very much in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
