Files
gander/web_server/blueprints/stripe.py
Christopher Ahern 2758be8680
Some checks are pending
CI / build (3.10) (push) Waiting to run
CI / build (3.8) (push) Waiting to run
CI / build (3.9) (push) Waiting to run
Fix/pylint cleanup (#8)
* Fix pylint warnings across all 24 Python files in web_server

- Add module, class, and function docstrings (C0114, C0115, C0116)
- Fix import ordering: stdlib before third-party before local (C0411)
- Replace wildcard imports with explicit named imports (W0401)
- Remove trailing whitespace and add missing final newlines (C0303, C0304)
- Replace dict() with dict literals (R1735)
- Remove unused imports and variables (W0611, W0612)
- Narrow broad Exception catches to specific exceptions (W0718)
- Replace f-string logging with lazy % formatting (W1203)
- Fix variable naming: UPPER_CASE for constants, snake_case for locals (C0103)
- Add pylint disable comments for necessary global statements (W0603)
- Fix no-else-return, simplifiable-if-expression, singleton-comparison
- Fix bad indentation in stripe.py (W0311)
- Add encoding="utf-8" to open() calls (W1514)
- Add check=True to subprocess.run() calls (W1510)
- Register Celery task modules via conf.include

* Update `package-lock.json` add peer dependencies
2026-02-07 20:57:28 +00:00

94 lines
2.7 KiB
Python

"""Stripe payment integration blueprint."""
import os
from flask import Blueprint, request, jsonify, session as s
from blueprints.middleware import login_required
from utils.user_utils import subscribe
import stripe
stripe_bp = Blueprint("stripe", __name__)
stripe.api_key = os.getenv("STRIPE_SECRET_KEY")
endpoint_secret = os.getenv("STRIPE_ENDPOINT_SECRET")
subscription = os.getenv("GANDER_SUBSCRIPTION")
@login_required
@stripe_bp.route('/create-checkout-session', methods=['POST'])
def create_checkout_session():
"""
Creates the stripe checkout session
"""
try:
# Checks to see who is subscribing to who
user_id = s.get("user_id")
streamer_id = request.args.get("streamer_id")
checkout_session = stripe.checkout.Session.create(
ui_mode = 'embedded',
payment_method_types=['card'],
line_items=[
{
'price': 'price_1QtGVsQoce1zhaP3csrztOoh',
'quantity': 1,
},
],
mode='subscription',
redirect_on_completion = 'never',
client_reference_id = f"{user_id}-{streamer_id}"
)
except (ValueError, TypeError, KeyError) as e:
return str(e), 500
return jsonify(clientSecret=checkout_session.client_secret)
@stripe_bp.route('/session-status') # check for payment status
def session_status():
"""
Used to query payment status
"""
checkout_session = stripe.checkout.Session.retrieve(
request.args.get('session_id')
)
return jsonify(
status=checkout_session.status,
customer_email=checkout_session.customer_details.email
)
@stripe_bp.route('/stripe/webhook', methods=['POST'])
def stripe_webhook():
"""
Webhook for handling stripe payments
"""
event = None
payload = request.data
sig_header = request.headers['STRIPE_SIGNATURE']
# Verifies signature is from Stripe
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
except ValueError as e:
raise e
except stripe.error.SignatureVerificationError as e:
raise e
# Handles payment success webhook
if event['type'] == "checkout.session.completed":
checkout_session = event['data']['object']
product_id = stripe.checkout.Session.list_line_items(
checkout_session['id']
)['data'][0]['price']['product']
if product_id == subscription:
client_reference_id = checkout_session.get(
"client_reference_id"
)
user_id, streamer_id = map(
int, client_reference_id.split("-")
)
subscribe(user_id, streamer_id)
return "Success", 200