#Jason - Webhooks

1 messages · Page 1 of 1 (latest)

grim osprey
#

HI 👋

#

Have you tried getting our Quickstart code running and then modify from there?

#

Our Python example uses Flask too

unique sparrow
#

Thank you I will try that.

grim osprey
#

Just be sure to swap out the endpoint_secret value for your actual webhook. If you are using the stripe listen command to forward webhooks to your local machine it'll be in the terminal where you run the stripe listen command.

#

Otherwise you can find it in the Dashboard

unique sparrow
#

So I just tried swapping the endpoint secret and made sure it was to the route I got stripe CLI to listen to. It still doesn't work.

grim osprey
#

Can you share a failed event ID? They start with evt_

unique sparrow
#

[evt_3LcdkpHwOsUKibMs06iOUYbO]

grim osprey
#

I see two webhook endpoints both of which returned success responses

unique sparrow
#

I see [400] POST

grim osprey
#

Where?

unique sparrow
#

in the stripe CLI where it was listening

grim osprey
#

What message is returned?

unique sparrow
grim osprey
#

There should be an exception message being thrown somewhere. What do the logs for the Flask app show?

unique sparrow
#

127.0.0.1 - - [30/Aug/2022 19:22:02] "POST /webhook HTTP/1.1" 400 -

grim osprey
#

Try running flask with the --debug flag and see if you get more verbose exception logging

unique sparrow
#

I put debug=True in app.run is that the same thing?

grim osprey
#

You should see more verbose logging of exceptions and the print() statements in the code being written out to the terminal

#

Line 27: print(':warning: Webhook error while parsing basic request.' + str(e))
Line 38: print(':warning: Webhook signature verification failed.' + str(e))

Otherwise code execution would reach line 55 return jsonify(success=True)

unique sparrow
#

yeah I'm not getting anything like that I have that code in there

grim osprey
#

try adding some more print() statements. One at the very start of the function, before event = None. Another one in the try: block. These will tell us if code execution is reaching those parts

unique sparrow
#

I just tried that and nothing new came into the terminal

grim osprey
#

that suggests your webhook is not being reached or the webhook function is not being called.

#

Can you share both the syntax of the command you use to start the flask app and the Stripe CLI listen command?

unique sparrow
#

stripe CLI: stripe listen --forward-to localhost:4000/webhook

#

flask: if name == "main":
app.run(debug=True, port=4000)

grim osprey
#

Don't you mean
if __name__ == "__main__":?

#

You should see the following when you start it up. Is this what you are seeing?

 python webhook.py
 * Serving Flask app 'webhook'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:4000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 446-954-647
unique sparrow
#

yep I have that, the underscores were deleted when i pasted it into discord for some reason

grim osprey
#

Okay I just copied/pasted the same Python code and added

if __name__ == "__main__":
    app.run(port=4200, debug=True)

to the bottom of the file.
Then I run it and get the following output (including a success response for charge.succeeded):

python webhook.py
 * Serving Flask app 'webhook'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:4200
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 446-954-647
Unhandled event type charge.succeeded
127.0.0.1 - - [30/Aug/2022 16:51:18] "POST /webhook HTTP/1.1" 200 -
#

I start my listener with stripe listen -l --forward-to localhost:4200/webhook
and copy/paste the whsec_XXXXX into the endpoint_secret = 'whsec...' section

#

When I use the right Endpoint Secret I get a success message. When I mangle the endpoint secret I get this warning but it still returns a success:
:warning: Webhook signature verification failed.No signatures found matching the expected signature for payload

#

Can you share your webhook() function, including the @app.route() decorator?

unique sparrow
#

@app.route("/webhook", methods=["POST"])
def webhook():
print("!!!!!!!!!!!!!!!!")
event = None
payload = request.data

try:
    print("!!!!!!!!!111")
    event = json.loads(payload)
except:
    print('⚠️  Webhook error while parsing basic request.' + str(e))
    return jsonify(success=False)
if endpoint_secret:
    # Only verify the event if there is an endpoint secret defined
    # Otherwise use the basic event deserialized with json
    sig_header = request.headers.get('stripe-signature')
    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, endpoint_secret
        )
    except stripe.error.SignatureVerificationError as e:
        print('⚠️  Webhook signature verification failed.' + str(e))
        return jsonify(success=False)

# Handle the event
if event and event['type'] == 'charge.succeeded':
    charge = event['data']['object']  # contains a stripe.PaymentIntent
    print('Payment for {} succeeded'.format(payment_intent['amount']))
    # Then define and call a method to handle the successful payment intent.
    # handle_payment_intent_succeeded(payment_intent)
else:
    # Unexpected event type
    print('Unhandled event type {}'.format(event['type']))

return jsonify(success=True)
grim osprey
#

You can format your text as code by placing it between three ` marks - FYI

unique sparrow
#

oh thanks

grim osprey
#

But yeah, that's the same code I'm running

#

Try adding this to your Python file:

@app.route('/', methods=['GET'])
def hello():
    return jsonify({'msg': 'Hello World'})
#

The call it with curl http://localhost:4000

#

I'm wondering if that port is occupied

unique sparrow
#

Nope, the status code was 200 when I ran that

grim osprey
#

Okay so Flask isn't entirely broken.

#

Okay so how are you calling your server.py file in the terminal?

unique sparrow
#

''' & C:/Users/jason/AppData/Local/Microsoft/WindowsApps/python3.10.exe "c:/Users/jason/Desktop/ecommerce/ecommerce website (stripe API)/main.py" '''

#

this is what VS Code puts in when I run it from there

grim osprey
#

And do you see the output starting like this?

  • Serving Flask app 'webhook'
  • Debug mode: on
unique sparrow
#

essentially yeah, I see (lazy loading) after the file name as well