|
| 1 | +import datetime |
| 2 | + |
| 3 | +import stripe |
| 4 | +from flask import Blueprint, render_template, request, redirect, url_for |
| 5 | +from flask_login import login_required, current_user |
| 6 | + |
| 7 | +from auth import db |
| 8 | +from auth.models import User |
| 9 | +from auth.settings import config |
| 10 | + |
| 11 | +stripe.api_key = config['STRIPE_SECRET_KEY'] |
| 12 | +billing_blueprint = Blueprint("billing", __name__) |
| 13 | + |
| 14 | + |
| 15 | +def format_ts(value, format='%d-%m-%Y'): |
| 16 | + return datetime.datetime.utcfromtimestamp(value).strftime(format) |
| 17 | + |
| 18 | + |
| 19 | +@billing_blueprint.route('/account') |
| 20 | +@login_required |
| 21 | +def account_info(): |
| 22 | + subscription = None |
| 23 | + if current_user.stripe_subscription_id: |
| 24 | + subscription = stripe.Subscription.retrieve(current_user.stripe_subscription_id) |
| 25 | + return render_template('account-info.html', user=current_user, subscription=subscription) |
| 26 | + |
| 27 | + |
| 28 | +def handle_card_error(e: stripe.error.CardError): |
| 29 | + return str(e) |
| 30 | + |
| 31 | + |
| 32 | +@billing_blueprint.route('/account/sub/create', methods=['POST']) |
| 33 | +@login_required |
| 34 | +def create_subscription(): |
| 35 | + plan = request.form['plan'] |
| 36 | + customer = None |
| 37 | + if current_user.stripe_customer_id: |
| 38 | + customer = stripe.Customer.retrieve(current_user.stripe_customer_id) |
| 39 | + if not customer.deleted: |
| 40 | + customer.source = request.form['stripeToken'] |
| 41 | + try: |
| 42 | + customer.save() |
| 43 | + except stripe.error.CardError as e: |
| 44 | + return handle_card_error(e) |
| 45 | + else: |
| 46 | + customer = None |
| 47 | + if customer is None: |
| 48 | + try: |
| 49 | + customer = stripe.Customer.create( |
| 50 | + description=f"{current_user.name or '(no name)'} (#{current_user.id})", |
| 51 | + email=f"{current_user.email}", |
| 52 | + source=request.form['stripeToken'], |
| 53 | + metadata={ |
| 54 | + 'user_id': current_user.id, |
| 55 | + } |
| 56 | + ) |
| 57 | + except stripe.error.CardError as e: |
| 58 | + return handle_card_error(e) |
| 59 | + current_user.stripe_customer_id = customer.stripe_id |
| 60 | + start_date = None |
| 61 | + to_cancel = None |
| 62 | + if current_user.stripe_subscription_id: |
| 63 | + sub = stripe.Subscription.retrieve(current_user.stripe_subscription_id) |
| 64 | + if sub.status != "canceled": |
| 65 | + # In this case we have an active subscription and are changing the billing |
| 66 | + # frequency. We need to delete the old item and create a new one. |
| 67 | + to_cancel = sub |
| 68 | + start_date = sub.current_period_end |
| 69 | + try: |
| 70 | + sub = stripe.Subscription.create( |
| 71 | + customer=customer.stripe_id, |
| 72 | + items=[{"plan": plan}], |
| 73 | + trial_end=start_date, |
| 74 | + ) |
| 75 | + except stripe.error.CardError as e: |
| 76 | + return handle_card_error(e) |
| 77 | + current_user.stripe_subscription_id = sub.stripe_id |
| 78 | + current_user.subscription_expiry = datetime.datetime.utcfromtimestamp(sub.current_period_end).replace(tzinfo=datetime.timezone.utc) + datetime.timedelta(days=1) |
| 79 | + db.session.commit() |
| 80 | + if to_cancel: |
| 81 | + to_cancel.delete() |
| 82 | + return redirect(url_for('.account_info')) |
| 83 | + |
| 84 | + |
| 85 | +@billing_blueprint.route('/account/sub/delete', methods=["POST"]) |
| 86 | +def cancel_subscription(): |
| 87 | + sub = stripe.Subscription.retrieve(current_user.stripe_subscription_id) |
| 88 | + sub.delete(at_period_end=True) |
| 89 | + return redirect(url_for('.account_info')) |
| 90 | + |
| 91 | + |
| 92 | +@billing_blueprint.route('/stripe/event', methods=["POST"]) |
| 93 | +def stripe_event(): |
| 94 | + payload = request.data |
| 95 | + signature = request.headers['Stripe-Signature'] |
| 96 | + try: |
| 97 | + event = stripe.Webhook.construct_event(payload, signature, config['STRIPE_WEBHOOK_KEY']) |
| 98 | + except ValueError: |
| 99 | + return '???', 400 |
| 100 | + except stripe.error.SignatureVerificationError: |
| 101 | + return 'signature verification failed', 400 |
| 102 | + |
| 103 | + if event.type == "invoice.payment_succeeded": |
| 104 | + # try and figure out if we care about this. |
| 105 | + results = [] |
| 106 | + for line in event.data.object.lines.data: |
| 107 | + if line.subscription: |
| 108 | + user = User.query.filter_by(stripe_subscription_id=line.subscription).one_or_none() |
| 109 | + if user is not None: |
| 110 | + user.subscription_expiry = datetime.datetime.utcfromtimestamp(line.period.end) + datetime.timedelta(days=1) |
| 111 | + db.session.commit() |
| 112 | + results.append(f"Set expiry date for user #{user.id} to {user.subscription_expiry}.") |
| 113 | + return '\n'.join(results) |
| 114 | + elif event.type == "customer.subscription.deleted": |
| 115 | + user = User.query.filter_by(stripe_subscription_id=event.data.object.id).one_or_none() |
| 116 | + if user is not None: |
| 117 | + user.subscription_expiry = None |
| 118 | + db.session.commit() |
| 119 | + return f'Terminated subscription for user #{user.id}.' |
| 120 | + |
| 121 | + return '' |
| 122 | + |
| 123 | + |
| 124 | +def init_app(app, prefix='/'): |
| 125 | + app.register_blueprint(billing_blueprint, url_prefix=prefix) |
| 126 | + app.jinja_env.filters['format_ts'] = format_ts |
| 127 | + app.extensions['csrf'].exempt(stripe_event) |
0 commit comments