Forums

stripe webhook not running in web app

Hi guys,

I'm trying to process payments in my web app with stripe. I've added a webhook in my app which seems to be connected with the app but not running anything inside the webhook. A snippet of my code is below:

@app.route('/stripe_pay')
def stripe_pay():
    session = stripe.checkout.Session.create(
        payment_method_types=['card','alipay'],
        line_items=[{
            'price': 'xxxxxxxxxxxxxxxxxxxxx',
            'quantity': 1,
        }],
        mode='payment',
        success_url=url_for('index_to_race', _external=True) + '?session_id={CHECKOUT_SESSION_ID}',
        cancel_url=url_for('index', _external=True),
    )
    return {
        'checkout_session_id': session['id'],
        'checkout_public_key': app.config['STRIPE_PUBLIC_KEY']
    }

@app.route('/stripe_webhook', methods=['POST'])
def stripe_webhook():
    print('WEBHOOK CALLED', flush = True)

    if request.content_length > 1024 * 1024:
        print('REQUEST TOO BIG')
        abort(400)
    payload = request.get_data()
    sig_header = request.environ.get('HTTP_STRIPE_SIGNATURE')
    endpoint_secret = 'xxxxxxxxxxxxx'
    event = None

    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, endpoint_secret
        )
        print(event['type'], flush = True)
    except ValueError as e:
        # Invalid payload
        print('INVALID PAYLOAD')
        return {}, 400
    except stripe.error.SignatureVerificationError as e:
        # Invalid signature
        print('INVALID SIGNATURE')
        return {}, 400
    print('adding user', flush=True)
    # Handle the checkout.session.completed event
    if event['type'] == 'checkout.session.completed':
        session = event['data']['object']
        print(session)
        line_items = stripe.checkout.Session.list_line_items(session['id'], limit=1)
        print(line_items['data'][0]['description'])
        print('adding user', flush=True)
        users(session['id'],request.environ.get('HTTP_X_REAL_IP', request.remote_addr))
    return {}

I have a stripe listener forwarding webhooks calls to my app which shows '200' responses:

2020-09-23 22:56:23 --> payment_intent.created [evt_1HUZOMC0E04hbWjX5LShpg6A] 2020-09-23 22:56:23 --> payment_intent.created [evt_1HUZONC0E04hbWjXvfLUHAMh] 2020-09-23 22:56:24 <-- [200] POST https://loperapjc.pythonanywhere.com/ [evt_1HUZOMC0E04hbWjX5LShpg6A] 2020-09-23 22:56:25 <-- [200] POST https://loperapjc.pythonanywhere.com/ [evt_1HUZONC0E04hbWjXvfLUHAMh] 2020-09-23 22:56:45 --> charge.succeeded [evt_1HUZOjC0E04hbWjXFdJHZYyJ] 2020-09-23 22:56:45 --> payment_method.attached [evt_1HUZOjC0E04hbWjXJj7iPyVG] 2020-09-23 22:56:45 --> customer.created [evt_1HUZOjC0E04hbWjXDMeknGyb] 2020-09-23 22:56:45 --> payment_intent.succeeded [evt_1HUZOjC0E04hbWjXNits3LDV] 2020-09-23 22:56:45 <-- [200] POST https://loperapjc.pythonanywhere.com/ [evt_1HUZOjC0E04hbWjXFdJHZYyJ] 2020-09-23 22:56:45 <-- [200] POST https://loperapjc.pythonanywhere.com/ [evt_1HUZOjC0E04hbWjXJj7iPyVG] 2020-09-23 22:56:46 --> checkout.session.completed [evt_1HUZOjC0E04hbWjXB8q5itkt] 2020-09-23 22:56:46 <-- [200] POST https://loperapjc.pythonanywhere.com/ [evt_1HUZOjC0E04hbWjXDMeknGyb] 2020-09-23 22:56:46 <-- [200] POST https://loperapjc.pythonanywhere.com/ [evt_1HUZOjC0E04hbWjXNits3LDV] 2020-09-23 22:56:46 <-- [200] POST https://loperapjc.pythonanywhere.com/ [evt_1HUZOjC0E04hbWjXB8q5itkt]

Still, nothing inside the webhook method is run. In my local machine all works fine... Could anyone give me a hand with this?.

Thanks,

Juan

If those log messages are correct, then you're posting to / on your site and not to /stripe_webhook, so that could be it. It could also be that You have another endpoint defined for /stripe_webhook that is getting the requests instead.

Cheers Glenn, I fixed the posting to /stripe_webhook and it's all working fine now.

I'm having a similar issue with webhooks with this code, webhooks are being sent to https://<user>.pythonanywhere.com/webhook, but nothing is sending to my broker app....any thoughts:

import json from flask import Flask, request import requests

client = Client(api_key=config.API_KEY, api_secret=config.API_SECRET)

app = Flask(name) WEBHOOK_PASSPHRASE = "xxxxxxx"

API_KEY = 'xxxxx' SECRET_KEY = 'xxxxxxxx' BASE_URL = "https://paper-api.alpaca.markets"

BASE_URL = "https://app.alpaca.markets"

ORDERS_URL = "{}/v2/orders".format(BASE_URL) HEADERS = {'APCA-API-KEY-ID': API_KEY, 'APCA-API-SECRET-KEY': SECRET_KEY}

@app.route('/') def welcome(): return "Why are you here? We are busy making money!"

@app.route('/webhook', methods=['POST']) def webhook(): data = json.loads(request.data) print(data) if data['PASSPHRASE'] != WEBHOOK_PASSPHRASE: return { "code": "error", "message": "Nice try, invalid passphrase" }

