Spaces:
Sleeping
Sleeping
| import os | |
| import stripe | |
| import smtplib | |
| from email.mime.text import MIMEText | |
| from storage import create_license_key | |
| stripe.api_key = os.environ.get("STRIPE_SECRET_KEY") | |
| WEBHOOK_SECRET = os.environ.get("STRIPE_WEBHOOK_SECRET") | |
| GMAIL_USER = os.environ.get("GMAIL_USER") | |
| GMAIL_PASS = os.environ.get("GMAIL_APP_PASS") | |
| SPACE_URL = os.environ.get("SPACE_URL", "https://huggingface.co/spaces") # nastav jako secret | |
| PLAN_MAP = { | |
| os.environ.get("STRIPE_PRICE_SINGLE"): "single", | |
| os.environ.get("STRIPE_PRICE_PRO"): "pro", | |
| } | |
| def send_license_email(to_email: str, key: str, plan: str): | |
| if not GMAIL_USER or not GMAIL_PASS: | |
| print("Gmail není nakonfigurován — email neodeslán.") | |
| return | |
| plan_label = "Pro (neomezený)" if plan == "pro" else "Jednorázová analýza" | |
| body = f"""Ahoj! | |
| Děkujeme za nákup ResumeLens AI — {plan_label}. | |
| Tvůj licenční klíč: | |
| {key} | |
| Jak ho použít: | |
| 1. Jdi na {SPACE_URL} | |
| 2. Rozbal sekci "Máš Pro licenci? Zadej klíč" | |
| 3. Vlož svůj klíč a klikni Analyzovat | |
| Klíč je aktivní okamžitě. | |
| Při jakémkoliv problému odpověz na tento email. | |
| — ResumeLens AI | |
| """ | |
| msg = MIMEText(body, "plain", "utf-8") | |
| msg["Subject"] = "Tvůj ResumeLens AI klíč 🎯" | |
| msg["From"] = GMAIL_USER | |
| msg["To"] = to_email | |
| try: | |
| with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server: | |
| server.login(GMAIL_USER, GMAIL_PASS) | |
| server.send_message(msg) | |
| print(f"Email odeslán na {to_email}") | |
| except Exception as e: | |
| print(f"Chyba emailu: {e}") | |
| def handle_stripe_webhook(payload: bytes, sig_header: str) -> dict: | |
| try: | |
| event = stripe.Webhook.construct_event(payload, sig_header, WEBHOOK_SECRET) | |
| except stripe.error.SignatureVerificationError as e: | |
| return {"ok": False, "error": f"Neplatný podpis: {e}"} | |
| except Exception as e: | |
| return {"ok": False, "error": str(e)} | |
| if event["type"] == "checkout.session.completed": | |
| session = event["data"]["object"] | |
| email = session.get("customer_details", {}).get("email", "unknown") | |
| price_id = None | |
| try: | |
| line_items = stripe.checkout.Session.list_line_items(session["id"]) | |
| if line_items.data: | |
| price_id = line_items.data[0].price.id | |
| except Exception: | |
| pass | |
| plan = PLAN_MAP.get(price_id, "single") | |
| key = create_license_key(email, plan) | |
| send_license_email(email, key, plan) | |
| return {"ok": True, "key": key, "email": email, "plan": plan} | |
| return {"ok": True, "key": None, "email": None} |