stripe does not save if transaction is successful in flask

丶灬走出姿态 提交于 2020-07-10 07:01:37

问题


I am trying to save some information in database if transaction is successful, in the stripe_webhook view. But not successful. is it that data cannot be saved directly in webhook ? so frustrating for me. I checked online for sample codes but could not find the ones that insert or update database for successful transaction.

from site.models import Post, Chapter, Order
import stripe
from sqlalchemy import desc

@posts.route("/paynow")
@login_required
def paynow():
    return render_template('paynow.html',)
        


@posts.route('/stripe_pay')
@login_required
def stripe_pay():
    amt = 10000
    stripe.api_key = current_app.config['STRIPE_SECRET_KEY']
    session = stripe.checkout.Session.create(
        payment_method_types=['card'],
        line_items=[{
            'price_data': {
            'currency': 'usd',
            'product_data': {
            'name': 'T-shirt',
            },
            'unit_amount': amt,
            },
            'quantity': 1,
        }],
        mode='payment',
        success_url=url_for('posts.payment_success', _external=True) + '?session_id={CHECKOUT_SESSION_ID}',
        cancel_url=url_for('posts.paynow', _external=True),
    )
    return {
    'checkout_session_id': session['id'], 
    'checkout_public_key': current_app.config['STRIPE_PUBLIC_KEY']
    }




@posts.route('/stripe_webhook', methods=['POST'])
@login_required
def stripe_webhook():
    print('WEBHOOK CALLED')

    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 = 'whsec_*************************************'
    event = None

    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, endpoint_secret
        )
    except ValueError as e:
        # Invalid payload
        print('INVALID PAYLOAD')
        return {}, 400
    except stripe.error.SignatureVerificationError as e:
        # Invalid signature
        print('INVALID SIGNATURE')
        return {}, 400

    # 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'])
        # save to database if successful
        save_order = Order(trans_id = "pppppppppp")
        db.session.add(save_order)
        db.session.commit()
        


    return {}

@posts.route('/payment_success')
@login_required
def payment_success():
    cart=Cart.query.filter_by(username = current_user.username).all()
    cart.status = "paid"
    db.session.commit()
    return render_template('payment_success.html')

回答1:


According to the Stripe customer care, I must used a live domain instead of local host



来源:https://stackoverflow.com/questions/62733977/stripe-does-not-save-if-transaction-is-successful-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!