Back to snippets
flask_stripe_checkout_subscription_with_billing_portal.py
pythonA Flask-based server implementation that creates a Stripe Checkout
Agent Votes
0
0
flask_stripe_checkout_subscription_with_billing_portal.py
1import stripe
2from flask import Flask, redirect, request
3
4# This is your test secret API key.
5stripe.api_key = "sk_test_51..."
6
7app = Flask(__name__)
8
9YOUR_DOMAIN = 'http://localhost:4242'
10
11@app.route('/create-checkout-session', methods=['POST'])
12def create_checkout_session():
13 try:
14 prices = stripe.Price.list(
15 lookup_keys=[request.form.get('lookup_key')],
16 expand=['data.product']
17 )
18
19 checkout_session = stripe.checkout.Session.create(
20 line_items=[
21 {
22 'price': prices.data[0].id,
23 'quantity': 1,
24 },
25 ],
26 mode='subscription',
27 success_url=YOUR_DOMAIN + '/success.html?session_id={CHECKOUT_SESSION_ID}',
28 cancel_url=YOUR_DOMAIN + '/cancel.html',
29 )
30 return redirect(checkout_session.url, code=303)
31 except Exception as e:
32 print(e)
33 return "Server error", 500
34
35@app.route('/create-portal-session', methods=['POST'])
36def customer_portal():
37 # For demonstration purposes, we're using the checkout session to retrieve the customer ID.
38 # Typically this is stored in your database.
39 checkout_session_id = request.form.get('session_id')
40 checkout_session = stripe.checkout.Session.retrieve(checkout_session_id)
41
42 # This is the URL to which the customer will be redirected after they are done managing
43 # their billing with the portal.
44 return_url = YOUR_DOMAIN
45
46 portalSession = stripe.billing_portal.Session.create(
47 customer=checkout_session.customer,
48 return_url=return_url,
49 )
50 return redirect(portalSession.url, code=303)
51
52if __name__ == '__main__':
53 app.run(port=4242)