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?