else:
    data = {
        "symbol": data['SYMBOL'].upper(),
        "qty": int(data['QTY']),
        "side": data['SIDE'].lower(),
        "type": "market",
        "time_in_force": "gtc",
        "order_class": "simple"
        # "take_profit": {
        #     "limit_price": data['close'] * 1.05
        # },
        # "stop_loss": {
        #     "stop_price": data['close'] * 0.98,
        # }
    }

    print(data)
    r = requests.post(ORDERS_URL, json=data, headers=HEADERS)

    response = json.loads(r.content)
    print(response)
    return {
        'webhook_message': data,
        'id': response['id'],
        'client_order_id': response['client_order_id']
    }

if name == 'main': app.run(host='0.0.0.0')

What do you see in your logs?

I also have the similar situation, where when I am running the app locally and doing a payment checkout session then I get results like this

Results Local 2024-08-29 23:17:38 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_3PtCuiFOEzKMsnzb1bjuJGOi] 2024-08-29 23:17:38 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_1PtCukFOEzKMsnzbldQdTdvX] 2024-08-29 23:17:38 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_1PtCukFOEzKMsnzbe7lYbdkB] 2024-08-29 23:17:38 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_1PtCukFOEzKMsnzb6HED0V1Z] 2024-08-29 23:17:38 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_1PtCulFOEzKMsnzbZ3GMOFEv] 2024-08-29 23:17:38 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_1PtCulFOEzKMsnzbsJThQreE] 2024-08-29 23:17:38 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_3PtCuiFOEzKMsnzb1R1BTeHe] 2024-08-29 23:17:38 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_3PtCuiFOEzKMsnzb1yVa7WIo] 2024-08-29 23:17:39 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_1PtCulFOEzKMsnzbQmUT7dGM] 2024-08-29 23:17:39 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_1PtCulFOEzKMsnzbfTdn9wil] 2024-08-29 23:17:39 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_1PtCulFOEzKMsnzbKWibLoZe] 2024-08-29 23:17:39 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_1PtCulFOEzKMsnzbBS7vl9Qq] 2024-08-29 23:17:39 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_1PtCulFOEzKMsnzbP8skY0rF] 2024-08-29 23:17:53 <-- [200] POST http://127.0.0.1:8000/stripe_webhook [evt_1PtCukFOEzKMsnzbI7Q3NvCo]

But when I try to setup on python anywhere I get error 401 like this

2024-08-29 23:22:52 --> charge.succeeded [evt_3PtCzxFOEzKMsnzb0oIWoYoK] 2024-08-29 23:22:52 --> payment_method.attached [evt_1PtCzzFOEzKMsnzb9ZwaL1kr] 2024-08-29 23:22:52 --> checkout.session.completed [evt_1PtCzzFOEzKMsnzbVihpGJC0] 2024-08-29 23:22:52 --> customer.created [evt_1PtCzzFOEzKMsnzb5JA96oWR] 2024-08-29 23:22:52 --> customer.updated [evt_1PtCzzFOEzKMsnzbNn2k2opy] 2024-08-29 23:22:52 --> customer.subscription.created [evt_1PtCzzFOEzKMsnzbOvr1LYEn] 2024-08-29 23:22:53 <-- [401] POST http://migurultd.pythonanywhere.com/stripe_webhook [evt_3PtCzxFOEzKMsnzb0oIWoYoK] 2024-08-29 23:22:53 <-- [401] POST http://migurultd.pythonanywhere.com/stripe_webhook [evt_1PtCzzFOEzKMsnzb9ZwaL1kr] 2024-08-29 23:22:53 <-- [401] POST http://migurultd.pythonanywhere.com/stripe_webhook [evt_1PtCzzFOEzKMsnzbVihpGJC0] 2024-08-29 23:22:53 --> customer.subscription.updated [evt_1PtCzzFOEzKMsnzb8bd9RsIQ] 2024-08-29 23:22:53 --> payment_intent.succeeded [evt_3PtCzxFOEzKMsnzb0Wbi1pyZ] 2024-08-29 23:22:53 <-- [401] POST http://migurultd.pythonanywhere.com/stripe_webhook [evt_1PtCzzFOEzKMsnzb5JA96oWR] 2024-08-29 23:22:53 --> payment_intent.created [evt_3PtCzxFOEzKMsnzb0er4AFVF] 2024-08-29 23:22:53 <-- [401] POST http://migurultd.pythonanywhere.com/stripe_webhook [evt_1PtCzzFOEzKMsnzbNn2k2opy] 2024-08-29 23:22:53 <-- [401] POST http://migurultd.pythonanywhere.com/stripe_webhook [evt_1PtCzzFOEzKMsnzbOvr1LYEn] 2024-08-29 23:22:53 <-- [401] POST http://migurultd.pythonanywhere.com/stripe_webhook [evt_1PtCzzFOEzKMsnzb8bd9RsIQ] 2024-08-29 23:22:53 --> invoice.created [evt_1PtCzzFOEzKMsnzbvfNfyUJt]

How do I fix this?

My current code for stripe webhook

def stripe_webhook(request):
    stripe.api_key = settings.STRIPE_SECRET_KEY
    time.sleep(10)
    payload = request.body
    signature_header = request.META['HTTP_STRIPE_SIGNATURE']
    event = None
    try:
        event = stripe.Webhook.construct_event(
            payload, signature_header, settings.STRIPE_WEBHOOK_SECRET
        )
    except ValueError as e:
        return HttpResponse(status=400)
    except stripe.error.SignatureVerificationError as e:
        return HttpResponse(status=400)
    if event['type'] == 'checkout.session.completed':
        session = event['data']['object']
        session_id = session.get('id', None)
        time.sleep(15)
    return HttpResponse(status=200)

That sounds like an authentication issue. I would double check that the STRIPE_WEBHOOK_SECRET is correct.