Belegnummern aus Order-Confirmation-Mails, Login-Cookies im Volume, Whop-Mails nicht mehr als manual. Chromium im Backend-Image. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Wd9aeH8MKgesfbsaS3kpnx
142 lines
5.3 KiB
Python
142 lines
5.3 KiB
Python
"""Whop-Ads-Belege per Browser-Roboter (Whop hat keine Rechnungs-API).
|
|
|
|
1. Belegnummern aus den "Order Confirmation"-Mails im Strato-Postfach ("Receipt XYZ" -> pay_XYZ)
|
|
2. Login bei Whop per Einmal-Code, den Whop an LOGIN_EMAIL schickt (landet im selben Postfach)
|
|
3. PDF über whop.com/api/receipt_pdf mit den Login-Cookies
|
|
|
|
Login-Cookies liegen in <storage>/.whop-state.json (nur NucBox-Volume, chmod 600), damit nicht jeder Lauf neu einloggt.
|
|
"""
|
|
|
|
import email
|
|
import os
|
|
import re
|
|
import time
|
|
from datetime import date
|
|
|
|
from backend.routers.emails import connect_imap, decode_hdr, parse_email_date
|
|
|
|
LOGIN_EMAIL = os.getenv("WHOP_LOGIN_EMAIL", "mkruse@c-stone-dev.com")
|
|
SENDER_DOMAINS = ("whop.com",) # deren Mails deckt der Roboter ab
|
|
FOLDERS = ("INBOX", "Archive", "Archive.2026", "Trash")
|
|
PDF_URL = "https://whop.com/api/receipt_pdf/?receiptId={}"
|
|
|
|
try:
|
|
import playwright # noqa: F401
|
|
ENABLED = os.getenv("WHOP_ROBOT", "1") == "1"
|
|
except ImportError:
|
|
ENABLED = False
|
|
|
|
|
|
def _text(msg) -> str:
|
|
parts = []
|
|
for p in msg.walk():
|
|
if p.get_content_type() in ("text/plain", "text/html"):
|
|
t = p.get_payload(decode=True).decode(p.get_content_charset() or "utf-8", "replace")
|
|
parts.append(re.sub(r"<[^>]+>", " ", re.sub(r"<style.*?</style>", "", t, flags=re.S)))
|
|
return re.sub(r"\s+", " ", " ".join(parts))
|
|
|
|
|
|
def parse_receipt(msg):
|
|
"""Order-Confirmation-Mail -> {pay_id, date, amount, sender} oder None."""
|
|
t = _text(msg)
|
|
r = re.search(r"Receipt\s+([A-Za-z0-9]{8,})", t)
|
|
if not r:
|
|
return None
|
|
a = re.search(r"Amount paid\s+\$?\s?([\d.,]+)", t)
|
|
d = parse_email_date(msg.get("Date", ""))
|
|
return {"pay_id": "pay_" + r[1], "date": d.replace(tzinfo=None) if d and d.tzinfo else d,
|
|
"amount": a[1] if a else "?", "sender": decode_hdr(msg.get("From", ""))}
|
|
|
|
|
|
def receipts(cfg: dict, since: date) -> list:
|
|
m = connect_imap(cfg["host"], cfg["port"], cfg["user"], cfg["password"])
|
|
out = {}
|
|
try:
|
|
for f in FOLDERS:
|
|
if m.select(f'"{f}"', readonly=True)[0] != "OK":
|
|
continue
|
|
for i in m.search(None, f'FROM "whop" SUBJECT "Order Confirmation" SINCE {since:%d-%b-%Y}')[1][0].split():
|
|
rec = parse_receipt(email.message_from_bytes(m.fetch(i, "(BODY.PEEK[])")[1][0][1]))
|
|
if rec:
|
|
out[rec["pay_id"]] = rec
|
|
finally:
|
|
m.logout()
|
|
return list(out.values())
|
|
|
|
|
|
def _code_ids(m) -> set:
|
|
m.select('"INBOX"', readonly=True)
|
|
return set(m.search(None, f'FROM "whop" SUBJECT "sign-in code" SINCE {date.today():%d-%b-%Y}')[1][0].split())
|
|
|
|
|
|
def _wait_code(cfg: dict, before: set) -> str:
|
|
# ponytail: Polling 2 Min; reicht, Whop-Codes kommen in Sekunden
|
|
for _ in range(24):
|
|
time.sleep(5)
|
|
m = connect_imap(cfg["host"], cfg["port"], cfg["user"], cfg["password"])
|
|
try:
|
|
new = sorted(_code_ids(m) - before, key=int)
|
|
if new:
|
|
subj = decode_hdr(email.message_from_bytes(
|
|
m.fetch(new[-1], "(BODY.PEEK[HEADER.FIELDS (SUBJECT)])")[1][0][1]).get("Subject", ""))
|
|
c = re.search(r"\b(\d{6})\b", subj)
|
|
if c:
|
|
return c[1]
|
|
finally:
|
|
m.logout()
|
|
raise RuntimeError("Whop: kein Login-Code im Postfach angekommen")
|
|
|
|
|
|
def _login(ctx, cfg: dict):
|
|
m = connect_imap(cfg["host"], cfg["port"], cfg["user"], cfg["password"])
|
|
try:
|
|
before = _code_ids(m)
|
|
finally:
|
|
m.logout()
|
|
pg = ctx.new_page()
|
|
pg.goto("https://whop.com/login/", wait_until="networkidle", timeout=60000)
|
|
for name in ("Alle ablehnen", "Reject all"): # Cookie-Banner datensparsam
|
|
b = pg.get_by_role("button", name=name)
|
|
if b.count():
|
|
b.first.click()
|
|
break
|
|
pg.fill("input[name=email]", LOGIN_EMAIL)
|
|
pg.get_by_role("button", name=re.compile("^(Weiter|Continue)$")).click()
|
|
pg.wait_for_selector("input[name=otp]", timeout=30000)
|
|
pg.fill("input[name=otp]", _wait_code(cfg, before))
|
|
pg.wait_for_url(lambda u: "/login" not in u, timeout=60000)
|
|
pg.close()
|
|
|
|
|
|
def fetch_pdfs(cfg: dict, pay_ids: list, state_path: str) -> dict:
|
|
"""-> {pay_id: pdf_bytes} für alle abrufbaren Belege. Loggt nur ein, wenn die gespeicherten Cookies nicht reichen."""
|
|
from playwright.sync_api import sync_playwright
|
|
|
|
out = {}
|
|
with sync_playwright() as p:
|
|
b = p.chromium.launch()
|
|
try:
|
|
ctx = b.new_context(locale="de-DE", storage_state=state_path if os.path.exists(state_path) else None)
|
|
|
|
def get(pid):
|
|
r = ctx.request.get(PDF_URL.format(pid), timeout=60000)
|
|
body = r.body() if r.ok else b""
|
|
return body if body.startswith(b"%PDF-") else None
|
|
|
|
first = get(pay_ids[0])
|
|
if first is None:
|
|
_login(ctx, cfg)
|
|
first = get(pay_ids[0])
|
|
if first is None:
|
|
raise RuntimeError("Whop: Login ok, aber kein PDF erhalten")
|
|
ctx.storage_state(path=state_path)
|
|
os.chmod(state_path, 0o600)
|
|
out[pay_ids[0]] = first
|
|
for pid in pay_ids[1:]:
|
|
pdf = get(pid)
|
|
if pdf:
|
|
out[pid] = pdf
|
|
time.sleep(1)
|
|
finally:
|
|
b.close()
|
|
return out
|