Download app.py from bxm0121/opllplus: direct link, hf CLI and curl.
- Browser
- Download file 125 kB
-
https://huggingface.co/spaces/bxm0121/opllplus/resolve/main/app.py
- Command line
-
hf download hf://spaces/bxm0121/opllplus/app.py
-
curl -L -o app.py https://huggingface.co/spaces/bxm0121/opllplus/resolve/main/app.py
125 kB
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import os
import re
import secrets
import shutil
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path
from urllib.parse import quote, unquote, urlencode, urlparse, urlsplit
from urllib.request import Request, urlopen
from flask import Flask, jsonify, redirect, render_template, request
def _load_local_env() -> None:
"""Load local deployment values without overwriting process variables."""
for filename in (".env", ".env.local"):
path = Path(__file__).resolve().parent / filename
if not path.is_file():
continue
try:
lines = path.read_text(encoding="utf-8").splitlines()
except OSError:
continue
for raw in lines:
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
name, value = line.split("=", 1)
name = name.strip()
value = value.strip().strip('"').strip("'")
if name and name not in os.environ:
os.environ[name] = value
_load_local_env()
# Worker stdout is parsed as UTF-8 JSON. Force child interpreters away from
# the Windows console code page so currency symbols remain serializable.
os.environ["PYTHONIOENCODING"] = "utf-8"
os.environ["PYTHONUTF8"] = "1"
async def sentinel_headers(
proxy: str = "",
action: str = "",
device_id: str = "",
did: str = "",
) -> dict[str, str]:
"""Return deployment-provided Sentinel headers, if configured.
The sanitized bundle does not contain a Sentinel token provider. Keeping
the hook asynchronous preserves the protocol worker contract while letting
an upstream deployment inject its own provider without embedding tokens.
"""
return {}
ROOT = Path(__file__).resolve().parent
app = Flask(__name__, template_folder="templates", static_folder="static")
app.json.ensure_ascii = False
REG_SESSION_SECRET = os.getenv("REG_SESSION_SECRET", "").strip()
REG_SESSION_COOKIE = os.getenv("REG_SESSION_COOKIE", "reg_access").strip() or "reg_access"
REG_INTERNAL_BASE = os.getenv("REG_INTERNAL_BASE", "http://127.0.0.1:18081").strip().rstrip("/")
PH_SHORT_BRIDGE_KEY = os.getenv("PH_SHORT_BRIDGE_KEY", "").strip()
JOB_TTL_SECONDS = max(1800, int(os.getenv("PH_PORTAL_JOB_TTL", "86400")))
MAX_JOBS = max(20, min(500, int(os.getenv("PH_PORTAL_MAX_JOBS", "120"))))
HARD_MAX_BATCH_CONCURRENCY = 200
MAX_BATCH_CONCURRENCY = max(
1,
min(
HARD_MAX_BATCH_CONCURRENCY,
int(os.getenv("PH_PORTAL_MAX_BATCH_CONCURRENCY", str(HARD_MAX_BATCH_CONCURRENCY))),
),
)
FLOW_JOB_CACHE_LIMIT = max(100, MAX_BATCH_CONCURRENCY)
def _resolve_helper_python() -> str:
configured = os.getenv("PAY153_PYTHON", "").strip()
candidates = [configured] if configured else []
# The sanitized bundle is also run directly on Windows. Prefer the
# workspace environment when it contains the helper dependencies, then
# fall back to the bundle environment and the current interpreter.
candidates.extend([
"/opt/pay153/venv/bin/python",
str(ROOT / ".venv" / "Scripts" / "python.exe"),
str(ROOT / ".venv" / "bin" / "python"),
str(ROOT.parent / ".venv" / "Scripts" / "python.exe"),
str(ROOT.parent / ".venv" / "bin" / "python"),
sys.executable,
])
seen = set()
for candidate in candidates:
value = str(candidate or "").strip()
if not value or value in seen:
continue
seen.add(value)
if Path(value).is_file() or shutil.which(value):
return value
return configured or sys.executable
PAY153_PYTHON = _resolve_helper_python()
PAY153_INTERNAL_BASE = os.getenv("PAY153_INTERNAL_BASE", "http://127.0.0.1:18096").strip().rstrip("/")
PAY153_INTERNAL_KEY = os.getenv("PAY153_INTERNAL_KEY", "").strip()
# Stripe publishable keys are public client configuration. This value was
# confirmed from the successful local HAR and avoids requiring PAY153 merely
# to initialize Stripe.js after payment_method returned a SetupIntent.
CARD_BIND_PUBLISHABLE_KEY = os.getenv(
"CARD_BIND_PUBLISHABLE_KEY",
"pk_live_51HOrSwC6h1nxGoI3lTAgRjYVrz4dU3fVOabyCcKR3pbEJguCVAlqCxdxCUvoRh1XWwRacViovU3kLKvpkjh7IqkW00iXQsjo3n",
).strip()
CARD_BIND_PROXY_REUSE_ATTEMPTS = max(
1, min(10, int(os.getenv("CARD_BIND_PROXY_REUSE_ATTEMPTS", "3")))
)
SET_DEFAULT_HELPER_TIMEOUT_SECONDS = max(
30, min(900, int(os.getenv("SET_DEFAULT_HELPER_TIMEOUT_SECONDS", "360")))
)
PROTOCOL_HELPER = str(ROOT / "ph_checkout_protocol.py")
CARD_BIND_HELPER = str(ROOT / "card_bind_session.py")
CARD_DEFAULT_HELPER = str(ROOT / "card_set_default.py")
CARD_CHECKOUT_CONTEXT_HELPER = str(ROOT / "card_checkout_context.py")
CARD_SERVER_TOKEN_HELPER = str(ROOT / "server_confirmation_token.py")
STANDALONE_PAY_HELPER = str(ROOT / "standalone_protocol_pay.py")
LOCAL_CHECKOUT_HELPER = str(ROOT / "local_checkout_bridge.py")
CHECKOUT_CONTEXT_PATH = ROOT / "data" / "checkout_contexts.jsonl"
PROXY_PREFLIGHT_HELPER = str(ROOT / "proxy_preflight.py")
CARD_BIND_ACCOUNT_EMAIL = os.getenv("CARD_BIND_ACCOUNT_EMAIL", "gosulasathish7420@gmail.com").strip().lower()
_jobs: dict[str, dict] = {}
_protocol_pay_jobs: dict[str, dict] = {}
_card_checkout_jobs: dict[str, dict] = {}
_unified_flow_jobs: dict[str, dict] = {}
_key_probe_jobs: dict[str, dict] = {}
_lock = threading.RLock()
_external_at_lock = threading.Lock()
class PrefixMiddleware:
def __init__(self, wrapped):
self.wrapped = wrapped
def __call__(self, environ, start_response):
prefix = str(environ.get("HTTP_X_SCRIPT_NAME") or "").rstrip("/")
if prefix:
path = str(environ.get("PATH_INFO") or "/")
if path == prefix:
path = "/"
elif path.startswith(prefix + "/"):
path = path[len(prefix):]
environ["SCRIPT_NAME"] = prefix
environ["PATH_INFO"] = path
return self.wrapped(environ, start_response)
app.wsgi_app = PrefixMiddleware(app.wsgi_app)
def shared_reg_session_valid() -> bool:
if not REG_SESSION_SECRET:
return True
expected = hmac.new(
REG_SESSION_SECRET.encode("utf-8"),
b"register-console-access",
hashlib.sha256,
).hexdigest()
provided = str(request.cookies.get(REG_SESSION_COOKIE) or "")
return bool(provided and hmac.compare_digest(provided, expected))
@app.before_request
def require_shared_reg_session():
public_mount = request.script_root in {"/card-link", "/protocol-pay"}
public_exact = {
"/",
"/card-flow/",
"/card-long/",
"/protocol-pay/",
"/api/card-bind/config",
"/api/card-bind/session",
"/api/card-bind/default",
"/api/card-flow/quick-checkout",
"/api/unified-flow/jobs",
"/static/card-flow.css",
"/static/card-flow.js",
"/api/protocol-pay/jobs",
"/api/protocol-pay/batch-confirm",
"/static/protocol-pay.css",
"/static/protocol-pay.js",
}
public_dynamic = request.path.startswith("/api/card-flow/task/") or request.path.startswith("/api/protocol-pay/jobs/") or request.path.startswith("/api/unified-flow/jobs/") or request.path.startswith("/api/card-bind/key-probe/")
if request.path == "/healthz":
return None
if public_mount and (request.path in public_exact or public_dynamic):
return None
if shared_reg_session_valid():
return None
if request.path.startswith("/api/"):
return jsonify({"ok": False, "error": "LOGIN_REQUIRED"}), 401
return redirect("/login")
def reg_console_request(path: str, method: str = "GET", payload: dict | None = None) -> tuple[int, dict]:
if not REG_SESSION_SECRET:
raise RuntimeError("REG_SESSION_SECRET_MISSING")
session_value = hmac.new(
REG_SESSION_SECRET.encode("utf-8"),
b"register-console-access",
hashlib.sha256,
).hexdigest()
data = None
headers = {
"Cookie": f"{REG_SESSION_COOKIE}={session_value}",
"Accept": "application/json",
}
if payload is not None:
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
headers["Content-Type"] = "application/json"
req = Request(
f"{REG_INTERNAL_BASE}{path}",
data=data,
headers=headers,
method=method.upper(),
)
try:
with urlopen(req, timeout=30) as response:
raw = response.read().decode("utf-8", errors="replace")
return int(response.status), json.loads(raw or "{}")
except Exception as exc:
status = int(getattr(exc, "code", 502) or 502)
raw = ""
if hasattr(exc, "read"):
try:
raw = exc.read().decode("utf-8", errors="replace")
except Exception:
raw = ""
try:
body = json.loads(raw or "{}")
except Exception:
body = {"ok": False, "error": raw[:300] or str(exc)}
return status, body
def reg_bridge_get(path: str, params: dict | None = None) -> dict:
if not PH_SHORT_BRIDGE_KEY:
raise RuntimeError("菲律宾短链账号桥接密钥尚未配置")
query = f"?{urlencode(params or {})}" if params else ""
req = Request(
f"{REG_INTERNAL_BASE}{path}{query}",
headers={"X-PH-Short-Bridge-Key": PH_SHORT_BRIDGE_KEY, "Accept": "application/json"},
)
try:
with urlopen(req, timeout=15) as response:
payload = json.loads(response.read().decode("utf-8", errors="replace"))
except Exception as exc:
detail = ""
if hasattr(exc, "read"):
try:
detail = exc.read().decode("utf-8", errors="replace")[:300]
except Exception:
detail = ""
raise RuntimeError(f"读取 APP.example 账号会话失败:{detail or exc}") from exc
if not isinstance(payload, dict) or payload.get("ok") is False or payload.get("error"):
raise RuntimeError(str((payload or {}).get("error") or "账号会话接口返回异常"))
return payload
def validate_short_url(raw: str) -> tuple[str, str, str]:
value = str(raw or "").strip()
parsed = urlparse(value)
if parsed.scheme != "https" or parsed.hostname != "chatgpt.com":
raise ValueError("短链必须使用 chatgpt.com 官方 HTTPS 地址")
parts = [part for part in parsed.path.split("/") if part]
if len(parts) != 3 or parts[0] != "checkout":
raise ValueError("短链路径格式不正确")
processor, session_id = parts[1], parts[2]
if processor not in {"openai_ie", "openai_llc"}:
raise ValueError("短链处理实体不正确")
if not re.fullmatch(r"(?:oaics_|cs_)[A-Za-z0-9_-]{12,}", session_id):
raise ValueError("Checkout Session ID 格式不正确")
return value, processor, session_id
def cleanup_jobs() -> None:
cutoff = time.time() - JOB_TTL_SECONDS
with _lock:
expired = [
key for key, value in _jobs.items()
if value.get("created_at", 0) < cutoff
and value.get("status") not in {"queued", "running", "verification_required"}
]
for key in expired:
_jobs.pop(key, None)
if len(_jobs) > MAX_JOBS:
finished = sorted(
(item for item in _jobs.values() if item.get("status") not in {"queued", "running", "verification_required"}),
key=lambda item: item.get("created_at", 0),
)
for item in finished[: max(0, len(_jobs) - MAX_JOBS)]:
_jobs.pop(str(item.get("id") or ""), None)
def public_job(job: dict) -> dict:
return {
"id": job["id"],
"task_id": job.get("task_id") or "",
"account_email": job.get("account_email") or "",
"status": job.get("status") or "queued",
"progress": int(job.get("progress") or 0),
"stage": job.get("stage") or "等待执行",
"message": job.get("message") or "",
"error": job.get("error") or "",
"result": dict(job.get("result") or {}),
"logs": list(job.get("logs") or []),
"cancel_requested": bool(job.get("cancel_requested")),
"created_at": job.get("created_at"),
"updated_at": job.get("updated_at"),
"finished_at": job.get("finished_at"),
}
def add_log(job_id: str, level: str, message: str) -> None:
text = str(message or "").strip()
if not text:
return
with _lock:
job = _jobs.get(job_id)
if not job:
return
logs = job.setdefault("logs", [])
if logs and logs[-1].get("message") == text:
return
logs.append({"time": time.strftime("%H:%M:%S"), "type": level, "message": text[:800]})
if len(logs) > 100:
del logs[:-100]
job["updated_at"] = time.time()
def parse_cards(raw) -> list[dict[str, str]]:
cards: list[dict[str, str]] = []
seen: set[tuple[str, str, str, str]] = set()
def luhn_ok(number: str) -> bool:
total = 0
parity = len(number) % 2
for index, char in enumerate(number):
digit = int(char)
if index % 2 == parity:
digit *= 2
if digit > 9:
digit -= 9
total += digit
return total % 10 == 0
def append_card(number: Any, month: Any, year: Any, cvc: Any) -> None:
number_text = re.sub(r"\D", "", str(number or ""))
month_text = re.sub(r"\D", "", str(month or ""))
year_text = re.sub(r"\D", "", str(year or ""))
cvc_text = re.sub(r"\D", "", str(cvc or ""))
if len(year_text) == 2:
year_text = "20" + year_text
if not (12 <= len(number_text) <= 19 and luhn_ok(number_text)
and 1 <= int(month_text or 0) <= 12 and len(year_text) == 4
and 3 <= len(cvc_text) <= 4):
return
key = (number_text, str(int(month_text)), year_text, cvc_text)
if key not in seen:
seen.add(key)
cards.append({"number": key[0], "exp_month": key[1], "exp_year": key[2], "cvc": key[3]})
if isinstance(raw, list):
for value in raw:
if isinstance(value, dict):
append_card(value.get("number"), value.get("exp_month") or value.get("month"),
value.get("exp_year") or value.get("year"),
value.get("cvc") or value.get("cvv") or value.get("csc"))
else:
parts = [item for item in re.split(r"[|,;\s]+", str(value or "").strip()) if item]
if len(parts) >= 4:
append_card(*parts[:4])
else:
text = str(raw or "")
for line in text.splitlines():
parts = [item for item in re.split(r"[|,;\s]+", line.strip()) if item]
if len(parts) >= 4:
append_card(*parts[:4])
number_pattern = re.compile(r"(?<!\d)(\d{12,19}|(?:\d{4}[ -]){3}\d{4}|(?:\d{4}[ -]){2}\d{3,4})(?!\d)")
expiry_pattern = re.compile(r"(?<!\d)(0?[1-9]|1[0-2])\s*[/|,-]\s*(\d{2}|\d{4})(?!\d)")
cvc_pattern = re.compile(r"(?:cvc|cvv|csc|verification|security(?:\s*code)?|\u5b89\u5168\u7801|\u9a8c\u8bc1\u7801)[^\d]{0,24}(\d{3,4})", re.I)
for match in number_pattern.finditer(text):
number = re.sub(r"\D", "", match.group(1))
if not (12 <= len(number) <= 19 and luhn_ok(number)):
continue
tail = text[match.end():match.end() + 240]
expiry = expiry_pattern.search(tail)
if not expiry:
continue
cvc_match = cvc_pattern.search(tail)
if cvc_match:
cvc = cvc_match.group(1)
else:
plain = re.search(r"(?<!\d)(\d{3,4})(?!\d)", tail[expiry.end():])
cvc = plain.group(1) if plain else ""
append_card(number, expiry.group(1), expiry.group(2), cvc)
if not cards:
raise ValueError("未识别到完整支付卡,请检查卡号、有效期和 CVC")
return cards[:20]
def parse_proxies(raw) -> list[str]:
values = raw if isinstance(raw, list) else re.split(r"[\r\n,]+", str(raw or ""))
result = []
for value in values:
item = str(value or "").strip()
if item and item not in result:
result.append(item)
return result[:100]
def update_job(job_id: str, **updates) -> dict | None:
with _lock:
job = _jobs.get(job_id)
if not job:
return None
job.update(updates)
job["updated_at"] = time.time()
return dict(job)
def job_cancelled(job_id: str) -> bool:
with _lock:
return bool((_jobs.get(job_id) or {}).get("cancel_requested"))
def stop_if_cancelled(job_id: str) -> None:
if job_cancelled(job_id):
raise InterruptedError("任务已停止")
def run_job(job_id: str) -> None:
with _lock:
job = _jobs.get(job_id)
if not job:
return
try:
update_job(job_id, status="running", progress=8, stage="读取账号任务", message="正在读取短链和原账号任务信息")
add_log(job_id, "info", "读取菲律宾短链与原账号会话")
stop_if_cancelled(job_id)
snapshot = reg_bridge_get("/api/internal/ph-short/session", {"task_id": job["task_id"]})
update_job(job_id, progress=20, stage="校验短链", message="正在核对 Checkout、币种和金额")
stop_if_cancelled(job_id)
short_url, processor, checkout_session_id = validate_short_url(snapshot.get("short_url"))
currency = str(snapshot.get("currency") or "PHP").upper()
if currency != "PHP":
raise RuntimeError(f"短链币种不匹配:{currency or '未知'}")
amount = int(snapshot.get("amount") or 0)
if amount < 0:
raise RuntimeError("短链金额不正确")
update_job(job_id, progress=28, stage="检查账号环境", message="正在确认原任务仍有可用账号环境")
stop_if_cancelled(job_id)
has_account_context = bool(
str(snapshot.get("access_token") or "").strip()
or str(snapshot.get("session_token") or "").strip()
or snapshot.get("session_cookies")
)
if not has_account_context:
raise RuntimeError("原任务账号环境已失效,请先在账号页刷新后重新提取短链")
user_proxy_pool = list(job.get("_proxies") or [])
proxy_candidates: list[str] = []
proxy_source = "user_pool" if user_proxy_pool else ""
if user_proxy_pool:
proxy_candidates.extend(user_proxy_pool)
else:
checkout_proxy = str(snapshot.get("checkout_proxy") or "").strip()
if checkout_proxy:
proxy_candidates.append(checkout_proxy)
proxy_source = "checkout_sticky_us"
add_log(job_id, "info", "Reusing the original US checkout session")
if not str(job.get("_confirmation_token") or "").strip():
for _ in range(2):
try:
generated = reg_bridge_get("/api/internal/ph-short/proxy", {"country": "US"})
candidate = str(generated.get("proxy") or "").strip()
if candidate and candidate not in proxy_candidates:
proxy_candidates.append(candidate)
except Exception as exc:
add_log(job_id, "warn", f"US fallback proxy fetch failed: {type(exc).__name__}")
else:
add_log(job_id, "info", "ConfirmationToken is locked to the original Checkout proxy")
if not proxy_candidates:
raise RuntimeError("No usable payment proxy is available")
proxy = proxy_candidates[0]
if not proxy_source:
proxy_source = "auto_us"
update_job(job_id, _selected_proxy=proxy, _proxy_source=proxy_source)
payload = {
"short_url": short_url,
"processor_entity": processor,
"checkout_session_id": checkout_session_id,
"access_token": snapshot.get("access_token"),
"chatgpt_account_id": str(snapshot.get("chatgpt_account_id") or ""),
"session_cookies": snapshot.get("session_cookies") or {},
"user_agent": str(snapshot.get("user_agent") or ""),
"checkout_device_id": str(snapshot.get("checkout_device_id") or ""),
"checkout_chatgpt_session_id": str(snapshot.get("checkout_chatgpt_session_id") or ""),
"email": str(snapshot.get("email") or job.get("account_email") or ""),
"proxy": proxy,
"proxies": proxy_candidates,
"cards": list(job.get("_cards") or []),
"saved_payment_method_id": str(job.get("_saved_payment_method_id") or ""),
"confirmation_token": str(job.get("_confirmation_token") or ""),
"preconfirmed_checkout": dict(job.get("_preconfirmed_checkout") or {}),
"card_retry_count": int(job.get("_card_retry_count", 2)),
"card_retry_delay": 1,
}
update_job(job_id, progress=36, stage="初始化 Stripe", message="正在初始化现有 PH Checkout")
process = subprocess.Popen(
[PAY153_PYTHON, PROTOCOL_HELPER],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
bufsize=1,
)
with _lock:
if job_id in _jobs:
_jobs[job_id]["_process"] = process
assert process.stdin is not None and process.stdout is not None
process.stdin.write(json.dumps(payload, ensure_ascii=False))
process.stdin.close()
result = {}
last_error = ""
for line in process.stdout:
stop_if_cancelled(job_id)
text = line.strip()
if not text:
continue
try:
event = json.loads(text)
except Exception:
add_log(job_id, "info", text)
continue
if event.get("type") == "log":
level = str(event.get("level") or "info")
message = str(event.get("message") or "")
add_log(job_id, level, message)
lower = message.lower()
if "oaics session resolved" in lower:
update_job(job_id, progress=48, stage="Resolve Checkout", message="Loading Stripe Elements context")
elif "elements session initialized" in lower or "billing snapshot" in lower:
update_job(job_id, progress=62, stage="Initialize payment", message="Preparing the saved PaymentMethod")
elif "paymentmethod created" in lower:
update_job(job_id, progress=74, stage="Prepare authorization", message="PaymentMethod is ready for Checkout")
elif "confirmationtoken created" in lower:
update_job(job_id, progress=82, stage="Submit payment", message="Submitting the Checkout confirmation")
elif "payment succeeded" in lower:
update_job(job_id, progress=96, stage="Payment complete", message="Payment succeeded; finalizing authorization")
elif "post-payment card binding status" in lower:
update_job(job_id, progress=98, stage="Finalize", message="Checking the final account binding")
elif "checkout confirm returned" in lower:
update_job(job_id, progress=90, stage="Checkout confirmed", message="Confirming the Stripe Intent")
elif "submit chatgpt checkout approval" in lower:
update_job(job_id, progress=94, stage="Checkout approval", message="Submitting final approval and confirming again")
elif event.get("type") == "result":
result = dict(event.get("result") or {})
elif event.get("type") == "error":
last_error = str(event.get("error") or "")
code = process.wait(timeout=10)
with _lock:
if job_id in _jobs:
_jobs[job_id]["_process"] = None
if code != 0 or not result:
clean_error = last_error or f"Protocol helper exited with code {code}"
if clean_error.startswith("RuntimeError: "):
clean_error = clean_error[len("RuntimeError: "):]
raise RuntimeError(clean_error)
result.update({
"short_url": short_url,
"processor_entity": processor,
"checkout_session_id": checkout_session_id,
"amount_minor": amount,
"currency": "PHP",
"billing_country": "PH",
"account_email": str(snapshot.get("email") or job.get("account_email") or ""),
"protocol_mode": "stripe_checkout_protocol",
})
if result.get("status") == "verification_required":
update_job(
job_id,
status="verification_required",
progress=92,
stage="等待支付验证",
message="支付方式需要额外验证,完成后点击继续确认",
result=result,
_resume_payload={
"mode": "resume",
"checkout_session_id": checkout_session_id,
"stripe_publishable_key": str(result.get("stripe_publishable_key") or ""),
"intent_type": str(result.get("intent_type") or ""),
"intent_client_secret": str(result.get("intent_client_secret") or ""),
"proxy": proxy,
"session_cookies": snapshot.get("session_cookies") or {},
},
)
else:
update_job(job_id, status="ready", progress=100, stage="支付完成", message="菲律宾 Checkout 协议支付完成", result=result, finished_at=time.time())
except InterruptedError as exc:
with _lock:
process = (_jobs.get(job_id) or {}).get("_process")
if process and process.poll() is None:
try:
process.terminate()
except Exception:
pass
update_job(
job_id,
status="cancelled",
progress=100,
stage="已停止",
message=str(exc),
finished_at=time.time(),
)
except Exception as exc:
add_log(job_id, "error", f"{type(exc).__name__}: {exc}")
update_job(
job_id,
status="error",
progress=100,
stage="执行失败",
error=str(exc),
message="任务执行失败",
finished_at=time.time(),
)
def run_resume_job(job_id: str) -> None:
with _lock:
job = _jobs.get(job_id)
payload = dict((job or {}).get("_resume_payload") or {})
previous_result = dict((job or {}).get("result") or {})
if not job or not payload:
return
try:
update_job(job_id, status="running", progress=94, stage="确认验证结果", message="正在轮询原 Checkout 的最终状态", error="")
process = subprocess.Popen(
[PAY153_PYTHON, PROTOCOL_HELPER],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
bufsize=1,
)
with _lock:
if job_id in _jobs:
_jobs[job_id]["_process"] = process
assert process.stdin is not None and process.stdout is not None
process.stdin.write(json.dumps(payload, ensure_ascii=False))
process.stdin.close()
result: dict = {}
last_error = ""
for line in process.stdout:
stop_if_cancelled(job_id)
text = line.strip()
if not text:
continue
try:
event = json.loads(text)
except Exception:
add_log(job_id, "info", text)
continue
if event.get("type") == "log":
add_log(job_id, str(event.get("level") or "info"), str(event.get("message") or ""))
elif event.get("type") == "result":
result = dict(event.get("result") or {})
elif event.get("type") == "error":
last_error = str(event.get("error") or "")
code = process.wait(timeout=10)
with _lock:
if job_id in _jobs:
_jobs[job_id]["_process"] = None
if code != 0 or not result:
raise RuntimeError(last_error or f"协议支付续跑进程退出:{code}")
merged = {**previous_result, **result}
if result.get("status") == "verification_required":
update_job(job_id, status="verification_required", progress=94, stage="等待支付验证", message="尚未检测到验证完成,可稍后再次继续确认", result=merged)
return
update_job(job_id, status="ready", progress=100, stage="支付完成", message="菲律宾 Checkout 已确认到账", result=merged, finished_at=time.time())
except InterruptedError as exc:
with _lock:
process = (_jobs.get(job_id) or {}).get("_process")
if process and process.poll() is None:
try:
process.terminate()
except Exception:
pass
update_job(job_id, status="cancelled", progress=100, stage="已停止", message=str(exc), finished_at=time.time())
except Exception as exc:
add_log(job_id, "error", f"{type(exc).__name__}: {exc}")
update_job(job_id, status="error", progress=100, stage="最终确认失败", error=str(exc), finished_at=time.time())
def request_script_root(value: str | None) -> str:
root = str(value or "").rstrip("/")
return root
def _decode_access_token_claims(access_token: str) -> dict:
token = str(access_token or "").strip()
parts = token.split(".")
if len(parts) < 2:
raise ValueError("AT_FORMAT_INVALID")
segment = parts[1] + "=" * (-len(parts[1]) % 4)
try:
claims = json.loads(base64.urlsafe_b64decode(segment.encode("ascii")).decode("utf-8"))
except Exception as exc:
raise ValueError("AT_PAYLOAD_INVALID") from exc
if not isinstance(claims, dict):
raise ValueError("AT_PAYLOAD_INVALID")
return claims
def _external_at_identity(access_token: str) -> tuple[str, str, str]:
claims = _decode_access_token_claims(access_token)
auth = claims.get("https://api.openai.com/auth") or {}
profile = claims.get("https://api.openai.com/profile") or {}
if not isinstance(auth, dict):
auth = {}
if not isinstance(profile, dict):
profile = {}
account_id = str(auth.get("chatgpt_account_id") or claims.get("chatgpt_account_id") or claims.get("account_id") or "").strip()
if not account_id:
raise ValueError("AT_ACCOUNT_ID_MISSING")
token_hash = hashlib.sha256(access_token.encode("utf-8")).hexdigest()
email = str(profile.get("email") or claims.get("email") or "").strip().lower()
if not email or "@" not in email:
email = f"external-{token_hash[:16]}@example.com"
record_id = hashlib.sha256(("external-at:" + account_id).encode("utf-8")).hexdigest()[:12]
return record_id, email, account_id
def ensure_external_at_account(access_token: str) -> str:
token = str(access_token or "").strip()
if len(token) < 300 or len(token) > 30000:
raise ValueError("AT_FORMAT_INVALID")
_record_id, email, _account_id = _external_at_identity(token)
# External ATs are decoded in memory only. They are never appended to the
# APP.example account archive.
return email
def resolve_card_bind_email(body: dict | None = None) -> str:
body = body or {}
requested_id = str(body.get("record_id") or request.args.get("record_id") or "").strip()
requested_email = str(body.get("email") or request.args.get("email") or "").strip().lower()
requested_at = str(body.get("access_token") or body.get("at") or request.args.get("access_token") or "").strip()
if not requested_id and not requested_email and not requested_at:
return CARD_BIND_ACCOUNT_EMAIL
matched_email = ""
account_file = Path("/opt/reg153/success_accounts.jsonl")
if account_file.exists():
with account_file.open(encoding="utf-8", errors="ignore") as handle:
for line in handle:
try:
item = json.loads(line)
except Exception:
continue
item_id = str(item.get("id") or "").strip()
item_email = str(item.get("email") or "").strip().lower()
item_at = str(item.get("access_token") or "").strip()
if ((requested_id and item_id == requested_id) or
(requested_email and item_email == requested_email) or
(requested_at and item_at and hmac.compare_digest(requested_at, item_at))):
matched_email = item_email
break
if matched_email:
return matched_email
if requested_at:
return ensure_external_at_account(requested_at)
raise ValueError("ACCOUNT_NOT_FOUND")
@app.get("/card-long/")
def card_long_page():
return render_template("card-long-flow.html")
def _find_protocol_publishable_key(value) -> str:
pattern = re.compile(r"pk_(?:live|test)_[A-Za-z0-9]{24,}")
if isinstance(value, dict):
for name in ("stripe_publishable_key", "publishable_key", "public_key", "key"):
candidate = str(value.get(name) or "").strip()
if pattern.fullmatch(candidate):
return candidate
for item in value.values():
found = _find_protocol_publishable_key(item)
if found:
return found
elif isinstance(value, list):
for item in value:
found = _find_protocol_publishable_key(item)
if found:
return found
elif isinstance(value, str):
match = pattern.search(value)
if match:
return match.group(0)
return ""
def initialize_card_stripe_via_checkout(record_id: str, proxy_pool: list[str], access_token: str = "") -> dict:
# Creating the temporary Checkout is the initialization side effect. Its
# response key is optional because a fresh payment_method call follows it.
token = str(access_token or "").strip()
if not token:
raise RuntimeError("AT_REQUIRED_FOR_CHECKOUT_KEY")
if not PAY153_INTERNAL_KEY:
if not proxy_pool:
raise RuntimeError("PROXY_POOL_REQUIRED")
initialized = _run_local_checkout_extractor(
token,
str(proxy_pool[0] or ""),
str(proxy_pool[0] or ""),
mode="initialize",
)
return {
"pay_job_id": "local",
"publishable_key": CARD_BIND_PUBLISHABLE_KEY,
"result": initialized,
}
status, created = _pay153_request("/api/checkout", "POST", {
"token": token, "plan": "plus", "link_type": "ph_short", "country": "US",
"entry_proxies": list(proxy_pool), "exit_proxies": list(proxy_pool),
"entry_proxy_country": "US", "exit_proxy_country": "US", "use_promo": False,
"promo_country": "US", "retry_count": 3, "use_sen": True, "use_so": True,
})
pay_job_id = str((created or {}).get("job_id") or "")
if status >= 400 or not pay_job_id:
raise RuntimeError(str((created or {}).get("error") or "CHECKOUT_KEY_TASK_CREATE_FAILED"))
observed_key = ""
for _ in range(720):
pstatus, progress = _pay153_request("/api/checkout-progress", params={"job_id": pay_job_id})
if pstatus >= 400:
raise RuntimeError(str((progress or {}).get("error") or "CHECKOUT_KEY_TASK_QUERY_FAILED"))
progress = progress if isinstance(progress, dict) else {}
state = str(progress.get("status") or "")
observed_key = observed_key or _find_protocol_publishable_key(progress)
if state == "done":
return {
"pay_job_id": pay_job_id,
"publishable_key": observed_key or _find_protocol_publishable_key(progress.get("result") or {}),
"result": progress.get("result") or {},
}
if state in {"error", "failed", "cancelled"}:
raise RuntimeError(str(progress.get("error") or progress.get("message") or "CHECKOUT_KEY_TASK_FAILED"))
time.sleep(1)
raise RuntimeError("CHECKOUT_INITIALIZATION_TIMEOUT")
def _run_card_bind_session_helper(account_email: str, selected_proxy: str, access_token: str) -> tuple[int, dict]:
try:
completed = subprocess.run(
[PAY153_PYTHON, CARD_BIND_HELPER, account_email, selected_proxy, access_token],
capture_output=True, text=True, timeout=70, check=False,
)
except FileNotFoundError as exc:
return 127, {
"ok": False,
"error": "CARD_BIND_HELPER_UNAVAILABLE",
"detail": f"Python helper executable is unavailable: {exc.filename or PAY153_PYTHON}",
}
except subprocess.TimeoutExpired:
return 124, {
"ok": False,
"error": "CARD_BIND_HELPER_TIMEOUT",
"detail": "Card session helper exceeded 70 seconds",
}
except OSError as exc:
return 126, {
"ok": False,
"error": "CARD_BIND_HELPER_START_FAILED",
"detail": f"Card session helper could not start: {exc}",
}
try:
payload = json.loads((completed.stdout or "{}").strip().splitlines()[-1])
except Exception:
stderr = str(completed.stderr or "").strip().splitlines()
payload = {
"ok": False,
"error": "BIND_SESSION_INVALID_RESPONSE",
"detail": (stderr[-1] if stderr else "helper returned no JSON")[:300],
}
return completed.returncode, payload
def _key_probe_public(job: dict) -> dict:
return {
"id": job.get("id"), "status": job.get("status"), "progress": int(job.get("progress") or 0),
"message": job.get("message") or "", "error": job.get("error") or "",
"publishable_key": job.get("publishable_key") or "",
"session": dict(job.get("session") or {}),
}
def _run_key_probe(probe_id: str):
with _lock: job = dict(_key_probe_jobs.get(probe_id) or {})
if not job: return
try:
token = str(job.get("_access_token") or "")
account_email = str(job.get("_account_email") or "")
selected_proxy = str(job.get("_selected_proxy") or "")
with _lock:
_key_probe_jobs[probe_id].update(status="running", progress=12, message="Creating temporary Checkout to initialize Stripe")
initialized = initialize_card_stripe_via_checkout(job.get("record_id") or "", list(job.get("_proxies") or []), token)
with _lock:
_key_probe_jobs[probe_id].update(progress=82, message="Checkout initialized; fetching a fresh SetupIntent and Stripe key")
refreshed = {}
last_detail = ""
for attempt in range(1, 13):
returncode, candidate = _run_card_bind_session_helper(account_email, selected_proxy, token)
if returncode == 0 and candidate.get("ok"):
refreshed = candidate
break
upstream = int(candidate.get("status") or 0)
detail = candidate.get("detail") or candidate.get("error") or "BIND_SESSION_REFETCH_FAILED"
last_detail = f"BIND_SESSION_REFETCH_FAILED[{upstream}]: {detail}"
if "no payment account exists" not in str(detail).lower() or attempt >= 12:
break
with _lock:
if probe_id in _key_probe_jobs:
_key_probe_jobs[probe_id].update(
progress=min(96, 82 + attempt),
message=f"Payment account initialization pending; SetupIntent retry {attempt}/12",
)
time.sleep(1)
if not refreshed.get("ok"):
raise RuntimeError(last_detail or "BIND_SESSION_REFETCH_FAILED")
key = _find_protocol_publishable_key(refreshed) or str(initialized.get("publishable_key") or "")
if not str(key).startswith("pk_"):
raise RuntimeError("CHECKOUT_INITIALIZED_BUT_KEY_NOT_RETURNED")
refreshed["publishable_key"] = key
refreshed["publishable_key_source"] = "checkout_then_refetch"
refreshed["pending"] = False
with _lock:
_key_probe_jobs[probe_id].update(
status="done", progress=100, message="Fresh SetupIntent and Stripe key resolved",
publishable_key=key, session=refreshed, _access_token="", finished_at=time.time(),
)
except Exception as exc:
with _lock:
if probe_id in _key_probe_jobs:
_key_probe_jobs[probe_id].update(status="error", progress=100, message="Stripe initialization/refetch failed", error=f"{type(exc).__name__}: {exc}"[:500], _access_token="", finished_at=time.time())
def _start_key_probe(record_id: str, account_email: str, selected_proxy: str, access_token: str, proxies: list[str], initial_session: dict | None = None) -> dict:
probe_id = secrets.token_hex(6); now = time.time()
job = {"id": probe_id, "record_id": record_id, "status": "queued", "progress": 2, "message": "Stripe initialization queued", "error": "", "publishable_key": "", "session": dict(initial_session or {}), "created_at": now, "finished_at": None, "_account_email": account_email, "_selected_proxy": selected_proxy, "_access_token": access_token, "_proxies": list(proxies)}
with _lock:
_key_probe_jobs[probe_id] = job
if len(_key_probe_jobs) > 100:
finished = sorted((x for x in _key_probe_jobs.values() if x.get("status") in {"done", "error"}), key=lambda x: x.get("created_at", 0))
for old in finished[:max(0, len(_key_probe_jobs)-100)]: _key_probe_jobs.pop(str(old.get("id") or ""), None)
threading.Thread(target=_run_key_probe, args=(probe_id,), daemon=True, name=f"key-probe-{probe_id}").start()
return job
@app.get("/api/card-bind/key-probe/<probe_id>")
def card_bind_key_probe(probe_id: str):
value = str(probe_id or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", value):
return jsonify({"ok": False, "error": "INVALID_KEY_PROBE_ID"}), 400
with _lock:
job = _key_probe_jobs.get(value)
payload = _key_probe_public(job) if job else None
if not payload:
return jsonify({"ok": False, "error": "KEY_PROBE_NOT_FOUND"}), 404
return jsonify({"ok": True, "probe": payload})
def normalize_user_proxy(raw: str) -> str:
value = str(raw or "").strip()
if not value:
raise ValueError("PROXY_REQUIRED")
if "://" in value:
parsed = urlsplit(value)
scheme = parsed.scheme.lower()
if scheme not in {"http", "https", "socks5", "socks5h"}:
raise ValueError("UNSUPPORTED_PROXY_SCHEME")
if not parsed.hostname or parsed.port is None:
raise ValueError("PROXY_HOST_OR_PORT_MISSING")
auth = ""
if parsed.username is not None:
auth = f"{quote(unquote(parsed.username), safe='')}:{quote(unquote(parsed.password or ''), safe='')}@"
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
return f"{scheme}://{auth}{host}:{parsed.port}"
if value.count("@") == 1:
left, right = value.split("@", 1)
if left.count(":") == 1 and right.count(":") >= 1:
username, password = left.split(":", 1)
host, port = right.rsplit(":", 1)
else:
host, port = left.rsplit(":", 1)
username, password = right.split(":", 1)
if not port.isdigit():
raise ValueError("PROXY_PORT_INVALID")
return f"http://{quote(username, safe='')}:{quote(password, safe='')}@{host}:{port}"
parts = value.split(":")
if len(parts) >= 4 and parts[1].isdigit():
host, port, username = parts[0], parts[1], parts[2]
password = ":".join(parts[3:])
return f"http://{quote(username, safe='')}:{quote(password, safe='')}@{host}:{port}"
if len(parts) == 2 and parts[1].isdigit():
return f"http://{value}"
raise ValueError("PROXY_FORMAT_INVALID")
def normalize_user_proxy_pool(raw) -> list[str]:
values = raw if isinstance(raw, list) else str(raw or "").replace("\r", "").split("\n")
result = []
seen = set()
for index, item in enumerate(values, 1):
text = str(item or "").strip()
if not text:
continue
try:
proxy = normalize_user_proxy(text)
except Exception as exc:
raise ValueError(f"PROXY_LINE_{index}: {exc}") from exc
if proxy not in seen:
seen.add(proxy); result.append(proxy)
if not result:
raise ValueError("PROXY_POOL_REQUIRED")
if len(result) > 500:
raise ValueError("PROXY_POOL_MAX_500")
return result
def card_helper_error_response(payload: dict, fallback_status: int = 502):
result = dict(payload or {})
if not result.get("error"):
result["error"] = "CARD_PROTOCOL_EMPTY_RESPONSE"
if result.get("error") in {
"CARD_BIND_HELPER_UNAVAILABLE",
"CARD_BIND_HELPER_TIMEOUT",
"CARD_BIND_HELPER_START_FAILED",
"CARD_BIND_DEPENDENCY_MISSING",
"CARD_BIND_RUNTIME_FILE_MISSING",
"CARD_BIND_UPSTREAM_NETWORK_ERROR",
"CARD_BIND_PROXY_POOL_EXHAUSTED",
"SET_DEFAULT_HELPER_UNAVAILABLE",
"SET_DEFAULT_HELPER_TIMEOUT",
"SET_DEFAULT_HELPER_START_FAILED",
"SET_DEFAULT_DEPENDENCY_MISSING",
"SET_DEFAULT_UPSTREAM_NETWORK_ERROR",
"SET_DEFAULT_TLS_CA_BUNDLE_ERROR",
"CARD_BIND_TLS_CA_BUNDLE_ERROR",
}:
return jsonify(result), 503
upstream = int(result.get("status") or 0)
if upstream == 401:
result["error"] = "AT_INVALIDATED_OR_EXPIRED"
result["upstream_status"] = upstream
return jsonify(result), 422
if upstream == 403:
result["error"] = "UPSTREAM_ROUTE_BLOCKED"
result["upstream_status"] = upstream
return jsonify(result), 503
if upstream == 429:
result["error"] = result.get("error") or "UPSTREAM_RATE_LIMITED"
return jsonify(result), 429
if upstream >= 500:
return jsonify(result), 503
return jsonify(result), fallback_status
def _run_card_set_default(
account_email: str,
payment_method_id: str,
selected_proxy: str,
access_token: str,
) -> tuple[int, dict]:
def safe_detail(value: object) -> str:
detail = str(value or "")
detail = re.sub(r"(?i)((?:https?|socks5h?)://)[^/@\s]+@", r"\1***@", detail)
detail = re.sub(
r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+",
"AT_REDACTED",
detail,
)
return detail[:500]
try:
completed = subprocess.run(
[PAY153_PYTHON, CARD_DEFAULT_HELPER, account_email, payment_method_id, selected_proxy, access_token],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=SET_DEFAULT_HELPER_TIMEOUT_SECONDS,
check=False,
)
except FileNotFoundError as exc:
return 127, {"ok": False, "error": "SET_DEFAULT_HELPER_UNAVAILABLE", "detail": safe_detail(exc)}
except subprocess.TimeoutExpired as exc:
return 124, {
"ok": False,
"error": "SET_DEFAULT_HELPER_TIMEOUT",
"detail": f"helper exceeded {SET_DEFAULT_HELPER_TIMEOUT_SECONDS}s",
}
except OSError as exc:
return 126, {"ok": False, "error": "SET_DEFAULT_HELPER_START_FAILED", "detail": safe_detail(exc)}
payload = None
stdout_lines = [line.strip() for line in str(completed.stdout or "").splitlines() if line.strip()]
for line in reversed(stdout_lines):
try:
candidate = json.loads(line)
except Exception:
continue
if isinstance(candidate, dict):
payload = candidate
break
stderr_lines = [line.strip() for line in str(completed.stderr or "").splitlines() if line.strip()]
if payload is None:
detail_source = stderr_lines[-1] if stderr_lines else (stdout_lines[-1] if stdout_lines else "helper returned no JSON")
payload = {
"ok": False,
"error": "SET_DEFAULT_HELPER_ERROR" if completed.returncode else "SET_DEFAULT_INVALID_RESPONSE",
"detail": safe_detail(detail_source),
}
elif completed.returncode and not payload.get("error"):
payload["error"] = "SET_DEFAULT_HELPER_ERROR"
if completed.returncode and not payload.get("detail") and stderr_lines:
payload["detail"] = safe_detail(stderr_lines[-1])
return completed.returncode, payload
@app.post("/api/card-bind/default")
def card_bind_default():
body = request.get_json(silent=True) or {}
payment_method_id = str(body.get("payment_method_id") or "").strip()
if not re.fullmatch(r"pm_[A-Za-z0-9]+", payment_method_id):
return jsonify({"ok": False, "error": "INVALID_PAYMENT_METHOD"}), 400
try:
account_email = resolve_card_bind_email(body)
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 404
try:
selected_proxy = normalize_user_proxy(body.get("proxy"))
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
submitted_at = str(body.get("access_token") or body.get("at") or "").strip()
returncode, payload = _run_card_set_default(
account_email, payment_method_id, selected_proxy, submitted_at
)
if returncode != 0 or not payload.get("ok"):
return card_helper_error_response(payload)
return jsonify(payload)
@app.post("/api/card-flow/context")
def card_flow_context():
body = request.get_json(silent=True) or {}
task_id = str(body.get("task_id") or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", task_id):
return jsonify({"ok": False, "error": "Checkout task ID is invalid"}), 400
try:
snapshot = reg_bridge_get("/api/internal/ph-short/session", {"task_id": task_id})
completed = subprocess.run(
[PAY153_PYTHON, CARD_CHECKOUT_CONTEXT_HELPER],
input=json.dumps(snapshot, ensure_ascii=False),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=90,
check=False,
)
try:
payload = json.loads((completed.stdout or "{}").strip().splitlines()[-1])
except Exception:
payload = {"ok": False, "error": "Checkout context response is invalid"}
if completed.returncode != 0 or not payload.get("ok"):
detail = (completed.stderr or "").strip().splitlines()
return jsonify({"ok": False, "error": payload.get("error") or (detail[-1] if detail else "Checkout context failed")}), 502
return jsonify(payload)
except Exception as exc:
return jsonify({"ok": False, "error": str(exc)}), 502
@app.post("/api/card-flow/server-token")
def card_flow_server_token():
body = request.get_json(silent=True) or {}
task_id = str(body.get("task_id") or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", task_id):
return jsonify({"ok": False, "error": "Checkout task ID is invalid"}), 400
try:
snapshot = reg_bridge_get("/api/internal/ph-short/session", {"task_id": task_id})
completed = subprocess.run(
[PAY153_PYTHON, CARD_SERVER_TOKEN_HELPER],
input=json.dumps(snapshot, ensure_ascii=False),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=120,
check=False,
)
lines = (completed.stdout or "").strip().splitlines()
try:
payload = json.loads(lines[-1] if lines else "{}")
except Exception:
payload = {"ok": False, "error": "Server ConfirmationToken response is invalid"}
if completed.returncode != 0 or not payload.get("ok"):
detail = (completed.stderr or "").strip().splitlines()
error_code = str(payload.get("error_code") or "")
status_code = 409 if error_code == "OFFER_NOT_ELIGIBLE" else 502
return jsonify({
"ok": False,
"error_code": error_code,
"error": payload.get("error") or (detail[-1] if detail else "Server ConfirmationToken failed"),
"offer_check_ok": payload.get("offer_check_ok"),
"offer_eligible": payload.get("offer_eligible"),
}), status_code
return jsonify(payload)
except Exception as exc:
return jsonify({"ok": False, "error": str(exc)}), 502
@app.get("/card-flow/")
def card_flow_page():
return render_template("card-flow.html")
def _checkout_result_context(result: dict, entry_proxies: list[str], source: str = "") -> dict:
session_id = str(result.get("checkout_session_id") or "").strip()
if not session_id:
return {}
try: attempt = max(1, int(result.get("attempt") or 1))
except Exception: attempt = 1
selected_proxy = str(result.get("checkout_proxy") or "").strip()
if entry_proxies:
selected_proxy = selected_proxy or str(entry_proxies[(attempt - 1) % len(entry_proxies)] or "").strip()
return {
"checkout_session_id": session_id,
"checkout_url": str(result.get("checkout_url") or result.get("short_link") or ""),
"processor_entity": str(result.get("processor_entity") or "openai_llc"),
"checkout_proxy": selected_proxy,
"checkout_device_id": str(result.get("checkout_device_id") or ""),
"checkout_chatgpt_session_id": str(result.get("checkout_chatgpt_session_id") or ""),
"checkout_user_agent": str(result.get("checkout_user_agent") or ""),
"session_cookies": {
str(name): str(value)
for name, value in dict(result.get("session_cookies") or {}).items()
if str(name) and str(value)
},
"created_at": time.time(),
"source": source,
}
def _persist_checkout_context(context: dict) -> None:
if not context or not context.get("checkout_session_id"):
return
CHECKOUT_CONTEXT_PATH.parent.mkdir(parents=True, exist_ok=True)
with _lock:
rows = []
if CHECKOUT_CONTEXT_PATH.exists():
for line in CHECKOUT_CONTEXT_PATH.read_text(encoding="utf-8", errors="ignore").splitlines():
try: item = json.loads(line)
except Exception: continue
if not isinstance(item, dict): continue
if str(item.get("checkout_session_id") or "") == str(context.get("checkout_session_id") or ""): continue
if float(item.get("created_at") or 0) < time.time() - 7 * 86400: continue
rows.append(item)
rows.append(dict(context))
CHECKOUT_CONTEXT_PATH.write_text("".join(json.dumps(item, ensure_ascii=False, separators=(",", ":")) + "\\n" for item in rows[-1000:]), encoding="utf-8")
def _lookup_checkout_context(session_id: str) -> dict:
target = str(session_id or "").strip()
if not target: return {}
candidates = []
pay153_contexts = Path("/opt/pay153/data/ph_short_contexts.jsonl")
if pay153_contexts.exists():
for line in pay153_contexts.read_text(encoding="utf-8", errors="ignore").splitlines():
try: item = json.loads(line)
except Exception: continue
if isinstance(item, dict) and str(item.get("checkout_session_id") or "") == target:
candidates.append(item)
if CHECKOUT_CONTEXT_PATH.exists():
for line in CHECKOUT_CONTEXT_PATH.read_text(encoding="utf-8", errors="ignore").splitlines():
try: item = json.loads(line)
except Exception: continue
if isinstance(item, dict) and str(item.get("checkout_session_id") or "") == target:
candidates.append(item)
# Backfill links created by the older reg quick-checkout path.
legacy_tasks = Path("/opt/reg153/account_tasks.jsonl")
if legacy_tasks.exists():
for line in legacy_tasks.read_text(encoding="utf-8", errors="ignore").splitlines():
try: task = json.loads(line)
except Exception: continue
result = task.get("result") if isinstance(task.get("result"), dict) else {}
if str(result.get("checkout_session_id") or "") != target: continue
options = task.get("options") if isinstance(task.get("options"), dict) else {}
entry = [str(item).strip() for item in (options.get("entry_proxies") or []) if str(item).strip()]
context = _checkout_result_context(result, entry, "legacy_reg_task")
context["created_at"] = float(task.get("finished_at") or task.get("created_at") or time.time())
candidates.append(context)
if not candidates: return {}
return dict(max(candidates, key=lambda item: float(item.get("created_at") or 0)))
def _lookup_reg_account_session(email: str, account_id: str) -> dict:
target_email = str(email or "").strip().lower()
target_account = str(account_id or "").strip()
source = Path("/opt/reg153/success_accounts.jsonl")
if not source.exists():
return {}
matches = []
for line in source.read_text(encoding="utf-8", errors="ignore").splitlines():
try:
row = json.loads(line)
except Exception:
continue
if not isinstance(row, dict):
continue
same_email = target_email and str(row.get("email") or "").strip().lower() == target_email
same_account = target_account and str(row.get("account_id") or "").strip() == target_account
if not (same_email or same_account):
continue
cookies = row.get("session_cookies") if isinstance(row.get("session_cookies"), dict) else {}
if cookies:
matches.append(row)
if not matches:
return {}
latest = max(matches, key=lambda row: str(row.get("last_checked_at") or row.get("created_at") or ""))
return {str(k): str(v) for k, v in dict(latest.get("session_cookies") or {}).items() if str(k) and str(v)}
def _pay153_request(path: str, method: str = "GET", payload: dict | None = None, params: dict | None = None) -> tuple[int, dict]:
if not PAY153_INTERNAL_KEY:
raise RuntimeError(
"PAY153_INTERNAL_KEY_MISSING: configure PAY153_INTERNAL_KEY in .env "
"and start the PAY153 bridge at " + PAY153_INTERNAL_BASE
)
query = f"?{urlencode(params or {})}" if params else ""
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
headers = {"X-Pay153-Internal-Key": PAY153_INTERNAL_KEY, "Accept": "application/json"}
if data is not None:
headers["Content-Type"] = "application/json"
req = Request(f"{PAY153_INTERNAL_BASE}{path}{query}", data=data, headers=headers, method=method)
try:
with urlopen(req, timeout=35) as response:
raw = response.read().decode("utf-8", errors="replace")
return int(response.status), json.loads(raw or "{}")
except Exception as exc:
status = int(getattr(exc, "code", 502) or 502)
raw = ""
if hasattr(exc, "read"):
try: raw = exc.read().decode("utf-8", errors="replace")
except Exception: raw = ""
try: body = json.loads(raw or "{}")
except Exception: body = {"error": raw[:300] or str(exc)}
return status, body
def _run_local_checkout_extractor(
access_token: str, entry_proxy: str, exit_proxy: str, mode: str = "extract"
) -> dict:
try:
completed = subprocess.run(
[PAY153_PYTHON, LOCAL_CHECKOUT_HELPER],
input=json.dumps(
{
"access_token": access_token,
"entry_proxy": entry_proxy,
"exit_proxy": exit_proxy,
"mode": mode,
},
ensure_ascii=False,
),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=15 * 60,
check=False,
)
except subprocess.TimeoutExpired as exc:
raise TimeoutError("LOCAL_CHECKOUT_TIMEOUT") from exc
lines = (completed.stdout or "").strip().splitlines()
try:
result = json.loads(lines[-1] if lines else "{}")
except Exception as exc:
raise RuntimeError("LOCAL_CHECKOUT_INVALID_RESPONSE") from exc
if completed.returncode != 0 or not result.get("ok"):
message = str(result.get("error") or f"LOCAL_CHECKOUT_EXIT_{completed.returncode}")
raw_trace = result.get("trace") if isinstance(result.get("trace"), list) else []
safe_trace = [
str(frame)
for frame in raw_trace[:6]
if re.fullmatch(r"[A-Za-z0-9_.-]+:\d+:[A-Za-z0-9_.<>-]+", str(frame))
]
if safe_trace:
message += " [trace: " + " <- ".join(safe_trace) + "]"
raise RuntimeError(message[:1200])
if not str(result.get("checkout_session_id") or "").startswith(("oaics_", "cs_")):
raise RuntimeError("LOCAL_CHECKOUT_SESSION_MISSING")
if not str(result.get("checkout_url") or "").startswith("https://chatgpt.com/checkout/"):
raise RuntimeError("LOCAL_CHECKOUT_URL_MISSING")
return result
def _extend_sticky_proxy_ttl(value: str, minutes: int = 120) -> str:
proxy = str(value or "").strip()
if not proxy:
return proxy
if re.search(r"-t-\d+", proxy):
return re.sub(r"-t-\d+", f"-t-{int(minutes)}", proxy, count=1)
return proxy
def _card_checkout_public(job: dict) -> dict:
return {
"id": job.get("id"), "task_id": job.get("id"), "status": job.get("status"),
"progress": int(job.get("progress") or 0), "message": job.get("message") or "",
"error": job.get("error") or "", "result": dict(job.get("result") or {}),
"created_at": job.get("created_at"), "finished_at": job.get("finished_at"),
}
def _run_isolated_card_checkout(task_id: str):
with _lock: job = dict(_card_checkout_jobs.get(task_id) or {})
if not job: return
try:
with _lock: _card_checkout_jobs[task_id].update(status="running", progress=5, message="Validating US/TR proxy pools")
preflight = subprocess.run(
[PAY153_PYTHON, PROXY_PREFLIGHT_HELPER],
input=json.dumps({
"entry": [_extend_sticky_proxy_ttl(item, 120) for item in job["_entry_proxies"]],
"exit": [_extend_sticky_proxy_ttl(item, 120) for item in job["_exit_proxies"]],
}, ensure_ascii=False),
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=45, check=False,
)
try: checked = json.loads((preflight.stdout or "{}").strip().splitlines()[-1])
except Exception: checked = {}
entry_valid = list(checked.get("entry") or [])
exit_valid = list(checked.get("exit") or [])
# A proxy that already completed card binding can be temporarily
# unobservable from Cloudflare's trace endpoint. Keep it usable when
# every probe is inconclusive, but never bypass a positive country
# mismatch.
entry_inconclusive = list(checked.get("entry_inconclusive") or [])
exit_inconclusive = list(checked.get("exit_inconclusive") or [])
entry_mismatch = list(checked.get("entry_mismatch") or [])
exit_mismatch = list(checked.get("exit_mismatch") or [])
preflight_note = ""
if not entry_valid and entry_inconclusive and not entry_mismatch:
entry_valid = entry_inconclusive
preflight_note = " US probe inconclusive; reused supplied binding proxy."
if not exit_valid and exit_inconclusive and not exit_mismatch:
exit_valid = exit_inconclusive
preflight_note += " TR probe inconclusive; reused supplied promo proxy."
if not entry_valid or not exit_valid:
mismatch_note = []
if entry_mismatch: mismatch_note.append("US country mismatch")
if exit_mismatch: mismatch_note.append("TR country mismatch")
raise RuntimeError(
f"PROXY_PREFLIGHT_FAILED: US {int(checked.get('entry_valid') or 0)}/{int(checked.get('entry_total') or 0)}, "
f"TR {int(checked.get('exit_valid') or 0)}/{int(checked.get('exit_total') or 0)}"
+ ("; " + ", ".join(mismatch_note) if mismatch_note else "")
)
with _lock: _card_checkout_jobs[task_id].update(status="running", progress=12, message=f"Proxy preflight passed: US {len(entry_valid)}, TR {len(exit_valid)}.{preflight_note}")
if not PAY153_INTERNAL_KEY:
with _lock:
_card_checkout_jobs[task_id].update(
progress=18,
message="PAY153 bridge not configured; using bundled local checkout extractor",
)
result = _run_local_checkout_extractor(
str(job.get("_access_token") or ""),
entry_valid[0],
exit_valid[0],
)
_persist_checkout_context(_checkout_result_context(result, entry_valid, "local_checkout_extractor"))
with _lock:
_card_checkout_jobs[task_id].update(
status="done",
progress=100,
message="Checkout completed by local extractor",
result=result,
finished_at=time.time(),
_access_token="",
)
return
payload = {
"token": job["_access_token"], "plan": "plus", "link_type": "ph_short", "country": "PH",
"entry_proxies": entry_valid, "exit_proxies": exit_valid,
"entry_proxy_country": "US", "exit_proxy_country": "TR", "use_promo": True,
"promo_country": "TR", "retry_count": 10, "paired_proxy_rotation": True,
"allow_missing_customer_session": True,
"use_sen": True, "use_so": True,
}
status, created = _pay153_request("/api/checkout", "POST", payload)
pay_job_id = str(created.get("job_id") or "")
if status >= 400 or not pay_job_id:
raise RuntimeError(str(created.get("error") or f"PAY153_HTTP_{status}"))
with _lock: _card_checkout_jobs[task_id].update(progress=18, message="Checkout extraction running", _pay_job_id=pay_job_id)
deadline = time.monotonic() + 15 * 60
while time.monotonic() < deadline:
status, progress = _pay153_request("/api/checkout-progress", params={"job_id": pay_job_id})
if status >= 400: raise RuntimeError(str(progress.get("error") or f"PAY153_PROGRESS_HTTP_{status}"))
state = str(progress.get("status") or "")
with _lock:
current = _card_checkout_jobs.get(task_id)
if not current: return
current.update(progress=min(96, max(18, int(progress.get("percent") or 0))), message=str(progress.get("text") or "Checkout extraction running"))
if state == "done":
result = progress.get("result") if isinstance(progress.get("result"), dict) else {}
_persist_checkout_context(_checkout_result_context(result, entry_valid, "isolated_card_flow"))
with _lock: _card_checkout_jobs[task_id].update(status="done", progress=100, message="Checkout completed", result=result, finished_at=time.time(), _access_token="")
return
if state in {"error", "cancelled"}: raise RuntimeError(str(progress.get("error") or progress.get("text") or "Checkout failed"))
time.sleep(2)
raise TimeoutError("CHECKOUT_TIMEOUT")
except Exception as exc:
with _lock:
child_job_id = str((_card_checkout_jobs.get(task_id) or {}).get("_pay_job_id") or "")
if child_job_id:
try:
_pay153_request("/api/checkout-cancel", "POST", {"job_id": child_job_id})
except Exception:
pass
with _lock:
if task_id in _card_checkout_jobs:
current = _card_checkout_jobs[task_id]
if current.get("status") != "cancelled":
current.update(status="error", progress=100, message="Checkout failed", error=f"{type(exc).__name__}: {exc}"[:500], finished_at=time.time(), _access_token="")
def _start_card_checkout_job(
access_token: str,
entry_proxy_pool: list[str],
exit_proxy_pool: list[str],
) -> dict:
task_id = secrets.token_hex(6); now = time.time()
job = {"id": task_id, "status": "queued", "progress": 0, "message": "Task created", "error": "", "result": {}, "created_at": now, "finished_at": None, "_access_token": access_token, "_entry_proxies": entry_proxy_pool, "_exit_proxies": exit_proxy_pool, "_pay_job_id": ""}
with _lock: _card_checkout_jobs[task_id] = job
threading.Thread(target=_run_isolated_card_checkout, args=(task_id,), daemon=True, name=f"card-checkout-{task_id}").start()
return job
@app.post("/api/card-flow/quick-checkout")
def public_card_flow_quick_checkout():
body = request.get_json(silent=True) or {}
try:
access_token = _extract_protocol_access_token(body.get("access_token") or body.get("at"))
entry_proxy_pool = normalize_user_proxy_pool(body.get("entry_proxy_pool") or body.get("bind_proxy_pool") or body.get("proxy_pool"))
exit_proxy_pool = normalize_user_proxy_pool(body.get("exit_proxy_pool") or body.get("promo_proxy_pool"))
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
job = _start_card_checkout_job(access_token, entry_proxy_pool, exit_proxy_pool)
task_id = str(job["id"])
return jsonify({"ok": True, "task_id": task_id, "status": "queued"}), 201
@app.get("/api/card-flow/task/<task_id>")
def public_card_flow_task(task_id: str):
value = str(task_id or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", value):
return jsonify({"ok": False, "error": "INVALID_TASK_ID"}), 400
with _lock:
isolated = _card_checkout_jobs.get(value)
if isolated:
return jsonify(_card_checkout_public(isolated))
status, payload = reg_console_request(f"/api/tasks/{value}", "GET")
if isinstance(payload, dict) and isinstance(payload.get("options"), dict):
payload = dict(payload)
payload["options"] = {
key: val for key, val in payload["options"].items()
if key not in {"entry_proxies", "exit_proxies", "proxies", "proxy_pool"}
}
return jsonify(payload), status
@app.post("/api/card-flow/task/<task_id>/cancel")
def public_card_flow_cancel(task_id: str):
value = str(task_id or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", value):
return jsonify({"ok": False, "error": "INVALID_TASK_ID"}), 400
with _lock:
job = _card_checkout_jobs.get(value)
child_job_id = str((job or {}).get("_pay_job_id") or "")
if job:
job.update(status="cancelled", progress=100, message="Task replaced by retry", error="", finished_at=time.time(), _access_token="")
if child_job_id:
try:
_pay153_request("/api/checkout-cancel", "POST", {"job_id": child_job_id})
except Exception:
pass
return jsonify({"ok": True, "task_id": value, "child_cancelled": bool(child_job_id)})
@app.get("/api/card-bind/config")
def card_bind_config():
return jsonify({
"ok": True,
"requires_access_token": True,
"max_batch_concurrency": MAX_BATCH_CONCURRENCY,
})
@app.post("/api/card-bind/session")
def card_bind_session():
body = request.get_json(silent=True) or {}
raw_at = body.get("access_token") or body.get("at")
if raw_at:
try:
body = dict(body)
body["access_token"] = _extract_protocol_access_token(raw_at)
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
try:
account_email = resolve_card_bind_email(body)
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 404
try:
proxy_pool = normalize_user_proxy_pool(body.get("proxy_pool") or [body.get("proxy")])
selected_proxy = normalize_user_proxy(body.get("proxy") or proxy_pool[0])
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
submitted_at = str(body.get("access_token") or "").strip()
if selected_proxy in proxy_pool:
selected_index = proxy_pool.index(selected_proxy)
proxy_candidates = proxy_pool[selected_index:] + proxy_pool[:selected_index]
else:
proxy_candidates = [selected_proxy] + proxy_pool
proxy_candidates = list(dict.fromkeys(proxy_candidates))[:5]
retryable_proxy_errors = {
"CARD_BIND_UPSTREAM_NETWORK_ERROR",
"CARD_BIND_HELPER_TIMEOUT",
}
returncode = 10
payload = {"ok": False, "error": "CARD_BIND_UPSTREAM_NETWORK_ERROR"}
attempted_proxies = 0
attempted_rounds = 0
stop_retrying = False
for proxy_round in range(1, CARD_BIND_PROXY_REUSE_ATTEMPTS + 1):
attempted_rounds = proxy_round
for candidate_proxy in proxy_candidates:
attempted_proxies += 1
returncode, payload = _run_card_bind_session_helper(account_email, candidate_proxy, submitted_at)
selected_proxy = candidate_proxy
if returncode == 0 and payload.get("ok"):
stop_retrying = True
break
if str(payload.get("error") or "") not in retryable_proxy_errors:
stop_retrying = True
break
if stop_retrying:
break
if proxy_round < CARD_BIND_PROXY_REUSE_ATTEMPTS:
time.sleep(0.5)
if returncode != 0 or not payload.get("ok"):
if str(payload.get("error") or "") in retryable_proxy_errors:
exhausted = (
attempted_rounds >= CARD_BIND_PROXY_REUSE_ATTEMPTS
and attempted_proxies >= len(proxy_candidates) * CARD_BIND_PROXY_REUSE_ATTEMPTS
)
payload = dict(payload)
payload.update({
"error": "CARD_BIND_PROXY_POOL_EXHAUSTED" if exhausted else payload.get("error"),
"detail": (
f"Tried {attempted_rounds} fresh connection round(s) across "
f"{len(proxy_candidates)} rotating endpoint(s) before reaching the upstream. "
f"Last: {str(payload.get('detail') or '')}"
)[:600],
"proxy_attempts": attempted_proxies,
"proxy_rounds": attempted_rounds,
"proxy_pool_size": len(proxy_candidates),
"proxy_pool_exhausted": exhausted,
})
upstream = int(payload.get("status") or 0)
detail = str(payload.get("detail") or payload.get("error") or "")
# New accounts can answer 403/5xx before any Checkout has initialized
# their Stripe context. Initialize once and then fetch a fresh session.
needs_payment_account = "no payment account exists" in detail.lower()
if submitted_at and (upstream in {403, 500, 502, 503, 504} or needs_payment_account):
probe = _start_key_probe("", account_email, selected_proxy, submitted_at, proxy_pool)
return jsonify({
"ok": True, "pending": True, "key_probe_id": str(probe.get("id") or ""),
"account_email": account_email, "publishable_key_source": "checkout_then_refetch",
"initialization_reason": "payment_account_missing" if needs_payment_account else "upstream_unavailable",
}), 202
return card_helper_error_response(payload)
if not str(payload.get("publishable_key") or "").startswith("pk_"):
if CARD_BIND_PUBLISHABLE_KEY.startswith("pk_"):
payload.update({
"publishable_key": CARD_BIND_PUBLISHABLE_KEY,
"publishable_key_source": "configured_protocol_fallback",
"pending": False,
})
return jsonify(payload)
probe = _start_key_probe(
str(payload.get("record_id") or ""), account_email, selected_proxy,
submitted_at, proxy_pool, initial_session=payload,
)
payload.update({
"pending": True,
"key_probe_id": str(probe.get("id") or ""),
"publishable_key_source": "checkout_then_refetch",
})
return jsonify(payload), 202
payload["publishable_key_source"] = "access_token_protocol"
return jsonify(payload)
@app.get("/")
def index():
if request.script_root == "/card-link":
return render_template("card-flow.html")
if request.script_root == "/protocol-pay":
return render_template("protocol-pay.html")
return render_template("index.html")
@app.get("/api/source/tasks")
def source_tasks():
try:
payload = reg_bridge_get("/api/internal/ph-short/tasks", {"limit": 100})
except (RuntimeError, ValueError) as exc:
return jsonify({"ok": False, "error": str(exc)}), 502
return jsonify({"ok": True, "items": payload.get("items") or []})
@app.get("/api/jobs")
def list_jobs():
cleanup_jobs()
with _lock:
items = sorted(_jobs.values(), key=lambda item: item.get("created_at", 0), reverse=True)
result = [public_job(item) for item in items]
return jsonify({"ok": True, "items": result})
@app.post("/api/jobs")
def create_job():
cleanup_jobs()
payload = request.get_json(silent=True) or {}
task_id = str(payload.get("task_id") or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", task_id):
return jsonify({"ok": False, "error": "请选择一个已完成的菲律宾短链任务"}), 400
try:
confirmation_token = str(payload.get("confirmation_token") or "").strip()
if confirmation_token and not re.fullmatch(r"ctoken_[A-Za-z0-9]+", confirmation_token):
raise ValueError("ConfirmationToken format is invalid")
preconfirmed_checkout = payload.get("preconfirmed_checkout") or {}
if not isinstance(preconfirmed_checkout, dict):
raise ValueError("Preconfirmed Checkout response is invalid")
saved_payment_method_id = str(payload.get("saved_payment_method_id") or "").strip()
if saved_payment_method_id and not re.fullmatch(r"pm_[A-Za-z0-9]+", saved_payment_method_id):
raise ValueError("Saved PaymentMethod format is invalid")
cards = [] if (confirmation_token or saved_payment_method_id) else parse_cards(payload.get("cards") or payload.get("card_pool"))
proxies = parse_proxies(payload.get("proxies") or payload.get("proxy_pool"))
try:
card_retry_count = int(payload.get("card_retry_count", 2))
except (TypeError, ValueError) as exc:
raise ValueError("\u91cd\u8bd5\u6b21\u6570\u5fc5\u987b\u662f\u6574\u6570") from exc
card_retry_count = max(0, min(10, card_retry_count))
source = reg_bridge_get("/api/internal/ph-short/tasks", {"limit": 100})
source_item = next((item for item in source.get("items") or [] if item.get("task_id") == task_id), None)
if not source_item:
raise RuntimeError("短链任务不存在或尚未完成")
except (RuntimeError, ValueError) as exc:
return jsonify({"ok": False, "error": str(exc)}), 409
with _lock:
active = next(
(
item for item in _jobs.values()
if item.get("task_id") == task_id and item.get("status") in {"queued", "running", "verification_required"}
),
None,
)
if active:
return jsonify({"ok": True, "job": public_job(active), "existing": True})
job_id = secrets.token_hex(6)
now = time.time()
job = {
"id": job_id,
"task_id": task_id,
"account_email": str(source_item.get("email") or ""),
"status": "queued",
"progress": 0,
"stage": "等待执行",
"message": "任务已创建",
"error": "",
"result": {},
"logs": [],
"cancel_requested": False,
"created_at": now,
"updated_at": now,
"finished_at": None,
"script_root": request.script_root,
"_cards": cards,
"_saved_payment_method_id": saved_payment_method_id,
"_confirmation_token": confirmation_token,
"_preconfirmed_checkout": preconfirmed_checkout,
"_proxies": proxies,
"_card_retry_count": card_retry_count,
"_process": None,
}
_jobs[job_id] = job
threading.Thread(target=run_job, args=(job_id,), name=f"ph-short-{job_id}", daemon=True).start()
return jsonify({"ok": True, "job": public_job(job)}), 201
@app.get("/api/jobs/<job_id>")
def get_job(job_id: str):
with _lock:
job = _jobs.get(job_id)
result = public_job(job) if job else None
if not result:
return jsonify({"ok": False, "error": "任务不存在或已过期"}), 404
return jsonify({"ok": True, "job": result})
@app.post("/api/jobs/<job_id>/cancel")
def cancel_job(job_id: str):
with _lock:
job = _jobs.get(job_id)
if not job:
return jsonify({"ok": False, "error": "任务不存在或已过期"}), 404
if job.get("status") in {"ready", "error", "cancelled"}:
return jsonify({"ok": True, "job": public_job(job)})
if job.get("status") == "verification_required" and not job.get("_process"):
job.update({
"status": "cancelled",
"progress": 100,
"stage": "已停止",
"message": "任务已停止",
"finished_at": time.time(),
"updated_at": time.time(),
})
return jsonify({"ok": True, "job": public_job(job)})
job["cancel_requested"] = True
job["message"] = "正在停止任务"
job["updated_at"] = time.time()
result = public_job(job)
return jsonify({"ok": True, "job": result})
@app.post("/api/jobs/<job_id>/resume")
def resume_job(job_id: str):
with _lock:
job = _jobs.get(job_id)
if not job:
return jsonify({"ok": False, "error": "任务不存在或已过期"}), 404
if job.get("status") != "verification_required":
return jsonify({"ok": False, "error": "当前任务不在等待验证状态"}), 409
if not job.get("_resume_payload"):
return jsonify({"ok": False, "error": "任务缺少验证续跑上下文"}), 409
job["cancel_requested"] = False
job["status"] = "queued"
job["stage"] = "准备确认验证结果"
job["message"] = "续跑任务已提交"
job["updated_at"] = time.time()
result = public_job(job)
threading.Thread(target=run_resume_job, args=(job_id,), name=f"ph-resume-{job_id}", daemon=True).start()
return jsonify({"ok": True, "job": result})
@app.delete("/api/jobs/<job_id>")
def delete_job(job_id: str):
with _lock:
job = _jobs.get(job_id)
if not job:
return jsonify({"ok": True})
if job.get("status") in {"queued", "running", "verification_required"}:
return jsonify({"ok": False, "error": "运行中的任务请先停止"}), 409
_jobs.pop(job_id, None)
return jsonify({"ok": True})
@app.get("/jobs/<job_id>/open")
def open_checkout(job_id: str):
with _lock:
job = _jobs.get(job_id)
result = dict((job or {}).get("result") or {})
short_url = str(result.get("short_url") or "")
if not short_url:
return redirect(f"{request.script_root}/?error=job_not_ready")
return redirect(short_url, code=302)
@app.get("/healthz")
def healthz():
cleanup_jobs()
with _lock:
active = sum(1 for item in _jobs.values() if item.get("status") in {"queued", "running", "verification_required"})
return jsonify({
"ok": True,
"service": "reg153-ph-short-protocol",
"mode": "stripe_checkout_protocol",
"temporary_browser": False,
"active_jobs": active,
"jobs": len(_jobs),
})
# --- Standalone saved-card payment: headless bootstrap, then protocol confirmation ---
def _extract_protocol_access_token(raw) -> str:
value = str(raw or "").strip()
if not value:
raise ValueError("AT_REQUIRED")
candidates: list[str] = []
if value.startswith(("{", "[")):
try:
obj = json.loads(value)
except Exception as exc:
raise ValueError("AT_JSON_INVALID") from exc
def collect_tokens(item) -> None:
if isinstance(item, dict):
for key in ("accessToken", "access_token", "token", "at"):
candidate = str(item.get(key) or "").strip()
if candidate.count(".") == 2 and candidate.startswith("eyJ"):
candidates.append(candidate)
for child in item.values():
collect_tokens(child)
elif isinstance(item, list):
for child in item:
collect_tokens(child)
collect_tokens(obj)
else:
if value.lower().startswith("bearer "):
value = value[7:].strip()
candidates.extend(
re.findall(r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", value)
)
if value.count(".") == 2 and value.startswith("eyJ"):
candidates.append(value)
candidates = list(dict.fromkeys(candidates))
if not candidates:
raise ValueError("AT_FORMAT_INVALID")
def token_rank(token: str) -> tuple[int, int, int]:
try:
claims = _decode_access_token_claims(token)
now = int(time.time())
exp = int(claims.get("exp") or 0)
issued = int(claims.get("iat") or 0)
return int(not exp or exp > now), issued, exp
except (TypeError, ValueError):
return 0, 0, 0
return max(candidates, key=token_rank)
def _protocol_token_identity(token: str) -> dict:
try:
segment = token.split(".")[1]
segment += "=" * (-len(segment) % 4)
claims = json.loads(base64.urlsafe_b64decode(segment.encode()).decode("utf-8"))
except Exception as exc:
raise ValueError("AT_PAYLOAD_INVALID") from exc
auth = claims.get("https://api.openai.com/auth") or {}
profile = claims.get("https://api.openai.com/profile") or {}
account_id = str(auth.get("chatgpt_account_id") or auth.get("account_id") or "").strip()
email = str(profile.get("email") or claims.get("email") or "").strip().lower()
if not account_id:
raise ValueError("AT_ACCOUNT_ID_MISSING")
exp = int(claims.get("exp") or 0)
if exp and exp <= int(time.time()):
raise ValueError("AT_EXPIRED")
return {"account_id": account_id, "email": email}
def _normalize_protocol_checkout_url(raw: str) -> tuple[str, str, str]:
value = str(raw or "").strip()
parsed = urlparse(value)
if parsed.scheme != "https":
raise ValueError("CHECKOUT_HTTPS_REQUIRED")
if parsed.hostname == "chatgpt.com":
return validate_short_url(value)
if parsed.hostname == "pay.openai.com":
parts = [part for part in parsed.path.split("/") if part]
if len(parts) >= 3 and parts[0] == "c" and parts[1] == "pay" and re.fullmatch(r"cs_[A-Za-z0-9_-]{12,}", parts[2]):
session_id = parts[2]
return f"https://chatgpt.com/checkout/openai_llc/{session_id}", "openai_llc", session_id
raise ValueError("CHECKOUT_URL_UNSUPPORTED")
def _protocol_public_job(job: dict) -> dict:
return {
"id": job.get("id"), "status": job.get("status"), "progress": int(job.get("progress") or 0),
"stage": job.get("stage"), "message": job.get("message"), "error": job.get("error"),
"result": dict(job.get("result") or {}), "logs": list(job.get("logs") or []),
"account_email": job.get("account_email") or "", "checkout_url": job.get("checkout_url") or "",
"created_at": job.get("created_at"), "updated_at": job.get("updated_at"), "finished_at": job.get("finished_at"),
}
def _protocol_update(job_id: str, **updates):
with _lock:
job = _protocol_pay_jobs.get(job_id)
if not job:
return
job.update(updates); job["updated_at"] = time.time()
def _protocol_log(job_id: str, level: str, message: str):
text = str(message or "").strip()
if not text:
return
with _lock:
job = _protocol_pay_jobs.get(job_id)
if not job:
return
logs = job.setdefault("logs", [])
logs.append({"time": time.strftime("%H:%M:%S"), "type": level, "message": text[:600]})
if len(logs) > 24:
del logs[:-24]
job["updated_at"] = time.time()
def _protocol_helper_error(stdout: str, fallback: str) -> str:
"""Extract a structured helper error, preserving non-JSON diagnostics."""
last_plain = ""
last_error = ""
for line in str(stdout or "").splitlines():
text = line.strip()
if not text:
continue
try:
event = json.loads(text)
except Exception:
last_plain = text[:500]
continue
if isinstance(event, dict) and event.get("type") == "error":
last_error = str(event.get("error") or "")
return last_error or last_plain or fallback
def _run_standalone_protocol_pay(job_id: str):
with _lock:
job = dict(_protocol_pay_jobs.get(job_id) or {})
if not job:
return
try:
_protocol_update(job_id, status="running", progress=8, stage="\u6821\u9a8c\u8d26\u53f7", message="\u6b63\u5728\u89e3\u6790 AT \u4e0e Checkout")
origin = dict(job.get("_origin_context") or {})
origin_cookies = dict(origin.get("session_cookies") or {})
account_cookies = _lookup_reg_account_session(job.get("account_email") or "", job.get("account_id") or "")
merged_cookies = dict(account_cookies)
merged_cookies.update(origin_cookies)
_protocol_log(job_id, "info", f"Session context merged: account={len(account_cookies)} checkout={len(origin_cookies)} total={len(merged_cookies)}")
snapshot = {
"short_url": job["checkout_url"], "processor_entity": job["processor_entity"],
"checkout_session_id": job["checkout_session_id"], "access_token": job["_access_token"],
"chatgpt_account_id": job["account_id"], "session_cookies": merged_cookies,
"user_agent": str(origin.get("checkout_user_agent") or "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:144.0) Gecko/20100101 Firefox/144.0"),
"checkout_device_id": str(origin.get("checkout_device_id") or uuid.uuid4()),
"checkout_chatgpt_session_id": str(origin.get("checkout_chatgpt_session_id") or ""),
"email": job.get("account_email") or "", "proxy": job["_proxies"][0],
"checkout_proxy": job["_proxies"][0],
"saved_payment_method_id": str(job.get("_saved_payment_method_id") or ""),
"preserve_checkout_identity": bool(origin),
"context_source": str(origin.get("source") or "generated"),
}
proc = subprocess.Popen(
[PAY153_PYTHON, STANDALONE_PAY_HELPER], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", bufsize=1,
)
with _lock:
if job_id in _protocol_pay_jobs:
_protocol_pay_jobs[job_id]["_process"] = proc
assert proc.stdin is not None and proc.stdout is not None
helper_mode = "prepare" if job.get("_defer_confirm") else "run"
proc.stdin.write(json.dumps({"mode": helper_mode, "snapshot": snapshot, "proxies": job["_proxies"]}, ensure_ascii=False)); proc.stdin.close()
result = {}; last_error = ""; last_plain = ""
for line in proc.stdout:
text = line.strip()
if not text: continue
try: event = json.loads(text)
except Exception:
last_plain = text[:500]
_protocol_log(job_id, "info", text); continue
if event.get("type") == "log":
message = str(event.get("message") or ""); phase = str(event.get("phase") or "")
_protocol_log(job_id, str(event.get("level") or "info"), message)
if phase == "validate": _protocol_update(job_id, progress=18, stage="\u68c0\u67e5\u5df2\u7ed1\u5361", message=message)
elif phase == "headless": _protocol_update(job_id, progress=38, stage="Checkout \u521d\u59cb\u5316", message=message)
elif phase == "headless_done": _protocol_update(job_id, progress=66, stage="\u534f\u8bae\u4e0a\u4e0b\u6587\u5c31\u7eea", message=message)
elif phase == "protocol": _protocol_update(job_id, progress=76, stage="\u534f\u8bae\u786e\u8ba4", message=message)
else:
lower = message.lower()
if "checkout confirm" in lower: _protocol_update(job_id, progress=84, stage="Checkout \u786e\u8ba4", message=message)
elif "stripe" in lower and "status=" in lower: _protocol_update(job_id, progress=93, stage="Stripe \u6700\u7ec8\u72b6\u6001", message=message)
elif event.get("type") == "result": result = dict(event.get("result") or {})
elif event.get("type") == "error": last_error = str(event.get("error") or "")
code = proc.wait(timeout=10)
if code != 0 or not result:
raise RuntimeError(last_error or last_plain or f"PAY_HELPER_EXIT_{code}")
status = str(result.get("status") or "").lower()
if status == "prepared" and job.get("_defer_confirm"):
private_prepared = dict(result.get("prepared") or {})
safe_result = dict(result.get("safe") or {})
if not private_prepared:
raise RuntimeError("PREPARED_CONTEXT_MISSING")
_protocol_update(job_id, status="prepared", progress=72, stage="\u51c6\u5907\u5b8c\u6210", message="\u5df2\u5c31\u7eea\uff0c\u7b49\u5f85\u6240\u6709\u4efb\u52a1\u540c\u65f6\u63d0\u4ea4", result=safe_result, _prepared=private_prepared)
return
if status == "verification_required":
_protocol_update(job_id, status="verification_required", progress=94, stage="\u7b49\u5f85\u9a8c\u8bc1", message="\u652f\u4ed8\u9700\u8981\u989d\u5916\u9a8c\u8bc1", result=result)
elif status == "pending_verification":
_protocol_update(job_id, status="pending_verification", progress=98, stage="\u7b49\u5f85\u8ba2\u9605\u540c\u6b65", message="Stripe \u5df2\u5b8c\u6210\uff0c\u6b63\u5728\u7b49\u5f85\u8ba2\u9605\u7ec8\u6001", result=result)
else:
_protocol_update(job_id, status="ready", progress=100, stage="\u652f\u4ed8\u5b8c\u6210", message="\u7eaf\u534f\u8bae\u76f4\u5361\u652f\u4ed8\u5df2\u5b8c\u6210", result=result, finished_at=time.time())
except Exception as exc:
message = str(exc)
if message.startswith("RuntimeError: "):
message = message[14:]
_protocol_log(job_id, "error", message)
_protocol_update(job_id, status="error", progress=100, stage="\u6267\u884c\u5931\u8d25", message=message, error=message, finished_at=time.time())
finally:
with _lock:
if job_id in _protocol_pay_jobs:
_protocol_pay_jobs[job_id]["_process"] = None
_protocol_pay_jobs[job_id].pop("_access_token", None)
_protocol_pay_jobs[job_id].pop("_cards", None)
_protocol_pay_jobs[job_id].pop("_saved_payment_method_id", None)
def _unified_public_job(job: dict) -> dict:
return {
"id": job.get("id"), "status": job.get("status"),
"progress": int(job.get("progress") or 0), "stage": job.get("stage") or "",
"message": job.get("message") or "", "error": job.get("error") or "",
"result": dict(job.get("result") or {}),
"account_email": job.get("account_email") or "",
"checkout_url": job.get("checkout_url") or "",
"created_at": job.get("created_at"), "updated_at": job.get("updated_at"),
"finished_at": job.get("finished_at"),
}
def _unified_update(job_id: str, **updates) -> None:
with _lock:
job = _unified_flow_jobs.get(job_id)
if not job:
return
job.update(updates)
job["updated_at"] = time.time()
def _unified_cancelled(job_id: str) -> bool:
with _lock:
return str((_unified_flow_jobs.get(job_id) or {}).get("status") or "") == "cancelled"
def _start_unified_protocol_child(parent: dict, checkout_result: dict) -> tuple[str, str]:
parent_job_id = str(parent.get("id") or "")
if _unified_cancelled(parent_job_id):
raise InterruptedError("任务已停止")
entry_proxies = list(parent.get("_entry_proxies") or [])
context = _checkout_result_context(checkout_result, entry_proxies, "unified_card_flow")
raw_url = str(context.get("checkout_url") or "")
checkout_url, processor, session_id = _normalize_protocol_checkout_url(raw_url)
context.update({
"checkout_url": checkout_url,
"processor_entity": processor,
"checkout_session_id": session_id,
"source": "unified_card_flow",
})
_persist_checkout_context(context)
origin_context = _lookup_checkout_context(session_id) or context
origin_proxy = str(origin_context.get("checkout_proxy") or "").strip()
selected_proxy = normalize_user_proxy(origin_proxy or entry_proxies[0])
protocol_job_id = secrets.token_hex(6)
now = time.time()
protocol_job = {
"id": protocol_job_id, "status": "queued", "progress": 0,
"stage": "等待执行", "message": "统一流程已交接到协议支付", "error": "",
"result": {}, "logs": [], "account_email": parent.get("account_email") or "",
"account_id": parent.get("account_id") or "", "checkout_url": checkout_url,
"processor_entity": processor, "checkout_session_id": session_id,
"created_at": now, "updated_at": now, "finished_at": None,
"_access_token": parent.get("_access_token") or "", "_proxies": [selected_proxy],
"_cards": [], "_saved_payment_method_id": parent.get("_payment_method_id") or "",
"_origin_context": origin_context, "_process": None,
"_defer_confirm": True, "_prepared": None,
}
with _lock:
parent_job = _unified_flow_jobs.get(parent_job_id)
if not parent_job or parent_job.get("status") == "cancelled":
raise InterruptedError("任务已停止")
_protocol_pay_jobs[protocol_job_id] = protocol_job
parent_job.update(_protocol_job_id=protocol_job_id, checkout_url=checkout_url, updated_at=time.time())
threading.Thread(
target=_run_standalone_protocol_pay,
args=(protocol_job_id,),
daemon=True,
name=f"unified-protocol-{protocol_job_id}",
).start()
return protocol_job_id, checkout_url
def _run_unified_flow(job_id: str) -> None:
with _lock:
job = dict(_unified_flow_jobs.get(job_id) or {})
if not job:
return
try:
_unified_update(job_id, status="running", progress=5, stage="设置默认卡", message="正在确认本次绑定的支付方式")
default_result = None
default_error = ""
for index, candidate in enumerate(list(job.get("_entry_proxies") or [])[:3], 1):
if _unified_cancelled(job_id):
raise InterruptedError("任务已停止")
_unified_update(job_id, progress=5 + index * 3, message=f"正在通过绑卡线路 {index} 设置默认卡")
try:
returncode, payload = _run_card_set_default(
str(job.get("account_email") or ""),
str(job.get("_payment_method_id") or ""),
candidate,
str(job.get("_access_token") or ""),
)
if returncode == 0 and payload.get("ok"):
default_result = payload
break
default_error = str(payload.get("error") or f"SET_DEFAULT_EXIT_{returncode}")
default_detail = str(payload.get("detail") or "").strip()
if default_detail and default_detail not in default_error:
default_error = f"{default_error}: {default_detail}"
if int(payload.get("status") or 0) in {401, 422}:
break
except Exception as exc:
default_error = f"{type(exc).__name__}: {exc}"
if default_result is None:
raise RuntimeError(default_error or "SET_DEFAULT_FAILED")
_unified_update(job_id, progress=18, stage="创建 Checkout", message="绑卡已确认,正在提取 Checkout")
checkout_job = _start_card_checkout_job(
str(job.get("_access_token") or ""),
list(job.get("_entry_proxies") or []),
list(job.get("_exit_proxies") or []),
)
checkout_task_id = str(checkout_job.get("id") or "")
_unified_update(job_id, _checkout_task_id=checkout_task_id)
checkout_result = {}
while True:
if _unified_cancelled(job_id):
raise InterruptedError("任务已停止")
with _lock:
child = dict(_card_checkout_jobs.get(checkout_task_id) or {})
if not child:
raise RuntimeError("CHECKOUT_CHILD_MISSING")
child_status = str(child.get("status") or "")
child_progress = int(child.get("progress") or 0)
_unified_update(
job_id,
progress=min(58, 18 + round(child_progress * 0.40)),
stage="创建 Checkout",
message=str(child.get("message") or "正在提取 Checkout"),
)
if child_status == "done":
checkout_result = dict(child.get("result") or {})
break
if child_status in {"error", "failed", "cancelled"}:
raise RuntimeError(str(child.get("error") or child.get("message") or "CHECKOUT_FAILED"))
time.sleep(0.5)
_unified_update(job_id, progress=60, stage="协议支付", message="Checkout 已生成,正在复用原始会话执行支付")
protocol_job_id, checkout_url = _start_unified_protocol_child(job, checkout_result)
_unified_update(job_id, checkout_url=checkout_url)
while True:
if _unified_cancelled(job_id):
raise InterruptedError("任务已停止")
with _lock:
child = dict(_protocol_pay_jobs.get(protocol_job_id) or {})
if not child:
raise RuntimeError("PROTOCOL_CHILD_MISSING")
child_status = str(child.get("status") or "")
child_progress = int(child.get("progress") or 0)
_unified_update(
job_id,
status="prepared" if child_status == "prepared" else "running",
progress=min(99, 60 + round(child_progress * 0.39)),
stage=str(child.get("stage") or "协议支付"),
message=str(child.get("message") or "正在执行协议支付"),
)
if child_status in {"ready", "verification_required", "pending_verification"}:
result = dict(child.get("result") or {})
result["checkout_url"] = checkout_url
if child_status == "ready":
_unified_update(
job_id, status="ready", progress=100, stage="完成",
message="绑卡、提链与协议支付已完成", result=result,
finished_at=time.time(),
)
else:
_unified_update(
job_id, status=child_status, progress=96,
stage=str(child.get("stage") or "等待验证"),
message=str(child.get("message") or "等待最终状态确认"),
result=result,
)
return
if child_status in {"error", "cancelled"}:
raise RuntimeError(str(child.get("error") or child.get("message") or "PROTOCOL_PAY_FAILED"))
time.sleep(0.5)
except InterruptedError as exc:
_unified_update(job_id, status="cancelled", progress=100, stage="已停止", message=str(exc), finished_at=time.time())
except Exception as exc:
if not _unified_cancelled(job_id):
message = str(exc)
if message.startswith("RuntimeError: "):
message = message[14:]
_unified_update(
job_id, status="error", progress=100, stage="执行失败",
message=message, error=message, finished_at=time.time(),
)
finally:
with _lock:
current = _unified_flow_jobs.get(job_id)
if current:
current.pop("_access_token", None)
current.pop("_payment_method_id", None)
current.pop("_entry_proxies", None)
current.pop("_exit_proxies", None)
@app.post("/api/unified-flow/jobs")
def create_unified_flow_job():
body = request.get_json(silent=True) or {}
try:
token = _extract_protocol_access_token(body.get("access_token") or body.get("at"))
identity = _protocol_token_identity(token)
payment_method_id = str(body.get("payment_method_id") or "").strip()
if not re.fullmatch(r"pm_[A-Za-z0-9]+", payment_method_id):
raise ValueError("INVALID_PAYMENT_METHOD")
entry_proxy_pool = normalize_user_proxy_pool(
body.get("entry_proxy_pool") or body.get("bind_proxy_pool") or body.get("proxy_pool")
)
exit_proxy_pool = normalize_user_proxy_pool(
body.get("exit_proxy_pool") or body.get("promo_proxy_pool")
)
account_email = str(identity.get("email") or "").strip().lower()
if not account_email:
account_email = resolve_card_bind_email({"access_token": token})
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
job_id = secrets.token_hex(6)
now = time.time()
job = {
"id": job_id, "status": "queued", "progress": 0, "stage": "等待执行",
"message": "统一任务已创建", "error": "", "result": {},
"account_email": account_email, "account_id": identity.get("account_id") or "",
"checkout_url": "", "created_at": now, "updated_at": now, "finished_at": None,
"_access_token": token, "_payment_method_id": payment_method_id,
"_entry_proxies": entry_proxy_pool, "_exit_proxies": exit_proxy_pool,
"_checkout_task_id": "", "_protocol_job_id": "",
}
with _lock:
_unified_flow_jobs[job_id] = job
if len(_unified_flow_jobs) > FLOW_JOB_CACHE_LIMIT:
finished = sorted(
(item for item in _unified_flow_jobs.values() if item.get("status") in {"ready", "error", "cancelled", "pending_verification"}),
key=lambda item: item.get("created_at", 0),
)
for old in finished[:max(0, len(_unified_flow_jobs) - FLOW_JOB_CACHE_LIMIT)]:
_unified_flow_jobs.pop(str(old.get("id") or ""), None)
threading.Thread(target=_run_unified_flow, args=(job_id,), daemon=True, name=f"unified-flow-{job_id}").start()
return jsonify({"ok": True, "job": _unified_public_job(job)}), 201
@app.post("/api/unified-flow/batch-confirm")
def confirm_unified_flow_batch():
body = request.get_json(silent=True) or {}
job_ids = []
for raw in body.get("job_ids") or []:
value = str(raw or "").strip().lower()
if value and value not in job_ids:
job_ids.append(value)
if (
not job_ids
or len(job_ids) > MAX_BATCH_CONCURRENCY
or any(not re.fullmatch(r"[a-f0-9]{12}", value) for value in job_ids)
):
return jsonify({"ok": False, "error": "JOB_IDS_INVALID"}), 400
with _lock:
missing = [value for value in job_ids if value not in _unified_flow_jobs]
protocol_ids = {
value: str((_unified_flow_jobs.get(value) or {}).get("_protocol_job_id") or "")
for value in job_ids
}
unready = [
value for value in job_ids
if (_unified_flow_jobs.get(value) or {}).get("status") != "prepared"
or not protocol_ids[value]
or (_protocol_pay_jobs.get(protocol_ids[value]) or {}).get("status") != "prepared"
]
if not missing and not unready:
for value in job_ids:
child = _protocol_pay_jobs[protocol_ids[value]]
child.update(
status="releasing", progress=78,
stage="\u7b49\u5f85\u540c\u6b65\u5c4f\u969c",
message="\u652f\u4ed8\u5df2\u5c31\u7eea\uff0c\u7b49\u5f85\u5e76\u53d1\u653e\u884c",
updated_at=time.time(),
)
_unified_flow_jobs[value].update(
status="running", progress=90,
stage="\u5e76\u53d1\u652f\u4ed8\u653e\u884c",
message="\u6240\u6709\u51c6\u5907\u4efb\u52a1\u5df2\u5230\u8fbe\u5c4f\u969c",
updated_at=time.time(),
)
if missing:
return jsonify({"ok": False, "error": "TASK_NOT_FOUND", "job_ids": missing}), 404
if unready:
return jsonify({"ok": False, "error": "TASKS_NOT_PREPARED", "job_ids": unready}), 409
gate = threading.Event()
for value in job_ids:
protocol_job_id = protocol_ids[value]
threading.Thread(
target=_run_prepared_protocol_confirm,
args=(protocol_job_id, gate),
daemon=True,
name=f"unified-confirm-{protocol_job_id}",
).start()
time.sleep(0.08)
gate.set()
with _lock:
jobs = [_unified_public_job(_unified_flow_jobs[value]) for value in job_ids]
return jsonify({"ok": True, "jobs": jobs, "released": len(jobs), "mode": "simultaneous"})
@app.get("/api/unified-flow/jobs/<job_id>")
def get_unified_flow_job(job_id: str):
value = str(job_id or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", value):
return jsonify({"ok": False, "error": "INVALID_TASK_ID"}), 400
with _lock:
job = _unified_flow_jobs.get(value)
payload = _unified_public_job(job) if job else None
if not payload:
return jsonify({"ok": False, "error": "TASK_NOT_FOUND"}), 404
return jsonify({"ok": True, "job": payload})
@app.post("/api/unified-flow/jobs/<job_id>/cancel")
def cancel_unified_flow_job(job_id: str):
value = str(job_id or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", value):
return jsonify({"ok": False, "error": "INVALID_TASK_ID"}), 400
with _lock:
job = _unified_flow_jobs.get(value)
if not job:
return jsonify({"ok": False, "error": "TASK_NOT_FOUND"}), 404
checkout_task_id = str(job.get("_checkout_task_id") or "")
protocol_job_id = str(job.get("_protocol_job_id") or "")
job.update(status="cancelled", progress=100, stage="已停止", message="用户停止任务", finished_at=time.time())
job.pop("_access_token", None)
job.pop("_payment_method_id", None)
job.pop("_entry_proxies", None)
job.pop("_exit_proxies", None)
checkout_child = _card_checkout_jobs.get(checkout_task_id)
pay153_job_id = str((checkout_child or {}).get("_pay_job_id") or "")
if checkout_child:
checkout_child.update(status="cancelled", progress=100, message="Parent task cancelled", _access_token="")
protocol_child = _protocol_pay_jobs.get(protocol_job_id)
process = (protocol_child or {}).get("_process")
if pay153_job_id:
try:
_pay153_request("/api/checkout-cancel", "POST", {"job_id": pay153_job_id})
except Exception:
pass
if process and process.poll() is None:
try:
process.terminate()
except Exception:
pass
with _lock:
payload = _unified_public_job(_unified_flow_jobs[value])
return jsonify({"ok": True, "job": payload})
@app.get("/protocol-pay/")
def standalone_protocol_pay_page():
return render_template("protocol-pay.html")
@app.post("/api/protocol-pay/jobs")
def create_standalone_protocol_pay_job():
body = request.get_json(silent=True) or {}
try:
token = _extract_protocol_access_token(body.get("access_token") or body.get("at"))
identity = _protocol_token_identity(token)
payment_method_id = str(body.get("payment_method_id") or "").strip()
if payment_method_id and not re.fullmatch(r"pm_[A-Za-z0-9]+", payment_method_id):
raise ValueError("INVALID_PAYMENT_METHOD")
raw_cards = body.get("cards") or body.get("card") or []
cards = parse_cards(raw_cards) if raw_cards else []
checkout_url, processor, session_id = _normalize_protocol_checkout_url(body.get("checkout_url") or body.get("url"))
origin_context = _lookup_checkout_context(session_id)
origin_proxy_raw = str(origin_context.get("checkout_proxy") or "")
ttl_match = re.search(r"-t-(\d+)", origin_proxy_raw)
origin_created = float(origin_context.get("created_at") or 0)
if ttl_match and origin_created:
ttl_seconds = max(60, int(ttl_match.group(1)) * 60)
age_seconds = max(0, time.time() - origin_created)
if age_seconds > max(60, ttl_seconds - 30):
raise ValueError(
f"CHECKOUT_PROXY_SESSION_EXPIRED: link age {int(age_seconds // 60)}m exceeds sticky session {int(ttl_seconds // 60)}m; regenerate the Checkout link"
)
proxies = []
origin_proxy = str(origin_context.get("checkout_proxy") or "").strip()
if origin_proxy:
proxies.append(normalize_user_proxy(origin_proxy))
proxy_errors = []
for _ in range(3):
try:
generated = reg_bridge_get("/api/internal/ph-short/proxy", {"country": "US"})
candidate = normalize_user_proxy(str(generated.get("proxy") or ""))
if candidate not in proxies:
proxies.append(candidate)
except Exception as exc:
proxy_errors.append(str(exc))
if not proxies:
raise RuntimeError("AUTO_PROXY_FAILED: " + (proxy_errors[-1] if proxy_errors else "NO_PROXY_RETURNED"))
preflight = subprocess.run(
[PAY153_PYTHON, PROXY_PREFLIGHT_HELPER],
input=json.dumps({"proxies": proxies, "expected": "US", "limit": 3}, ensure_ascii=False),
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=45, check=False,
)
try:
checked = json.loads((preflight.stdout or "{}").strip().splitlines()[-1])
except Exception:
checked = {}
proxies = list(checked.get("proxies") or [])
if not proxies:
raise RuntimeError(
f"US_PROXY_PREFLIGHT_FAILED: {int(checked.get('valid') or 0)}/{int(checked.get('total') or 0)}"
)
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
except RuntimeError as exc:
return jsonify({"ok": False, "error": str(exc)}), 502
job_id = secrets.token_hex(6); now = time.time()
job = {
"id": job_id, "status": "queued", "progress": 0, "stage": "\u7b49\u5f85\u6267\u884c", "message": "\u4efb\u52a1\u5df2\u521b\u5efa",
"error": "", "result": {}, "logs": [], "account_email": identity.get("email") or "",
"account_id": identity["account_id"], "checkout_url": checkout_url, "processor_entity": processor,
"checkout_session_id": session_id, "created_at": now, "updated_at": now, "finished_at": None,
"_access_token": token, "_proxies": proxies, "_cards": cards, "_origin_context": origin_context, "_process": None,
"_saved_payment_method_id": payment_method_id,
"_defer_confirm": bool(body.get("defer_confirm")), "_prepared": None,
}
with _lock:
_protocol_pay_jobs[job_id] = job
if len(_protocol_pay_jobs) > FLOW_JOB_CACHE_LIMIT:
finished = sorted((x for x in _protocol_pay_jobs.values() if x.get("status") in {"ready","error","cancelled","pending_verification"}), key=lambda x:x.get("created_at",0))
for old in finished[:max(0,len(_protocol_pay_jobs)-FLOW_JOB_CACHE_LIMIT)]: _protocol_pay_jobs.pop(str(old.get("id")),None)
threading.Thread(target=_run_standalone_protocol_pay, args=(job_id,), daemon=True, name=f"protocol-pay-{job_id}").start()
return jsonify({"ok": True, "job": _protocol_public_job(job)}), 201
def _run_prepared_protocol_confirm(job_id: str, gate: threading.Event) -> None:
with _lock:
job = dict(_protocol_pay_jobs.get(job_id) or {})
if not job or not job.get("_prepared"):
return
try:
_protocol_update(job_id, status="queued", progress=78, stage="\u7b49\u5f85\u540c\u6b65\u5c4f\u969c", message="\u6240\u6709\u4efb\u52a1\u5df2\u5c31\u7eea")
gate.wait(timeout=30)
_protocol_update(job_id, status="running", progress=82, stage="\u540c\u65f6\u63d0\u4ea4\u8ba2\u9605", message="\u5c4f\u969c\u5df2\u91ca\u653e")
proc = subprocess.Popen([PAY153_PYTHON, STANDALONE_PAY_HELPER], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", bufsize=1)
with _lock:
if job_id in _protocol_pay_jobs: _protocol_pay_jobs[job_id]["_process"] = proc
assert proc.stdin is not None and proc.stdout is not None
proc.stdin.write(json.dumps({"mode":"confirm","prepared":job["_prepared"]},ensure_ascii=False));proc.stdin.close()
result={};last_error=""
for line in proc.stdout:
text=line.strip()
if not text:continue
try:event=json.loads(text)
except Exception:_protocol_log(job_id,"info",text);continue
if event.get("type")=="log":
message=str(event.get("message") or "");_protocol_log(job_id,str(event.get("level") or "info"),message)
if "checkout confirm" in message.lower():_protocol_update(job_id,progress=90,stage="Checkout \u786e\u8ba4",message=message)
elif event.get("type")=="result":result=dict(event.get("result") or {})
elif event.get("type")=="error":last_error=str(event.get("error") or "")
code=proc.wait(timeout=10)
if code!=0 or not result:raise RuntimeError(last_error or f"PAY_HELPER_EXIT_{code}")
result_status=str(result.get("status") or "").lower()
if result_status=="verification_required":_protocol_update(job_id,status="verification_required",progress=94,stage="\u7b49\u5f85\u9a8c\u8bc1",message="\u652f\u4ed8\u9700\u8981\u989d\u5916\u9a8c\u8bc1",result=result)
elif result_status=="pending_verification":_protocol_update(job_id,status="pending_verification",progress=98,stage="\u7b49\u5f85\u8ba2\u9605\u540c\u6b65",message="Stripe \u5df2\u5b8c\u6210\uff0c\u6b63\u5728\u7b49\u5f85\u8ba2\u9605\u7ec8\u6001",result=result)
else:_protocol_update(job_id,status="ready",progress=100,stage="\u8ba2\u9605\u5b8c\u6210",message="\u540c\u6b65\u534f\u8bae\u8ba2\u9605\u5df2\u5b8c\u6210",result=result,finished_at=time.time())
except Exception as exc:
message=str(exc);_protocol_log(job_id,"error",message);_protocol_update(job_id,status="error",progress=100,stage="\u6267\u884c\u5931\u8d25",message=message,error=message,finished_at=time.time())
finally:
with _lock:
if job_id in _protocol_pay_jobs:
_protocol_pay_jobs[job_id]["_process"]=None;_protocol_pay_jobs[job_id].pop("_prepared",None)
@app.post("/api/protocol-pay/batch-confirm")
def confirm_protocol_pay_batch():
body=request.get_json(silent=True) or {};job_ids=[]
for value in body.get("job_ids") or []:
jid=str(value or "").strip()
if jid and jid not in job_ids:job_ids.append(jid)
if not job_ids or len(job_ids)>MAX_BATCH_CONCURRENCY:return jsonify({"ok":False,"error":"JOB_IDS_INVALID"}),400
with _lock:
missing=[jid for jid in job_ids if jid not in _protocol_pay_jobs]
unready=[jid for jid in job_ids if jid in _protocol_pay_jobs and _protocol_pay_jobs[jid].get("status")!="prepared"]
if missing:return jsonify({"ok":False,"error":"TASK_NOT_FOUND","job_ids":missing}),404
if unready:return jsonify({"ok":False,"error":"TASKS_NOT_PREPARED","job_ids":unready}),409
gate=threading.Event()
for jid in job_ids:
threading.Thread(target=_run_prepared_protocol_confirm,args=(jid,gate),daemon=True,name=f"protocol-confirm-{jid}").start()
time.sleep(0.08);gate.set()
with _lock:jobs=[_protocol_public_job(_protocol_pay_jobs[jid]) for jid in job_ids]
return jsonify({"ok":True,"jobs":jobs,"released":len(jobs),"mode":"simultaneous"})
@app.get("/api/protocol-pay/jobs/<job_id>")
def get_standalone_protocol_pay_job(job_id: str):
with _lock:
job = _protocol_pay_jobs.get(str(job_id or ""))
payload = _protocol_public_job(job) if job else None
if not payload:
return jsonify({"ok": False, "error": "TASK_NOT_FOUND"}), 404
return jsonify({"ok": True, "job": payload})
if __name__ == "__main__":
app.run(host="127.0.0.1", port=int(os.getenv("PORT", "5088")), debug=False)
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import os
import re
import secrets
import shutil
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path
from urllib.parse import quote, unquote, urlencode, urlparse, urlsplit
from urllib.request import Request, urlopen
from flask import Flask, jsonify, redirect, render_template, request
def _load_local_env() -> None:
"""Load local deployment values without overwriting process variables."""
for filename in (".env", ".env.local"):
path = Path(__file__).resolve().parent / filename
if not path.is_file():
continue
try:
lines = path.read_text(encoding="utf-8").splitlines()
except OSError:
continue
for raw in lines:
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
name, value = line.split("=", 1)
name = name.strip()
value = value.strip().strip('"').strip("'")
if name and name not in os.environ:
os.environ[name] = value
_load_local_env()
# Worker stdout is parsed as UTF-8 JSON. Force child interpreters away from
# the Windows console code page so currency symbols remain serializable.
os.environ["PYTHONIOENCODING"] = "utf-8"
os.environ["PYTHONUTF8"] = "1"
async def sentinel_headers(
proxy: str = "",
action: str = "",
device_id: str = "",
did: str = "",
) -> dict[str, str]:
"""Return deployment-provided Sentinel headers, if configured.
The sanitized bundle does not contain a Sentinel token provider. Keeping
the hook asynchronous preserves the protocol worker contract while letting
an upstream deployment inject its own provider without embedding tokens.
"""
return {}
ROOT = Path(__file__).resolve().parent
app = Flask(__name__, template_folder="templates", static_folder="static")
app.json.ensure_ascii = False
REG_SESSION_SECRET = os.getenv("REG_SESSION_SECRET", "").strip()
REG_SESSION_COOKIE = os.getenv("REG_SESSION_COOKIE", "reg_access").strip() or "reg_access"
REG_INTERNAL_BASE = os.getenv("REG_INTERNAL_BASE", "http://127.0.0.1:18081").strip().rstrip("/")
PH_SHORT_BRIDGE_KEY = os.getenv("PH_SHORT_BRIDGE_KEY", "").strip()
JOB_TTL_SECONDS = max(1800, int(os.getenv("PH_PORTAL_JOB_TTL", "86400")))
MAX_JOBS = max(20, min(500, int(os.getenv("PH_PORTAL_MAX_JOBS", "120"))))
HARD_MAX_BATCH_CONCURRENCY = 200
MAX_BATCH_CONCURRENCY = max(
1,
min(
HARD_MAX_BATCH_CONCURRENCY,
int(os.getenv("PH_PORTAL_MAX_BATCH_CONCURRENCY", str(HARD_MAX_BATCH_CONCURRENCY))),
),
)
FLOW_JOB_CACHE_LIMIT = max(100, MAX_BATCH_CONCURRENCY)
def _resolve_helper_python() -> str:
configured = os.getenv("PAY153_PYTHON", "").strip()
candidates = [configured] if configured else []
# The sanitized bundle is also run directly on Windows. Prefer the
# workspace environment when it contains the helper dependencies, then
# fall back to the bundle environment and the current interpreter.
candidates.extend([
"/opt/pay153/venv/bin/python",
str(ROOT / ".venv" / "Scripts" / "python.exe"),
str(ROOT / ".venv" / "bin" / "python"),
str(ROOT.parent / ".venv" / "Scripts" / "python.exe"),
str(ROOT.parent / ".venv" / "bin" / "python"),
sys.executable,