Files
vontor-cz/backend/thirdparty/stripe/client.py
Brunobrno c0bd24ee5e Refactor commerce models and enhance payment logic
Refactored commerce models to remove language prefixes from status choices, improved order and payment validation, and enforced business rules for payment and shipping combinations. Updated order item and cart calculations to use VAT-inclusive prices, added unique constraints and indexes to reviews, and improved stock management logic. Added new Stripe client methods for session and refund management, and updated Zasilkovna and Deutsche Post models for consistency. Minor fixes and improvements across related tasks, URLs, and configuration models.
2026-01-20 23:45:21 +01:00

178 lines
5.5 KiB
Python

import stripe
from django.conf import settings
import json
import os
FRONTEND_URL = os.getenv("FRONTEND_URL") if not settings.DEBUG else os.getenv("DEBUG_DOMAIN")
SSL = "https://" if os.getenv("USE_SSL") == "true" else "http://"
stripe.api_key = os.getenv("STRIPE_SECRET_KEY")
class StripeClient:
@staticmethod
def create_checkout_session(order):
"""
Vytvoří Stripe Checkout Session pro danou objednávku.
Args:
order (Order): Instance objednávky pro kterou se vytváří session.
Returns:
stripe.checkout.Session: Vytvořená Stripe Checkout Session.
"""
session = stripe.checkout.Session.create(
mode="payment",
payment_method_types=["card"],
success_url=f"{SSL}{FRONTEND_URL}/payment/success?order={order.id}", #jenom na grafickou část (webhook reálně ověří stav)
cancel_url=f"{SSL}{FRONTEND_URL}/payment/cancel?order={order.id}",
client_reference_id=str(order.id),
line_items=[{
"price_data": {
"currency": "czk",
"product_data": {
"name": f"Objednávka {order.id}",
},
"unit_amount": int(order.total_price * 100), # cena v haléřích
},
"quantity": 1,
}],
)
return session
@staticmethod
def cancel_checkout_session(session_id):
"""
Zruší Stripe Checkout Session.
Args:
session_id (str): ID Stripe Checkout Session k zrušení.
Returns:
stripe.checkout.Session: Zrušená Stripe Checkout Session.
"""
try:
session = stripe.checkout.Session.expire(session_id)
return session
except Exception as e:
return {"error": str(e)}
@staticmethod
def get_checkout_session(session_id):
"""
Získá informace o Stripe Checkout Session.
Args:
session_id (str): ID Stripe Checkout Session.
Returns:
stripe.checkout.Session: Stripe Checkout Session objekt.
"""
try:
session = stripe.checkout.Session.retrieve(session_id)
return session
except Exception as e:
return {"error": str(e)}
@staticmethod
def get_payment_intent(payment_intent_id):
"""
Získá informace o Stripe Payment Intent.
Args:
payment_intent_id (str): ID Stripe Payment Intent.
Returns:
stripe.PaymentIntent: Stripe Payment Intent objekt.
"""
try:
payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id)
return payment_intent
except Exception as e:
return {"error": str(e)}
@staticmethod
def refund_order(stripe_payment_intent):
"""
Vrátí platbu pro danou objednávku.
Args:
stripe_payment_intent (str): ID Stripe Payment Intent k vrácení.
Returns:
stripe.Refund: Vytvořený refund objekt nebo chyba.
"""
try:
refund = stripe.Refund.create(
payment_intent=stripe_payment_intent
)
return refund
except Exception as e:
return {"error": str(e)}
@staticmethod
def partial_refund_order(stripe_payment_intent, amount):
"""
Částečně vrátí platbu pro danou objednávku.
Args:
stripe_payment_intent (str): ID Stripe Payment Intent k vrácení.
amount (int): Částka k vrácení v haléřích.
Returns:
stripe.Refund: Vytvořený refund objekt nebo chyba.
"""
try:
refund = stripe.Refund.create(
payment_intent=stripe_payment_intent,
amount=amount
)
return refund
except Exception as e:
return {"error": str(e)}
@staticmethod
def create_customer(email, name=None, phone=None):
"""
Vytvoří Stripe Customer.
Args:
email (str): Email zákazníka.
name (str, optional): Jméno zákazníka.
phone (str, optional): Telefon zákazníka.
Returns:
stripe.Customer: Vytvořený Stripe Customer.
"""
try:
customer_data = {"email": email}
if name:
customer_data["name"] = name
if phone:
customer_data["phone"] = phone
customer = stripe.Customer.create(**customer_data)
return customer
except Exception as e:
return {"error": str(e)}
@staticmethod
def webhook_verify_signature(payload, sig_header, endpoint_secret):
"""
Ověří webhook signature od Stripe.
Args:
payload: Raw webhook payload.
sig_header: Stripe signature header.
endpoint_secret: Webhook endpoint secret.
Returns:
stripe.Event: Ověřený event objekt.
"""
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
return event
except ValueError as e:
return {"error": "Invalid payload"}
except stripe.error.SignatureVerificationError as e:
return {"error": "Invalid signature"}