我试图保存一些信息在数据库中,如果事务成功,在stripe\u webhook视图。但并不成功。是不是数据不能直接保存在webhook中?真让我沮丧。我在线查看了示例代码,但找不到为成功事务插入或更新数据库的代码。
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条答案
按热度按时间s4chpxco1#
根据客户关怀,我必须使用一个活域而不是本地主机