Spaces:
Paused
Paused
Download app.py from bxm0121/session-link-gen: direct link, hf CLI and curl.
- Browser
- Download file 296 kB
-
https://huggingface.co/spaces/bxm0121/session-link-gen/resolve/main/app.py
- Command line
-
hf download hf://spaces/bxm0121/session-link-gen/app.py
-
curl -L -o app.py https://huggingface.co/spaces/bxm0121/session-link-gen/resolve/main/app.py
296 kB
from __future__ import annotations
import contextvars
import base64
import binascii
import hashlib
import json
import logging
import os
import random
import re
import secrets
import sqlite3
import time
import uuid
from collections import Counter, deque
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from pathlib import Path
from threading import Event, Lock, Thread, local
from typing import Any
from urllib.parse import parse_qsl, quote, unquote, urlencode, urljoin, urlsplit, urlunsplit
import requests
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, JSONResponse, Response
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, ConfigDict, Field
try:
from curl_cffi.requests import Session as CurlCffiSession # type: ignore
except ImportError: # pragma: no cover - optional dependency
CurlCffiSession = None # type: ignore
DEFAULT_STRIPE_PK = (
"pk_live_51HOrSwC6h1nxGoI3lTAgRjYVrz4dU3fVOabyCcKR3pbEJguCVAlqCxdxCUvoRh1XWwRac"
"ViovU3kLKvpkjh7IqkW00iXQsjo3n"
)
STRIPE_VERSION_FULL = (
os.getenv(
"OPENAI_PAY_STRIPE_VERSION",
"2025-03-31.basil; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1",
).strip()
or "2025-03-31.basil; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1"
)
UPI_STRIPE_VERSION_FULL = (
os.getenv(
"OPENAI_PAY_UPI_STRIPE_VERSION",
"2026-06-24.dahlia; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1",
).strip()
or "2026-06-24.dahlia; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1"
)
DEFAULT_TIMEOUT = 30
def env_int(name: str, default: int, minimum: int = 1, maximum: int = 10000) -> int:
try:
value = int(str(os.getenv(name, str(default))).strip())
except (TypeError, ValueError):
return default
return min(max(value, minimum), maximum)
def env_bool(name: str, default: bool) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return str(raw).strip().lower() not in {"0", "false", "no", "off", ""}
APPROVE_POOL_WORKERS = env_int("OPENAI_PAY_APPROVE_POOL_WORKERS", 50, minimum=1, maximum=100)
APPROVE_POOL_MAX_WORKERS = env_int(
"OPENAI_PAY_APPROVE_POOL_MAX_WORKERS",
max(APPROVE_POOL_WORKERS, 75),
minimum=1,
maximum=100,
)
APPROVE_POOL_MIN_WORKERS = env_int(
"OPENAI_PAY_APPROVE_POOL_MIN_WORKERS",
min(APPROVE_POOL_WORKERS, 25),
minimum=1,
maximum=100,
)
APPROVE_POOL_ADAPTIVE = env_bool("OPENAI_PAY_APPROVE_POOL_ADAPTIVE", True)
APPROVE_POOL_ADAPT_INTERVAL = env_int("OPENAI_PAY_APPROVE_POOL_ADAPT_INTERVAL", 100, minimum=10, maximum=1000)
APPROVE_POOL_RAMP_STEP = env_int("OPENAI_PAY_APPROVE_POOL_RAMP_STEP", 5, minimum=1, maximum=50)
APPROVE_POOL_LATENCY_LOW_MS = env_int("OPENAI_PAY_APPROVE_POOL_LATENCY_LOW_MS", 3500, minimum=100, maximum=30000)
APPROVE_POOL_LATENCY_HIGH_MS = env_int("OPENAI_PAY_APPROVE_POOL_LATENCY_HIGH_MS", 8000, minimum=500, maximum=60000)
APPROVE_POOL_ERROR_RATE_HIGH_PERCENT = env_int(
"OPENAI_PAY_APPROVE_POOL_ERROR_RATE_HIGH_PERCENT",
5,
minimum=1,
maximum=100,
)
APPROVE_POOL_EARLY_SHUTDOWN = env_bool("OPENAI_PAY_APPROVE_POOL_EARLY_SHUTDOWN", True)
APPROVE_MAX_ATTEMPTS = env_int("OPENAI_PAY_APPROVE_MAX_ATTEMPTS", 3, minimum=1, maximum=5)
APPROVE_RETRY_DELAY_MS = env_int("OPENAI_PAY_APPROVE_RETRY_DELAY_MS", 700, minimum=100, maximum=5000)
LONG_LINK_MAX_ATTEMPTS = env_int("OPENAI_PAY_LONG_LINK_MAX_ATTEMPTS", 10, minimum=1, maximum=50)
ADMIN_LONG_LINK_MAX_ATTEMPTS = env_int("OPENAI_PAY_ADMIN_LONG_LINK_MAX_ATTEMPTS", 10, minimum=1, maximum=100)
APPROVE_PROGRESS_INTERVAL = env_int("OPENAI_PAY_APPROVE_PROGRESS_INTERVAL", 50, minimum=1, maximum=1000)
APPROVE_BLOCKED_RESTART_AFTER = env_int("OPENAI_PAY_APPROVE_BLOCKED_RESTART_AFTER", 600, minimum=0, maximum=10000)
APPROVE_BLOCKED_RESTART_MIN_BLOCKED = env_int("OPENAI_PAY_APPROVE_BLOCKED_RESTART_MIN_BLOCKED", 480, minimum=1, maximum=10000)
APPROVE_BLOCKED_RESTART_RATIO = env_int("OPENAI_PAY_APPROVE_BLOCKED_RESTART_RATIO", 80, minimum=1, maximum=100)
APPROVE_IP_SAMPLE_INTERVAL = env_int("OPENAI_PAY_APPROVE_IP_SAMPLE_INTERVAL", 50, minimum=0, maximum=10000)
APPROVE_IP_SAMPLE_ENABLED = env_bool("OPENAI_PAY_APPROVE_IP_SAMPLE", True)
APPROVE_STICKY_PER_PROXY_CONCURRENCY = env_int(
"OPENAI_PAY_APPROVE_STICKY_PER_PROXY_CONCURRENCY",
50,
minimum=1,
maximum=200,
)
APPROVE_STICKY_MAX_WORKERS = env_int("OPENAI_PAY_APPROVE_STICKY_MAX_WORKERS", 300, minimum=1, maximum=500)
APPROVE_STICKY_FAIL_WINDOW = env_int("OPENAI_PAY_APPROVE_STICKY_FAIL_WINDOW", 50, minimum=1, maximum=500)
APPROVE_STICKY_FAIL_DELETE = env_bool("OPENAI_PAY_APPROVE_STICKY_FAIL_DELETE", True)
AUTO_PROXY_COUNTRY_REWRITE = env_bool("OPENAI_PAY_AUTO_PROXY_COUNTRY", False)
PROXY_SESSION_KEY = re.sub(
r"[^a-z0-9]",
"",
os.getenv("OPENAI_PAY_PROXY_SESSION_KEY", "session").strip().lower(),
) or "session"
if PROXY_SESSION_KEY not in {"session", "sid", "sessid"}:
PROXY_SESSION_KEY = "session"
STRIPE_REDIRECT_POLL_MAX_ATTEMPTS = env_int("OPENAI_PAY_STRIPE_REDIRECT_POLL_MAX_ATTEMPTS", 3, minimum=1, maximum=3)
STRIPE_REDIRECT_POLL_WORKERS = env_int("OPENAI_PAY_STRIPE_REDIRECT_POLL_WORKERS", 20, minimum=1, maximum=100)
UPI_CONFIRM_TIMEOUT_SECONDS = env_int("OPENAI_PAY_UPI_CONFIRM_TIMEOUT_SECONDS", 60, minimum=30, maximum=120)
STRIPE_INIT_RESOURCE_MISSING_ATTEMPTS = env_int(
"OPENAI_PAY_STRIPE_INIT_RESOURCE_MISSING_ATTEMPTS",
4,
minimum=1,
maximum=10,
)
STRIPE_INIT_RESOURCE_MISSING_DELAY_MS = env_int(
"OPENAI_PAY_STRIPE_INIT_RESOURCE_MISSING_DELAY_MS",
1000,
minimum=100,
maximum=10000,
)
BASE_DIR = Path(__file__).resolve().parent
PUBLIC_DIR = BASE_DIR / "public"
PAYPAL_HOST_SUFFIXES = ("paypal.com", "paypalobjects.com")
IDEAL_HOST_SUFFIXES = ("ideal.nl",)
UPI_HOST_SUFFIXES = ("stripe.com", "stripe.network")
LOG_LEVEL = os.getenv("OPENAI_PAY_LOG_LEVEL", "INFO").strip().upper() or "INFO"
logging.basicConfig(
level=getattr(logging, LOG_LEVEL, logging.INFO),
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
LOG = logging.getLogger("openai_pay")
REQUEST_ID: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="-")
TASK_LOG_CALLBACK: contextvars.ContextVar[Any | None] = contextvars.ContextVar("task_log_callback", default=None)
TASK_CANCEL_CHECK: contextvars.ContextVar[Any | None] = contextvars.ContextVar("task_cancel_check", default=None)
APP_USERNAME = os.getenv("APP_USERNAME", "admin")
APP_PASSWORD = os.getenv("APP_PASSWORD", "anxiaomo294")
APP_API_KEY = (os.getenv("APP_API_KEY") or os.getenv("OPENAI_PAY_API_KEY") or "").strip()
DEFAULT_USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36"
)
DEFAULT_STRIPE_RUNTIME_VERSION = "6f8494a281"
DEFAULT_CHECKOUT_PROXY = ""
DEFAULT_APPROVE_PROXY = ""
DEFAULT_PROVIDER_PROXY = ""
RUN_MODE_SPLIT = "jp-us"
RUN_MODE_CHECKOUT_JP_REST_PROVIDER = "checkout-jp-rest-provider"
RUN_MODE_UIAI_STYLE = "uiai-style"
RUN_MODE_US_CHECKOUT_JP_PAYPAL = "us-checkout-jp-paypal"
SUPPORTED_RUN_MODES = {
RUN_MODE_SPLIT,
RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
}
DEFAULT_PROBE_COUNTRIES_RAW = os.getenv(
"OPENAI_PAY_PROBE_COUNTRIES",
"US,CA,MX,BR,GB,IE,AU,NZ,DE,FR,IT,ES,NL,AT,BE,CH,PT,SE,NO,DK,FI,"
"PL,CZ,RO,HU,GR,BG,HR,SI,SK,LT,LV,EE,CY,MT,LU,IS,LI,JP,KR,SG,HK,"
"TW,ID,MY,TH,IN,TR,UA,ZA",
)
US_BILLING_PROFILES = [
{
"first_name": "James",
"last_name": "Miller",
"line1": "123 Market St",
"city": "San Francisco",
"state": "CA",
"postal_code": "94105",
},
{
"first_name": "Emily",
"last_name": "Walker",
"line1": "456 Grant Ave",
"city": "San Jose",
"state": "CA",
"postal_code": "95112",
},
{
"first_name": "Daniel",
"last_name": "Hughes",
"line1": "789 Mission Blvd",
"city": "Seattle",
"state": "WA",
"postal_code": "98101",
},
{
"first_name": "Sophia",
"last_name": "Johnson",
"line1": "512 Oak Court",
"city": "Austin",
"state": "TX",
"postal_code": "73301",
},
{
"first_name": "Michael",
"last_name": "Brown",
"line1": "188 Cedar Lane",
"city": "Chicago",
"state": "IL",
"postal_code": "60601",
},
{
"first_name": "Olivia",
"last_name": "Davis",
"line1": "44 Madison Avenue",
"city": "New York",
"state": "NY",
"postal_code": "10001",
},
{
"first_name": "Noah",
"last_name": "Miller",
"line1": "901 Lake Street",
"city": "Denver",
"state": "CO",
"postal_code": "80202",
},
{
"first_name": "Emma",
"last_name": "Martinez",
"line1": "760 Palm Drive",
"city": "Miami",
"state": "FL",
"postal_code": "33101",
},
{
"first_name": "Ethan",
"last_name": "Garcia",
"line1": "27 River Bend",
"city": "Boston",
"state": "MA",
"postal_code": "02108",
},
{
"first_name": "Ava",
"last_name": "White",
"line1": "66 West End Road",
"city": "Portland",
"state": "OR",
"postal_code": "97205",
},
{
"first_name": "Liam",
"last_name": "Clark",
"line1": "318 Mountain View",
"city": "Phoenix",
"state": "AZ",
"postal_code": "85001",
},
{
"first_name": "Isabella",
"last_name": "Moore",
"line1": "90 Harbor Point",
"city": "Houston",
"state": "TX",
"postal_code": "77002",
},
{
"first_name": "Lucas",
"last_name": "Taylor",
"line1": "230 Jefferson Ave",
"city": "Detroit",
"state": "MI",
"postal_code": "48201",
},
{
"first_name": "Mia",
"last_name": "Anderson",
"line1": "15 Pine Grove",
"city": "Atlanta",
"state": "GA",
"postal_code": "30301",
},
{
"first_name": "James",
"last_name": "Wilson",
"line1": "250 Broadway",
"city": "Minneapolis",
"state": "MN",
"postal_code": "55401",
},
]
BILLING_PROFILES = {
"US": US_BILLING_PROFILES,
"GB": {
"first_name": "George",
"last_name": "Taylor",
"line1": "221 Baker Street",
"city": "London",
"state": "",
"postal_code": "NW1 6XE",
},
"CA": {
"first_name": "Noah",
"last_name": "Wilson",
"line1": "100 King St W",
"city": "Toronto",
"state": "ON",
"postal_code": "M5X 1A9",
},
"BR": {
"first_name": "Pedro",
"last_name": "Silva",
"line1": "Avenida Paulista 1000",
"city": "Sao Paulo",
"state": "SP",
"postal_code": "01310-100",
},
"NZ": {
"first_name": "Jack",
"last_name": "Williams",
"line1": "188 Quay Street",
"city": "Auckland",
"state": "",
"postal_code": "1010",
},
"DE": {
"first_name": "Lukas",
"last_name": "Schneider",
"line1": "Friedrichstrasse 68",
"city": "Berlin",
"state": "",
"postal_code": "10117",
},
"JP": {
"first_name": "Haruto",
"last_name": "Sato",
"line1": "1-1-2 Marunouchi",
"city": "Chiyoda-ku",
"state": "Tokyo",
"postal_code": "100-0005",
},
"AU": {
"first_name": "Oliver",
"last_name": "Brown",
"line1": "200 George St",
"city": "Sydney",
"state": "NSW",
"postal_code": "2000",
},
"IE": {
"first_name": "Liam",
"last_name": "Murphy",
"line1": "1 Grand Canal Square",
"city": "Dublin",
"state": "D",
"postal_code": "D02 P820",
},
"ZA": {
"first_name": "Ethan",
"last_name": "Botha",
"line1": "1 Adderley Street",
"city": "Cape Town",
"state": "WC",
"postal_code": "8000",
},
"TR": {
"first_name": "Can",
"last_name": "Demir",
"line1": "Marmara Caddesi 12",
"city": "Istanbul",
"state": "IST",
"postal_code": "34000",
},
"IN": {
"first_name": "Ravi",
"last_name": "Sharma",
"line1": "221B Nehru Marg",
"city": "New Delhi",
"state": "DL",
"postal_code": "110001",
},
}
COUNTRY_NAME_SEEDS = [
("Alex", "Morgan"),
("Daniel", "Evans"),
("Mason", "Clark"),
("Lucas", "Walker"),
("Henry", "Scott"),
("Oscar", "Hall"),
]
COUNTRY_CITY_SEEDS = {
"AT": ("Vienna", "", "1010", "Karntner Strasse 12"),
"BE": ("Brussels", "", "1000", "Rue Neuve 25"),
"BR": ("Sao Paulo", "SP", "01310-100", "Avenida Paulista 1000"),
"BG": ("Sofia", "", "1000", "Vitosha Boulevard 18"),
"CH": ("Zurich", "", "8001", "Bahnhofstrasse 20"),
"CY": ("Nicosia", "", "1010", "Ledra Street 14"),
"CZ": ("Prague", "", "110 00", "Narodni 12"),
"DK": ("Copenhagen", "", "1050", "Ostergade 22"),
"EE": ("Tallinn", "", "10111", "Viru Street 8"),
"ES": ("Madrid", "", "28013", "Gran Via 28"),
"FI": ("Helsinki", "", "00100", "Mannerheimintie 10"),
"FR": ("Paris", "", "75001", "Rue de Rivoli 99"),
"GR": ("Athens", "", "105 63", "Ermou Street 15"),
"HR": ("Zagreb", "", "10000", "Ilica 21"),
"HU": ("Budapest", "", "1051", "Vaci utca 10"),
"IS": ("Reykjavik", "", "101", "Laugavegur 18"),
"IT": ("Rome", "", "00186", "Via del Corso 30"),
"LI": ("Vaduz", "", "9490", "Stadtle 17"),
"LT": ("Vilnius", "", "01100", "Gedimino pr. 16"),
"LU": ("Luxembourg", "", "L-2449", "Boulevard Royal 20"),
"LV": ("Riga", "", "LV-1050", "Brivibas iela 12"),
"MT": ("Valletta", "", "VLT 1111", "Republic Street 22"),
"NL": ("Amsterdam", "", "1012 LG", "Damrak 40"),
"NO": ("Oslo", "", "0159", "Karl Johans gate 14"),
"PL": ("Warsaw", "", "00-001", "Marszalkowska 20"),
"PT": ("Lisbon", "", "1100-148", "Rua Augusta 25"),
"RO": ("Bucharest", "", "010011", "Calea Victoriei 30"),
"SE": ("Stockholm", "", "111 22", "Drottninggatan 15"),
"SI": ("Ljubljana", "", "1000", "Slovenska cesta 12"),
"SK": ("Bratislava", "", "811 01", "Obchodna 10"),
}
COUNTRY_TIMEZONE = {
"AU": "Australia/Sydney",
"BR": "America/Sao_Paulo",
"CA": "America/Toronto",
"DE": "Europe/Berlin",
"IE": "Europe/Dublin",
"JP": "Asia/Tokyo",
"ZA": "Africa/Johannesburg",
"US": "America/New_York",
}
COUNTRY_CURRENCY = {
"AD": "EUR",
"AL": "ALL",
"AT": "EUR",
"AU": "AUD",
"BE": "EUR",
"BG": "BGN",
"BA": "BAM",
"BY": "BYN",
"BR": "BRL",
"CA": "CAD",
"CH": "CHF",
"CY": "EUR",
"CZ": "CZK",
"DE": "EUR",
"DK": "DKK",
"EE": "EUR",
"ES": "EUR",
"FI": "EUR",
"FR": "EUR",
"GB": "GBP",
"GR": "EUR",
"HR": "EUR",
"HK": "HKD",
"HU": "HUF",
"ID": "IDR",
"IE": "EUR",
"IS": "ISK",
"IN": "INR",
"IT": "EUR",
"JP": "JPY",
"KR": "KRW",
"LI": "CHF",
"LT": "EUR",
"LU": "EUR",
"LV": "EUR",
"MC": "EUR",
"MD": "MDL",
"ME": "EUR",
"MK": "MKD",
"MT": "EUR",
"MX": "MXN",
"MY": "MYR",
"NL": "EUR",
"NO": "NOK",
"NZ": "NZD",
"PL": "PLN",
"PT": "EUR",
"RO": "RON",
"RS": "RSD",
"SE": "SEK",
"SI": "EUR",
"SK": "EUR",
"SM": "EUR",
"SG": "SGD",
"TH": "THB",
"TR": "TRY",
"TW": "TWD",
"UA": "UAH",
"US": "USD",
"VA": "EUR",
"VN": "VND",
"ZA": "ZAR",
}
LOCALE_MAP = {
"de": ("de-DE", "de"),
"en": ("en-US", "en"),
"en-US": ("en-US", "en"),
"es": ("es-ES", "es"),
"fr": ("fr-FR", "fr"),
"id": ("id-ID", "id"),
"it": ("it-IT", "it"),
"ja": ("ja-JP", "ja"),
"ko": ("ko-KR", "ko"),
"pt-BR": ("pt-BR", "pt-BR"),
"zh-CN": ("zh-CN", "zh-CN"),
"zh-TW": ("zh-TW", "zh-TW"),
}
class LongLinkRequest(BaseModel):
model_config = ConfigDict(populate_by_name=True)
access_token: str = Field(..., alias="accessToken")
cdk: str = ""
proxy: str = ""
checkout_proxy: str = Field("", alias="checkoutProxy")
approve_proxy: str = Field("", alias="approveProxy")
provider_proxy: str = Field("", alias="providerProxy")
promotion_proxy: str = Field("", alias="promotionProxy")
stripe_publishable_key: str = ""
billing_country: str = "US"
pm_country: str = Field("AU", alias="pmCountry")
checkout_ui_mode: str = "custom"
payment_locale: str = "en"
link_type: str = "paypal"
proxy_pool_mode: str = Field("", alias="proxyPoolMode")
device_id: str = ""
user_agent: str = ""
auto_probe: bool = Field(True, alias="autoProbe")
probe_countries: str = Field("", alias="probeCountries")
class LongLinkResponse(BaseModel):
ok: bool
cs_id: str
processor_entity: str
billing_country: str
currency: str
checkout_amount: str = ""
payment_locale: str
link_type: str
payment_method_type: str
payment_method_id: str
stripe_redirect_url: str
provider_redirect_url: str
fallback: bool = False
provider_error: str = ""
stripe_hosted_url: str
long_url: str
ideal_qr_url: str = ""
success_attempt: int = 0
class LongLinkTaskStartResponse(BaseModel):
ok: bool
task_id: str
class LongLinkTaskStatusResponse(BaseModel):
ok: bool
task_id: str
status: str
progress: int = 0
stage: str = ""
message: str = ""
paused: bool = False
elapsed_ms: int = 0
attempt: int = 0
result: LongLinkResponse | None = None
error: str = ""
logs: list[dict[str, Any]] = Field(default_factory=list)
probe_results: list[dict[str, Any]] = Field(default_factory=list)
created_at: int = 0
updated_at: int = 0
result_expires_at: int = 0
class TaskPauseRequest(BaseModel):
paused: bool = True
class TaskCancelled(RuntimeError):
pass
class AuthRequest(BaseModel):
username: str
password: str
class RegisterRequest(BaseModel):
username: str
password: str
invite_code: str = Field(..., alias="inviteCode")
class UserResponse(BaseModel):
ok: bool
authenticated: bool
username: str = ""
role: str = ""
class MemberResponse(BaseModel):
username: str
role: str
created_at: int
disabled_at: int = 0
active_sessions: int = 0
success_count: int = 0
class MemberListResponse(BaseModel):
ok: bool
members: list[MemberResponse]
class ApiExtractRequest(BaseModel):
model_config = ConfigDict(populate_by_name=True)
access_token: str = Field("", alias="accessToken")
session_json: Any | None = Field(None, alias="sessionJson")
token: str = ""
cdk: str = ""
class BusinessCheckoutRequest(BaseModel):
"""Independent Business checkout creator.
Business uses a different plan/promotion payload from the normal PP flow.
"""
model_config = ConfigDict(populate_by_name=True)
access_token: str = Field("", alias="accessToken")
session_json: Any | None = Field(None, alias="sessionJson")
token: str = ""
checkout_url: str = Field("", alias="checkoutUrl")
promo_code: str = Field("", alias="promoCode")
promo_campaign_id: str = Field("", alias="promoCampaignId")
plan_name: str = Field("chatgptteamplan", alias="planName")
seat_quantity: int = Field(5, alias="seatQuantity", ge=2, le=100)
price_interval: str = Field("month", alias="priceInterval")
billing_country: str = Field("US", alias="billingCountry")
proxy: str = ""
class BusinessCheckoutResponse(BaseModel):
ok: bool
checkout_url: str = Field("", alias="checkoutUrl")
external_url: str = Field("", alias="externalUrl")
processor_entity: str = Field("", alias="processorEntity")
cs_id: str = Field("", alias="csId")
plan_name: str = Field("", alias="planName")
promo_code: str = Field("", alias="promoCode")
seat_quantity: int = Field(5, alias="seatQuantity")
message: str = ""
class CdkCheckRequest(BaseModel):
cdk: str = ""
class CdkCheckResponse(BaseModel):
model_config = ConfigDict(populate_by_name=True)
ok: bool
code: str
max_uses: int = Field(10, alias="maxUses")
use_count: int = Field(0, alias="useCount")
remaining_uses: int = Field(0, alias="remainingUses")
class InviteResponse(BaseModel):
code: str
created_by: str
created_at: int
used_by: str = ""
used_at: int = 0
revoked_at: int = 0
max_uses: int = 10
use_count: int = 0
remaining_uses: int = 10
last_used_at: int = 0
class InviteListResponse(BaseModel):
ok: bool
invites: list[InviteResponse]
class InviteCreateRequest(BaseModel):
count: int = Field(1, ge=1, le=50)
max_uses: int = Field(10, ge=1, le=100, alias="maxUses")
request_id: str = Field("", alias="requestId")
class InviteCreateResponse(BaseModel):
ok: bool
invite: InviteResponse
invites: list[InviteResponse] = Field(default_factory=list)
class ProxyCheckRequest(BaseModel):
model_config = ConfigDict(populate_by_name=True)
checkout_proxy: str = Field("", alias="checkoutProxy")
provider_proxy: str = Field("", alias="providerProxy")
class RuntimeConfigRequest(BaseModel):
model_config = ConfigDict(populate_by_name=True)
run_mode: str = Field(RUN_MODE_CHECKOUT_JP_REST_PROVIDER, alias="runMode")
proxy_pool_mode: str = Field("dynamic", alias="proxyPoolMode")
billing_country: str = Field("US", alias="billingCountry")
pm_country: str = Field("AU", alias="pmCountry")
payment_locale: str = Field("en", alias="paymentLocale")
jp_proxy: str = Field("", alias="jpProxy")
us_proxy: str = Field("", alias="usProxy")
sticky_jp_proxy: str = Field("", alias="stickyJpProxy")
sticky_us_proxy: str = Field("", alias="stickyUsProxy")
ideal_promo_proxy: str = Field("", alias="idealPromoProxy")
sticky_ideal_promo_proxy: str = Field("", alias="stickyIdealPromoProxy")
checkout_proxy: str = Field("", alias="checkoutProxy")
approve_proxy: str = Field("", alias="approveProxy")
provider_proxy: str = Field("", alias="providerProxy")
def elapsed_ms(start: float) -> int:
return int((time.perf_counter() - start) * 1000)
def mask_identifier(value: Any, keep_start: int = 8, keep_end: int = 4) -> str:
text = str(value or "").strip()
if not text:
return ""
if len(text) <= keep_start + keep_end + 3:
return text
return f"{text[:keep_start]}…{text[-keep_end:]}"
def redact_text(value: Any, max_len: int = 300) -> str:
text = str(value or "")
if not text:
return ""
text = re.sub(r"Bearer\s+[A-Za-z0-9._~+/=-]+", "Bearer <redacted>", text, flags=re.IGNORECASE)
text = re.sub(r"[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}", "<jwt-redacted>", text)
text = re.sub(r"(https?://)([^:/@\s]+):([^@\s]+)@", r"\1\2:***@", text)
text = re.sub(
r'("(?:accessToken|access_token|sessionToken|Authorization|authorization|token|proxy|password|secret|key)"\s*:\s*")([^"]+)(")',
r"\1<redacted>\3",
text,
flags=re.IGNORECASE,
)
if len(text) > max_len:
return f"{text[:max_len]}…<{len(text)} chars>"
return text
def safe_url(url: Any) -> str:
raw = str(url or "").strip()
if not raw:
return ""
try:
parsed = urlsplit(raw)
except Exception:
return redact_text(raw, max_len=180)
if not parsed.scheme or not parsed.netloc:
return redact_text(mask_identifier(raw, keep_start=24, keep_end=8), max_len=180)
try:
port_value = parsed.port
except ValueError:
port_value = None
port = f":{port_value}" if port_value else ""
segments = [mask_identifier(segment, keep_start=10, keep_end=4) for segment in parsed.path.split("/")]
path = "/".join(segments)
query_keys = [key for key, _ in parse_qsl(parsed.query, keep_blank_values=True)]
query = f"?query_keys={','.join(query_keys[:8])}" if query_keys else ""
if len(query_keys) > 8:
query += f",+{len(query_keys) - 8}"
return f"{parsed.scheme}://{parsed.hostname or ''}{port}{path}{query}"
def normalize_proxy_url(proxy: str) -> str:
proxy = str(proxy or "").strip()
if not proxy:
return ""
if "://" not in proxy:
parts = proxy.split(":")
if len(parts) >= 4:
host = parts[0].strip()
port = parts[1].strip()
username = ":".join(parts[2:-1]).strip()
password = parts[-1].strip()
if host and port and username and password:
proxy = f"http://{quote(username, safe='')}:{quote(password, safe='')}@{host}:{port}"
else:
proxy = f"http://{proxy}"
else:
proxy = f"http://{proxy}"
return proxy
def proxy_pool(value: Any) -> list[str]:
raw = str(value or "").strip()
if not raw:
return []
proxies: list[str] = []
for item in re.split(r"[\r\n,;|\s]+", raw):
proxy = normalize_proxy_url(item)
if proxy and proxy not in proxies:
proxies.append(proxy)
return proxies
def normalize_proxy_pool_value(value: Any) -> str:
return "\n".join(proxy_pool(value))
def select_proxy_from_pool(value: Any, index: int = 0) -> str:
# A configured pool may intentionally contain mixed countries. Preserve
# its order and use exactly the selected entry; country is not a filter.
proxies = proxy_pool(value)
if not proxies:
return ""
return proxies[max(0, int(index or 0)) % len(proxies)]
def first_proxy_from_pool(value: Any) -> str:
return select_proxy_from_pool(value, 0)
def ordered_proxy_pool(value: Any, preferred: Any = "") -> list[str]:
proxies = proxy_pool(value)
preferred_proxy = normalize_proxy_url(str(preferred or ""))
if preferred_proxy:
if preferred_proxy in proxies:
index = proxies.index(preferred_proxy)
proxies = proxies[index:] + proxies[:index]
else:
proxies.insert(0, preferred_proxy)
ordered: list[str] = []
for proxy in proxies:
if proxy and proxy not in ordered:
ordered.append(proxy)
return ordered
def proxy_country_hint(proxy: Any) -> str:
proxy_url = normalize_proxy_url(str(proxy or ""))
if not proxy_url:
return ""
try:
username = unquote(urlsplit(proxy_url).username or "")
except Exception:
return ""
# Country is controlled by the proxy account itself. Support common
# vendor formats such as "region-BR", "res-BR", and "country-BR";
# never rewrite the country later.
match = re.search(r"(?:^|[-_])(?:region|res|country|cc)-([A-Za-z]{2})(?:[-_]|$)", username)
return match.group(1).upper() if match else ""
def proxy_pool_primary_country(proxies: list[str]) -> str:
for proxy in proxies:
country = proxy_country_hint(proxy)
if country:
return country
return ""
def filter_proxy_pool_same_country(proxies: list[str], country: str = "") -> list[str]:
country = str(country or "").strip().upper()
if not proxies:
return []
if not country:
country = proxy_pool_primary_country(proxies)
if not country:
return proxies
filtered: list[str] = []
for proxy in proxies:
hint = proxy_country_hint(proxy)
if hint and hint != country:
continue
if proxy not in filtered:
filtered.append(proxy)
return filtered or proxies[:1]
def proxy_with_region(proxy: Any, country: str) -> str:
proxy_url = normalize_proxy_url(str(proxy or ""))
target_country = supported_country(country, "")
if not proxy_url or not target_country:
return proxy_url
if proxy_supports_country_rewrite(proxy_url):
return proxy_for_probe_country(proxy_url, target_country)
current_country = proxy_country_hint(proxy_url)
if current_country and current_country != target_country:
return ""
return proxy_url
PROXY_COUNTRY_MARKER_RE = re.compile(
r"((?:^|[-_])(?:region|res|country|cc)-)([A-Za-z]{2})(?=[-_]|$)",
re.IGNORECASE,
)
def proxy_supports_country_rewrite(proxy: Any) -> bool:
proxy_url = normalize_proxy_url(str(proxy or ""))
if not proxy_url:
return False
try:
username = unquote(urlsplit(proxy_url).username or "")
except Exception:
return False
return bool(PROXY_COUNTRY_MARKER_RE.search(username))
def proxy_for_probe_country(proxy: Any, country: str, sid: str = "") -> str:
"""Rewrite only an explicit proxy country marker for the isolated promo probe."""
proxy_url = normalize_proxy_url(str(proxy or ""))
target_country = supported_country(country, "")
if not proxy_url or not target_country:
return ""
try:
parsed = urlsplit(proxy_url)
username = unquote(parsed.username or "")
password = unquote(parsed.password or "")
def replace_country(match: re.Match[str]) -> str:
previous = match.group(2)
replacement = target_country.lower() if previous.islower() else target_country.upper()
return f"{match.group(1)}{replacement}"
username, replaced = PROXY_COUNTRY_MARKER_RE.subn(replace_country, username, count=1)
if not replaced:
return ""
netloc = parsed.hostname or ""
if parsed.port:
netloc = f"{netloc}:{parsed.port}"
auth = quote(username, safe="")
if password:
auth = f"{auth}:{quote(password, safe='')}"
rewritten = urlunsplit((parsed.scheme, f"{auth}@{netloc}", parsed.path, parsed.query, parsed.fragment))
return proxy_with_sid(rewritten, sid) if sid else rewritten
except Exception:
return ""
def proxy_for_payment_country(proxy: Any, country: str, sid: str = "") -> str:
"""Keep a payment-stage proxy in the requested country and optionally pin its session."""
proxy_url = normalize_proxy_url(str(proxy or ""))
target_country = supported_country(country, "")
if not proxy_url:
return ""
if not target_country:
return proxy_with_sid(proxy_url, sid) if sid else proxy_url
if proxy_supports_country_rewrite(proxy_url):
return proxy_for_probe_country(proxy_url, target_country, sid)
current_country = proxy_country_hint(proxy_url)
if current_country and current_country != target_country:
return ""
return proxy_with_sid(proxy_url, sid) if sid else proxy_url
def proxy_for_required_country(proxy: Any, country: str) -> str:
"""Return the configured proxy unchanged.
The country argument is retained for call-site compatibility and logging,
but a proxy's country must never be rewritten or rejected based on it.
Each configured lane is authoritative: whatever the operator enters is
the proxy used for that stage.
"""
return normalize_proxy_url(str(proxy or ""))
def proxy_without_sid(proxy: Any) -> str:
proxy_url = normalize_proxy_url(str(proxy or ""))
if not proxy_url:
return ""
try:
parsed = urlsplit(proxy_url)
username = unquote(parsed.username or "")
password = unquote(parsed.password or "")
username = re.sub(r"(^|-)(?:sid|session|sessid)-[^-:@]+", "", username, count=1).strip("-")
netloc = parsed.hostname or ""
if parsed.port:
netloc = f"{netloc}:{parsed.port}"
if username:
auth = quote(username, safe="")
if password:
auth = f"{auth}:{quote(password, safe='')}"
netloc = f"{auth}@{netloc}"
return urlunsplit((parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment))
except Exception:
return proxy_url
def proxies_compatible(saved_proxy: Any, base_proxy: Any) -> bool:
saved = normalize_proxy_url(str(saved_proxy or ""))
base = normalize_proxy_url(str(base_proxy or ""))
if not saved or not base:
return False
try:
saved_parts = urlsplit(saved)
base_parts = urlsplit(base)
if (saved_parts.hostname or "").lower() != (base_parts.hostname or "").lower():
return False
if saved_parts.port != base_parts.port:
return False
saved_country = proxy_country_hint(saved)
base_country = proxy_country_hint(base)
if saved_country and base_country and saved_country != base_country:
return False
return proxy_without_sid(saved) == proxy_without_sid(base)
except Exception:
return False
def proxy_supports_auto_sid(proxy: Any) -> bool:
proxy_url = normalize_proxy_url(str(proxy or ""))
if not proxy_url:
return False
try:
username = unquote(urlsplit(proxy_url).username or "")
except Exception:
return False
return bool(
re.search(r"(?:^|-)(?:sid|session|sessid)-[^-:@]+", username)
or re.search(r"(?:^|[-_])(?:region|res|country|cc)-[A-Za-z]{2}(?:[-_]|$)", username)
)
def proxy_with_sid(proxy: Any, sid: str) -> str:
proxy_url = normalize_proxy_url(str(proxy or ""))
sid = re.sub(r"[^A-Za-z0-9]", "", str(sid or ""))[:16]
if not proxy_url or not sid or not proxy_supports_auto_sid(proxy_url):
return proxy_url
try:
parsed = urlsplit(proxy_url)
username = unquote(parsed.username or "")
password = unquote(parsed.password or "")
session_pattern = r"(^|-)(?:sid|session|sessid)-[^-:@]+"
if re.search(session_pattern, username):
username = re.sub(session_pattern, rf"\1{PROXY_SESSION_KEY}-{sid}", username, count=1)
else:
username = f"{username}-{PROXY_SESSION_KEY}-{sid}"
netloc = parsed.hostname or ""
if parsed.port:
netloc = f"{netloc}:{parsed.port}"
auth = quote(username, safe="")
if password:
auth = f"{auth}:{quote(password, safe='')}"
netloc = f"{auth}@{netloc}"
return urlunsplit((parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment))
except Exception:
return proxy_url
def proxy_for_attempt(proxy: Any, attempt: int, stage: str = "", force: bool = False) -> str:
proxy_url = normalize_proxy_url(str(proxy or ""))
if not proxy_url:
return proxy_url
attempt_no = max(1, int(attempt or 1))
if attempt_no <= 1 and not force:
return proxy_url
sid = f"{stage[:1] or 'p'}{attempt_no:02d}{secrets.token_hex(4)}"
return proxy_with_sid(proxy_url, sid)
def redact_proxy(proxy: Any) -> str:
proxy_url = normalize_proxy_url(str(proxy or ""))
if not proxy_url:
return ""
try:
parsed = urlsplit(proxy_url)
host = parsed.hostname or ""
try:
port_value = parsed.port
except ValueError:
port_value = None
port = f":{port_value}" if port_value else ""
auth = ""
if parsed.username:
auth = f"{mask_identifier(parsed.username, keep_start=6, keep_end=3)}:***@"
return f"{parsed.scheme}://{auth}{host}{port}"
except Exception:
return "<proxy-redacted>"
def redact_proxy_pool(value: Any) -> str:
proxies = proxy_pool(value)
if not proxies:
return ""
labels = [redact_proxy(proxy) for proxy in proxies[:3]]
if len(proxies) > 3:
labels.append(f"+{len(proxies) - 3}")
return " | ".join(labels)
def response_keys(payload: Any, limit: int = 12) -> str:
if not isinstance(payload, dict):
return type(payload).__name__
keys = sorted(str(key) for key in payload.keys())
suffix = f",+{len(keys) - limit}" if len(keys) > limit else ""
return ",".join(keys[:limit]) + suffix
def interesting_payload_fields(payload: Any, limit: int = 18) -> str:
interesting_names = (
"paypal",
"redirect",
"url",
"next_action",
"submission",
"state",
"status",
"error",
"message",
"payment_method",
)
found: list[str] = []
def visit(value: Any, path: str, depth: int) -> None:
if len(found) >= limit or depth > 5:
return
if isinstance(value, dict):
for key, item in value.items():
if len(found) >= limit:
return
key_text = str(key)
child_path = f"{path}.{key_text}" if path else key_text
lowered = key_text.lower()
if any(name in lowered for name in interesting_names):
if isinstance(item, (str, int, float, bool)) or item is None:
if "url" in lowered or "redirect" in lowered:
rendered = safe_url(item)
elif "error" in lowered or "message" in lowered:
rendered = redact_text(item, max_len=120)
else:
rendered = mask_identifier(item) if isinstance(item, str) and len(item) > 24 else str(item)
found.append(f"{child_path}={rendered}")
else:
found.append(f"{child_path}<{type(item).__name__}>")
visit(item, child_path, depth + 1)
elif isinstance(value, list):
for index, item in enumerate(value[:8]):
if len(found) >= limit:
return
visit(item, f"{path}[{index}]", depth + 1)
elif isinstance(value, str) and ("http://" in value or "https://" in value):
found.append(f"{path}={safe_url(value)}")
visit(payload, "", 0)
return " | ".join(found)
def approve_result_value(payload: Any) -> str:
if not isinstance(payload, dict):
return ""
for key in ("result", "status", "state", "approval_status"):
value = payload.get(key)
if value is not None:
return str(value).strip()
return ""
def is_approved_result(result: Any) -> bool:
return str(result or "").strip().lower() in {
"approved",
"already_approved",
"success",
"succeeded",
}
def approve_outcome(item: dict[str, Any]) -> str:
if item.get("skipped"):
return "skipped"
result = str(item.get("result") or "").strip().lower()
status_code = int(item.get("status_code") or 0)
if is_approved_result(result):
return "approved"
if status_code == 0:
return "exception"
if status_code in {401, 403}:
return "auth_error"
if status_code == 404:
return "missing"
if status_code == 408:
return "timeout"
if status_code == 409:
return "conflict"
if status_code == 429:
return "rate_limited"
if status_code >= 500:
return "server_error"
if result == "blocked":
return "blocked"
if result:
return f"pending_{result}"[:48]
return "pending_empty"
def log_event(level: int, event: str, **fields: Any) -> None:
safe_fields: dict[str, Any] = {}
for key, value in fields.items():
lowered = key.lower()
if value is None:
continue
# Only redact actual proxy URL fields. Counters/modes/indices such as
# proxy_pool_count and proxy_pool_mode are ordinary metadata; passing
# them through redact_proxy turns values like 1/dynamic into http://1
# and http://dynamic in the logs.
is_proxy_value = (
"proxy" in lowered
and not lowered.endswith(("_count", "_index", "_mode"))
)
if is_proxy_value:
safe_fields[key] = value if isinstance(value, bool) else (redact_proxy(value) if value else "")
elif "url" in lowered or "location" in lowered:
safe_fields[key] = safe_url(value)
elif "token" in lowered or "authorization" in lowered or "secret" in lowered or "password" in lowered:
safe_fields[key] = value if isinstance(value, bool) else ("<redacted>" if value else "")
elif lowered.endswith("_id") or lowered in {"cs_id", "pm_id", "checkout_session"}:
safe_fields[key] = value if isinstance(value, bool) else mask_identifier(value)
elif "body" in lowered or "error" in lowered or "detail" in lowered:
safe_fields[key] = redact_text(value)
else:
safe_fields[key] = value
suffix = " ".join(f"{key}={safe_fields[key]!r}" for key in sorted(safe_fields))
LOG.log(level, "[req=%s] %s%s", REQUEST_ID.get(), event, f" {suffix}" if suffix else "")
callback = TASK_LOG_CALLBACK.get()
if callback:
try:
# Task logs are returned through an API. Store the same redacted
# fields that are written to journald so proxy credentials, tokens,
# secrets and full payment URLs never enter the task response.
raw_fields: dict[str, Any] = {
key: value if isinstance(value, (str, int, float, bool)) else str(value)
for key, value in safe_fields.items()
}
callback(
{
"time": time.strftime("%H:%M:%S"),
"level": logging.getLevelName(level).lower(),
"event": event,
"fields": raw_fields,
}
)
except Exception:
pass
def log_info(event: str, **fields: Any) -> None:
log_event(logging.INFO, event, **fields)
def log_warning(event: str, **fields: Any) -> None:
log_event(logging.WARNING, event, **fields)
def http_error_detail(label: str, response: Any) -> str:
body_text = redact_text(getattr(response, "text", "") or "", max_len=500)
return f"{label}: status={getattr(response, 'status_code', '')} body={body_text}"
def percentile_ms(values: list[int] | tuple[int, ...], percent: int = 95) -> int:
clean = sorted(int(value) for value in values if int(value) >= 0)
if not clean:
return 0
index = max(0, min(len(clean) - 1, ((len(clean) * percent + 99) // 100) - 1))
return clean[index]
def compact_counts(counter: Counter[str]) -> str:
return ",".join(f"{name}:{count}" for name, count in sorted(counter.items()) if count)
def new_session() -> Any:
if CurlCffiSession is not None:
return CurlCffiSession(impersonate="chrome136")
return requests.Session()
def clone_session(source: Any) -> Any:
session = new_session()
try:
session.headers.update(dict(getattr(source, "headers", {}) or {}))
except Exception:
pass
try:
proxies = dict(getattr(source, "proxies", {}) or {})
if proxies:
session.proxies = proxies
except Exception:
pass
try:
session.cookies.update(getattr(source, "cookies", {}) or {})
except Exception:
pass
return session
def set_proxy_url(session: Any, proxy: str) -> None:
proxy = normalize_proxy_url(proxy)
if proxy:
session.proxies = {"http": proxy, "https": proxy}
# 动态代理:不要复用同一条 TCP 连接,让代理商有机会在下一次请求/重试切换出口 IP。
try:
session.headers.update({"Connection": "close", "Proxy-Connection": "close"})
except Exception:
pass
def clear_proxy_url(session: Any) -> None:
try:
session.proxies = {}
except Exception:
pass
def session_proxy_url(session: Any) -> str:
try:
proxies = dict(getattr(session, "proxies", {}) or {})
except Exception:
return ""
return normalize_proxy_url(str(proxies.get("https") or proxies.get("http") or ""))
def sample_session_exit_ip(session: Any) -> tuple[str, str]:
try:
started = time.perf_counter()
response = session.get("https://api.ipify.org?format=json", timeout=8)
elapsed = elapsed_ms(started)
ip = ""
try:
data = response.json()
ip = str(data.get("ip") or "")
except Exception:
ip = str(getattr(response, "text", "") or "").strip()[:80]
return ip, str(elapsed)
except Exception as exc:
return "", repr(exc)
def requested_checkout_proxy(req: LongLinkRequest) -> str:
return first_proxy_from_pool(req.checkout_proxy or req.proxy)
def checkout_stage_proxy(req: LongLinkRequest) -> str:
return (
first_proxy_from_pool(req.checkout_proxy or req.proxy)
or first_proxy_from_pool(os.getenv("OPENAI_PAY_CHECKOUT_PROXY", ""))
)
def provider_stage_proxy(req: LongLinkRequest) -> str:
explicit_provider = first_proxy_from_pool(req.provider_proxy)
if explicit_provider:
return explicit_provider
explicit_checkout = requested_checkout_proxy(req)
if explicit_checkout:
return explicit_checkout
return first_proxy_from_pool(os.getenv("OPENAI_PAY_PROVIDER_PROXY", ""))
def promotion_stage_proxy(req: LongLinkRequest) -> str:
return (
first_proxy_from_pool(req.promotion_proxy)
or first_proxy_from_pool(os.getenv("OPENAI_PAY_PROMOTION_PROXY", ""))
)
def redirect_poll_proxy_pool(req: LongLinkRequest, stripe_session: Any) -> list[str]:
current_proxy = session_proxy_url(stripe_session) or provider_stage_proxy(req)
return [current_proxy] if current_proxy else []
def approve_stage_proxy(req: LongLinkRequest) -> str:
return (
first_proxy_from_pool(req.approve_proxy)
or requested_checkout_proxy(req)
or first_proxy_from_pool(os.getenv("OPENAI_PAY_APPROVE_PROXY", ""))
or checkout_stage_proxy(req)
)
def apply_approve_proxy(session: Any, proxy: str) -> None:
proxy = normalize_proxy_url(proxy)
if proxy:
set_proxy_url(session, proxy)
else:
clear_proxy_url(session)
log_info(
"session.approve_proxy.apply",
route="approve_proxy" if proxy else "direct",
proxy_configured=bool(proxy),
approve_proxy=proxy,
)
def host_matches_suffixes(host: str, suffixes: tuple[str, ...]) -> bool:
host = str(host or "").lower().strip(".")
return any(host == suffix or host.endswith(f".{suffix}") for suffix in suffixes)
def currency_for_country(country: str) -> str:
return COUNTRY_CURRENCY.get(str(country or "").upper(), "USD")
def supported_country(value: str, default: str = "DE") -> str:
country = str(value or "").strip().upper()
return country if country in COUNTRY_CURRENCY else default
def timezone_for_country(country: str) -> str:
return COUNTRY_TIMEZONE.get(supported_country(country), "Europe/Berlin")
def normalize_link_type(link_type: str) -> str:
value = str(link_type or "paypal").strip().lower()
aliases = {
"ideal": "ideal",
"idealpay": "ideal",
"i-deal": "ideal",
"upi": "upi",
"payment": "paypal",
"pay": "paypal",
"long": "paypal",
"pp": "paypal",
"paypal": "paypal",
}
return aliases.get(value, "paypal")
def stripe_version_for(link_type: str) -> str:
# Keep the API version that has already been proven against the existing
# PayPal/iDEAL Checkout schema. UPI's hosted QR action was added later and
# therefore uses the newer schema in isolation.
return UPI_STRIPE_VERSION_FULL if normalize_link_type(link_type) == "upi" else STRIPE_VERSION_FULL
def effective_country(req: LongLinkRequest) -> str:
return supported_country(req.billing_country, "DE")
def effective_pm_country(req: LongLinkRequest) -> str:
return supported_country(req.pm_country, effective_country(req))
def locale_parts(locale: str) -> tuple[str, str]:
return LOCALE_MAP.get(str(locale or "").strip(), LOCALE_MAP["en"])
def find_token(value: Any) -> str:
if isinstance(value, dict):
for key in ("accessToken", "access_token", "token"):
token = str(value.get(key) or "").strip()
if token:
return token
for item in value.values():
token = find_token(item)
if token:
return token
if isinstance(value, list):
for item in value:
token = find_token(item)
if token:
return token
return ""
def normalize_access_token(raw: str) -> str:
token = str(raw or "").strip()
if not token:
return ""
if token.startswith("{") or token.startswith("["):
try:
return find_token(json.loads(token)) or token
except json.JSONDecodeError:
return token
return token
def extract_processor_entity(data: Any) -> str:
if not isinstance(data, dict):
return ""
direct = data.get("processor_entity") or data.get("processorEntity")
if direct:
return str(direct).strip()
for key in ("checkout_session", "session", "checkout", "data"):
nested = data.get(key)
if isinstance(nested, dict):
found = extract_processor_entity(nested)
if found:
return found
return ""
def extract_stripe_publishable_key(data: Any) -> str:
if isinstance(data, dict):
preferred_keys = (
"stripe_publishable_key",
"stripePublishableKey",
"publishable_key",
"publishableKey",
"stripe_key",
)
for key in preferred_keys:
value = str(data.get(key) or "").strip()
if value.startswith(("pk_live_", "pk_test_")):
return value
for value in data.values():
found = extract_stripe_publishable_key(value)
if found:
return found
elif isinstance(data, list):
for value in data:
found = extract_stripe_publishable_key(value)
if found:
return found
elif isinstance(data, str):
match = re.search(r"\bpk_(?:live|test)_[A-Za-z0-9]+\b", data)
if match:
return match.group(0)
return ""
def extract_checkout_url(data: Any) -> str:
if isinstance(data, dict):
for key in (
"url",
"stripe_hosted_url",
"checkout_url",
"checkoutUrl",
"hosted_url",
):
value = str(data.get(key) or "").strip()
if value.startswith(("https://", "http://")):
return value
for value in data.values():
found = extract_checkout_url(value)
if found:
return found
elif isinstance(data, list):
for value in data:
found = extract_checkout_url(value)
if found:
return found
return ""
def extract_checkout_session_id(data: Any) -> str:
if isinstance(data, dict):
for key in (
"checkout_session_id",
"checkoutSessionId",
"stripe_checkout_session_id",
"stripeCheckoutSessionId",
"stripe_session_id",
"stripeSessionId",
"session_id",
"id",
"client_secret",
):
found = extract_checkout_session_id(data.get(key))
if found:
return found
for value in data.values():
found = extract_checkout_session_id(value)
if found:
return found
elif isinstance(data, list):
for value in data:
found = extract_checkout_session_id(value)
if found:
return found
elif isinstance(data, str):
value = data.strip()
for candidate in (value, unquote(value)):
if candidate.startswith(("cs_live_", "cs_test_", "oaics_")):
return candidate.split("_secret_", 1)[0]
match = re.search(r"(?:cs_(?:live|test)_[A-Za-z0-9_]+|oaics_[A-Za-z0-9_]+)", candidate)
if match:
return match.group(0)
return ""
def checkout_debug_value(value: Any) -> str:
if value is None:
return "null"
if isinstance(value, (dict, list)):
return f"{type(value).__name__}(len={len(value)})"
text = str(value)
return f"{type(value).__name__}(len={len(text)}, value={redact_text(text, max_len=130)})"
def checkout_response_summary(data: Any) -> str:
if not isinstance(data, dict):
return checkout_debug_value(data)
interesting = (
"checkout_session_id",
"checkoutSessionId",
"session_id",
"id",
"client_secret",
"customer_session_client_secret",
"confirm_return_url",
"checkout_provider",
"checkout_kind",
"checkout_state",
"checkout_ui_mode",
)
parts: list[str] = []
for key in interesting:
if key in data:
parts.append(f"{key}={checkout_debug_value(data.get(key))}")
hits: list[str] = []
def walk(value: Any, path: str = "$") -> None:
if len(hits) >= 8:
return
if isinstance(value, dict):
for key, item in value.items():
walk(item, f"{path}.{key}")
elif isinstance(value, list):
for index, item in enumerate(value[:20]):
walk(item, f"{path}[{index}]")
elif isinstance(value, str):
text = value.strip()
lowered = text.lower()
if any(marker in lowered for marker in ("cs_", "checkout", "stripe", "session", "secret", "pay.openai.com")):
hits.append(f"{path}={checkout_debug_value(text)}")
walk(data)
if hits:
parts.append("hits=" + " | ".join(hits))
return "; ".join(parts) or f"keys={response_keys(data)}"
def stripe_key_fingerprint(value: str) -> str:
key = str(value or "").strip()
if not key:
return ""
return mask_identifier(key, keep_start=15, keep_end=6)
def stripe_key_env_name(processor_entity: str) -> str:
normalized = re.sub(r"[^A-Za-z0-9]+", "_", str(processor_entity or "").upper()).strip("_")
return f"OPENAI_PAY_STRIPE_PK_{normalized}" if normalized else ""
def resolve_stripe_publishable_key(
req: LongLinkRequest,
checkout: dict[str, Any],
) -> tuple[str, str]:
explicit = req.stripe_publishable_key.strip()
if explicit:
return explicit, "request"
checkout_key = str(checkout.get("stripe_publishable_key") or "").strip()
if checkout_key:
return checkout_key, "checkout_response"
processor_entity = processor_entity_for_country(
str(checkout.get("billing_country") or ""),
str(checkout.get("processor_entity") or ""),
)
entity_env = stripe_key_env_name(processor_entity)
if entity_env:
entity_key = str(os.getenv(entity_env, "") or "").strip()
if entity_key:
return entity_key, entity_env
generic_key = str(os.getenv("OPENAI_PAY_STRIPE_PUBLISHABLE_KEY", "") or "").strip()
if generic_key:
return generic_key, "OPENAI_PAY_STRIPE_PUBLISHABLE_KEY"
if processor_entity == "openai_llc":
return DEFAULT_STRIPE_PK, "legacy_openai_llc_default"
return "", ""
def discover_stripe_key_from_hosted_page(
checkout: dict[str, Any],
req: LongLinkRequest,
provider_proxy: str,
) -> str:
hosted_url = str(checkout.get("checkout_url") or "").strip()
if not hosted_url:
hosted_url = f"https://checkout.stripe.com/c/pay/{checkout['cs_id']}"
session = build_stripe_session(req, proxy_override=provider_proxy)
try:
started = time.perf_counter()
response = session.get(hosted_url, allow_redirects=True, timeout=10)
found = extract_stripe_publishable_key(getattr(response, "text", "") or "")
log_info(
"stripe.key_discovery.hosted_page",
status_code=getattr(response, "status_code", ""),
elapsed_ms=elapsed_ms(started),
hosted_url=hosted_url,
key_found=bool(found),
key_fingerprint=stripe_key_fingerprint(found),
)
return found
except Exception as exc:
log_warning(
"stripe.key_discovery.hosted_page_error",
hosted_url=hosted_url,
error=repr(exc),
)
return ""
def build_chatgpt_session(req: LongLinkRequest) -> Any:
access_token = normalize_access_token(req.access_token)
if not access_token:
raise HTTPException(status_code=400, detail="accessToken is required")
device_id = req.device_id.strip() or str(uuid.uuid4())
user_agent = req.user_agent.strip() or DEFAULT_USER_AGENT
checkout_proxy = checkout_stage_proxy(req)
log_info(
"session.chatgpt.create",
route="checkout_proxy" if checkout_proxy else "direct",
proxy_configured=bool(checkout_proxy),
checkout_proxy=checkout_proxy,
access_token_present=bool(access_token),
device_id=device_id,
custom_user_agent=bool(req.user_agent.strip()),
)
session = new_session()
session.headers.update(
{
"User-Agent": user_agent,
"Accept": "*/*",
"Accept-Language": "en-US,en;q=0.9",
"Authorization": f"Bearer {access_token}",
"Origin": "https://chatgpt.com",
"Referer": "https://chatgpt.com/",
"Content-Type": "application/json",
"oai-device-id": device_id,
"oai-language": "en-US",
"sec-ch-ua": '"Google Chrome";v="147", "Not.A/Brand";v="8", "Chromium";v="147"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"Cookie": f"oai-did={device_id}",
}
)
if checkout_proxy:
set_proxy_url(session, checkout_proxy)
# The ChatGPT session is used only for checkout and approve. Stripe provider
# requests use their own US-routed session.
return session
def create_checkout(
req: LongLinkRequest,
chatgpt_session: Any | None = None,
allow_openai_checkout: bool = False,
include_promo: bool = True,
) -> dict[str, Any]:
billing_country = effective_country(req)
currency = currency_for_country(billing_country)
checkout_ui_mode = (req.checkout_ui_mode or "hosted").strip() or "hosted"
checkout_proxy_configured = bool(
getattr(chatgpt_session, "proxies", {}) if chatgpt_session is not None else checkout_stage_proxy(req)
)
log_info(
"chatgpt.checkout.start",
route="checkout_proxy" if checkout_proxy_configured else "direct",
checkout_proxy_configured=checkout_proxy_configured,
billing_country=billing_country,
currency=currency,
checkout_ui_mode=checkout_ui_mode,
)
body = {
"entry_point": "all_plans_pricing_modal",
"plan_name": "chatgptplusplan",
"billing_details": {
"country": billing_country,
"currency": currency,
},
"checkout_ui_mode": checkout_ui_mode,
}
if include_promo:
body["promo_campaign"] = {
"promo_campaign_id": "plus-1-month-free",
"is_coupon_from_query_param": False,
}
headers = {
"Referer": "https://chatgpt.com/",
"x-openai-target-path": "/backend-api/payments/checkout",
"x-openai-target-route": "/backend-api/payments/checkout",
}
started = time.perf_counter()
response = (chatgpt_session or build_chatgpt_session(req)).post(
"https://chatgpt.com/backend-api/payments/checkout",
json=body,
headers=headers,
timeout=DEFAULT_TIMEOUT,
)
log_info(
"chatgpt.checkout.http",
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
url="https://chatgpt.com/backend-api/payments/checkout",
)
if response.status_code >= 400:
detail = http_error_detail("checkout create failed", response)
log_warning("chatgpt.checkout.error", status_code=response.status_code, detail=detail)
raise HTTPException(
status_code=response.status_code,
detail=detail,
)
data = response.json() or {}
cs_id = extract_checkout_session_id(data)
id_ok = bool(cs_id and (str(cs_id).startswith("cs_") or (allow_openai_checkout and str(cs_id).startswith("oaics_"))))
if not id_ok:
summary = checkout_response_summary(data)
detail = f"checkout response missing cs_id: keys={response_keys(data)} summary={summary}"
log_warning("chatgpt.checkout.missing_cs_id", detail=detail, summary=summary)
raise HTTPException(status_code=502, detail=detail)
processor_entity = extract_processor_entity(data) or processor_entity_for_country(billing_country)
stripe_publishable_key = extract_stripe_publishable_key(data)
checkout_url = extract_checkout_url(data)
confirm_return_url = str(data.get("confirm_return_url") or "").strip()
checkout_provider = str(data.get("checkout_provider") or "").strip()
log_info(
"chatgpt.checkout.done",
cs_id=str(cs_id),
checkout_provider=checkout_provider,
processor_entity=processor_entity,
billing_country=billing_country,
currency=currency,
checkout_url_present=bool(checkout_url),
confirm_return_url_present=bool(confirm_return_url),
stripe_key_present=bool(stripe_publishable_key),
stripe_key_fingerprint=stripe_key_fingerprint(stripe_publishable_key),
response_keys=response_keys(data),
)
return {
"cs_id": str(cs_id),
"processor_entity": processor_entity,
"billing_country": billing_country,
"currency": currency,
"stripe_publishable_key": stripe_publishable_key,
"checkout_url": checkout_url,
"confirm_return_url": confirm_return_url,
"checkout_provider": checkout_provider,
"raw_checkout": data,
}
def update_checkout_promotion(chatgpt: Any, checkout: dict[str, Any], promotion_proxy: str) -> dict[str, Any]:
path = "/backend-api/payments/checkout/update"
original_proxy = session_proxy_url(chatgpt)
promotion_proxy = normalize_proxy_url(promotion_proxy)
if promotion_proxy:
set_proxy_url(chatgpt, promotion_proxy)
else:
clear_proxy_url(chatgpt)
body = {
"checkout_session_id": checkout["cs_id"],
"processor_entity": checkout["processor_entity"],
"plan_name": "chatgptplusplan",
"price_interval": "month",
"seat_quantity": 1,
"promo_campaign": {
"promo_campaign_id": "plus-1-month-free",
"is_coupon_from_query_param": False,
},
}
started = time.perf_counter()
try:
response = chatgpt.post(
f"https://chatgpt.com{path}",
json=body,
headers={
"Referer": f"https://chatgpt.com/checkout/{checkout['processor_entity']}/{checkout['cs_id']}",
"x-openai-target-path": path,
"x-openai-target-route": path,
},
timeout=DEFAULT_TIMEOUT,
)
log_info(
"chatgpt.checkout.promotion_update.http",
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
promotion_proxy=promotion_proxy,
)
if response.status_code >= 400:
raise HTTPException(status_code=response.status_code, detail=http_error_detail("checkout promotion update failed", response))
try:
payload = response.json() or {}
except Exception:
payload = {}
if isinstance(payload, dict) and payload.get("success") is False:
raise HTTPException(status_code=502, detail=f"checkout promotion update rejected: {redact_text(payload)}")
log_info("chatgpt.checkout.promotion_update.done", cs_id=checkout["cs_id"], response_keys=response_keys(payload))
return payload if isinstance(payload, dict) else {}
finally:
if original_proxy:
set_proxy_url(chatgpt, original_proxy)
else:
clear_proxy_url(chatgpt)
def update_ideal_tax_context(
chatgpt: Any,
checkout: dict[str, Any],
req: LongLinkRequest,
stripe_pk: str,
provider_proxy: str,
) -> None:
billing = billing_for_link_type("ideal", "NL")
path = "/backend-api/payments/checkout/taxes"
response = chatgpt.post(
f"https://chatgpt.com{path}",
json={
"checkout_session_id": checkout["cs_id"],
"checkout_email": billing["email"],
"billing_country": "NL",
"billing_name": billing["name"],
"currency": "EUR",
"tax_id": None,
"processor_entity": checkout["processor_entity"],
"billing_address": {
"line1": billing["line1"],
"city": billing["city"],
"country": "NL",
"postal_code": billing["postal_code"],
},
},
headers={
"Referer": f"https://chatgpt.com/checkout/{checkout['processor_entity']}/{checkout['cs_id']}",
"x-openai-target-path": path,
"x-openai-target-route": path,
},
timeout=DEFAULT_TIMEOUT,
)
if response.status_code >= 400:
raise HTTPException(status_code=response.status_code, detail=http_error_detail("iDEAL checkout taxes failed", response))
stripe = build_stripe_session(req, proxy_override=provider_proxy)
tax_response = stripe.post(
f"https://api.stripe.com/v1/payment_pages/{checkout['cs_id']}",
data={
"eid": "NA",
"tax_region[country]": "NL",
"tax_region[postal_code]": billing["postal_code"],
"tax_region[line1]": billing["line1"],
"tax_region[city]": billing["city"],
"key": stripe_pk,
},
timeout=DEFAULT_TIMEOUT,
)
if tax_response.status_code >= 400:
raise HTTPException(status_code=tax_response.status_code, detail=http_error_detail("iDEAL Stripe tax region failed", tax_response))
log_info("ideal.tax_context.done", cs_id=checkout["cs_id"], country="NL")
def stripe_error_fields(response: Any) -> dict[str, str]:
try:
payload = response.json() or {}
except Exception:
payload = {}
error = payload.get("error") if isinstance(payload, dict) else None
error = error if isinstance(error, dict) else {}
return {
"code": str(error.get("code") or ""),
"param": str(error.get("param") or ""),
"type": str(error.get("type") or ""),
"message": str(error.get("message") or ""),
}
def stripe_init(
cs_id: str,
req: LongLinkRequest,
proxy_override: str = "",
stripe_pk_override: str = "",
stripe_key_source: str = "",
processor_entity: str = "",
) -> dict[str, Any]:
stripe_pk = str(stripe_pk_override or req.stripe_publishable_key).strip()
if not stripe_pk:
raise HTTPException(
status_code=422,
detail=(
f"missing Stripe publishable key for processor_entity={processor_entity or 'unknown'}; "
"supply stripe_publishable_key or configure the matching processor environment variable"
),
)
browser_locale, elements_locale = locale_parts(req.payment_locale)
browser_timezone = timezone_for_country(effective_country(req))
proxy_override = normalize_proxy_url(proxy_override)
log_info(
"stripe.init.start",
route="provider_proxy" if proxy_override else "direct",
cs_id=cs_id,
browser_locale=browser_locale,
browser_timezone=browser_timezone,
elements_locale=elements_locale,
custom_stripe_pk=bool(req.stripe_publishable_key.strip()),
stripe_key_source=stripe_key_source,
stripe_key_fingerprint=stripe_key_fingerprint(stripe_pk),
processor_entity=processor_entity,
provider_proxy=proxy_override,
)
stripe = new_session()
stripe.headers.update(
{
"User-Agent": req.user_agent.strip() or DEFAULT_USER_AGENT,
"Accept-Language": "en-US,en;q=0.9",
}
)
if proxy_override:
set_proxy_url(stripe, proxy_override)
body = {
"browser_locale": browser_locale,
"browser_timezone": browser_timezone,
"elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
"elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
"elements_session_client[elements_init_source]": "custom_checkout",
"elements_session_client[referrer_host]": "chatgpt.com",
"elements_session_client[stripe_js_id]": str(uuid.uuid4()),
"elements_session_client[locale]": elements_locale,
"elements_session_client[is_aggregation_expected]": "false",
"elements_options_client[saved_payment_method][enable_save]": "never",
"elements_options_client[saved_payment_method][enable_redisplay]": "never",
"key": stripe_pk,
"_stripe_version": stripe_version_for(req.link_type),
}
response = None
error_fields: dict[str, str] = {}
for attempt in range(1, STRIPE_INIT_RESOURCE_MISSING_ATTEMPTS + 1):
started = time.perf_counter()
response = stripe.post(
f"https://api.stripe.com/v1/payment_pages/{cs_id}/init",
data=body,
timeout=DEFAULT_TIMEOUT,
)
error_fields = stripe_error_fields(response)
log_info(
"stripe.init.http",
attempt=attempt,
max_attempts=STRIPE_INIT_RESOURCE_MISSING_ATTEMPTS,
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
stripe_error_code=error_fields["code"],
stripe_error_param=error_fields["param"],
url=f"https://api.stripe.com/v1/payment_pages/{cs_id}/init",
)
if response.status_code < 400:
break
is_resource_missing = (
response.status_code == 404
and error_fields["code"] == "resource_missing"
and error_fields["param"] == "payment_page"
)
if not is_resource_missing or attempt >= STRIPE_INIT_RESOURCE_MISSING_ATTEMPTS:
break
time.sleep(STRIPE_INIT_RESOURCE_MISSING_DELAY_MS / 1000)
assert response is not None
if response.status_code >= 400:
if (
response.status_code == 404
and error_fields["code"] == "resource_missing"
and error_fields["param"] == "payment_page"
):
detail = (
f"Stripe checkout session is not visible to the selected publishable key "
f"(processor_entity={processor_entity or 'unknown'}, key_source={stripe_key_source or 'unknown'}, "
f"key={stripe_key_fingerprint(stripe_pk)}). Configure the matching key via "
f"{stripe_key_env_name(processor_entity) or 'stripe_publishable_key'} or submit stripe_publishable_key."
)
else:
detail = http_error_detail("stripe init failed", response)
log_warning(
"stripe.init.error",
status_code=response.status_code,
stripe_error_code=error_fields["code"],
stripe_error_param=error_fields["param"],
detail=detail,
)
raise HTTPException(status_code=response.status_code, detail=detail)
payload = response.json() or {}
log_info(
"stripe.init.done",
response_keys=response_keys(payload),
hosted_url=payload.get("stripe_hosted_url", ""),
currency=payload.get("currency", ""),
init_checksum_present=bool(payload.get("init_checksum")),
)
return payload
def to_openai_pay_url(stripe_hosted_url: str) -> str:
url = str(stripe_hosted_url or "").strip()
if not url:
return ""
if url.startswith("https://checkout.stripe.com"):
return "https://pay.openai.com" + url[len("https://checkout.stripe.com") :]
parsed = urlsplit(url)
if parsed.netloc.lower() == "checkout.stripe.com":
return urlunsplit((parsed.scheme or "https", "pay.openai.com", parsed.path, parsed.query, parsed.fragment))
return url
def hosted_checkout_referrer(cs_id: str, init_payload: dict[str, Any], stripe_hosted_url: str) -> str:
raw = (
to_openai_pay_url(stripe_hosted_url)
or to_openai_pay_url(str(init_payload.get("hosted_checkout_url") or ""))
or to_openai_pay_url(str(init_payload.get("stripe_hosted_url") or ""))
or to_openai_pay_url(str(init_payload.get("url") or ""))
or f"https://pay.openai.com/c/pay/{cs_id}"
)
return raw.split("#", 1)[0]
def processor_entity_for_country(country: str, processor_entity: str = "") -> str:
entity = str(processor_entity or "").strip()
if entity:
return entity
return "openai_llc" if str(country or "").upper() == "US" else "openai_ie"
def chatgpt_success_return_url(cs_id: str, country: str, processor_entity: str = "") -> str:
entity = processor_entity_for_country(country, processor_entity)
return f"https://chatgpt.com/checkout/verify?stripe_session_id={cs_id}&processor_entity={entity}&plan_type=plus"
def stripe_checkout_long_url(cs_id: str, country: str, processor_entity: str = "") -> str:
return (
f"https://checkout.stripe.com/c/pay/{cs_id}"
f"?returned_from_redirect=true&ui_mode=custom&return_url="
f"{quote(chatgpt_success_return_url(cs_id, country, processor_entity), safe='')}"
)
def stripe_confirm_return_url(cs_id: str, checkout: dict[str, Any], stripe_hosted_url: str, payment_method_type: str = "paypal") -> str:
hosted_url = to_openai_pay_url(stripe_hosted_url) or stripe_checkout_long_url(
cs_id,
checkout["billing_country"],
checkout.get("processor_entity", ""),
)
if "pay.openai.com/" in hosted_url or "checkout.stripe.com/" in hosted_url:
parsed = urlsplit(hosted_url)
query = dict(parse_qsl(parsed.query, keep_blank_values=True))
query.setdefault("redirect_pm_type", normalize_link_type(payment_method_type))
query.setdefault("lid", "".join(random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") for _ in range(24)))
query.setdefault("ui_mode", "hosted")
query.setdefault(
"success_return_url",
chatgpt_success_return_url(
cs_id,
checkout["billing_country"],
checkout.get("processor_entity", ""),
),
)
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path, urlencode(query), parsed.fragment))
return hosted_url
def expected_amount(init_payload: Any) -> str:
if not isinstance(init_payload, dict):
return "0"
total_summary = init_payload.get("total_summary")
if isinstance(total_summary, dict) and total_summary.get("due") is not None:
return str(total_summary.get("due"))
invoice = init_payload.get("invoice")
if isinstance(invoice, dict) and invoice.get("amount_due") is not None:
return str(invoice.get("amount_due"))
line_items = init_payload.get("line_items")
if isinstance(line_items, list):
total = 0
found = False
for item in line_items:
if isinstance(item, dict) and item.get("amount") is not None:
try:
total += int(item.get("amount") or 0)
found = True
except Exception:
pass
if found:
return str(total)
preferred_keys = (
"amount_due",
"amount_total",
"total_amount",
"checkout_amount",
"due",
"total",
"amount",
"unit_amount",
)
def scan_amount(value: Any, depth: int = 0) -> str:
if depth > 8:
return ""
if isinstance(value, dict):
for key in preferred_keys:
if key in value:
amount = value.get(key)
if isinstance(amount, bool):
continue
if isinstance(amount, (int, float)) and amount >= 0:
return str(int(amount))
text = str(amount if amount is not None else "").strip()
if re.fullmatch(r"\d+(?:\.\d+)?", text):
return text
for item in value.values():
found = scan_amount(item, depth + 1)
if found:
return found
elif isinstance(value, list):
for item in value:
found = scan_amount(item, depth + 1)
if found:
return found
return ""
scanned = scan_amount(init_payload)
if scanned:
return scanned
return "0"
def int_amount(value: Any, default: int = 0) -> int:
if isinstance(value, bool):
return default
if isinstance(value, int):
return value
text = str(value if value is not None else "").strip()
if re.fullmatch(r"-?\d+", text):
return int(text)
return default
def display_amounts(init_payload: Any) -> dict[str, int]:
if not isinstance(init_payload, dict):
return {
"subtotal": 0,
"total_exclusive_tax": 0,
"total_inclusive_tax": 0,
"total_discount_amount": 0,
"shipping_rate_amount": 0,
"due": 0,
}
invoice = init_payload.get("invoice") if isinstance(init_payload.get("invoice"), dict) else {}
total_summary = init_payload.get("total_summary") if isinstance(init_payload.get("total_summary"), dict) else {}
line_item_group = init_payload.get("line_item_group") if isinstance(init_payload.get("line_item_group"), dict) else {}
lines = invoice.get("lines") if isinstance(invoice.get("lines"), dict) else {}
line_items = lines.get("data") if isinstance(lines.get("data"), list) else []
line_subtotal = sum(int_amount(item.get("amount")) for item in line_items if isinstance(item, dict))
subtotal = int_amount(total_summary.get("subtotal"), line_subtotal)
total = int_amount(total_summary.get("total"), int_amount(line_item_group.get("total"), int_amount(invoice.get("amount_due"), 0)))
due = int_amount(total_summary.get("due"), int_amount(invoice.get("amount_due"), total))
return {
"subtotal": subtotal,
"total_exclusive_tax": int_amount(total_summary.get("total_exclusive_tax"), 0),
"total_inclusive_tax": int_amount(total_summary.get("total_inclusive_tax"), total),
"total_discount_amount": max(subtotal - total, 0),
"shipping_rate_amount": 0,
"due": due,
}
def stripe_checksum_plaintext(raw: str) -> str:
if not raw:
return ""
xored = bytearray(ch ^ 5 for ch in raw.encode("utf-8"))
pad = 3 - (len(raw) % 3)
if pad > 0:
xored.extend((ord(" ") ^ 5) for _ in range(pad))
return quote(base64.b64encode(bytes(xored)).decode("ascii"), safe="")
def stripe_shift_checksum(value: dict[str, str]) -> str:
raw = json.dumps(value, separators=(",", ":"))
encoded = stripe_checksum_plaintext(raw)
if not encoded:
return ""
out: list[str] = []
for ch in encoded:
code = ord(ch)
if code < 32 or code > 126:
out.append(ch)
else:
out.append(chr((code - 32 + 11) % 95 + 32))
return "".join(out)
def stripe_checkout_payment_user_agent() -> str:
stripe_js_build = "0711c6012f"
return f"stripe.js/{stripe_js_build}; stripe-js-v3/{stripe_js_build}; checkout"
def merge_stripe_context(target: dict[str, Any], payload: Any) -> dict[str, Any]:
if not isinstance(target, dict) or not isinstance(payload, dict):
return target
for key in (
"init_checksum",
"total_summary",
"invoice",
"line_item_group",
"line_items",
"payment_method_types",
"ordered_payment_method_types",
"payment_method_specs",
"customer_email",
"geocoding",
"config_id",
):
if payload.get(key) is not None:
target[key] = payload[key]
return target
def stripe_pre_confirm_paypal(
stripe: Any,
cs_id: str,
stripe_pk: str,
init_payload: dict[str, Any],
stripe_hosted_url: str,
) -> dict[str, Any]:
referer = to_openai_pay_url(stripe_hosted_url) or str(init_payload.get("stripe_hosted_url") or "")
referer = referer or f"https://pay.openai.com/c/pay/{cs_id}"
body = {
"eid": "NA",
"payment_method_type": "paypal",
"key": stripe_pk,
}
log_info(
"stripe.pre_confirm.start",
route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
cs_id=cs_id,
referer=referer,
)
started = time.perf_counter()
response = stripe.post(
f"https://api.stripe.com/v1/payment_pages/{cs_id}/pre_confirm",
data=body,
headers={
"Origin": "https://pay.openai.com",
"Referer": referer.split("#", 1)[0],
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
timeout=DEFAULT_TIMEOUT,
)
log_info(
"stripe.pre_confirm.http",
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
url=f"https://api.stripe.com/v1/payment_pages/{cs_id}/pre_confirm",
)
if response.status_code >= 400:
detail = http_error_detail("stripe pre_confirm failed", response)
log_warning("stripe.pre_confirm.error", status_code=response.status_code, detail=detail)
return init_payload
try:
payload = response.json() or {}
except Exception:
log_warning("stripe.pre_confirm.bad_json", body=redact_text(response.text, max_len=300))
return init_payload
merge_stripe_context(init_payload, payload)
log_info(
"stripe.pre_confirm.done",
response_keys=response_keys(payload),
init_checksum_present=bool(init_payload.get("init_checksum")),
expected_amount=expected_amount(init_payload),
interesting_fields=interesting_payload_fields(payload),
)
return init_payload
def stripe_prepare_paypal(
stripe: Any,
cs_id: str,
stripe_pk: str,
init_payload: dict[str, Any],
req: LongLinkRequest,
stripe_hosted_url: str,
) -> dict[str, Any]:
referer = to_openai_pay_url(stripe_hosted_url) or str(init_payload.get("stripe_hosted_url") or "")
referer = referer or f"https://pay.openai.com/c/pay/{cs_id}"
route = "provider_proxy" if getattr(stripe, "proxies", {}) else "direct"
def request_json(method: str, url: str, *, params: dict[str, Any] | None = None, data: dict[str, Any] | None = None, step: str) -> dict[str, Any]:
started = time.perf_counter()
try:
response = stripe.request(
method,
url,
params=params,
data=data,
headers={
"Origin": "https://pay.openai.com",
"Referer": referer.split("#", 1)[0],
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
timeout=DEFAULT_TIMEOUT,
)
except Exception as exc:
log_warning("stripe.prepare.exception", step=step, route=route, error=repr(exc))
return {}
log_info(
"stripe.prepare.http",
step=step,
route=route,
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
url=url,
)
if response.status_code >= 400:
log_warning("stripe.prepare.error", step=step, status_code=response.status_code, detail=http_error_detail("stripe prepare failed", response))
return {}
try:
payload = response.json() or {}
except Exception:
log_warning("stripe.prepare.bad_json", step=step, body=redact_text(response.text, max_len=300))
return {}
merge_stripe_context(init_payload, payload)
found_redirect = extract_redirect_to_url(payload)
if found_redirect:
init_payload["_prepared_redirect_url"] = found_redirect
log_info(
"stripe.prepare.done",
step=step,
response_keys=response_keys(payload),
redirect_present=bool(found_redirect),
init_checksum_present=bool(init_payload.get("init_checksum")),
expected_amount=expected_amount(init_payload),
)
return payload
log_info("stripe.prepare.start", route=route, cs_id=cs_id)
request_json(
"GET",
"https://api.stripe.com/v1/payment_pages/allowed_origins",
params={"key": stripe_pk, "session_id": cs_id},
step="allowed_origins",
)
_, elements_locale = locale_parts(req.payment_locale)
request_json(
"GET",
"https://api.stripe.com/v1/elements/sessions",
params={
"client_betas[0]": "google_pay_beta_1",
"client_betas[1]": "disable_deferred_intent_client_validation_beta_1",
"client_betas[2]": "blocked_card_brands_beta_2",
"deferred_intent[mode]": "subscription",
"deferred_intent[amount]": expected_amount(init_payload),
"deferred_intent[currency]": str(init_payload.get("currency") or currency_for_country(effective_country(req))).lower(),
"deferred_intent[setup_future_usage]": "off_session",
"deferred_intent[payment_method_types][0]": "card",
"currency": str(init_payload.get("currency") or currency_for_country(effective_country(req))).lower(),
"key": stripe_pk,
"elements_init_source": "checkout",
"hosted_surface": "checkout",
"referrer_host": "pay.openai.com",
"stripe_js_id": str(uuid.uuid4()),
"locale": elements_locale,
"type": "deferred_intent",
"checkout_session_id": cs_id,
},
step="elements_sessions",
)
for tax_country in [effective_country(req), "US"]:
request_json(
"POST",
f"https://api.stripe.com/v1/payment_pages/{cs_id}",
data={"eid": "NA", "tax_region[country]": tax_country, "key": stripe_pk},
step=f"tax_region_{tax_country}",
)
break
log_info(
"stripe.prepare.finish",
cs_id=cs_id,
init_checksum_present=bool(init_payload.get("init_checksum")),
expected_amount=expected_amount(init_payload),
prepared_redirect_present=bool(init_payload.get("_prepared_redirect_url")),
)
return init_payload
def amount_is_zero(value: Any) -> bool:
text = str(value if value is not None else "").strip()
if not text:
return False
try:
return float(text) == 0
except Exception:
digits = re.sub(r"[^\d.-]+", "", text)
try:
return bool(digits) and float(digits) == 0
except Exception:
return text in {"0", "0.0", "0.00"}
def enforce_zero_checkout_amount(init_payload: dict[str, Any], req: LongLinkRequest, cs_id: str) -> None:
amount = expected_amount(init_payload)
currency = str(init_payload.get("currency") or currency_for_country(effective_country(req))).upper()
if amount_is_zero(amount):
log_info(
"stripe.amount_guard.ok",
cs_id=cs_id,
amount=amount,
currency=currency,
billing_country=effective_country(req),
pm_country=effective_pm_country(req),
)
return
detail = f"付款金额不是 0,已停止:amount={amount} {currency}"
log_warning(
"stripe.amount_guard.blocked",
cs_id=cs_id,
amount=amount,
currency=currency,
billing_country=effective_country(req),
pm_country=effective_pm_country(req),
detail=detail,
)
raise HTTPException(status_code=402, detail=detail)
def is_amount_guard_error(exc: Exception) -> bool:
if not isinstance(exc, HTTPException):
return False
detail = str(exc.detail or "")
return exc.status_code == 402 and ("付款金额不是 0" in detail or "amount not zero" in detail.lower())
NON_RETRYABLE_ERROR_MARKERS = (
"could not parse your authentication token",
"invalid cdk",
"cdk exhausted",
"cdk revoked",
"payment_method_types_mismatch",
"does not offer paypal",
"does not offer ideal",
"does not offer upi",
"payment method is not available",
"payment_method_not_available",
"payment_method_unsupported_type",
"setup_attempt_failed",
"generic_decline",
"requires a new payment method",
"付款金额不是 0",
"amount not zero",
)
FRESH_CHECKOUT_RETRYABLE_MARKERS = (
"setup_attempt_failed",
"generic_decline",
"requires a new payment method",
"checkout_not_active_session",
)
def retryable_failure(detail: Any, status_code: int = 0, fresh_checkout: bool = False) -> bool:
text = str(detail or "").strip().lower()
# These are terminal for the current Stripe/Checkout object, but historical
# successes show that a new CS plus a fresh proxy SID can recover. Never
# repeat them inside the same checkout; only the bounded outer loop opts in.
if fresh_checkout and any(marker in text for marker in FRESH_CHECKOUT_RETRYABLE_MARKERS):
return True
if any(marker in text for marker in NON_RETRYABLE_ERROR_MARKERS):
return False
if status_code in {400, 401, 402, 422}:
return False
if status_code in {403, 408, 409, 425, 429, 500, 502, 503, 504}:
return True
transient_markers = (
"timeout",
"timed out",
"tls connect error",
"proxy",
"connection",
"checkout_not_active_session",
"approve blocked",
"result: 'blocked'",
"server error",
)
return any(marker in text for marker in transient_markers)
def provider_error_diagnostic(
detail: Any,
link_type: str,
checkout: dict[str, Any],
req: LongLinkRequest,
) -> str:
original = str(detail or "").strip()
lowered = original.lower()
method = normalize_link_type(link_type)
if method == "paypal" and ("setup_attempt_failed" in lowered or "generic_decline" in lowered):
return (
"PayPal SetupIntent 被 Stripe/PayPal 拒绝(当前 Checkout 已终止,需切换新 CS/代理会话);"
f"processor={checkout.get('processor_entity') or 'unknown'}, "
f"billing={effective_country(req)}, pm={effective_pm_country(req)}, "
f"checkout_proxy_country={proxy_country_hint(checkout_stage_proxy(req)) or 'unknown'}, "
f"provider_proxy_country={proxy_country_hint(provider_stage_proxy(req)) or 'unknown'}; "
f"upstream={original}"
)
if method == "upi" and "payment_method_types_mismatch" in lowered:
return (
"当前 Checkout 未向 UPI 开放该支付流程;"
f"billing={effective_country(req)}, provider_proxy_country="
f"{proxy_country_hint(provider_stage_proxy(req)) or 'unknown'}; upstream={original}"
)
return original
KNOWN_PAYMENT_METHOD_TYPES = {
"card",
"link",
"paypal",
"ideal",
"upi",
"google_pay",
"apple_pay",
}
def available_payment_method_types(payload: Any) -> set[str]:
"""Read only Stripe's explicit method lists/specs, avoiding loose key-name matches."""
found: set[str] = set()
def add(value: Any) -> None:
method = str(value or "").strip().lower()
if method in KNOWN_PAYMENT_METHOD_TYPES:
found.add(method)
def visit(value: Any, depth: int = 0, in_specs: bool = False) -> None:
if depth > 9:
return
if isinstance(value, dict):
for key, item in value.items():
key_text = str(key).strip().lower()
if key_text in {"payment_method_types", "ordered_payment_method_types"}:
if isinstance(item, list):
for method in item:
add(method)
else:
add(item)
elif key_text in {"payment_method_type", "expected_payment_method_type"}:
add(item)
elif in_specs and key_text == "type":
add(item)
visit(item, depth + 1, in_specs or key_text == "payment_method_specs")
elif isinstance(value, list):
for item in value[:200]:
visit(item, depth + 1, in_specs)
visit(payload)
return found
def payload_has_paypal(value: Any, depth: int = 0) -> bool:
del depth # compatibility with the former recursive signature
return "paypal" in available_payment_method_types(value)
def payment_method_is_available(payload: Any, link_type: str) -> bool:
return normalize_link_type(link_type) in available_payment_method_types(payload)
def require_payment_method_available(payload: Any, link_type: str) -> None:
method = normalize_link_type(link_type)
methods = available_payment_method_types(payload)
if method in methods:
return
available = ",".join(sorted(methods)) or "none"
raise HTTPException(
status_code=422,
detail=(
f"Stripe Checkout does not offer {method} for this country/currency/flow; "
f"available={available}"
),
)
def stripe_context(cs_id: str, init_payload: dict[str, Any], req: LongLinkRequest) -> dict[str, Any]:
_, elements_locale = locale_parts(req.payment_locale)
return {
"stripe_js_id": str(uuid.uuid4()),
"elements_session_id": f"elements_session_{uuid.uuid4().hex[:11]}",
"elements_session_config_id": str(init_payload.get("config_id") or uuid.uuid4()),
"config_id": init_payload.get("config_id") or "",
"init_checksum": init_payload.get("init_checksum") or "",
"currency": str(init_payload.get("currency") or currency_for_country(effective_country(req))).lower(),
"checkout_amount": expected_amount(init_payload),
"locale": elements_locale,
"checkout_ui_mode": (req.checkout_ui_mode or "hosted").strip() or "hosted",
"stripe_version": stripe_version_for(req.link_type),
}
def generated_billing_profile(country: str) -> dict[str, str]:
billing_country = supported_country(country, "US")
if billing_country in BILLING_PROFILES:
profile_entry = BILLING_PROFILES[billing_country]
if isinstance(profile_entry, list):
return random.choice(profile_entry)
return profile_entry
city, state, postal_code, line1 = COUNTRY_CITY_SEEDS.get(
billing_country,
("Capital City", billing_country, "1000", "Central Avenue 10"),
)
first_name, last_name = COUNTRY_NAME_SEEDS[sum(ord(ch) for ch in billing_country) % len(COUNTRY_NAME_SEEDS)]
return {
"first_name": first_name,
"last_name": last_name,
"line1": line1,
"city": city,
"state": state,
"postal_code": postal_code,
}
def billing_for_link_type(link_type: str, country: str = "US") -> dict[str, str]:
billing_country = supported_country(country, "US")
profile = generated_billing_profile(billing_country)
first_name = profile["first_name"]
last_name = profile["last_name"]
suffix = random.randint(1000, 9999)
return {
"name": f"{first_name} {last_name}",
"email": f"{first_name.lower()}.{last_name.lower()}{suffix}@example.com",
"country": billing_country,
"line1": profile["line1"],
"city": profile["city"],
"state": profile["state"],
"postal_code": profile["postal_code"],
}
def build_stripe_session(req: LongLinkRequest, proxy_override: str = "") -> Any:
proxy_override = normalize_proxy_url(proxy_override)
log_info(
"session.stripe.create",
route="provider_proxy" if proxy_override else "direct",
proxy_configured=bool(proxy_override),
provider_proxy=proxy_override,
)
stripe = new_session()
stripe.headers.update(
{
"User-Agent": req.user_agent.strip() or DEFAULT_USER_AGENT,
"Accept-Language": "en-US,en;q=0.9",
}
)
if proxy_override:
set_proxy_url(stripe, proxy_override)
return stripe
def stripe_create_payment_method(
stripe: Any,
cs_id: str,
stripe_pk: str,
billing: dict[str, str],
payment_method_type: str,
ctx: dict[str, Any],
init_payload: dict[str, Any] | None = None,
stripe_hosted_url: str = "",
) -> str:
payment_method_type = normalize_link_type(payment_method_type)
runtime_version = str(ctx.get("runtime_version") or DEFAULT_STRIPE_RUNTIME_VERSION)
log_info(
"stripe.payment_method.start",
route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
cs_id=cs_id,
payment_method_type=payment_method_type,
billing_country=billing.get("country") or "US",
billing_name=billing.get("name") or "",
billing_city=billing.get("city") or "",
billing_state=billing.get("state") or "",
billing_postal_code=billing.get("postal_code") or "",
currency=ctx.get("currency", ""),
checkout_amount=ctx.get("checkout_amount", ""),
)
hosted_mode = str(ctx.get("checkout_ui_mode") or "").lower() == "hosted"
if hosted_mode:
body = {
"billing_details[name]": billing.get("name") or "John Doe",
"billing_details[email]": billing.get("email") or "buyer@example.com",
"billing_details[address][country]": billing.get("country") or "US",
"billing_details[address][line1]": billing.get("line1") or "123 Market St",
"billing_details[address][city]": billing.get("city") or "San Francisco",
"billing_details[address][postal_code]": billing.get("postal_code") or "94105",
"billing_details[address][state]": billing.get("state") or "CA",
"type": payment_method_type,
"payment_user_agent": stripe_checkout_payment_user_agent(),
"client_attribution_metadata[checkout_session_id]": cs_id,
"client_attribution_metadata[merchant_integration_source]": "checkout",
"client_attribution_metadata[merchant_integration_subtype]": "hosted",
"client_attribution_metadata[merchant_integration_version]": "hosted_checkout",
"client_attribution_metadata[payment_method_selection_flow]": "automatic",
"key": stripe_pk,
"_stripe_version": str(ctx.get("stripe_version") or stripe_version_for(payment_method_type)),
}
if ctx.get("config_id"):
body["client_attribution_metadata[checkout_config_id]"] = str(ctx.get("config_id") or "")
else:
body = {
"billing_details[name]": billing.get("name") or "John Doe",
"billing_details[email]": billing.get("email") or "buyer@example.com",
"billing_details[address][country]": billing.get("country") or "US",
"billing_details[address][line1]": billing.get("line1") or "123 Market St",
"billing_details[address][city]": billing.get("city") or "San Francisco",
"billing_details[address][postal_code]": billing.get("postal_code") or "94105",
"billing_details[address][state]": billing.get("state") or "CA",
"type": payment_method_type,
"payment_user_agent": f"stripe.js/{runtime_version}; stripe-js-v3/{runtime_version}; payment-element; deferred-intent",
"referrer": "https://chatgpt.com",
"time_on_page": str(random.randint(25000, 55000)),
"client_attribution_metadata[checkout_session_id]": cs_id,
"client_attribution_metadata[client_session_id]": ctx["stripe_js_id"],
"client_attribution_metadata[checkout_config_id]": ctx.get("config_id") or "",
"client_attribution_metadata[elements_session_id]": ctx["elements_session_id"],
"client_attribution_metadata[elements_session_config_id]": ctx["elements_session_config_id"],
"client_attribution_metadata[merchant_integration_source]": "elements",
"client_attribution_metadata[merchant_integration_subtype]": "payment-element",
"client_attribution_metadata[merchant_integration_version]": "2021",
"client_attribution_metadata[payment_intent_creation_flow]": "deferred",
"client_attribution_metadata[payment_method_selection_flow]": "automatic",
"client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
"client_attribution_metadata[merchant_integration_additional_elements][1]": "address",
"key": stripe_pk,
"_stripe_version": str(ctx.get("stripe_version") or stripe_version_for(payment_method_type)),
}
started = time.perf_counter()
headers = None
if hosted_mode:
headers = {
"Origin": "https://pay.openai.com",
"Referer": hosted_checkout_referrer(cs_id, init_payload or {}, stripe_hosted_url),
}
response = stripe.post("https://api.stripe.com/v1/payment_methods", data=body, headers=headers, timeout=DEFAULT_TIMEOUT)
log_info(
"stripe.payment_method.http",
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
url="https://api.stripe.com/v1/payment_methods",
)
if response.status_code >= 400:
detail = http_error_detail("stripe payment_methods failed", response)
log_warning("stripe.payment_method.error", status_code=response.status_code, detail=detail)
raise HTTPException(status_code=response.status_code, detail=detail)
payload = response.json() or {}
pm_id = str(payload.get("id") or "")
if not pm_id.startswith("pm_"):
detail = f"stripe payment_methods bad response: keys={response_keys(payload)} body={redact_text(response.text, max_len=300)}"
log_warning("stripe.payment_method.bad_response", detail=detail)
raise HTTPException(status_code=502, detail=detail)
log_info("stripe.payment_method.done", payment_method_id=pm_id, response_keys=response_keys(payload))
return pm_id
def stripe_confirm(
stripe: Any,
cs_id: str,
pm_id: str,
stripe_pk: str,
payment_method_type: str,
init_payload: dict[str, Any],
ctx: dict[str, Any],
checkout: dict[str, Any],
req: LongLinkRequest,
stripe_hosted_url: str,
) -> dict[str, Any]:
payment_method_type = normalize_link_type(payment_method_type)
return_url = stripe_confirm_return_url(cs_id, checkout, stripe_hosted_url, payment_method_type)
runtime_version = str(ctx.get("runtime_version") or DEFAULT_STRIPE_RUNTIME_VERSION)
hosted_mode = str(ctx.get("checkout_ui_mode") or "").lower() == "hosted"
log_info(
"stripe.confirm.start",
route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
cs_id=cs_id,
payment_method_id=pm_id,
expected_amount=str(ctx.get("checkout_amount") or expected_amount(init_payload)),
payment_method_type=payment_method_type,
return_url=return_url,
mode="hosted" if hosted_mode else "custom",
)
if hosted_mode:
amounts = display_amounts(init_payload)
body = {
"eid": "NA",
"payment_method": pm_id,
"init_checksum": str(init_payload.get("init_checksum") or ctx.get("init_checksum") or ""),
"expected_amount": str(ctx.get("checkout_amount") or expected_amount(init_payload)),
"expected_payment_method_type": payment_method_type,
"consent[terms_of_service]": "accepted",
"last_displayed_line_item_group_details[subtotal]": str(amounts["subtotal"]),
"last_displayed_line_item_group_details[total_exclusive_tax]": str(amounts["total_exclusive_tax"]),
"last_displayed_line_item_group_details[total_inclusive_tax]": str(amounts["total_inclusive_tax"]),
"last_displayed_line_item_group_details[total_discount_amount]": str(amounts["total_discount_amount"]),
"last_displayed_line_item_group_details[shipping_rate_amount]": str(amounts["shipping_rate_amount"]),
"return_url": return_url,
"js_checksum": stripe_shift_checksum({"id": pm_id}),
"rv_timestamp": stripe_shift_checksum(
{
"rvTs": "2024-01-01 00:00:00 -0000",
"rv": "0711c6012fed57bca21a1857e407d89e5745e3df",
"sv": "d616dee94d164fb10d46843aec403d3beeb078d097c08dd8d77451247f21d924",
}
),
"client_attribution_metadata[checkout_session_id]": cs_id,
"client_attribution_metadata[merchant_integration_source]": "checkout",
"client_attribution_metadata[merchant_integration_subtype]": "hosted",
"client_attribution_metadata[merchant_integration_version]": "hosted_checkout",
"client_attribution_metadata[payment_method_selection_flow]": "automatic",
"key": stripe_pk,
"_stripe_version": str(ctx.get("stripe_version") or stripe_version_for(payment_method_type)),
}
if ctx.get("config_id"):
body["client_attribution_metadata[checkout_config_id]"] = str(ctx.get("config_id") or "")
else:
body = {
"guid": uuid.uuid4().hex,
"muid": uuid.uuid4().hex,
"sid": uuid.uuid4().hex,
"payment_method": pm_id,
"init_checksum": str(init_payload.get("init_checksum") or ctx.get("init_checksum") or ""),
"version": runtime_version,
"expected_amount": str(ctx.get("checkout_amount") or expected_amount(init_payload)),
"expected_payment_method_type": payment_method_type,
"return_url": return_url,
"elements_session_client[session_id]": ctx["elements_session_id"],
"elements_session_client[locale]": str(ctx.get("locale") or "en"),
"elements_session_client[referrer_host]": "chatgpt.com",
"elements_session_client[is_aggregation_expected]": "false",
"elements_session_client[elements_init_source]": "custom_checkout",
"elements_session_client[stripe_js_id]": ctx["stripe_js_id"],
"elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
"elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
"elements_options_client[saved_payment_method][enable_save]": "never",
"elements_options_client[saved_payment_method][enable_redisplay]": "never",
"client_attribution_metadata[client_session_id]": ctx["stripe_js_id"],
"client_attribution_metadata[checkout_session_id]": cs_id,
"client_attribution_metadata[checkout_config_id]": ctx.get("config_id") or "",
"client_attribution_metadata[elements_session_id]": ctx["elements_session_id"],
"client_attribution_metadata[elements_session_config_id]": ctx["elements_session_config_id"],
"client_attribution_metadata[merchant_integration_source]": "checkout",
"client_attribution_metadata[merchant_integration_subtype]": "payment-element",
"client_attribution_metadata[merchant_integration_version]": "custom",
"client_attribution_metadata[payment_intent_creation_flow]": "deferred",
"client_attribution_metadata[payment_method_selection_flow]": "automatic",
"client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
"client_attribution_metadata[merchant_integration_additional_elements][1]": "address",
"consent[terms_of_service]": "accepted",
"key": stripe_pk,
"_stripe_version": str(ctx.get("stripe_version") or stripe_version_for(payment_method_type)),
}
started = time.perf_counter()
headers = None
if hosted_mode:
headers = {
"Origin": "https://pay.openai.com",
"Referer": hosted_checkout_referrer(cs_id, init_payload, stripe_hosted_url),
}
confirm_timeout = UPI_CONFIRM_TIMEOUT_SECONDS if payment_method_type == "upi" else DEFAULT_TIMEOUT
response = stripe.post(
f"https://api.stripe.com/v1/payment_pages/{cs_id}/confirm",
data=body,
headers=headers,
timeout=confirm_timeout,
)
log_info(
"stripe.confirm.http",
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
timeout_seconds=confirm_timeout,
url=f"https://api.stripe.com/v1/payment_pages/{cs_id}/confirm",
)
if response.status_code >= 400:
detail = http_error_detail("stripe confirm failed", response)
log_warning("stripe.confirm.error", status_code=response.status_code, detail=detail)
raise HTTPException(status_code=response.status_code, detail=detail)
payload = response.json() or {}
submission = payload.get("submission_attempt") if isinstance(payload, dict) else None
submission_state = submission.get("state") if isinstance(submission, dict) else ""
intent_state = stripe_intent_state(payload)
log_info(
"stripe.confirm.done",
response_keys=response_keys(payload),
interesting_fields=interesting_payload_fields(payload),
has_redirect=bool(extract_redirect_to_url(payload)),
submission_state=submission_state,
checkout_status=payload.get("status", "") if isinstance(payload, dict) else "",
checkout_state=payload.get("state", "") if isinstance(payload, dict) else "",
payment_intent_present=bool(payload.get("payment_intent")) if isinstance(payload, dict) else False,
setup_intent_present=bool(payload.get("setup_intent")) if isinstance(payload, dict) else False,
next_action_present=bool(payload.get("next_action")) if isinstance(payload, dict) else False,
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
next_action_type=intent_state.get("next_action_type", ""),
)
return payload
def stripe_confirm_direct_paypal(
stripe: Any,
cs_id: str,
stripe_pk: str,
billing: dict[str, str],
init_payload: dict[str, Any],
ctx: dict[str, Any],
checkout: dict[str, Any],
req: LongLinkRequest,
stripe_hosted_url: str,
) -> dict[str, Any]:
return_url = stripe_confirm_return_url(cs_id, checkout, stripe_hosted_url)
runtime_version = str(ctx.get("runtime_version") or DEFAULT_STRIPE_RUNTIME_VERSION)
log_info(
"stripe.confirm_direct.start",
route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
cs_id=cs_id,
billing_country=billing.get("country") or "",
expected_amount=str(ctx.get("checkout_amount") or expected_amount(init_payload)),
return_url=return_url,
)
body = {
"guid": uuid.uuid4().hex,
"muid": uuid.uuid4().hex,
"sid": uuid.uuid4().hex,
"payment_method_data[type]": "paypal",
"payment_method_data[billing_details][name]": billing.get("name") or "",
"payment_method_data[billing_details][email]": billing.get("email") or "",
"payment_method_data[billing_details][address][country]": billing.get("country") or "",
"payment_method_data[billing_details][address][line1]": billing.get("line1") or "",
"payment_method_data[billing_details][address][city]": billing.get("city") or "",
"payment_method_data[billing_details][address][postal_code]": billing.get("postal_code") or "",
"payment_method_data[billing_details][address][state]": billing.get("state") or "",
"init_checksum": str(init_payload.get("init_checksum") or ctx.get("init_checksum") or ""),
"version": runtime_version,
"expected_amount": str(ctx.get("checkout_amount") or expected_amount(init_payload)),
"expected_payment_method_type": "paypal",
"return_url": return_url,
"elements_session_client[session_id]": ctx["elements_session_id"],
"elements_session_client[locale]": str(ctx.get("locale") or "en"),
"elements_session_client[referrer_host]": "chatgpt.com",
"elements_session_client[is_aggregation_expected]": "false",
"elements_session_client[elements_init_source]": "custom_checkout",
"elements_session_client[stripe_js_id]": ctx["stripe_js_id"],
"elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
"elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
"elements_options_client[saved_payment_method][enable_save]": "never",
"elements_options_client[saved_payment_method][enable_redisplay]": "never",
"client_attribution_metadata[client_session_id]": ctx["stripe_js_id"],
"client_attribution_metadata[checkout_session_id]": cs_id,
"client_attribution_metadata[checkout_config_id]": ctx.get("config_id") or "",
"client_attribution_metadata[elements_session_id]": ctx["elements_session_id"],
"client_attribution_metadata[elements_session_config_id]": ctx["elements_session_config_id"],
"client_attribution_metadata[merchant_integration_source]": "checkout",
"client_attribution_metadata[merchant_integration_subtype]": "payment-element",
"client_attribution_metadata[merchant_integration_version]": "custom",
"client_attribution_metadata[payment_intent_creation_flow]": "deferred",
"client_attribution_metadata[payment_method_selection_flow]": "automatic",
"client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
"client_attribution_metadata[merchant_integration_additional_elements][1]": "address",
"consent[terms_of_service]": "accepted",
"key": stripe_pk,
"_stripe_version": str(ctx.get("stripe_version") or stripe_version_for("paypal")),
}
started = time.perf_counter()
response = stripe.post(f"https://api.stripe.com/v1/payment_pages/{cs_id}/confirm", data=body, timeout=DEFAULT_TIMEOUT)
log_info(
"stripe.confirm_direct.http",
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
url=f"https://api.stripe.com/v1/payment_pages/{cs_id}/confirm",
)
if response.status_code >= 400:
detail = http_error_detail("stripe direct paypal confirm failed", response)
log_warning("stripe.confirm_direct.error", status_code=response.status_code, detail=detail)
raise HTTPException(status_code=response.status_code, detail=detail)
payload = response.json() or {}
intent_state = stripe_intent_state(payload)
log_info(
"stripe.confirm_direct.done",
response_keys=response_keys(payload),
interesting_fields=interesting_payload_fields(payload),
has_redirect=bool(extract_redirect_to_url(payload)),
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
next_action_type=intent_state.get("next_action_type", ""),
)
return payload
NEXT_ACTION_URL_KEYS = (
"hosted_instructions_url",
"mobile_auth_url",
"url",
"hosted_voucher_url",
"hosted_verification_url",
"image_url_svg",
"image_url_png",
)
def next_action_from_payload(payload: Any) -> dict[str, Any]:
if not isinstance(payload, dict):
return {}
action = payload.get("next_action")
if isinstance(action, dict):
return action
for key in ("setup_intent", "payment_intent"):
nested = payload.get(key)
found = next_action_from_payload(nested)
if found:
return found
return {}
def next_action_type(payload: Any) -> str:
return str(next_action_from_payload(payload).get("type") or "").strip()
def extract_action_url(value: Any, depth: int = 0) -> str:
if depth > 5:
return ""
if isinstance(value, dict):
for key in NEXT_ACTION_URL_KEYS:
candidate = str(value.get(key) or "").strip()
if candidate.startswith(("https://", "http://")):
return candidate
for item in value.values():
candidate = extract_action_url(item, depth + 1)
if candidate:
return candidate
elif isinstance(value, list):
for item in value[:20]:
candidate = extract_action_url(item, depth + 1)
if candidate:
return candidate
return ""
def extract_redirect_to_url(payload: Any) -> str:
action = next_action_from_payload(payload)
if not action:
return ""
action_type = str(action.get("type") or "").strip()
action_payload = action.get(action_type)
if not isinstance(action_payload, dict) and action_type == "redirect_to_url":
action_payload = action.get("redirect_to_url")
if isinstance(action_payload, dict):
found = extract_action_url(action_payload)
if found:
return found
return extract_action_url(action)
def stripe_intent_state(payload: Any) -> dict[str, str]:
if not isinstance(payload, dict):
return {}
candidates: list[dict[str, Any]] = []
if payload.get("object") in {"setup_intent", "payment_intent"}:
candidates.append(payload)
for key in ("setup_intent", "payment_intent"):
nested = payload.get(key)
if isinstance(nested, dict):
candidates.append(nested)
for intent in candidates:
object_type = str(intent.get("object") or "")
error_key = "last_setup_error" if object_type == "setup_intent" else "last_payment_error"
error = intent.get(error_key)
error = error if isinstance(error, dict) else {}
next_action = intent.get("next_action")
next_action = next_action if isinstance(next_action, dict) else {}
return {
"object": object_type,
"status": str(intent.get("status") or ""),
"error_code": str(error.get("code") or ""),
"decline_code": str(error.get("decline_code") or ""),
"error_message": str(error.get("message") or ""),
"next_action_type": str(next_action.get("type") or ""),
}
return {}
def stripe_terminal_intent_error(payload: Any) -> str:
state = stripe_intent_state(payload)
status = state.get("status", "")
if status == "canceled":
return f"{state.get('object') or 'stripe intent'} canceled"
if status != "requires_payment_method":
return ""
code = state.get("error_code", "")
decline_code = state.get("decline_code", "")
message = state.get("error_message", "")
if not any((code, decline_code, message)):
return ""
parts = [f"{state.get('object') or 'stripe intent'} requires a new payment method"]
if code:
parts.append(f"code={code}")
if decline_code:
parts.append(f"decline_code={decline_code}")
if message:
parts.append(f"message={message}")
return "; ".join(parts)
def checkout_approval_reason(payload: Any) -> str:
if not isinstance(payload, dict):
return ""
submission = payload.get("submission_attempt")
if isinstance(submission, dict) and str(submission.get("state") or "").lower() == "requires_approval":
return "submission_requires_approval"
status = str(payload.get("status") or "").strip().lower()
state = str(payload.get("state") or "").strip().lower()
if status == "open" and state == "active":
return "checkout_open_active"
return ""
def stripe_payment_page_redirect_url(
stripe: Any,
cs_id: str,
stripe_pk: str,
req: LongLinkRequest,
ctx: dict[str, Any] | None = None,
timeout_seconds: float = 30,
max_attempts: int = STRIPE_REDIRECT_POLL_MAX_ATTEMPTS,
) -> str:
deadline = time.time() + max(1.0, float(timeout_seconds or 30))
# Provider actions can appear shortly after ChatGPT approval. Poll a small,
# bounded number of times; never fan out concurrent requests for one CS ID.
max_attempts = max(1, min(int(max_attempts or 1), STRIPE_REDIRECT_POLL_MAX_ATTEMPTS))
pool_workers = min(max(1, STRIPE_REDIRECT_POLL_WORKERS), max_attempts)
sequential = True
poll_proxies = redirect_poll_proxy_pool(req, stripe)
last_err = ""
log_info(
"stripe.redirect_poll.start",
route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
cs_id=cs_id,
timeout_seconds=timeout_seconds,
max_attempts=max_attempts,
pool_workers=1 if sequential else pool_workers,
reuse_context=bool(ctx),
poll_proxy_pool_count=len(poll_proxies),
poll_proxy_label=redact_proxy(poll_proxies[0]) if poll_proxies else "",
elements_session_id=str((ctx or {}).get("elements_session_id") or ""),
stripe_js_id=str((ctx or {}).get("stripe_js_id") or ""),
concurrent=not sequential,
)
request_id = REQUEST_ID.get()
task_callback = TASK_LOG_CALLBACK.get()
thread_state = local()
def poll_once(attempt: int) -> dict[str, Any]:
request_token = REQUEST_ID.set(request_id)
callback_token = TASK_LOG_CALLBACK.set(task_callback)
try:
session = clone_session(stripe)
poll_proxy = poll_proxies[(attempt - 1) % len(poll_proxies)] if poll_proxies else ""
if poll_proxy:
set_proxy_url(session, poll_proxy)
params = {
"elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
"elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
"elements_session_client[elements_init_source]": "custom_checkout",
"elements_session_client[referrer_host]": "chatgpt.com",
"elements_session_client[session_id]": str((ctx or {}).get("elements_session_id") or f"elements_session_{uuid.uuid4().hex[:11]}"),
"elements_session_client[stripe_js_id]": str((ctx or {}).get("stripe_js_id") or uuid.uuid4()),
"elements_session_client[locale]": str((ctx or {}).get("locale") or locale_parts(req.payment_locale)[1]),
"elements_session_client[is_aggregation_expected]": "false",
"elements_options_client[saved_payment_method][enable_save]": "never",
"elements_options_client[saved_payment_method][enable_redisplay]": "never",
"key": stripe_pk,
"_stripe_version": str((ctx or {}).get("stripe_version") or stripe_version_for(req.link_type)),
}
started = time.perf_counter()
try:
response = session.get(
f"https://api.stripe.com/v1/payment_pages/{cs_id}",
params=params,
timeout=DEFAULT_TIMEOUT,
)
except Exception as exc:
return {
"attempt": attempt,
"status_code": 0,
"elapsed_ms": elapsed_ms(started),
"redirect_url": "",
"terminal_error": "",
"detail": f"stripe redirect poll exception: {repr(exc)}",
"intent_state": {},
"response_keys": "",
"interesting_fields": "",
"poll_proxy_index": ((attempt - 1) % len(poll_proxies) + 1) if poll_proxies else 0,
"poll_proxy_count": len(poll_proxies),
"poll_proxy_label": redact_proxy(poll_proxy),
}
duration = elapsed_ms(started)
if response.status_code == 200:
payload = response.json() or {}
redirect_url = extract_redirect_to_url(payload)
intent_state = stripe_intent_state(payload)
terminal_error = stripe_terminal_intent_error(payload)
return {
"attempt": attempt,
"status_code": response.status_code,
"elapsed_ms": duration,
"redirect_url": redirect_url,
"terminal_error": terminal_error,
"detail": terminal_error or f"keys=[{','.join(sorted(payload.keys())[:8])}]",
"intent_state": intent_state,
"response_keys": response_keys(payload),
"interesting_fields": interesting_payload_fields(payload),
"poll_proxy_index": ((attempt - 1) % len(poll_proxies) + 1) if poll_proxies else 0,
"poll_proxy_count": len(poll_proxies),
"poll_proxy_label": redact_proxy(poll_proxy),
}
return {
"attempt": attempt,
"status_code": response.status_code,
"elapsed_ms": duration,
"redirect_url": "",
"terminal_error": "",
"detail": f"http {response.status_code}: {redact_text(response.text, max_len=120)}",
"intent_state": {},
"response_keys": "",
"interesting_fields": "",
"poll_proxy_index": ((attempt - 1) % len(poll_proxies) + 1) if poll_proxies else 0,
"poll_proxy_count": len(poll_proxies),
"poll_proxy_label": redact_proxy(poll_proxy),
}
finally:
TASK_LOG_CALLBACK.reset(callback_token)
REQUEST_ID.reset(request_token)
if sequential:
completed = 0
terminal_errors = 0
for attempt in range(1, max_attempts + 1):
if time.time() >= deadline:
break
item = poll_once(attempt)
completed += 1
status_code = int(item.get("status_code") or 0)
duration = int(item.get("elapsed_ms") or 0)
intent_state = item.get("intent_state") if isinstance(item.get("intent_state"), dict) else {}
candidate_url = str(item.get("redirect_url") or "")
terminal_error = str(item.get("terminal_error") or "")
if status_code == 200:
log_info(
"stripe.redirect_poll.http",
attempt=attempt,
completed=completed,
submitted=attempt,
pool_workers=1,
status_code=status_code,
elapsed_ms=duration,
has_redirect=bool(candidate_url),
poll_proxy_index=int(item.get("poll_proxy_index") or 0),
poll_proxy_count=int(item.get("poll_proxy_count") or 0),
poll_proxy_label=str(item.get("poll_proxy_label") or ""),
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
next_action_type=intent_state.get("next_action_type", ""),
response_keys=str(item.get("response_keys") or ""),
interesting_fields=str(item.get("interesting_fields") or ""),
)
else:
log_warning(
"stripe.redirect_poll.http_error",
attempt=attempt,
completed=completed,
submitted=attempt,
pool_workers=1,
status_code=status_code,
elapsed_ms=duration,
poll_proxy_index=int(item.get("poll_proxy_index") or 0),
poll_proxy_count=int(item.get("poll_proxy_count") or 0),
poll_proxy_label=str(item.get("poll_proxy_label") or ""),
detail=str(item.get("detail") or ""),
)
if candidate_url:
log_info(
"stripe.redirect_poll.done",
attempt=attempt,
completed=completed,
submitted=attempt,
pool_workers=1,
poll_proxy_index=int(item.get("poll_proxy_index") or 0),
poll_proxy_count=int(item.get("poll_proxy_count") or 0),
poll_proxy_label=str(item.get("poll_proxy_label") or ""),
redirect_url=candidate_url,
)
return candidate_url
if terminal_error:
terminal_errors += 1
last_err = terminal_error
log_warning(
"stripe.redirect_poll.intent_terminal",
attempt=attempt,
completed=completed,
submitted=attempt,
pool_workers=1,
poll_proxy_index=int(item.get("poll_proxy_index") or 0),
poll_proxy_count=int(item.get("poll_proxy_count") or 0),
poll_proxy_label=str(item.get("poll_proxy_label") or ""),
detail=terminal_error,
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
)
raise HTTPException(status_code=402, detail=terminal_error)
else:
last_err = str(item.get("detail") or last_err)
if attempt < max_attempts:
time.sleep(1)
if completed >= max_attempts:
detail = f"redirect url resolution stopped after {completed} sequential attempts: {last_err}"
log_warning(
"stripe.redirect_poll.max_attempts",
attempt=completed,
submitted=completed,
pool_workers=1,
terminal_errors=terminal_errors,
detail=detail,
)
if terminal_errors:
raise HTTPException(status_code=402, detail=last_err or detail)
raise HTTPException(status_code=504, detail=detail)
detail = f"redirect url resolution timeout after {completed} sequential attempts: {last_err}"
log_warning(
"stripe.redirect_poll.timeout",
attempt=completed,
submitted=completed,
pool_workers=1,
terminal_errors=terminal_errors,
detail=detail,
)
if terminal_errors:
raise HTTPException(status_code=402, detail=last_err or detail)
raise HTTPException(status_code=504, detail=detail)
executor = ThreadPoolExecutor(max_workers=pool_workers, thread_name_prefix="stripe-poll")
futures: dict[Any, int] = {}
next_attempt = 1
completed = 0
terminal_errors = 0
redirect_url = ""
def submit_until_full() -> None:
nonlocal next_attempt
while len(futures) < pool_workers and next_attempt <= max_attempts and time.time() < deadline:
future = executor.submit(poll_once, next_attempt)
futures[future] = next_attempt
next_attempt += 1
try:
submit_until_full()
while futures and not redirect_url and time.time() < deadline:
done, _ = wait(tuple(futures), return_when=FIRST_COMPLETED, timeout=max(0.2, min(1.0, deadline - time.time())))
if not done:
continue
for future in done:
futures.pop(future, None)
try:
item = future.result()
except Exception as exc:
item = {
"attempt": 0,
"status_code": 0,
"elapsed_ms": 0,
"redirect_url": "",
"terminal_error": "",
"detail": f"stripe redirect poll worker exception: {repr(exc)}",
"intent_state": {},
"response_keys": "",
"interesting_fields": "",
}
completed += 1
attempt = int(item.get("attempt") or 0)
status_code = int(item.get("status_code") or 0)
duration = int(item.get("elapsed_ms") or 0)
intent_state = item.get("intent_state") if isinstance(item.get("intent_state"), dict) else {}
candidate_url = str(item.get("redirect_url") or "")
terminal_error = str(item.get("terminal_error") or "")
if status_code == 200:
log_info(
"stripe.redirect_poll.http",
attempt=attempt,
completed=completed,
submitted=next_attempt - 1,
pool_workers=pool_workers,
status_code=status_code,
elapsed_ms=duration,
has_redirect=bool(candidate_url),
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
next_action_type=intent_state.get("next_action_type", ""),
response_keys=str(item.get("response_keys") or ""),
interesting_fields=str(item.get("interesting_fields") or ""),
)
else:
log_warning(
"stripe.redirect_poll.http_error",
attempt=attempt,
completed=completed,
submitted=next_attempt - 1,
pool_workers=pool_workers,
status_code=status_code,
elapsed_ms=duration,
detail=str(item.get("detail") or ""),
)
if candidate_url:
redirect_url = candidate_url
log_info(
"stripe.redirect_poll.done",
attempt=attempt,
completed=completed,
submitted=next_attempt - 1,
pool_workers=pool_workers,
redirect_url=redirect_url,
)
break
if terminal_error:
terminal_errors += 1
last_err = terminal_error
log_warning(
"stripe.redirect_poll.intent_terminal",
attempt=attempt,
completed=completed,
submitted=next_attempt - 1,
pool_workers=pool_workers,
detail=terminal_error,
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
)
else:
last_err = str(item.get("detail") or last_err)
if not redirect_url:
submit_until_full()
finally:
for future in futures:
future.cancel()
executor.shutdown(wait=not bool(redirect_url), cancel_futures=True)
if redirect_url:
return redirect_url
if completed >= max_attempts:
detail = f"redirect url resolution stopped after {completed} concurrent attempts: {last_err}"
log_warning(
"stripe.redirect_poll.max_attempts",
attempt=completed,
submitted=next_attempt - 1,
pool_workers=pool_workers,
terminal_errors=terminal_errors,
detail=detail,
)
if terminal_errors:
raise HTTPException(status_code=402, detail=last_err or detail)
raise HTTPException(status_code=504, detail=detail)
detail = f"redirect url resolution timeout after {completed} concurrent attempts: {last_err}"
log_warning(
"stripe.redirect_poll.timeout",
attempt=completed,
submitted=next_attempt - 1,
pool_workers=pool_workers,
terminal_errors=terminal_errors,
detail=detail,
)
if terminal_errors:
raise HTTPException(status_code=402, detail=last_err or detail)
raise HTTPException(status_code=504, detail=detail)
def approve_request(
session: Any,
cs_id: str,
processor_entity: str,
attempt: int,
) -> dict[str, Any]:
started = time.perf_counter()
try:
response = session.post(
"https://chatgpt.com/backend-api/payments/checkout/approve",
json={"checkout_session_id": cs_id, "processor_entity": processor_entity},
headers={
"Referer": f"https://chatgpt.com/checkout/{processor_entity}/{cs_id}",
"x-openai-target-path": "/backend-api/payments/checkout/approve",
"x-openai-target-route": "/backend-api/payments/checkout/approve",
},
timeout=DEFAULT_TIMEOUT,
)
except Exception as exc:
return {
"attempt": attempt,
"status_code": 0,
"elapsed_ms": elapsed_ms(started),
"result": "",
"response_keys": "",
"detail": f"chatgpt approve exception: {repr(exc)}",
}
try:
payload = response.json() or {}
except Exception:
payload = {}
result = approve_result_value(payload)
detail = ""
if response.status_code >= 400:
detail = http_error_detail("chatgpt approve failed", response)
elif not is_approved_result(result):
detail = f"chatgpt approve pending result: {result!r} keys={response_keys(payload)}"
return {
"attempt": attempt,
"status_code": response.status_code,
"elapsed_ms": elapsed_ms(started),
"result": result,
"response_keys": response_keys(payload),
"detail": detail,
}
def _legacy_chatgpt_approve_pool_disabled(
chatgpt: Any,
cs_id: str,
checkout: dict[str, Any],
approve_pool: list[str] | None = None,
) -> None:
country = checkout["billing_country"]
processor_entity = processor_entity_for_country(country, checkout.get("processor_entity", ""))
max_attempts = APPROVE_MAX_ATTEMPTS
approve_base_proxy = session_proxy_url(chatgpt)
sticky_requested = approve_pool is not None
approve_pool = ordered_proxy_pool("\n".join(approve_pool or []), approve_base_proxy)
if not approve_pool and approve_base_proxy:
approve_pool = [approve_base_proxy]
sticky_pool_mode = sticky_requested and bool(approve_pool)
if sticky_pool_mode:
pool_workers = min(
max_attempts,
APPROVE_STICKY_MAX_WORKERS,
max(1, len(approve_pool) * APPROVE_STICKY_PER_PROXY_CONCURRENCY),
)
initial_pool_workers = pool_workers
min_pool_workers = min(pool_workers, max(1, len(approve_pool)))
target_inflight = pool_workers
else:
initial_pool_workers = min(max(1, APPROVE_POOL_WORKERS), max_attempts)
pool_workers = min(max(initial_pool_workers, APPROVE_POOL_MAX_WORKERS), max_attempts)
min_pool_workers = min(max(1, APPROVE_POOL_MIN_WORKERS), pool_workers)
target_inflight = max(min_pool_workers, initial_pool_workers)
log_info(
"chatgpt.approve.start",
route="approve_proxy" if getattr(chatgpt, "proxies", {}) else "direct",
cs_id=cs_id,
processor_entity=processor_entity,
collision_mode="same_cs_id",
same_cs_id=True,
pool_workers=initial_pool_workers,
max_pool_workers=pool_workers,
min_pool_workers=min_pool_workers,
adaptive=APPROVE_POOL_ADAPTIVE and not sticky_pool_mode,
max_attempts=max_attempts,
sticky_pool=sticky_pool_mode,
sticky_pool_count=len(approve_pool),
sticky_per_proxy=APPROVE_STICKY_PER_PROXY_CONCURRENCY if sticky_pool_mode else 0,
)
if approve_base_proxy and not sticky_pool_mode:
initial_applied_proxy = proxy_for_attempt(approve_base_proxy, 1, "approve", force=True)
if initial_applied_proxy and initial_applied_proxy != approve_base_proxy:
set_proxy_url(chatgpt, initial_applied_proxy)
log_info(
"chatgpt.approve.dynamic_proxy.sessionized",
cs_id=cs_id,
same_cs_id=True,
session_key=PROXY_SESSION_KEY,
proxy_template=approve_base_proxy,
proxy_applied=initial_applied_proxy,
)
try:
started = time.perf_counter()
ping_response = chatgpt.post(
"https://chatgpt.com/backend-api/sentinel/ping",
json={},
headers={
"Referer": "https://chatgpt.com/",
"x-openai-target-path": "/backend-api/sentinel/ping",
"x-openai-target-route": "/backend-api/sentinel/ping",
},
timeout=DEFAULT_TIMEOUT,
)
log_info(
"chatgpt.sentinel_ping.done",
elapsed_ms=elapsed_ms(started),
status_code=getattr(ping_response, "status_code", ""),
)
except Exception as exc:
log_warning("chatgpt.sentinel_ping.error", error=repr(exc))
initial = approve_request(chatgpt, cs_id, processor_entity, 1)
initial["proxy_url"] = approve_base_proxy
initial["proxy_applied"] = session_proxy_url(chatgpt)
initial_outcome = approve_outcome(initial)
log_info(
"chatgpt.approve.http",
attempt=1,
max_attempts=max_attempts,
status_code=initial["status_code"],
elapsed_ms=initial["elapsed_ms"],
result=initial["result"],
outcome=initial_outcome,
response_keys=initial["response_keys"],
cs_id=cs_id,
same_cs_id=True,
url="https://chatgpt.com/backend-api/payments/checkout/approve",
)
if is_approved_result(initial["result"]):
if sticky_pool_mode and approve_base_proxy:
save_success_proxy("approve", approve_base_proxy)
log_info(
"chatgpt.approve.done",
attempt=1,
total_completed=1,
result=initial["result"],
cs_id=cs_id,
same_cs_id=True,
)
return
if max_attempts <= 1:
raise HTTPException(status_code=502, detail=initial["detail"] or "chatgpt approve failed")
stop_event = Event()
request_id = REQUEST_ID.get()
task_callback = TASK_LOG_CALLBACK.get()
task_cancel_check = TASK_CANCEL_CHECK.get()
active_sticky_proxies: list[str] = list(approve_pool)
sticky_proxy_stats: dict[str, Counter[str]] = {
proxy: Counter() for proxy in active_sticky_proxies
}
def pool_cancel_requested() -> bool:
return bool(task_cancel_check and task_cancel_check())
def pool_worker(attempt: int, selected_proxy: str = "") -> dict[str, Any]:
if stop_event.is_set() or pool_cancel_requested():
return {"attempt": attempt, "skipped": True}
request_token = REQUEST_ID.set(request_id)
callback_token = TASK_LOG_CALLBACK.set(task_callback)
session = None
try:
session = clone_session(chatgpt)
base_proxy = normalize_proxy_url(selected_proxy or approve_base_proxy)
applied_proxy = base_proxy
if base_proxy and not sticky_pool_mode:
applied_proxy = proxy_for_attempt(base_proxy, attempt, "approve")
if applied_proxy:
set_proxy_url(session, applied_proxy)
try:
session.headers.update({"Connection": "close"})
except Exception:
pass
item = approve_request(session, cs_id, processor_entity, attempt)
item["proxy_url"] = base_proxy
item["proxy_applied"] = session_proxy_url(session)
if (
not sticky_pool_mode
and APPROVE_IP_SAMPLE_ENABLED
and APPROVE_IP_SAMPLE_INTERVAL
and attempt % APPROVE_IP_SAMPLE_INTERVAL == 0
):
ip, ip_elapsed_or_error = sample_session_exit_ip(session)
log_info(
"chatgpt.approve.ip_sample",
attempt=attempt,
cs_id=cs_id,
same_cs_id=True,
exit_ip=ip,
elapsed_ms=ip_elapsed_or_error if ip else "",
error="" if ip else ip_elapsed_or_error,
proxy_label=redact_proxy(session_proxy_url(session)),
)
return item
finally:
if session is not None:
try:
session.close()
except Exception:
pass
TASK_LOG_CALLBACK.reset(callback_token)
REQUEST_ID.reset(request_token)
log_info(
"chatgpt.approve.pool.start",
cs_id=cs_id,
same_cs_id=True,
pool_workers=target_inflight,
max_pool_workers=pool_workers,
min_pool_workers=min_pool_workers,
adaptive=APPROVE_POOL_ADAPTIVE and not sticky_pool_mode,
adapt_interval=APPROVE_POOL_ADAPT_INTERVAL,
max_attempts=max_attempts,
initial_result=initial["result"],
initial_outcome=initial_outcome,
per_attempt_proxy=True,
sticky_pool=sticky_pool_mode,
sticky_pool_count=len(approve_pool),
sticky_per_proxy=APPROVE_STICKY_PER_PROXY_CONCURRENCY if sticky_pool_mode else 0,
approve_auto_session=proxy_supports_auto_sid(approve_base_proxy),
session_key=PROXY_SESSION_KEY if proxy_supports_auto_sid(approve_base_proxy) else "",
)
executor = ThreadPoolExecutor(max_workers=pool_workers, thread_name_prefix="approve")
futures: dict[Any, dict[str, Any]] = {}
next_attempt = 2
completed = 1
http_200 = 1 if initial["status_code"] == 200 else 0
min_elapsed = int(initial["elapsed_ms"] or 0)
max_elapsed = int(initial["elapsed_ms"] or 0)
last_detail = str(initial["detail"] or "")
last_result = str(initial["result"] or "")
next_progress = APPROVE_PROGRESS_INTERVAL
next_adapt = APPROVE_POOL_ADAPT_INTERVAL
recent: deque[dict[str, Any]] = deque(maxlen=max(20, APPROVE_POOL_ADAPT_INTERVAL))
recent.append(initial | {"outcome": initial_outcome})
outcomes: Counter[str] = Counter([initial_outcome])
approved: dict[str, Any] | None = None
terminal_failure: dict[str, Any] | None = None
def choose_submit_proxy() -> str:
if not sticky_pool_mode:
return approve_base_proxy
if not active_sticky_proxies:
return ""
inflight = Counter(
str(meta.get("proxy_url") or "")
for meta in futures.values()
if str(meta.get("proxy_url") or "")
)
available = [
proxy
for proxy in active_sticky_proxies
if inflight[proxy] < APPROVE_STICKY_PER_PROXY_CONCURRENCY
]
if not available:
return ""
return min(available, key=lambda proxy: inflight[proxy])
def submit_until_full() -> None:
nonlocal next_attempt
while (
len(futures) < target_inflight
and next_attempt <= max_attempts
and not stop_event.is_set()
and not pool_cancel_requested()
):
selected_proxy = choose_submit_proxy()
if sticky_pool_mode and not selected_proxy:
break
future = executor.submit(pool_worker, next_attempt, selected_proxy)
futures[future] = {"attempt": next_attempt, "proxy_url": selected_proxy}
next_attempt += 1
try:
submit_until_full()
while futures and not approved and not terminal_failure:
if pool_cancel_requested():
stop_event.set()
raise TaskCancelled("task cancelled")
done, _ = wait(tuple(futures), timeout=0.5, return_when=FIRST_COMPLETED)
if not done:
continue
for future in done:
meta = futures.pop(future, {}) or {}
try:
item = future.result()
except Exception as exc:
item = {
"attempt": int(meta.get("attempt") or 0),
"status_code": 0,
"elapsed_ms": 0,
"result": "",
"detail": f"approve worker exception: {repr(exc)}",
"proxy_url": str(meta.get("proxy_url") or ""),
}
if item.get("skipped"):
continue
if not item.get("proxy_url"):
item["proxy_url"] = str(meta.get("proxy_url") or "")
completed += 1
elapsed = int(item.get("elapsed_ms") or 0)
outcome = approve_outcome(item)
item["outcome"] = outcome
recent.append(dict(item))
outcomes[outcome] += 1
min_elapsed = min(min_elapsed, elapsed)
max_elapsed = max(max_elapsed, elapsed)
if int(item.get("status_code") or 0) == 200:
http_200 += 1
last_detail = str(item.get("detail") or last_detail)
last_result = str(item.get("result") or last_result)
item_proxy = normalize_proxy_url(str(item.get("proxy_url") or ""))
if sticky_pool_mode and item_proxy:
stats = sticky_proxy_stats.setdefault(item_proxy, Counter())
stats["total"] += 1
if is_approved_result(item.get("result")):
stats["success"] += 1
else:
stats["failure"] += 1
if (
APPROVE_STICKY_FAIL_DELETE
and stats["total"] >= APPROVE_STICKY_FAIL_WINDOW
and stats["success"] <= 0
and item_proxy in active_sticky_proxies
):
active_sticky_proxies.remove(item_proxy)
log_warning(
"chatgpt.approve.sticky_proxy.removed",
cs_id=cs_id,
same_cs_id=True,
proxy_label=redact_proxy(item_proxy),
attempts=stats["total"],
failures=stats["failure"],
active_count=len(active_sticky_proxies),
)
if is_approved_result(item.get("result")):
approved = item
if item_proxy:
save_success_proxy("approve", item_proxy)
log_info(
"chatgpt.approve.sticky_proxy.success",
cs_id=cs_id,
same_cs_id=True,
proxy_label=redact_proxy(item_proxy),
attempt=item.get("attempt"),
)
stop_event.set()
break
if sticky_pool_mode and not active_sticky_proxies and not approved and not terminal_failure:
terminal_failure = {
"attempt": completed,
"status_code": 0,
"result": "",
"outcome": "proxy_pool_exhausted",
"detail": "approve sticky proxy pool exhausted",
}
stop_event.set()
if (
not sticky_pool_mode
and not approved
and not terminal_failure
and APPROVE_BLOCKED_RESTART_AFTER > 0
and completed >= APPROVE_BLOCKED_RESTART_AFTER
):
blocked_count = int(outcomes.get("blocked", 0))
blocked_percent = int(round((blocked_count / max(1, completed)) * 100))
if blocked_count >= APPROVE_BLOCKED_RESTART_MIN_BLOCKED and blocked_percent >= APPROVE_BLOCKED_RESTART_RATIO:
terminal_failure = {
"attempt": completed,
"status_code": 200,
"result": "blocked",
"outcome": "blocked_restart",
"detail": (
f"approve blocked threshold reached: blocked={blocked_count}/{completed} "
f"({blocked_percent}%), restart checkout with fresh CS/IP"
),
}
stop_event.set()
log_warning(
"chatgpt.approve.blocked_restart",
cs_id=cs_id,
same_cs_id=True,
completed=completed,
blocked=blocked_count,
blocked_percent=blocked_percent,
restart_after=APPROVE_BLOCKED_RESTART_AFTER,
min_blocked=APPROVE_BLOCKED_RESTART_MIN_BLOCKED,
)
if APPROVE_POOL_ADAPTIVE and not sticky_pool_mode and completed >= next_adapt and not approved and not terminal_failure:
window_items = list(recent)
elapsed_window = [int(item.get("elapsed_ms") or 0) for item in window_items]
p95_elapsed = percentile_ms(elapsed_window, 95)
unstable_count = sum(
1
for item in window_items
if str(item.get("outcome") or "") in {"exception", "timeout", "rate_limited", "server_error"}
)
unstable_percent = int(round((unstable_count / max(1, len(window_items))) * 100))
old_target = target_inflight
if unstable_percent >= APPROVE_POOL_ERROR_RATE_HIGH_PERCENT or p95_elapsed >= APPROVE_POOL_LATENCY_HIGH_MS:
target_inflight = max(min_pool_workers, target_inflight - APPROVE_POOL_RAMP_STEP)
elif (
p95_elapsed <= APPROVE_POOL_LATENCY_LOW_MS
and unstable_percent == 0
and target_inflight < pool_workers
):
target_inflight = min(pool_workers, target_inflight + APPROVE_POOL_RAMP_STEP)
if target_inflight != old_target:
log_info(
"chatgpt.approve.pool.adjust",
cs_id=cs_id,
same_cs_id=True,
old_target_inflight=old_target,
target_inflight=target_inflight,
max_pool_workers=pool_workers,
min_pool_workers=min_pool_workers,
p95_elapsed_ms=p95_elapsed,
unstable_percent=unstable_percent,
window_size=len(window_items),
)
while next_adapt <= completed:
next_adapt += APPROVE_POOL_ADAPT_INTERVAL
if completed >= next_progress or approved or terminal_failure or (not futures and next_attempt > max_attempts):
window_elapsed = [int(item.get("elapsed_ms") or 0) for item in recent]
log_info(
"chatgpt.approve.pool.progress",
cs_id=cs_id,
same_cs_id=True,
completed=completed,
submitted=next_attempt - 1,
http_200=http_200,
pool_workers=target_inflight,
max_pool_workers=pool_workers,
max_attempts=max_attempts,
sticky_pool=sticky_pool_mode,
sticky_active_count=len(active_sticky_proxies) if sticky_pool_mode else 0,
min_elapsed_ms=min_elapsed,
max_elapsed_ms=max_elapsed,
p95_elapsed_ms=percentile_ms(window_elapsed, 95),
outcomes=compact_counts(outcomes),
last_result=last_result,
last_outcome=approve_outcome(approved or terminal_failure or item),
approved=bool(approved),
terminal_failure=bool(terminal_failure),
)
while next_progress <= completed:
next_progress += APPROVE_PROGRESS_INTERVAL
if not approved and not terminal_failure:
submit_until_full()
finally:
if approved or terminal_failure:
stop_event.set()
for future in futures:
future.cancel()
executor.shutdown(wait=not ((approved or terminal_failure) and APPROVE_POOL_EARLY_SHUTDOWN), cancel_futures=True)
if approved:
window_elapsed = [int(item.get("elapsed_ms") or 0) for item in recent]
log_info(
"chatgpt.approve.pool.done",
cs_id=cs_id,
same_cs_id=True,
approved_attempt=approved.get("attempt"),
completed=completed,
submitted=next_attempt - 1,
http_200=http_200,
pool_workers=target_inflight,
max_pool_workers=pool_workers,
sticky_pool=sticky_pool_mode,
sticky_active_count=len(active_sticky_proxies) if sticky_pool_mode else 0,
p95_elapsed_ms=percentile_ms(window_elapsed, 95),
outcomes=compact_counts(outcomes),
early_shutdown=APPROVE_POOL_EARLY_SHUTDOWN,
result=approved.get("result"),
)
log_info(
"chatgpt.approve.done",
attempt=approved.get("attempt"),
total_completed=completed,
result=approved.get("result"),
cs_id=cs_id,
same_cs_id=True,
)
return
if terminal_failure:
log_warning(
"chatgpt.approve.pool.terminal",
cs_id=cs_id,
same_cs_id=True,
attempt=terminal_failure.get("attempt"),
status_code=terminal_failure.get("status_code"),
result=terminal_failure.get("result"),
outcome=terminal_failure.get("outcome"),
detail=terminal_failure.get("detail"),
completed=completed,
submitted=next_attempt - 1,
outcomes=compact_counts(outcomes),
)
raise HTTPException(
status_code=502,
detail=str(terminal_failure.get("detail") or f"chatgpt approve terminal outcome: {terminal_failure.get('outcome')}"),
)
raise HTTPException(
status_code=502,
detail=last_detail or f"chatgpt approve exhausted {max_attempts} attempts",
)
def chatgpt_approve(
chatgpt: Any,
cs_id: str,
checkout: dict[str, Any],
approve_pool: list[str] | None = None,
) -> None:
"""Approve once per response state, without racing the same checkout ID."""
country = checkout["billing_country"]
processor_entity = processor_entity_for_country(country, checkout.get("processor_entity", ""))
max_attempts = max(1, min(APPROVE_MAX_ATTEMPTS, 5))
exact_proxy = session_proxy_url(chatgpt)
if approve_pool:
log_info(
"chatgpt.approve.pool.ignored",
reason="same checkout must keep one session/IP",
configured_count=len(approve_pool),
)
log_info(
"chatgpt.approve.start",
route="approve_proxy" if exact_proxy else "direct",
cs_id=cs_id,
processor_entity=processor_entity,
max_attempts=max_attempts,
pool_workers=1,
same_session=True,
approve_proxy=exact_proxy,
)
try:
started = time.perf_counter()
ping_response = chatgpt.post(
"https://chatgpt.com/backend-api/sentinel/ping",
json={},
headers={
"Referer": "https://chatgpt.com/",
"x-openai-target-path": "/backend-api/sentinel/ping",
"x-openai-target-route": "/backend-api/sentinel/ping",
},
timeout=DEFAULT_TIMEOUT,
)
log_info(
"chatgpt.sentinel_ping.done",
elapsed_ms=elapsed_ms(started),
status_code=getattr(ping_response, "status_code", ""),
)
except Exception as exc:
log_warning("chatgpt.sentinel_ping.error", error=repr(exc))
last_item: dict[str, Any] = {}
for attempt in range(1, max_attempts + 1):
cancel_check = TASK_CANCEL_CHECK.get()
if cancel_check and cancel_check():
raise TaskCancelled("task cancelled")
item = approve_request(chatgpt, cs_id, processor_entity, attempt)
last_item = item
outcome = approve_outcome(item)
log_info(
"chatgpt.approve.http",
attempt=attempt,
max_attempts=max_attempts,
status_code=item.get("status_code", 0),
elapsed_ms=item.get("elapsed_ms", 0),
result=item.get("result", ""),
outcome=outcome,
response_keys=item.get("response_keys", ""),
cs_id=cs_id,
same_session=True,
url="https://chatgpt.com/backend-api/payments/checkout/approve",
)
if is_approved_result(item.get("result")):
if exact_proxy:
save_success_proxy("approve", exact_proxy)
log_info(
"chatgpt.approve.done",
attempt=attempt,
total_completed=attempt,
result=item.get("result", ""),
cs_id=cs_id,
same_session=True,
)
return
# These responses describe the checkout itself. Repeating the same
# request hundreds of times cannot change them and only triggers abuse
# controls. A fresh outer checkout attempt is the only useful retry.
if outcome in {
"blocked",
"auth_error",
"missing",
"conflict",
"pending_expired",
"pending_canceled",
"pending_cancelled",
}:
detail = str(item.get("detail") or f"chatgpt approve terminal outcome: {outcome}")
status_code = 409 if outcome == "blocked" else 502
log_warning(
"chatgpt.approve.terminal",
attempt=attempt,
outcome=outcome,
detail=detail,
cs_id=cs_id,
)
raise HTTPException(status_code=status_code, detail=detail)
if attempt < max_attempts:
time.sleep((APPROVE_RETRY_DELAY_MS * attempt) / 1000)
detail = str(last_item.get("detail") or f"chatgpt approve exhausted {max_attempts} bounded attempts")
raise HTTPException(status_code=502, detail=detail)
def redirect_url_after_confirm(
chatgpt: Any,
stripe: Any,
confirm_payload: dict[str, Any],
cs_id: str,
pm_id: str,
stripe_pk: str,
init_payload: dict[str, Any],
ctx: dict[str, Any],
checkout: dict[str, Any],
req: LongLinkRequest,
stripe_hosted_url: str,
) -> str:
redirect_url = extract_redirect_to_url(confirm_payload)
if redirect_url:
log_info("provider.redirect.after_confirm", source="confirm_payload", redirect_url=redirect_url)
return redirect_url
terminal_error = stripe_terminal_intent_error(confirm_payload)
if terminal_error:
intent_state = stripe_intent_state(confirm_payload)
log_warning(
"provider.redirect.intent_terminal",
detail=terminal_error,
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
)
raise HTTPException(status_code=402, detail=terminal_error)
submission = confirm_payload.get("submission_attempt") if isinstance(confirm_payload, dict) else None
approval_reason = checkout_approval_reason(confirm_payload)
if approval_reason:
log_info(
"provider.redirect.requires_approval",
reason=approval_reason,
submission_state=submission.get("state") if isinstance(submission, dict) else "",
checkout_status=confirm_payload.get("status", "") if isinstance(confirm_payload, dict) else "",
checkout_state=confirm_payload.get("state", "") if isinstance(confirm_payload, dict) else "",
)
approve_proxy = approve_stage_proxy(req)
apply_approve_proxy(chatgpt, approve_proxy)
runtime_config = get_runtime_config()
approve_pool_mode = normalize_proxy_pool_mode(req.proxy_pool_mode or runtime_config.get("proxyPoolMode"))
approve_pool = approve_proxy_pool_for_request(req) if approve_pool_mode == "sticky" else None
if approve_pool_mode == "sticky":
log_info(
"chatgpt.approve.sticky_pool.enabled",
cs_id=cs_id,
pool_count=len(approve_pool or []),
per_proxy=APPROVE_STICKY_PER_PROXY_CONCURRENCY,
)
chatgpt_approve(chatgpt, cs_id, checkout, approve_pool=approve_pool)
log_info(
"provider.redirect.poll_after_approval",
stripe_route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
approve_route="approve_proxy" if approve_proxy else "direct",
)
return stripe_payment_page_redirect_url(stripe, cs_id, stripe_pk, req, ctx, timeout_seconds=45)
log_info(
"provider.redirect.poll_required",
submission_state=submission.get("state") if isinstance(submission, dict) else "",
response_keys=response_keys(confirm_payload),
)
return stripe_payment_page_redirect_url(stripe, cs_id, stripe_pk, req, ctx, timeout_seconds=30)
def resolve_external_redirect(
direct_session: Any,
redirect_url: str,
preferred_hosts: tuple[str, ...] = (),
proxied_session: Any | None = None,
proxied_hosts: tuple[str, ...] = (),
max_hops: int = 5,
) -> str:
current = str(redirect_url or "").strip()
preferred = tuple(host.lower().lstrip(".") for host in preferred_hosts if host)
proxied = tuple(host.lower().lstrip(".") for host in proxied_hosts if host)
provider_proxy_configured = bool(getattr(direct_session, "proxies", {})) or bool(
getattr(proxied_session, "proxies", {}) if proxied_session is not None else {}
)
log_info(
"provider.redirect_resolve.start",
redirect_url=current,
preferred_hosts=",".join(preferred),
proxied_hosts=",".join(proxied),
provider_proxy_configured=provider_proxy_configured,
max_hops=max_hops,
)
for hop in range(1, max(1, int(max_hops or 1)) + 1):
if not current:
log_warning("provider.redirect_resolve.empty", hop=hop)
return ""
host = (urlsplit(current).hostname or "").lower()
if preferred and host_matches_suffixes(host, preferred):
log_info("provider.redirect_resolve.preferred_host", hop=hop, host=host, final_url=current)
return current
try:
use_proxy = proxied_session is not None and host_matches_suffixes(host, proxied)
session = proxied_session if use_proxy else direct_session
route = "paypal_proxy" if use_proxy else ("provider_proxy" if getattr(session, "proxies", {}) else "direct")
started = time.perf_counter()
response = session.get(current, allow_redirects=False, timeout=DEFAULT_TIMEOUT)
log_info(
"provider.redirect_resolve.hop",
hop=hop,
host=host,
route=route,
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
url=current,
)
except Exception as exc:
log_warning("provider.redirect_resolve.exception", hop=hop, host=host, url=current, error=repr(exc))
return current
if response.status_code not in (301, 302, 303, 307, 308):
log_info(
"provider.redirect_resolve.final_non_redirect",
hop=hop,
host=host,
status_code=response.status_code,
final_url=current,
)
return current
location = str(response.headers.get("Location") or "").strip()
if not location:
log_warning("provider.redirect_resolve.missing_location", hop=hop, host=host, status_code=response.status_code)
return current
log_info(
"provider.redirect_resolve.location",
hop=hop,
status_code=response.status_code,
location=location,
)
current = urljoin(current, location)
log_info("provider.redirect_resolve.max_hops", final_url=current)
return current
def create_provider_link(
chatgpt: Any,
checkout: dict[str, Any],
init_payload: dict[str, Any],
stripe_hosted_url: str,
req: LongLinkRequest,
provider_proxy: str = "",
) -> dict[str, str]:
link_type = normalize_link_type(req.link_type)
require_payment_method_available(init_payload, link_type)
stripe_pk = str(checkout.get("stripe_publishable_key") or req.stripe_publishable_key).strip()
if not stripe_pk:
raise HTTPException(status_code=422, detail="provider stage missing resolved Stripe publishable key")
provider_proxy = normalize_proxy_url(provider_proxy)
log_info(
"provider.create.start",
link_type=link_type,
cs_id=checkout.get("cs_id", ""),
provider_proxy_configured=bool(provider_proxy),
provider_proxy=provider_proxy,
)
stripe = build_stripe_session(req, proxy_override=provider_proxy)
log_info("stripe.prepare.skip", reason="use_zip_provider_flow")
log_info("stripe.pre_confirm.skip", reason="use_zip_provider_flow")
ctx = stripe_context(checkout["cs_id"], init_payload, req)
log_info(
"provider.context.ready",
cs_id=checkout["cs_id"],
currency=ctx.get("currency", ""),
checkout_amount=ctx.get("checkout_amount", ""),
locale=ctx.get("locale", ""),
init_checksum_present=bool(ctx.get("init_checksum")),
)
billing = billing_for_link_type(link_type, effective_pm_country(req))
log_info("provider.direct_confirm.skip", reason="use_pm_create_confirm_flow")
pm_id = stripe_create_payment_method(
stripe,
checkout["cs_id"],
stripe_pk,
billing,
link_type,
ctx,
init_payload,
stripe_hosted_url,
)
confirm_payload = stripe_confirm(
stripe,
checkout["cs_id"],
pm_id,
stripe_pk,
link_type,
init_payload,
ctx,
checkout,
req,
stripe_hosted_url,
)
stripe_redirect_url = redirect_url_after_confirm(
chatgpt,
stripe,
confirm_payload,
checkout["cs_id"],
pm_id,
stripe_pk,
init_payload,
ctx,
checkout,
req,
stripe_hosted_url,
)
action_type = next_action_type(confirm_payload)
if link_type == "upi" and action_type == "upi_handle_redirect_or_display_qr_code":
# This is already Stripe's hosted QR/instructions page. Following it
# server-side can consume time, hide the QR action, or hit app-only URLs.
provider_url = stripe_redirect_url
else:
provider_url = resolve_external_redirect(
stripe,
stripe_redirect_url,
preferred_hosts=(
PAYPAL_HOST_SUFFIXES
if link_type == "paypal"
else IDEAL_HOST_SUFFIXES
if link_type == "ideal"
else UPI_HOST_SUFFIXES
),
)
log_info(
"provider.create.done",
payment_method_id=pm_id,
stripe_redirect_url=stripe_redirect_url,
provider_redirect_url=provider_url,
long_url=provider_url or stripe_redirect_url,
next_action_type=action_type,
)
return {
"payment_method_id": pm_id,
"stripe_redirect_url": stripe_redirect_url,
"provider_redirect_url": provider_url,
"long_url": provider_url or stripe_redirect_url,
}
app = FastAPI(title="OpenAI Pay Long Link")
app.mount("/public", StaticFiles(directory=PUBLIC_DIR), name="public")
TASK_LOCK = Lock()
TASKS: dict[str, dict[str, Any]] = {}
LATEST_RESULT: dict[str, Any] = {
"task_id": "",
"updated_at": 0.0,
"result": None,
"logs": [],
"probe_results": [],
"result_expires_at": 0,
}
TASK_RETENTION_SECONDS = 60 * 60
ACTIVE_TASK_STATUSES = {"queued", "running", "paused"}
TASK_LOG_LIMIT = 300
IDEAL_LINK_VALID_SECONDS = 30 * 60
AUTH_DB_PATH = Path(os.getenv("OPENAI_PAY_AUTH_DB", str(BASE_DIR / "auth.sqlite3")))
SESSION_COOKIE = "opay_session"
SESSION_TTL_SECONDS = env_int("OPENAI_PAY_SESSION_TTL_SECONDS", 60 * 60 * 24 * 7, minimum=3600, maximum=60 * 60 * 24 * 30)
SESSION_COOKIE_SECURE = env_bool("OPENAI_PAY_COOKIE_SECURE", False)
PASSWORD_ITERATIONS = 260_000
AUTH_LOCK = Lock()
def now_ts() -> int:
return int(time.time())
def auth_db() -> sqlite3.Connection:
conn = sqlite3.connect(AUTH_DB_PATH, timeout=30)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA busy_timeout = 30000")
return conn
def normalize_username(username: str) -> str:
return re.sub(r"\s+", "", str(username or "").strip().lower())
def success_proxy_for_stage(stage: str, base_proxy: Any) -> str:
base = normalize_proxy_url(str(base_proxy or ""))
if not base:
return ""
try:
with auth_db() as conn:
row = conn.execute(
"SELECT proxy_url FROM proxy_success WHERE stage = ?",
(str(stage or "").strip().lower(),),
).fetchone()
except Exception:
return ""
saved = str(row["proxy_url"] or "") if row else ""
return saved if proxies_compatible(saved, base) else ""
def success_proxy_for_pool(stage: str, candidates: Any) -> str:
proxies = proxy_pool(candidates)
if not proxies:
return ""
try:
with auth_db() as conn:
row = conn.execute(
"SELECT proxy_url FROM proxy_success WHERE stage = ?",
(str(stage or "").strip().lower(),),
).fetchone()
except Exception:
return ""
saved = str(row["proxy_url"] or "") if row else ""
if not saved:
return ""
return saved if any(proxies_compatible(saved, proxy) for proxy in proxies) else ""
def approve_proxy_pool_for_request(req: LongLinkRequest) -> list[str]:
try:
config = get_runtime_config()
except Exception:
config = default_runtime_config()
run_mode = normalize_run_mode(config.get("runMode", ""))
link_type = normalize_link_type(req.link_type)
if link_type in {"ideal", "upi"} or run_mode in {RUN_MODE_SPLIT, RUN_MODE_US_CHECKOUT_JP_PAYPAL}:
pool_value = runtime_proxy_pool(config, "jp") or req.approve_proxy
else:
pool_value = runtime_proxy_pool(config, "us") or req.approve_proxy
proxies = proxy_pool(pool_value)
explicit = first_proxy_from_pool(req.approve_proxy)
if explicit and explicit not in proxies:
proxies.insert(0, explicit)
saved = success_proxy_for_pool("approve", "\n".join(proxies))
if saved:
proxies = [saved] + [proxy for proxy in proxies if not proxies_compatible(saved, proxy)]
return proxies
def save_success_proxy(stage: str, proxy_url: Any, username: str = "") -> None:
proxy = normalize_proxy_url(str(proxy_url or ""))
stage = str(stage or "").strip().lower()
if not stage or not proxy:
return
with AUTH_LOCK, auth_db() as conn:
conn.execute(
"""
INSERT INTO proxy_success (stage, proxy_url, username, updated_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(stage) DO UPDATE SET
proxy_url = excluded.proxy_url,
username = excluded.username,
updated_at = excluded.updated_at
""",
(stage, proxy, normalize_username(username), now_ts()),
)
def update_success_proxy_ip(stage: str, info: dict[str, Any]) -> None:
stage = str(stage or "").strip().lower()
if not stage or not info.get("ok"):
return
with AUTH_LOCK, auth_db() as conn:
conn.execute(
"""
UPDATE proxy_success
SET ip = ?, country = ?, city = ?, updated_at = ?
WHERE stage = ?
""",
(
str(info.get("ip") or ""),
str(info.get("country") or ""),
str(info.get("city") or ""),
now_ts(),
stage,
),
)
def refresh_success_proxy_ip(stage: str, proxy_url: str) -> None:
try:
info = proxy_check_one(stage.upper(), proxy_url)
update_success_proxy_ip(stage, info)
log_info(
"proxy_success.ip_refreshed",
stage=stage,
proxy=proxy_url,
ip=info.get("ip", ""),
country=info.get("country", ""),
ok=bool(info.get("ok")),
)
except Exception as exc:
log_warning("proxy_success.ip_refresh_failed", stage=stage, proxy=proxy_url, error=repr(exc))
def record_proxy_success(username: str, req: LongLinkRequest) -> None:
stages = {
"checkout": checkout_stage_proxy(req),
"provider": provider_stage_proxy(req),
}
for stage, proxy in stages.items():
proxy = normalize_proxy_url(proxy)
if not proxy:
continue
save_success_proxy(stage, proxy, username)
Thread(target=refresh_success_proxy_ip, args=(stage, proxy), daemon=True).start()
log_info(
"proxy_success.record",
username=normalize_username(username),
checkout_proxy=stages.get("checkout", ""),
provider_proxy=stages.get("provider", ""),
)
def password_hash(password: str, salt: bytes | None = None) -> str:
salt = salt or secrets.token_bytes(16)
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, PASSWORD_ITERATIONS)
return f"pbkdf2_sha256${PASSWORD_ITERATIONS}${base64.b64encode(salt).decode()}${base64.b64encode(digest).decode()}"
def verify_password(password: str, stored: str) -> bool:
try:
scheme, iterations_raw, salt_raw, digest_raw = stored.split("$", 3)
if scheme != "pbkdf2_sha256":
return False
salt = base64.b64decode(salt_raw)
expected = base64.b64decode(digest_raw)
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, int(iterations_raw))
return secrets.compare_digest(digest, expected)
except Exception:
return False
def init_auth_db() -> None:
with AUTH_LOCK:
AUTH_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
with auth_db() as conn:
conn.executescript(
"""
PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
created_at INTEGER NOT NULL,
disabled_at INTEGER NOT NULL DEFAULT 0,
success_count INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS invites (
code TEXT PRIMARY KEY,
created_by TEXT NOT NULL,
created_at INTEGER NOT NULL,
used_by TEXT NOT NULL DEFAULT '',
used_at INTEGER NOT NULL DEFAULT 0,
revoked_at INTEGER NOT NULL DEFAULT 0,
max_uses INTEGER NOT NULL DEFAULT 10,
use_count INTEGER NOT NULL DEFAULT 0,
last_used_at INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
username TEXT NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS runtime_config (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_by TEXT NOT NULL DEFAULT '',
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS proxy_success (
stage TEXT PRIMARY KEY,
proxy_url TEXT NOT NULL DEFAULT '',
ip TEXT NOT NULL DEFAULT '',
country TEXT NOT NULL DEFAULT '',
city TEXT NOT NULL DEFAULT '',
username TEXT NOT NULL DEFAULT '',
updated_at INTEGER NOT NULL
);
"""
)
columns = {row["name"] for row in conn.execute("PRAGMA table_info(users)").fetchall()}
if "disabled_at" not in columns:
conn.execute("ALTER TABLE users ADD COLUMN disabled_at INTEGER NOT NULL DEFAULT 0")
if "success_count" not in columns:
conn.execute("ALTER TABLE users ADD COLUMN success_count INTEGER NOT NULL DEFAULT 0")
invite_columns = {row["name"] for row in conn.execute("PRAGMA table_info(invites)").fetchall()}
if "max_uses" not in invite_columns:
conn.execute("ALTER TABLE invites ADD COLUMN max_uses INTEGER NOT NULL DEFAULT 10")
if "use_count" not in invite_columns:
conn.execute("ALTER TABLE invites ADD COLUMN use_count INTEGER NOT NULL DEFAULT 0")
if "last_used_at" not in invite_columns:
conn.execute("ALTER TABLE invites ADD COLUMN last_used_at INTEGER NOT NULL DEFAULT 0")
admin_password = APP_PASSWORD or os.getenv("OPENAI_PAY_ADMIN_PASSWORD", "")
if admin_password:
existing = conn.execute("SELECT id FROM users WHERE username = ?", (normalize_username(APP_USERNAME),)).fetchone()
if not existing:
conn.execute(
"INSERT INTO users (username, password_hash, role, created_at) VALUES (?, ?, 'admin', ?)",
(normalize_username(APP_USERNAME), password_hash(admin_password), now_ts()),
)
def default_runtime_config() -> dict[str, str]:
return {
"runMode": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"proxyPoolMode": "dynamic",
"billingCountry": "US",
"pmCountry": "JP",
"paymentLocale": "en",
"jpProxy": "",
"usProxy": "",
"stickyJpProxy": "",
"stickyUsProxy": "",
"idealPromoProxy": "",
"stickyIdealPromoProxy": "",
}
def normalize_run_mode(value: str) -> str:
mode = str(value or "").strip()
aliases = {
"split": RUN_MODE_SPLIT,
"jp_us": RUN_MODE_SPLIT,
"jp-us": RUN_MODE_SPLIT,
"checkout-only-jp": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"checkout_jp_rest_provider": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"checkout-jp-rest-provider": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"uiai": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"uiai_style": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"uiai-style": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"us-au": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"us-jp": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"us_jp": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"us-checkout-jp": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"us_checkout_jp_paypal": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"us-checkout-jp-paypal": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
}
return aliases.get(mode, mode if mode in SUPPORTED_RUN_MODES else RUN_MODE_CHECKOUT_JP_REST_PROVIDER)
def normalize_proxy_pool_mode(value: Any) -> str:
mode = str(value or "").strip().lower()
return "sticky" if mode in {"sticky", "stick", "sticky_pool", "黏性", "粘性"} else "dynamic"
def normalize_runtime_config(payload: RuntimeConfigRequest | dict[str, Any] | None = None) -> dict[str, str]:
base = default_runtime_config()
if payload is None:
raw: dict[str, Any] = {}
elif isinstance(payload, RuntimeConfigRequest):
raw = payload.model_dump(by_alias=True)
else:
raw = dict(payload)
run_mode = normalize_run_mode(raw.get("runMode") or raw.get("run_mode") or base["runMode"])
proxy_pool_mode = normalize_proxy_pool_mode(raw.get("proxyPoolMode") or raw.get("proxy_pool_mode") or base["proxyPoolMode"])
billing_country = supported_country(str(raw.get("billingCountry") or raw.get("billing_country") or base["billingCountry"]).strip().upper(), "US")
pm_country = supported_country(
str(
raw.get("pmCountry")
or raw.get("pm_country")
or raw.get("billingCountry")
or raw.get("billing_country")
or base["pmCountry"]
or base["billingCountry"]
).strip().upper(),
"AU",
)
locale = str(raw.get("paymentLocale") or raw.get("payment_locale") or base["paymentLocale"]).strip() or base["paymentLocale"]
if locale not in LOCALE_MAP:
locale = "en"
us_proxy = normalize_proxy_pool_value(raw.get("usProxy") or raw.get("providerProxy") or raw.get("us_proxy") or "")
jp_proxy = normalize_proxy_pool_value(raw.get("jpProxy") or raw.get("checkoutProxy") or raw.get("jp_proxy") or "")
sticky_us_proxy = normalize_proxy_pool_value(raw.get("stickyUsProxy") or raw.get("stickyProviderProxy") or raw.get("sticky_us_proxy") or "")
sticky_jp_proxy = normalize_proxy_pool_value(raw.get("stickyJpProxy") or raw.get("stickyCheckoutProxy") or raw.get("sticky_jp_proxy") or "")
ideal_promo_proxy = normalize_proxy_pool_value(raw.get("idealPromoProxy") or raw.get("ideal_promo_proxy") or "")
sticky_ideal_promo_proxy = normalize_proxy_pool_value(raw.get("stickyIdealPromoProxy") or raw.get("sticky_ideal_promo_proxy") or "")
if not jp_proxy and not us_proxy:
jp_proxy = normalize_proxy_pool_value(raw.get("approveProxy") or "")
return {
"runMode": run_mode,
"proxyPoolMode": proxy_pool_mode,
"billingCountry": billing_country,
"pmCountry": pm_country,
"paymentLocale": locale,
"jpProxy": jp_proxy,
"usProxy": us_proxy,
"stickyJpProxy": sticky_jp_proxy,
"stickyUsProxy": sticky_us_proxy,
"idealPromoProxy": ideal_promo_proxy,
"stickyIdealPromoProxy": sticky_ideal_promo_proxy,
}
def runtime_proxy_pool(config: dict[str, str], lane: str) -> str:
mode = normalize_proxy_pool_mode(config.get("proxyPoolMode", "dynamic"))
lane = str(lane or "").strip().lower()
if lane in {"ideal-promo", "ideal_promo", "promo", "promotion"}:
return config.get("stickyIdealPromoProxy" if mode == "sticky" else "idealPromoProxy", "")
if mode == "sticky":
return config.get("stickyJpProxy" if lane == "jp" else "stickyUsProxy", "")
return config.get("jpProxy" if lane == "jp" else "usProxy", "")
def get_runtime_config() -> dict[str, str]:
config = default_runtime_config()
with auth_db() as conn:
rows = conn.execute("SELECT key, value FROM runtime_config").fetchall()
for row in rows:
key = str(row["key"])
if key in config:
config[key] = str(row["value"] or "")
return normalize_runtime_config(config)
def save_runtime_config(config: dict[str, str], username: str) -> dict[str, str]:
normalized = normalize_runtime_config(config)
with AUTH_LOCK, auth_db() as conn:
for key, value in normalized.items():
conn.execute(
"""
INSERT INTO runtime_config (key, value, updated_by, updated_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(key) DO UPDATE SET
value = excluded.value,
updated_by = excluded.updated_by,
updated_at = excluded.updated_at
""",
(key, value, username, now_ts()),
)
return normalized
def apply_runtime_defaults(req: LongLinkRequest) -> LongLinkRequest:
config = get_runtime_config()
data = req.model_dump(by_alias=True)
supplied = set(getattr(req, "model_fields_set", set()) or set())
data["payment_locale"] = config["paymentLocale"]
data["proxyPoolMode"] = config["proxyPoolMode"]
run_mode = normalize_run_mode(config["runMode"])
requested_checkout = first_proxy_from_pool(str(data.get("checkoutProxy") or data.get("proxy") or ""))
requested_approve = first_proxy_from_pool(str(data.get("approveProxy") or ""))
requested_provider = first_proxy_from_pool(str(data.get("providerProxy") or ""))
requested_promotion = first_proxy_from_pool(str(data.get("promotionProxy") or ""))
checkout_supplied = ("checkout_proxy" in supplied or "proxy" in supplied) and bool(requested_checkout)
approve_supplied = "approve_proxy" in supplied and bool(requested_approve)
provider_supplied = "provider_proxy" in supplied and bool(requested_provider)
promotion_supplied = "promotion_proxy" in supplied and bool(requested_promotion)
active_jp_pool = runtime_proxy_pool(config, "jp")
active_us_pool = runtime_proxy_pool(config, "us")
active_promotion_pool = runtime_proxy_pool(config, "ideal-promo")
jp_proxy = requested_checkout if checkout_supplied else first_proxy_from_pool(active_jp_pool)
provider_proxy = requested_provider if provider_supplied else select_proxy_from_pool(active_us_pool)
approve_proxy = requested_approve if approve_supplied else provider_proxy
promotion_proxy = requested_promotion if promotion_supplied else first_proxy_from_pool(active_promotion_pool)
data["promotionProxy"] = promotion_proxy
data["billing_country"] = supported_country(config["billingCountry"], "US")
data["pmCountry"] = supported_country(config["pmCountry"], "AU")
if run_mode == RUN_MODE_US_CHECKOUT_JP_PAYPAL:
data["checkout_ui_mode"] = "custom"
data["checkoutProxy"] = jp_proxy
data["approveProxy"] = jp_proxy
data["providerProxy"] = jp_proxy
return LongLinkRequest(**data)
if run_mode == RUN_MODE_UIAI_STYLE:
data["checkout_ui_mode"] = "custom"
data["checkoutProxy"] = jp_proxy
data["approveProxy"] = approve_proxy
data["providerProxy"] = provider_proxy
return LongLinkRequest(**data)
if run_mode == RUN_MODE_CHECKOUT_JP_REST_PROVIDER:
data["checkoutProxy"] = jp_proxy
data["approveProxy"] = approve_proxy
data["providerProxy"] = provider_proxy
return LongLinkRequest(**data)
if run_mode == RUN_MODE_SPLIT:
data["checkoutProxy"] = jp_proxy
data["approveProxy"] = jp_proxy
data["providerProxy"] = jp_proxy if jp_proxy and not provider_proxy else provider_proxy
return LongLinkRequest(**data)
if "checkout_proxy" not in supplied and "proxy" not in supplied:
data["checkoutProxy"] = jp_proxy
if "approve_proxy" not in supplied:
data["approveProxy"] = approve_proxy or jp_proxy
if "provider_proxy" not in supplied:
us_proxy = select_proxy_from_pool(active_us_pool)
data["providerProxy"] = jp_proxy if jp_proxy and not us_proxy else us_proxy
return LongLinkRequest(**data)
def user_from_session_token(token: str) -> dict[str, Any] | None:
if not token:
return None
with auth_db() as conn:
row = conn.execute(
"""
SELECT users.username, users.role
FROM sessions
JOIN users ON users.username = sessions.username
WHERE sessions.token = ? AND sessions.expires_at > ? AND COALESCE(users.disabled_at, 0) = 0
""",
(token, now_ts()),
).fetchone()
return dict(row) if row else None
def current_user(request: Request) -> dict[str, Any] | None:
return user_from_session_token(request.cookies.get(SESSION_COOKIE, ""))
def api_key_authenticated(request: Request) -> bool:
if not APP_API_KEY:
return False
supplied = (request.headers.get("X-API-Key") or "").strip()
auth_header = (request.headers.get("Authorization") or "").strip()
if not supplied and auth_header.lower().startswith("bearer "):
supplied = auth_header[7:].strip()
return bool(supplied) and secrets.compare_digest(supplied, APP_API_KEY)
def request_authenticated(request: Request) -> bool:
return bool(current_user(request) or api_key_authenticated(request))
def require_user(request: Request) -> dict[str, Any]:
user = current_user(request)
if not user and api_key_authenticated(request):
return {"username": "api", "role": "api"}
if not user:
raise HTTPException(status_code=401, detail="not authenticated")
return user
def require_admin(request: Request) -> dict[str, Any]:
user = require_user(request)
if user.get("role") != "admin":
raise HTTPException(status_code=403, detail="admin required")
return user
def normalize_cdk(code: Any) -> str:
return re.sub(r"\s+", "", str(code or "").strip()).upper()
def cdk_owner(code: str) -> str:
fingerprint = hashlib.sha256(normalize_cdk(code).encode("utf-8")).hexdigest()[:12]
return f"cdk_{fingerprint}"
def cdk_usage_from_row(row: sqlite3.Row) -> tuple[int, int, int]:
max_uses = max(1, int(row["max_uses"] or 10))
use_count = max(0, int(row["use_count"] or 0))
return max_uses, use_count, max(0, max_uses - use_count)
def cdk_status(code: Any) -> CdkCheckResponse:
cdk = normalize_cdk(code)
if not cdk:
raise HTTPException(status_code=403, detail="CDK required")
with auth_db() as conn:
row = conn.execute("SELECT * FROM invites WHERE code = ?", (cdk,)).fetchone()
if not row:
raise HTTPException(status_code=403, detail="invalid CDK")
max_uses, use_count, remaining = cdk_usage_from_row(row)
if int(row["revoked_at"] or 0):
raise HTTPException(status_code=403, detail="CDK revoked")
if remaining <= 0:
raise HTTPException(status_code=403, detail="CDK exhausted")
return CdkCheckResponse(ok=True, code=cdk, maxUses=max_uses, useCount=use_count, remainingUses=remaining)
def require_cdk_user(code: Any, consume: bool = False) -> dict[str, Any]:
cdk = normalize_cdk(code)
status = cdk_status(cdk)
max_uses = status.max_uses
use_count = status.use_count
if consume:
with AUTH_LOCK, auth_db() as conn:
row = conn.execute("SELECT * FROM invites WHERE code = ?", (cdk,)).fetchone()
if not row:
raise HTTPException(status_code=403, detail="invalid CDK")
max_uses, use_count, remaining = cdk_usage_from_row(row)
if int(row["revoked_at"] or 0):
raise HTTPException(status_code=403, detail="CDK revoked")
if remaining <= 0:
raise HTTPException(status_code=403, detail="CDK exhausted")
updated = conn.execute(
"""
UPDATE invites
SET use_count = use_count + 1,
last_used_at = ?
WHERE code = ?
AND revoked_at = 0
AND use_count < max_uses
""",
(now_ts(), cdk),
).rowcount
if not updated:
raise HTTPException(status_code=403, detail="CDK exhausted")
use_count += 1
log_info("cdk.verify", code=mask_identifier(cdk, keep_start=4, keep_end=4), consume=consume, remaining=max_uses - use_count)
return {"username": cdk_owner(cdk), "role": "cdk", "cdk": cdk}
def link_request_user(req: LongLinkRequest, request: Request, consume_cdk: bool = False) -> dict[str, Any]:
user = current_user(request)
if user:
return user
if api_key_authenticated(request):
return {"username": "api", "role": "api"}
return require_cdk_user(req.cdk, consume=consume_cdk)
def create_session(username: str) -> str:
token = secrets.token_urlsafe(32)
with AUTH_LOCK, auth_db() as conn:
conn.execute(
"INSERT INTO sessions (token, username, created_at, expires_at) VALUES (?, ?, ?, ?)",
(token, username, now_ts(), now_ts() + SESSION_TTL_SECONDS),
)
return token
def auth_response(user: dict[str, Any], token: str | None = None) -> JSONResponse:
response = JSONResponse({"ok": True, "authenticated": True, "username": user["username"], "role": user["role"]})
if token:
response.set_cookie(
SESSION_COOKIE,
token,
max_age=SESSION_TTL_SECONDS,
httponly=True,
samesite="lax",
secure=SESSION_COOKIE_SECURE,
)
return response
@app.on_event("startup")
def startup_auth() -> None:
init_auth_db()
@app.middleware("http")
async def require_session_for_private_api(request: Request, call_next: Any):
path = request.url.path
protected = path.startswith("/api/admin/")
if protected and not request_authenticated(request):
return JSONResponse({"detail": "not authenticated"}, status_code=401)
return await call_next(request)
def long_link_response_to_dict(response: LongLinkResponse) -> dict[str, Any]:
return response.model_dump()
def is_ideal_provider_url(value: Any) -> bool:
try:
parsed = urlsplit(str(value or "").strip())
except Exception:
return False
host = str(parsed.hostname or "").lower().rstrip(".")
return parsed.scheme == "https" and (host == "ideal.nl" or host.endswith(".ideal.nl"))
def extract_ideal_qr_url(provider_url: Any) -> str:
try:
outer = urlsplit(str(provider_url or "").strip())
except Exception:
return ""
outer_host = str(outer.hostname or "").lower().rstrip(".")
if outer.scheme != "https" or not (outer_host == "ideal.nl" or outer_host.endswith(".ideal.nl")):
return ""
marker = "/transactions/"
marker_at = outer.path.find(marker)
if marker_at < 0:
return ""
encoded = outer.path[marker_at + len(marker):]
if not encoded:
return ""
candidate = unquote(encoded)
try:
inner = urlsplit(candidate)
except Exception:
return ""
inner_host = str(inner.hostname or "").lower().rstrip(".")
if inner.scheme.lower() != "https" or inner_host != "tx.ideal.nl":
return ""
if not inner.query and outer.query:
candidate = f"{candidate}?{outer.query}"
return candidate
def cdk_ideal_response_succeeded(response: LongLinkResponse | None) -> bool:
return bool(
response
and not response.fallback
and response.provider_redirect_url
and is_ideal_provider_url(response.provider_redirect_url)
and (response.ideal_qr_url or extract_ideal_qr_url(response.provider_redirect_url))
)
def long_link_response_from_dict(data: dict[str, Any] | None) -> LongLinkResponse | None:
return LongLinkResponse(**data) if data else None
def access_token_fingerprint(req: LongLinkRequest) -> str:
token = normalize_access_token(req.access_token)
return hashlib.sha256(token.encode("utf-8")).hexdigest() if token else ""
def task_request_metadata(req: LongLinkRequest) -> dict[str, Any]:
"""Keep operational metadata only; never retain tokens, CDKs or proxy credentials."""
return {
"link_type": normalize_link_type(req.link_type),
"billing_country": effective_country(req),
"pm_country": effective_pm_country(req),
"checkout_ui_mode": str(req.checkout_ui_mode or ""),
"payment_locale": str(req.payment_locale or ""),
}
def cleanup_tasks_locked() -> None:
now = time.time()
stale = [
task_id
for task_id, task in TASKS.items()
if task.get("status") in {"done", "failed", "cancelled"}
and now - float(task.get("updated_at") or 0) > TASK_RETENTION_SECONDS
]
for task_id in stale:
TASKS.pop(task_id, None)
def active_task_for_token_locked(token_fingerprint: str) -> str:
if not token_fingerprint:
return ""
cleanup_tasks_locked()
for task_id, task in TASKS.items():
if str(task.get("token_fingerprint") or "") != token_fingerprint:
continue
if str(task.get("status") or "") in ACTIVE_TASK_STATUSES and not bool(task.get("cancel_requested")):
return task_id
return ""
def mark_task_cancelled_locked(task: dict[str, Any], message: str = "任务已停止,不会继续跑") -> None:
task["cancel_requested"] = True
task["paused"] = False
task["status"] = "cancelled"
task["progress"] = 0
task["stage"] = "已重置"
task["message"] = message
task["error"] = ""
task["updated_at"] = time.time()
def cancel_token_tasks_locked(token_fingerprint: str, message: str = "同一 token 已停止旧任务") -> list[str]:
cancelled: list[str] = []
if not token_fingerprint:
return cancelled
for task_id, task in TASKS.items():
if str(task.get("token_fingerprint") or "") != token_fingerprint:
continue
if str(task.get("status") or "") in ACTIVE_TASK_STATUSES:
mark_task_cancelled_locked(task, message)
cancelled.append(task_id)
return cancelled
def task_cancel_requested(task_id: str) -> bool:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
return True
return bool(task.get("cancel_requested")) or str(task.get("status") or "") == "cancelled"
def set_task_state(task_id: str, **updates: Any) -> None:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
return
if bool(task.get("cancel_requested")) or str(task.get("status") or "") == "cancelled":
allowed = {"elapsed_ms"}
updates = {key: value for key, value in updates.items() if key in allowed}
if not updates:
return
task.update(updates)
task["updated_at"] = time.time()
cleanup_tasks_locked()
def is_task_owner(task: dict[str, Any], user: dict[str, Any]) -> bool:
if not user:
return False
if user.get("role") == "admin":
return True
return str(task.get("owner") or "") == str(user.get("username") or "")
def task_user_from_request(request: Request) -> dict[str, Any] | None:
user = current_user(request)
if user:
return user
if api_key_authenticated(request):
return {"username": "api", "role": "api"}
return None
def require_task_access(task: dict[str, Any], request: Request) -> dict[str, Any] | None:
user = task_user_from_request(request)
if str(task.get("owner_role") or "") == "cdk":
if user and user.get("role") == "admin":
return user
supplied_cdk = normalize_cdk(request.headers.get("X-CDK") or "")
if supplied_cdk and cdk_owner(supplied_cdk) == str(task.get("owner") or ""):
return {"username": cdk_owner(supplied_cdk), "role": "cdk"}
raise HTTPException(status_code=403, detail="task CDK does not match")
if user and is_task_owner(task, user):
return user
if not user:
raise HTTPException(status_code=401, detail="not authenticated")
raise HTTPException(status_code=403, detail="not task owner")
def is_admin_request(request: Request) -> bool:
user = current_user(request)
return bool(user and user.get("role") == "admin")
def public_task_logs(logs: Any) -> list[dict[str, Any]]:
public_logs: list[dict[str, Any]] = []
for entry in list(logs or [])[-TASK_LOG_LIMIT:]:
if not isinstance(entry, dict):
continue
fields = entry.get("fields") if isinstance(entry.get("fields"), dict) else {}
safe_fields: dict[str, Any] = {}
for key, value in fields.items():
lowered = str(key).lower()
if "proxy" in lowered:
continue
if "token" in lowered or "authorization" in lowered or "secret" in lowered or "password" in lowered:
continue
safe_fields[key] = value
public_logs.append(
{
"time": entry.get("time", ""),
"level": entry.get("level", "info"),
"event": entry.get("event", ""),
"fields": safe_fields,
}
)
return public_logs
def wait_for_task_resume(task_id: str) -> str:
while True:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
return "missing"
status = str(task.get("status") or "")
if status in {"failed", "done", "cancelled"} or bool(task.get("cancel_requested")):
return status
if not bool(task.get("paused")):
return status
time.sleep(0.45)
def set_task_probe_results(task_id: str, results: list[dict[str, Any]]) -> None:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
return
task["probe_results"] = [dict(item) for item in results]
task["updated_at"] = time.time()
def append_task_log(task_id: str, entry: dict[str, Any]) -> None:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
return
logs = task.setdefault("logs", [])
entry = dict(entry)
entry["seq"] = int(task.get("log_seq") or 0) + 1
task["log_seq"] = entry["seq"]
logs.append(entry)
if len(logs) > TASK_LOG_LIMIT:
del logs[: len(logs) - TASK_LOG_LIMIT]
task["updated_at"] = time.time()
def task_log_callback(task_id: str):
def collect(entry: dict[str, Any]) -> None:
append_task_log(task_id, entry)
return collect
def set_latest_result(task_id: str, response: LongLinkResponse, success_attempt: int = 0) -> None:
with TASK_LOCK:
task = TASKS.get(task_id) or {}
response = response.model_copy(update={"success_attempt": success_attempt})
result_expires_at = result_expiry_timestamp(response)
LATEST_RESULT.update(
{
"task_id": task_id,
"updated_at": time.time(),
"result": long_link_response_to_dict(response),
"logs": list(task.get("logs") or []),
"probe_results": list(task.get("probe_results") or []),
"result_expires_at": result_expires_at,
}
)
def task_progress_callback(task_id: str):
def update(progress: int, stage: str, message: str) -> None:
if task_cancel_requested(task_id):
raise TaskCancelled("task cancelled")
resume_status = wait_for_task_resume(task_id)
if resume_status in {"cancelled", "missing"}:
raise TaskCancelled("task cancelled")
set_task_state(
task_id,
progress=max(0, min(99, int(progress))),
stage=stage,
message=message,
)
return update
def result_expiry_timestamp(response: LongLinkResponse | None) -> int:
if not response or normalize_link_type(response.link_type) != "ideal" or not str(response.long_url or "").strip():
return 0
return now_ts() + IDEAL_LINK_VALID_SECONDS
@app.get("/")
def index() -> FileResponse:
return FileResponse(PUBLIC_DIR / "index.html")
@app.get("/api/health")
def health() -> dict[str, bool]:
return {"ok": True}
@app.post("/api/cdk/check", response_model=CdkCheckResponse)
def check_cdk(payload: CdkCheckRequest) -> CdkCheckResponse:
return cdk_status(payload.cdk)
@app.get("/api/auth/me", response_model=UserResponse)
def auth_me(request: Request) -> UserResponse:
user = current_user(request)
if not user:
return UserResponse(ok=True, authenticated=False)
return UserResponse(ok=True, authenticated=True, username=user["username"], role=user["role"])
@app.post("/api/auth/login")
def auth_login(payload: AuthRequest) -> JSONResponse:
start = time.perf_counter()
username = normalize_username(payload.username)
log_info("auth.login.attempt", username=username, username_present=bool(username))
if not username or not payload.password:
raise HTTPException(status_code=400, detail="username and password required")
with auth_db() as conn:
row = conn.execute("SELECT username, password_hash, role, disabled_at FROM users WHERE username = ?", (username,)).fetchone()
if not row or not verify_password(payload.password, row["password_hash"]):
log_info("auth.login.failed", username=username, user_found=bool(row))
raise HTTPException(status_code=401, detail="invalid username or password")
if int(row["disabled_at"] or 0):
log_info("auth.login.disabled", username=username)
raise HTTPException(status_code=403, detail="user disabled")
token = create_session(row["username"])
log_info("auth.login.success", username=row["username"], role=row["role"], elapsed_ms=elapsed_ms(start))
return auth_response({"username": row["username"], "role": row["role"]}, token)
@app.post("/api/auth/logout")
def auth_logout(request: Request) -> JSONResponse:
token = request.cookies.get(SESSION_COOKIE, "")
if token:
with AUTH_LOCK, auth_db() as conn:
conn.execute("DELETE FROM sessions WHERE token = ?", (token,))
response = JSONResponse({"ok": True})
response.delete_cookie(SESSION_COOKIE)
return response
@app.post("/api/auth/register")
def auth_register(payload: RegisterRequest) -> JSONResponse:
raise HTTPException(status_code=410, detail="registration disabled; use CDK on the client")
def invite_from_row(row: sqlite3.Row) -> InviteResponse:
max_uses = max(1, int(row["max_uses"] or 10))
use_count = max(0, int(row["use_count"] or 0))
return InviteResponse(
code=row["code"],
created_by=row["created_by"],
created_at=int(row["created_at"] or 0),
used_by=row["used_by"] or "",
used_at=int(row["used_at"] or 0),
revoked_at=int(row["revoked_at"] or 0),
max_uses=max_uses,
use_count=use_count,
remaining_uses=max(0, max_uses - use_count),
last_used_at=int(row["last_used_at"] or 0),
)
def invite_create_cache_path(username: str, request_id: str) -> Path:
clean_user = re.sub(r"[^a-z0-9_.-]+", "_", normalize_username(username)) or "admin"
clean_request = re.sub(r"[^A-Za-z0-9_.-]+", "_", str(request_id or "").strip())[:80]
return BASE_DIR / ".invite-create-cache" / f"{clean_user}-{clean_request}.json"
def member_from_row(row: sqlite3.Row) -> MemberResponse:
return MemberResponse(
username=row["username"],
role=row["role"],
created_at=int(row["created_at"] or 0),
disabled_at=int(row["disabled_at"] or 0),
active_sessions=int(row["active_sessions"] or 0),
success_count=int(row["success_count"] or 0),
)
def record_user_success(username: str, response: LongLinkResponse) -> None:
user = normalize_username(username)
if not user or user == "api" or user.startswith("cdk_") or response.fallback:
return
with AUTH_LOCK, auth_db() as conn:
conn.execute(
"UPDATE users SET success_count = COALESCE(success_count, 0) + 1 WHERE username = ?",
(user,),
)
log_info("member.success_count.increment", username=user, cs_id=response.cs_id)
@app.post("/api/admin/invites", response_model=InviteCreateResponse)
def create_invite(request: Request, payload: InviteCreateRequest | None = None) -> InviteCreateResponse:
start = time.perf_counter()
admin = require_admin(request)
count = payload.count if payload else 1
max_uses = payload.max_uses if payload else 10
request_id = str(payload.request_id or "").strip() if payload else ""
cache_path = invite_create_cache_path(admin["username"], request_id) if request_id else None
if cache_path and cache_path.exists():
try:
cached = json.loads(cache_path.read_text(encoding="utf-8"))
codes = [str(code) for code in cached.get("codes", []) if code]
if codes:
with auth_db() as conn:
rows = [
conn.execute("SELECT * FROM invites WHERE code = ?", (code,)).fetchone()
for code in codes
]
invites = [invite_from_row(row) for row in rows if row]
if invites:
return InviteCreateResponse(ok=True, invite=invites[0], invites=invites)
except Exception:
try:
cache_path.unlink()
except OSError:
pass
created: list[InviteResponse] = []
with AUTH_LOCK, auth_db() as conn:
while len(created) < count:
code = f"CDK-{secrets.token_urlsafe(12).replace('-', '').replace('_', '').upper()[:16]}"
try:
conn.execute(
"INSERT INTO invites (code, created_by, created_at, max_uses, use_count, last_used_at) VALUES (?, ?, ?, ?, 0, 0)",
(code, admin["username"], now_ts(), max_uses),
)
except sqlite3.IntegrityError:
continue
row = conn.execute("SELECT * FROM invites WHERE code = ?", (code,)).fetchone()
created.append(invite_from_row(row))
if cache_path:
cache_path.parent.mkdir(parents=True, exist_ok=True)
cache_path.write_text(
json.dumps({"created_at": now_ts(), "codes": [invite.code for invite in created]}),
encoding="utf-8",
)
log_info(
"admin.invite.create",
username=admin["username"],
count=len(created),
max_uses=max_uses,
request_id_present=bool(request_id),
elapsed_ms=elapsed_ms(start),
)
return InviteCreateResponse(ok=True, invite=created[0], invites=created)
@app.get("/api/admin/invites", response_model=InviteListResponse)
def list_invites(request: Request) -> InviteListResponse:
require_admin(request)
with auth_db() as conn:
rows = conn.execute(
"""
SELECT * FROM invites
WHERE revoked_at = 0
AND COALESCE(use_count, 0) < COALESCE(max_uses, 10)
ORDER BY created_at DESC
LIMIT 100
"""
).fetchall()
return InviteListResponse(ok=True, invites=[invite_from_row(row) for row in rows])
@app.post("/api/admin/invites/{code}/revoke")
def revoke_invite(code: str, request: Request) -> dict[str, bool]:
require_admin(request)
invite_code = str(code or "").strip().upper()
with AUTH_LOCK, auth_db() as conn:
row = conn.execute("SELECT * FROM invites WHERE code = ?", (invite_code,)).fetchone()
if not row:
raise HTTPException(status_code=404, detail="invite not found")
if row["used_at"]:
raise HTTPException(status_code=400, detail="invite already used")
conn.execute("UPDATE invites SET revoked_at = ? WHERE code = ? AND revoked_at = 0", (now_ts(), invite_code))
return {"ok": True}
@app.post("/api/admin/invites/{code}/delete")
def delete_invite(code: str, request: Request) -> dict[str, bool]:
start = time.perf_counter()
require_admin(request)
invite_code = str(code or "").strip().upper()
with AUTH_LOCK, auth_db() as conn:
row = conn.execute("SELECT * FROM invites WHERE code = ?", (invite_code,)).fetchone()
if not row:
raise HTTPException(status_code=404, detail="invite not found")
if row["used_at"]:
raise HTTPException(status_code=400, detail="invite already used")
conn.execute("DELETE FROM invites WHERE code = ?", (invite_code,))
log_info("admin.invite.delete", code=invite_code, elapsed_ms=elapsed_ms(start))
return {"ok": True}
@app.get("/api/admin/members", response_model=MemberListResponse)
def list_members(request: Request) -> MemberListResponse:
require_admin(request)
with auth_db() as conn:
rows = conn.execute(
"""
SELECT
users.username,
users.role,
users.created_at,
COALESCE(users.disabled_at, 0) AS disabled_at,
COALESCE(users.success_count, 0) AS success_count,
COUNT(sessions.token) AS active_sessions
FROM users
LEFT JOIN sessions
ON sessions.username = users.username AND sessions.expires_at > ?
GROUP BY users.username, users.role, users.created_at, users.disabled_at, users.success_count
ORDER BY users.role = 'admin' DESC, users.created_at DESC
""",
(now_ts(),),
).fetchall()
return MemberListResponse(ok=True, members=[member_from_row(row) for row in rows])
@app.post("/api/admin/members", response_model=MemberResponse)
def create_member(payload: AuthRequest, request: Request) -> MemberResponse:
require_admin(request)
username = normalize_username(payload.username)
if not username or len(username) < 3:
raise HTTPException(status_code=400, detail="username must be at least 3 characters")
if not payload.password or len(payload.password) < 6:
raise HTTPException(status_code=400, detail="password must be at least 6 characters")
with AUTH_LOCK, auth_db() as conn:
exists = conn.execute("SELECT id FROM users WHERE username = ?", (username,)).fetchone()
if exists:
raise HTTPException(status_code=409, detail="username already exists")
conn.execute(
"INSERT INTO users (username, password_hash, role, created_at, disabled_at) VALUES (?, ?, 'user', ?, 0)",
(username, password_hash(payload.password), now_ts()),
)
row = conn.execute(
"""
SELECT username, role, created_at, disabled_at, 0 AS active_sessions, 0 AS success_count
FROM users
WHERE username = ?
""",
(username,),
).fetchone()
return member_from_row(row)
def proxy_check_payload(response: Any) -> dict[str, str]:
text = str(getattr(response, "text", "") or "").strip()
payload: Any = {}
if text:
try:
payload = json.loads(text)
except Exception:
payload = {}
if isinstance(payload, dict):
ip = str(payload.get("ip") or payload.get("query") or payload.get("origin") or "").split(",")[0].strip()
country = str(
payload.get("country_code")
or payload.get("countryCode")
or payload.get("country")
or ""
).strip()
city = str(payload.get("city") or "").strip()
else:
ip = ""
country = ""
city = ""
if not ip:
match = re.search(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", text)
if match:
ip = match.group(0)
return {"ip": ip, "country": country, "city": city}
def proxy_check_one(label: str, proxy: str) -> dict[str, Any]:
proxy = normalize_proxy_url(proxy)
session = new_session()
if proxy:
set_proxy_url(session, proxy)
checks = (
"http://ip-api.com/json/?fields=status,message,query,countryCode,city",
"https://ipinfo.io/json",
"https://api.ipify.org?format=json",
"https://ifconfig.me/ip",
)
last_error = ""
last_status = 0
total_started = time.perf_counter()
for url in checks:
started = time.perf_counter()
try:
response = session.get(url, timeout=12)
last_status = int(getattr(response, "status_code", 0) or 0)
parsed = proxy_check_payload(response)
if last_status == 200 and parsed["ip"]:
return {
"ok": True,
"label": label,
"status_code": last_status,
"ip": parsed["ip"],
"country": parsed["country"],
"city": parsed["city"],
"source": urlsplit(url).netloc,
"elapsed_ms": elapsed_ms(started),
}
last_error = f"status={last_status} body={redact_text(getattr(response, 'text', '') or '', max_len=120)}"
except Exception as exc:
last_error = redact_text(repr(exc), max_len=160)
return {
"ok": False,
"label": label,
"status_code": last_status,
"ip": "",
"country": "",
"city": "",
"source": "",
"elapsed_ms": elapsed_ms(total_started),
"error": last_error,
}
@app.post("/api/admin/proxy-check")
def admin_proxy_check(payload: ProxyCheckRequest | None, request: Request) -> dict[str, Any]:
require_admin(request)
payload = payload or ProxyCheckRequest()
checkout_proxy = select_proxy_from_pool(payload.checkout_proxy, 0)
provider_proxy = select_proxy_from_pool(payload.provider_proxy, 0)
return {
"ok": True,
"checkout": proxy_check_one("Checkout", checkout_proxy),
"provider": proxy_check_one("Provider", provider_proxy),
}
@app.get("/api/runtime-config")
def runtime_config(request: Request) -> dict[str, Any]:
config = get_runtime_config()
if not request_authenticated(request):
config = {
**config,
"jpProxy": "",
"usProxy": "",
"stickyJpProxy": "",
"stickyUsProxy": "",
"idealPromoProxy": "",
"stickyIdealPromoProxy": "",
}
return {"ok": True, "config": config}
@app.post("/api/admin/runtime-config")
def update_runtime_config(payload: RuntimeConfigRequest, request: Request) -> dict[str, Any]:
admin = require_admin(request)
config = save_runtime_config(payload.model_dump(by_alias=True), admin["username"])
log_info(
"admin.runtime_config.save",
username=admin["username"],
run_mode=config["runMode"],
proxy_pool_mode=config["proxyPoolMode"],
billing_country=config["billingCountry"],
pm_country=config["pmCountry"],
payment_locale=config["paymentLocale"],
jp_proxy=redact_proxy(config["jpProxy"]),
us_proxy=redact_proxy_pool(config["usProxy"]),
sticky_jp_proxy=redact_proxy_pool(config["stickyJpProxy"]),
sticky_us_proxy=redact_proxy_pool(config["stickyUsProxy"]),
ideal_promo_proxy=redact_proxy_pool(config["idealPromoProxy"]),
sticky_ideal_promo_proxy=redact_proxy_pool(config["stickyIdealPromoProxy"]),
)
return {"ok": True, "config": config}
def require_manageable_member(conn: sqlite3.Connection, username: str) -> sqlite3.Row:
row = conn.execute("SELECT username, role, disabled_at FROM users WHERE username = ?", (username,)).fetchone()
if not row:
raise HTTPException(status_code=404, detail="member not found")
if row["role"] == "admin":
raise HTTPException(status_code=400, detail="admin member cannot be changed here")
return row
@app.post("/api/admin/members/{username}/disable")
def disable_member(username: str, request: Request) -> dict[str, bool]:
require_admin(request)
member_username = normalize_username(username)
with AUTH_LOCK, auth_db() as conn:
require_manageable_member(conn, member_username)
conn.execute("UPDATE users SET disabled_at = ? WHERE username = ? AND role != 'admin'", (now_ts(), member_username))
conn.execute("DELETE FROM sessions WHERE username = ?", (member_username,))
return {"ok": True}
@app.post("/api/admin/members/{username}/enable")
def enable_member(username: str, request: Request) -> dict[str, bool]:
require_admin(request)
member_username = normalize_username(username)
with AUTH_LOCK, auth_db() as conn:
require_manageable_member(conn, member_username)
conn.execute("UPDATE users SET disabled_at = 0 WHERE username = ? AND role != 'admin'", (member_username,))
return {"ok": True}
@app.post("/api/admin/members/{username}/logout")
def logout_member(username: str, request: Request) -> dict[str, bool]:
require_admin(request)
member_username = normalize_username(username)
with AUTH_LOCK, auth_db() as conn:
require_manageable_member(conn, member_username)
conn.execute("DELETE FROM sessions WHERE username = ?", (member_username,))
return {"ok": True}
@app.post("/api/admin/members/{username}/delete")
def delete_member(username: str, request: Request) -> dict[str, bool]:
require_admin(request)
member_username = normalize_username(username)
with AUTH_LOCK, auth_db() as conn:
require_manageable_member(conn, member_username)
conn.execute("DELETE FROM sessions WHERE username = ?", (member_username,))
conn.execute("DELETE FROM users WHERE username = ? AND role != 'admin'", (member_username,))
return {"ok": True}
def build_long_link_response(
req: LongLinkRequest,
progress: Any | None = None,
request_id: str | None = None,
should_stop: Any | None = None,
) -> LongLinkResponse:
request_id = request_id or f"ll_{uuid.uuid4().hex[:10]}"
context_token = REQUEST_ID.set(request_id)
started = time.perf_counter()
def stop_if_requested() -> None:
if should_stop and should_stop():
raise TaskCancelled("task cancelled")
def advance(percent: int, stage: str, message: str) -> None:
stop_if_requested()
if progress:
try:
progress(percent, stage, message)
except TaskCancelled:
raise
except Exception as exc:
log_warning("api.progress_callback.error", error=repr(exc))
try:
link_type = normalize_link_type(req.link_type)
advance(8, "读取 Token", "已读取参数,准备创建 OpenAI Checkout")
log_info(
"api.long_link.start",
link_type=link_type,
submitted_link_type=req.link_type,
billing_country=effective_country(req),
pm_country=effective_pm_country(req),
payment_locale=req.payment_locale,
checkout_ui_mode=req.checkout_ui_mode,
checkout_proxy_configured=bool(checkout_stage_proxy(req)),
checkout_proxy=checkout_stage_proxy(req),
approve_proxy_configured=bool(approve_stage_proxy(req)),
approve_proxy=approve_stage_proxy(req),
provider_proxy_configured=bool(provider_stage_proxy(req)),
provider_proxy=provider_stage_proxy(req),
custom_stripe_pk=bool(req.stripe_publishable_key.strip()),
custom_device_id=bool(req.device_id.strip()),
custom_user_agent=bool(req.user_agent.strip()),
)
chatgpt = build_chatgpt_session(req)
advance(18, "OpenAI Checkout", "正在创建 Checkout")
checkout = create_checkout(req, chatgpt)
stop_if_requested()
post_checkout_proxy = provider_stage_proxy(req)
stripe_pk, stripe_key_source = resolve_stripe_publishable_key(req, checkout)
if not stripe_pk:
discovered_key = discover_stripe_key_from_hosted_page(checkout, req, post_checkout_proxy)
if discovered_key:
stripe_pk = discovered_key
stripe_key_source = "hosted_page"
if not stripe_pk:
processor_entity = processor_entity_for_country(
checkout["billing_country"],
checkout.get("processor_entity", ""),
)
env_name = stripe_key_env_name(processor_entity)
detail = (
f"no Stripe publishable key available for processor_entity={processor_entity}; "
f"set {env_name} or submit stripe_publishable_key"
)
log_warning(
"stripe.key_resolution.missing",
processor_entity=processor_entity,
expected_env=env_name,
checkout_key_present=bool(checkout.get("stripe_publishable_key")),
checkout_url_present=bool(checkout.get("checkout_url")),
detail=detail,
)
raise HTTPException(status_code=422, detail=detail)
checkout["stripe_publishable_key"] = stripe_pk
checkout["stripe_key_source"] = stripe_key_source
log_info(
"stripe.key_resolution.done",
processor_entity=checkout.get("processor_entity", ""),
stripe_key_source=stripe_key_source,
stripe_key_fingerprint=stripe_key_fingerprint(stripe_pk),
)
advance(40, "Stripe init", "正在初始化 Stripe 支付页")
init_payload = stripe_init(
checkout["cs_id"],
req,
proxy_override=post_checkout_proxy,
stripe_pk_override=stripe_pk,
stripe_key_source=stripe_key_source,
processor_entity=checkout.get("processor_entity", ""),
)
if link_type in {"ideal", "paypal"}:
# iDEAL must be present at NL bootstrap. PayPal can be absent on
# the initial country/currency combination; checkout/update may
# enable it on the same Checkout, so validate PayPal only after
# the VN promotion refresh.
if link_type == "ideal":
require_payment_method_available(init_payload, "ideal")
promotion_proxy = promotion_stage_proxy(req)
if not promotion_proxy:
promotion_proxy = proxy_for_required_country(checkout_stage_proxy(req) or post_checkout_proxy, "VN")
if (checkout_stage_proxy(req) or post_checkout_proxy) and not promotion_proxy:
raise HTTPException(status_code=422, detail=f"{link_type.upper()} 优惠阶段缺少可切换到 VN 的代理模板")
advance(43, "VN 优惠更新", f"保持同一 {link_type.upper()} Checkout,正在通过 VN 更新优惠")
update_checkout_promotion(chatgpt, checkout, promotion_proxy)
stop_if_requested()
advance(47, "主线路 Stripe init", "优惠已更新,正在切回主线路重新初始化 Stripe")
init_payload = stripe_init(
checkout["cs_id"],
req,
proxy_override=post_checkout_proxy,
stripe_pk_override=stripe_pk,
stripe_key_source=stripe_key_source,
processor_entity=checkout.get("processor_entity", ""),
)
require_payment_method_available(init_payload, link_type)
if link_type == "ideal":
advance(50, "NL 税务同步", "正在同步荷兰账单与 Stripe 税务地区")
update_ideal_tax_context(chatgpt, checkout, req, stripe_pk, post_checkout_proxy)
stop_if_requested()
init_payload = stripe_init(
checkout["cs_id"],
req,
proxy_override=post_checkout_proxy,
stripe_pk_override=stripe_pk,
stripe_key_source=stripe_key_source,
processor_entity=checkout.get("processor_entity", ""),
)
require_payment_method_available(init_payload, "ideal")
enforce_zero_checkout_amount(init_payload, req, checkout["cs_id"])
stop_if_requested()
checkout_amount = expected_amount(init_payload)
checkout_amount_currency = str(init_payload.get("currency") or checkout["currency"]).upper()
advance(45, "金额检测", f"付款金额 {checkout_amount} {checkout_amount_currency}")
stripe_hosted_url = str(init_payload.get("stripe_hosted_url") or "").strip()
if not stripe_hosted_url:
detail = f"stripe init response missing stripe_hosted_url, keys={response_keys(init_payload)}"
log_warning("stripe.init.missing_hosted_url", detail=detail)
raise HTTPException(status_code=502, detail=detail)
hosted_long_url = to_openai_pay_url(stripe_hosted_url)
log_info("api.hosted_url.ready", stripe_hosted_url=stripe_hosted_url, hosted_long_url=hosted_long_url)
advance(55, "重写长链", f"已获得 hosted 长链,正在提取 {link_type.upper()} 链")
provider = {
"payment_method_id": "",
"stripe_redirect_url": "",
"provider_redirect_url": "",
"long_url": hosted_long_url,
}
fallback = False
provider_error = ""
try:
advance(65, "Provider", f"正在创建 {link_type.upper()} 支付方式并确认")
provider = create_provider_link(
chatgpt,
checkout,
init_payload,
stripe_hosted_url,
req,
provider_proxy=post_checkout_proxy,
)
stop_if_requested()
advance(92, "Provider", f"已获得 {link_type.upper()} 跳转链接")
except HTTPException as exc:
fallback = True
provider_error = provider_error_diagnostic(exc.detail, link_type, checkout, req)
advance(92, "回退 hosted", "PP 提取失败,返回 hosted 长链")
log_warning(
"provider.create.fallback_http_exception",
status_code=exc.status_code,
detail=provider_error,
fallback_url=hosted_long_url,
)
except Exception as exc:
fallback = True
provider_error = provider_error_diagnostic(repr(exc), link_type, checkout, req)
advance(92, "回退 hosted", "PP 提取异常,返回 hosted 长链")
log_warning(
"provider.create.fallback_exception",
error=provider_error,
fallback_url=hosted_long_url,
)
response_payload = LongLinkResponse(
ok=True,
cs_id=checkout["cs_id"],
processor_entity=checkout["processor_entity"],
billing_country=checkout["billing_country"],
currency=checkout["currency"],
checkout_amount=checkout_amount,
payment_locale=locale_parts(req.payment_locale)[0],
link_type=link_type,
payment_method_type=link_type,
payment_method_id=provider["payment_method_id"],
stripe_redirect_url=provider["stripe_redirect_url"],
provider_redirect_url=provider["provider_redirect_url"],
fallback=fallback,
provider_error=provider_error,
stripe_hosted_url=stripe_hosted_url,
long_url=provider["long_url"] or hosted_long_url,
ideal_qr_url=(
extract_ideal_qr_url(provider["provider_redirect_url"])
if link_type == "ideal" and not fallback
else ""
),
)
log_info(
"api.long_link.done",
elapsed_ms=elapsed_ms(started),
fallback=fallback,
cs_id=response_payload.cs_id,
payment_method_id=response_payload.payment_method_id,
provider_redirect_url=response_payload.provider_redirect_url,
long_url=response_payload.long_url,
)
advance(100, "完成", "生成完成" if not fallback else "已回退 hosted 长链")
return response_payload
except HTTPException as exc:
advance(100, "失败", str(exc.detail))
log_warning(
"api.long_link.http_exception",
elapsed_ms=elapsed_ms(started),
status_code=exc.status_code,
detail=str(exc.detail),
)
raise
except TaskCancelled:
log_info("api.long_link.cancelled", elapsed_ms=elapsed_ms(started))
raise
except Exception as exc:
advance(100, "失败", repr(exc))
log_warning("api.long_link.exception", elapsed_ms=elapsed_ms(started), error=repr(exc))
raise
finally:
REQUEST_ID.reset(context_token)
def probe_base_proxy(req: LongLinkRequest) -> str:
return (
first_proxy_from_pool(provider_stage_proxy(req))
or first_proxy_from_pool(checkout_stage_proxy(req))
or first_proxy_from_pool(approve_stage_proxy(req))
)
def clone_request_for_country(base_req: LongLinkRequest, country: str, index: int = 0) -> LongLinkRequest:
target_country = supported_country(country, "")
if not target_country:
raise HTTPException(status_code=400, detail=f"unsupported probe country: {country}")
base_proxy = probe_base_proxy(base_req)
sid = f"gp{target_country.lower()}{max(0, int(index)):02d}{secrets.token_hex(3)}"
country_proxy = proxy_for_probe_country(base_proxy, target_country, sid)
if not country_proxy:
raise HTTPException(
status_code=422,
detail="proxy username must contain region-XX/res-XX/country-XX/cc-XX for global probe",
)
data = base_req.model_dump(by_alias=True)
data.update(
{
"link_type": "paypal",
"billing_country": target_country,
"pmCountry": target_country,
"checkout_ui_mode": "custom",
"checkoutProxy": country_proxy,
"approveProxy": country_proxy,
"providerProxy": country_proxy,
"autoProbe": False,
}
)
return LongLinkRequest(**data)
def parse_probe_countries(req: LongLinkRequest) -> list[str]:
raw = str(req.probe_countries or "").strip() or DEFAULT_PROBE_COUNTRIES_RAW
values: list[str] = []
for item in re.split(r"[\s,;|/]+", raw):
country = supported_country(item, "")
if country and country not in values:
values.append(country)
current = effective_country(req)
if current and current not in values:
values.append(current)
return (values or [current or "DE"])[:80]
def probe_one_country(base_req: LongLinkRequest, country: str, index: int, total: int) -> dict[str, Any]:
req = clone_request_for_country(base_req, country, index)
started = time.perf_counter()
result: dict[str, Any] = {
"country": effective_country(req),
"currency": currency_for_country(effective_country(req)),
"result": "FAIL",
"amount": "",
"zero_offer": False,
"paypal": False,
"ideal": False,
"upi": False,
"payment_methods": [],
"provider": "",
"proxy_country": proxy_country_hint(checkout_stage_proxy(req)),
"elapsed_ms": 0,
"error": "",
}
log_info("probe.country.start", index=index, total=total, country=result["country"], currency=result["currency"])
try:
chatgpt = build_chatgpt_session(req)
checkout = create_checkout(req, chatgpt)
provider_proxy = provider_stage_proxy(req)
stripe_pk, stripe_key_source = resolve_stripe_publishable_key(req, checkout)
if not stripe_pk:
discovered_key = discover_stripe_key_from_hosted_page(checkout, req, provider_proxy)
if discovered_key:
stripe_pk = discovered_key
stripe_key_source = "hosted_page"
if not stripe_pk:
raise HTTPException(status_code=422, detail="missing stripe publishable key")
init_payload = stripe_init(
checkout["cs_id"],
req,
proxy_override=provider_proxy,
stripe_pk_override=stripe_pk,
stripe_key_source=stripe_key_source,
processor_entity=checkout.get("processor_entity", ""),
)
amount = expected_amount(init_payload)
methods = sorted(available_payment_method_types(init_payload))
has_paypal = "paypal" in methods
provider = processor_entity_for_country(checkout["billing_country"], checkout.get("processor_entity", ""))
result.update(
{
"result": "OK",
"amount": amount,
"zero_offer": amount_is_zero(amount),
"paypal": has_paypal,
"ideal": "ideal" in methods,
"upi": "upi" in methods,
"payment_methods": methods,
"provider": provider,
"elapsed_ms": elapsed_ms(started),
"checkout_session_id": checkout["cs_id"],
}
)
log_info(
"probe.country.done",
index=index,
total=total,
country=result["country"],
currency=result["currency"],
amount=amount,
zero_offer=result["zero_offer"],
paypal=has_paypal,
ideal="ideal" in methods,
upi="upi" in methods,
payment_methods=",".join(methods),
provider=provider,
elapsed_ms=result["elapsed_ms"],
)
except Exception as exc:
detail = str(exc.detail) if isinstance(exc, HTTPException) else repr(exc)
result.update({"result": "FAIL", "error": redact_text(detail, max_len=180), "elapsed_ms": elapsed_ms(started)})
log_warning(
"probe.country.failed",
index=index,
total=total,
country=result["country"],
currency=result["currency"],
error=result["error"],
elapsed_ms=result["elapsed_ms"],
)
return result
def run_country_probe(task_id: str, req: LongLinkRequest) -> tuple[LongLinkRequest, list[dict[str, Any]]]:
countries = parse_probe_countries(req)
results: list[dict[str, Any]] = []
selected_country = ""
total = len(countries)
set_task_state(task_id, progress=4, stage="国家探针", message=f"正在探测 {total} 个账单地区")
for index, country in enumerate(countries, start=1):
set_task_state(
task_id,
progress=max(4, min(20, int((index - 1) / max(1, total) * 16) + 4)),
stage="国家探针",
message=f"正在探测 {country}/{currency_for_country(country)}",
)
result = probe_one_country(req, country, index, total)
results.append(result)
set_task_probe_results(task_id, results)
if result.get("result") == "OK" and amount_is_zero(result.get("amount")) and result.get("paypal"):
selected_country = str(result.get("country") or country)
break
if selected_country:
set_task_state(task_id, progress=22, stage="国家探针", message=f"探针命中 {selected_country},继续生成 PP 链")
log_info("probe.country.selected", country=selected_country, tested=len(results), total=total)
return clone_request_for_country(req, selected_country), results
fallback_country = effective_country(req)
set_task_state(task_id, progress=22, stage="国家探针", message=f"未命中 0 元 PayPal 地区,使用当前地区 {fallback_country}")
log_warning("probe.country.no_match", fallback_country=fallback_country, tested=len(results), total=total)
return clone_request_for_country(req, fallback_country), results
def run_global_promo_probe_task(task_id: str, req: LongLinkRequest, owner: str) -> None:
request_id = f"probe_{task_id[-10:]}"
started = time.perf_counter()
log_callback_token = TASK_LOG_CALLBACK.set(task_log_callback(task_id))
cancel_check_token = TASK_CANCEL_CHECK.set(lambda: task_cancel_requested(task_id))
countries = parse_probe_countries(req)
results: list[dict[str, Any]] = []
set_task_state(
task_id,
status="running",
progress=1,
stage="全球优惠探针",
message=f"准备依次探测 {len(countries)} 个国家",
)
request_context = REQUEST_ID.set(request_id)
try:
total = len(countries)
for index, country in enumerate(countries, start=1):
if task_cancel_requested(task_id):
raise TaskCancelled("task cancelled")
resume_status = wait_for_task_resume(task_id)
if resume_status in {"cancelled", "missing"}:
raise TaskCancelled("task cancelled")
set_task_state(
task_id,
status="running",
progress=max(1, min(98, int(((index - 1) / max(1, total)) * 98) + 1)),
stage=f"探测 {index}/{total}",
message=f"正在切换 {country} 代理并检查 0 元优惠",
attempt=index,
)
result = probe_one_country(req, country, index, total)
results.append(result)
set_task_probe_results(task_id, results)
if index < total:
time.sleep(0.25)
successful = [item for item in results if str(item.get("result") or "").upper() == "OK"]
zero_countries = [str(item.get("country") or "") for item in successful if bool(item.get("zero_offer"))]
failed_count = len(results) - len(successful)
if not successful:
set_task_state(
task_id,
status="failed",
progress=100,
stage="探针失败",
message=f"{len(results)} 个国家全部探测失败",
elapsed_ms=elapsed_ms(started),
error="所有国家探测失败,请检查 Token 或动态代理模板",
probe_results=results,
)
return
summary = (
f"探针完成,发现 {len(zero_countries)} 个 0 元优惠国家:{', '.join(zero_countries)}"
if zero_countries
else "探针完成,未发现 0 元优惠国家"
)
if failed_count:
summary += f";{failed_count} 个国家失败"
set_task_state(
task_id,
status="done",
progress=100,
stage="探针完成",
message=summary,
elapsed_ms=elapsed_ms(started),
error="",
probe_results=results,
)
log_info(
"probe.global.done",
owner=owner,
tested=len(results),
successful=len(successful),
zero_offer_countries=zero_countries,
failed=failed_count,
elapsed_ms=elapsed_ms(started),
)
except TaskCancelled:
set_task_state(
task_id,
status="cancelled",
progress=0,
stage="已停止",
message="全球优惠探针已停止",
elapsed_ms=elapsed_ms(started),
error="",
probe_results=results,
)
except Exception as exc:
detail = str(exc.detail) if isinstance(exc, HTTPException) else repr(exc)
set_task_state(
task_id,
status="failed",
progress=100,
stage="探针失败",
message=detail,
elapsed_ms=elapsed_ms(started),
error=detail,
probe_results=results,
)
finally:
REQUEST_ID.reset(request_context)
TASK_LOG_CALLBACK.reset(log_callback_token)
TASK_CANCEL_CHECK.reset(cancel_check_token)
def launch_global_promo_probe_worker(task_id: str, req: LongLinkRequest, owner: str) -> None:
Thread(target=run_global_promo_probe_task, args=(task_id, req, owner), daemon=True).start()
@app.post("/api/global-promo-probe-task", response_model=LongLinkTaskStartResponse)
def start_global_promo_probe_task(req: LongLinkRequest, request: Request) -> LongLinkTaskStartResponse:
admin = require_admin(request)
req = apply_runtime_defaults(req)
req = req.model_copy(update={"link_type": "paypal", "auto_probe": True, "checkout_ui_mode": "custom"})
countries = parse_probe_countries(req)
base_proxy = probe_base_proxy(req)
if not base_proxy:
raise HTTPException(status_code=422, detail="全球探针需要动态代理模板")
if not proxy_supports_country_rewrite(base_proxy):
raise HTTPException(
status_code=422,
detail="代理用户名需要包含 region-XX、res-XX、country-XX 或 cc-XX 才能自动切换国家",
)
if not countries:
raise HTTPException(status_code=400, detail="至少需要一个探针国家")
task_id = f"prb_{uuid.uuid4().hex[:12]}"
token_fingerprint = access_token_fingerprint(req)
with TASK_LOCK:
active_task_id = active_task_for_token_locked(token_fingerprint)
if active_task_id:
raise HTTPException(status_code=409, detail=f"当前 token 已有任务运行:{active_task_id},请先停止或等待结束")
TASKS[task_id] = {
"task_id": task_id,
"task_kind": "global_promo_probe",
"status": "queued",
"progress": 1,
"stage": "全球优惠探针",
"message": f"探针已创建,共 {len(countries)} 个国家",
"attempt": 0,
"created_at": time.time(),
"updated_at": time.time(),
"elapsed_ms": 0,
"result": None,
"result_expires_at": 0,
"error": "",
"logs": [],
"probe_results": [],
"log_seq": 0,
"paused": False,
"owner": admin["username"],
"owner_role": admin["role"],
"request_payload": task_request_metadata(req),
"token_fingerprint": token_fingerprint,
"cancel_requested": False,
}
cleanup_tasks_locked()
launch_global_promo_probe_worker(task_id, req, admin["username"])
return LongLinkTaskStartResponse(ok=True, task_id=task_id)
@app.post("/api/long-link", response_model=LongLinkResponse)
def generate_long_link(req: LongLinkRequest, request: Request) -> LongLinkResponse:
user = link_request_user(req, request, consume_cdk=False)
if user.get("role") == "cdk" and normalize_link_type(req.link_type) != "ideal":
raise HTTPException(status_code=403, detail="CDK only supports iDEAL extraction")
req = apply_runtime_defaults(req)
response = build_long_link_response(req)
if user.get("role") == "cdk" and not response.fallback and response.provider_redirect_url:
user = require_cdk_user(req.cdk, consume=True)
record_user_success(user["username"], response)
if not response.fallback and response.provider_redirect_url:
record_proxy_success(user["username"], req)
return response
def token_from_any(value: Any) -> str:
if not value:
return ""
if isinstance(value, str):
text = value.strip()
if text.startswith("{") or text.startswith("["):
try:
return token_from_any(json.loads(text)) or text
except Exception:
return text
return text
if isinstance(value, list):
for item in value:
token = token_from_any(item)
if token:
return token
if isinstance(value, dict):
for key in ("accessToken", "access_token", "token"):
token = token_from_any(value.get(key))
if token:
return token
for item in value.values():
token = token_from_any(item)
if token:
return token
return ""
def long_link_request_from_access_token(access_token: str) -> LongLinkRequest:
return apply_runtime_defaults(
LongLinkRequest(
accessToken=access_token,
link_type="paypal",
checkout_ui_mode="custom",
)
)
@app.post("/api/extract-pp", response_model=LongLinkResponse)
def api_extract_pp(payload: ApiExtractRequest, request: Request) -> LongLinkResponse:
access_token = token_from_any(payload.access_token) or token_from_any(payload.token) or token_from_any(payload.session_json)
if not access_token:
raise HTTPException(status_code=400, detail="accessToken required")
req = long_link_request_from_access_token(access_token)
req = req.model_copy(update={"cdk": payload.cdk})
user = link_request_user(req, request, consume_cdk=False)
if user.get("role") == "cdk":
raise HTTPException(status_code=403, detail="CDK only supports iDEAL extraction")
response = build_long_link_response(req)
record_user_success(user["username"], response)
if not response.fallback and response.provider_redirect_url:
record_proxy_success(user["username"], req)
return response
@app.post("/api/business-checkout", response_model=BusinessCheckoutResponse)
def create_business_checkout(payload: BusinessCheckoutRequest) -> BusinessCheckoutResponse:
"""Create or inspect an independent ChatGPT Business checkout.
This endpoint intentionally does not enter the PP/iDEAL provider flow. A
pasted Business checkout is returned as-is; Token mode creates a new
Business checkout while preserving the supplied campaign id.
"""
pasted = str(payload.checkout_url or "").strip()
if pasted:
parsed = urlsplit(pasted)
if parsed.scheme != "https" or parsed.netloc.lower() != "chatgpt.com":
raise HTTPException(status_code=400, detail="Business Checkout URL 必须是 https://chatgpt.com/checkout/... 链接")
match = re.search(r"/checkout/([^/]+)/((?:cs|oaics)_[A-Za-z0-9_-]+)", parsed.path)
if not match:
raise HTTPException(status_code=400, detail="Business Checkout URL 缺少有效的 cs_id")
return BusinessCheckoutResponse(
ok=True,
checkoutUrl=pasted,
externalUrl="",
processorEntity=match.group(1),
csId=match.group(2),
planName=payload.plan_name,
promoCode=payload.promo_code or payload.promo_campaign_id,
seatQuantity=payload.seat_quantity,
message="已识别 Business Checkout;粘贴链接本身已是支付长链。",
)
access_token = token_from_any(payload.access_token) or token_from_any(payload.token) or token_from_any(payload.session_json)
if not access_token:
raise HTTPException(status_code=400, detail="请粘贴 Business Checkout 链接,或提供对应 Token/session JSON")
plan_name = re.sub(r"[^a-zA-Z0-9_.-]", "", payload.plan_name.strip()) or "chatgptteamplan"
billing_country = supported_country(payload.billing_country, "US")
currency = currency_for_country(billing_country)
req = LongLinkRequest(
accessToken=access_token,
checkoutProxy=payload.proxy,
billing_country=billing_country,
pmCountry=billing_country,
checkout_ui_mode="custom",
)
session = build_chatgpt_session(req)
# Business/Team uses the legacy team plan enum. Do not send checkout_ui_mode
# (the endpoint rejects that mode field for this order type).
body: dict[str, Any] = {
"entry_point": "all_plans_pricing_modal",
"plan_name": plan_name,
"billing_details": {"country": billing_country, "currency": currency},
"team_plan_data": {
"price_interval": payload.price_interval if payload.price_interval in {"month", "year"} else "month",
"seat_quantity": payload.seat_quantity,
"workspace_name": "ChatGPT Business",
},
}
campaign = (payload.promo_campaign_id or payload.promo_code).strip()
promo_match = re.search(r"(?:[?&]promoCode=|^)([A-Za-z0-9_.:-]+)$", campaign)
if promo_match:
campaign = promo_match.group(1)
if campaign:
# Business promo links use the short promo code at order creation;
# promo_campaign_id alone is accepted but does not apply the discount.
body["promo_code"] = campaign
body["promo_campaign"] = {"promo_campaign_id": campaign, "is_coupon_from_query_param": False}
response = session.post(
"https://chatgpt.com/backend-api/payments/checkout",
json=body,
headers={
"Referer": "https://chatgpt.com/",
"x-openai-target-path": "/backend-api/payments/checkout",
"x-openai-target-route": "/backend-api/payments/checkout",
},
timeout=DEFAULT_TIMEOUT,
)
if response.status_code >= 400:
raise HTTPException(status_code=response.status_code, detail=http_error_detail("Business Checkout 创建失败", response))
data = response.json() or {}
cs_id = extract_checkout_session_id(data)
if not cs_id:
raise HTTPException(status_code=502, detail=f"Business Checkout 未返回 cs_id: keys={response_keys(data)}")
processor = extract_processor_entity(data) or "openai_llc"
checkout_url = extract_checkout_url(data) or f"https://chatgpt.com/checkout/{processor}/{cs_id}"
stripe_pk = extract_stripe_publishable_key(data)
external_url = ""
if stripe_pk:
req = req.model_copy(update={"stripe_publishable_key": stripe_pk})
init_payload = stripe_init(
cs_id,
req,
proxy_override=payload.proxy,
stripe_pk_override=stripe_pk,
stripe_key_source="business_checkout_response",
processor_entity=processor,
)
external_url = str(init_payload.get("stripe_hosted_url") or "").strip()
return BusinessCheckoutResponse(
ok=True,
checkoutUrl=checkout_url,
externalUrl=external_url,
processorEntity=processor,
csId=cs_id,
planName=plan_name,
promoCode=campaign,
seatQuantity=payload.seat_quantity,
message="Business Checkout 已创建,并已生成站外 Stripe 支付长链。" if external_url else "Business Checkout 已创建,但未返回站外 Stripe 长链。",
)
def run_long_link_task(task_id: str, req: LongLinkRequest, owner: str) -> None:
request_id = f"ll_{task_id[-10:]}"
started = time.perf_counter()
log_callback_token = TASK_LOG_CALLBACK.set(task_log_callback(task_id))
cancel_check_token = TASK_CANCEL_CHECK.set(lambda: task_cancel_requested(task_id))
set_task_state(task_id, status="running", progress=3, stage="排队", message="任务已开始")
try:
response = build_long_link_response(
req,
progress=task_progress_callback(task_id),
request_id=request_id,
should_stop=lambda: task_cancel_requested(task_id),
)
if task_cancel_requested(task_id):
return
record_user_success(owner, response)
if not response.fallback and response.provider_redirect_url:
record_proxy_success(owner, req)
set_latest_result(task_id, response)
result_expires_at = result_expiry_timestamp(response)
set_task_state(
task_id,
status="done",
progress=100,
stage="完成",
message="生成完成" if not response.fallback else "PP 提取失败,已回退 hosted 长链",
elapsed_ms=elapsed_ms(started),
result=long_link_response_to_dict(response),
result_expires_at=result_expires_at,
error="",
)
except HTTPException as exc:
set_task_state(
task_id,
status="failed",
progress=100,
stage="失败",
message=str(exc.detail),
elapsed_ms=elapsed_ms(started),
error=str(exc.detail),
)
except TaskCancelled:
set_task_state(task_id, status="cancelled", progress=0, stage="已重置", message="任务已停止", elapsed_ms=elapsed_ms(started), error="")
except Exception as exc:
set_task_state(
task_id,
status="failed",
progress=100,
stage="失败",
message=repr(exc),
elapsed_ms=elapsed_ms(started),
error=repr(exc),
)
finally:
TASK_LOG_CALLBACK.reset(log_callback_token)
TASK_CANCEL_CHECK.reset(cancel_check_token)
def request_for_retry_attempt(req: LongLinkRequest, attempt: int) -> LongLinkRequest:
config = get_runtime_config()
run_mode = normalize_run_mode(config["runMode"])
if run_mode not in {RUN_MODE_SPLIT, RUN_MODE_UIAI_STYLE, RUN_MODE_CHECKOUT_JP_REST_PROVIDER, RUN_MODE_US_CHECKOUT_JP_PAYPAL}:
return req
link_type = normalize_link_type(req.link_type)
ideal_mode = link_type == "ideal"
upi_mode = link_type == "upi"
dynamic_pool = normalize_proxy_pool_mode(req.proxy_pool_mode or config.get("proxyPoolMode")) == "dynamic"
attempt_index = max(0, attempt - 1)
fingerprint = access_token_fingerprint(req)
pool_index = attempt_index + (int(fingerprint[:8], 16) if fingerprint else 0)
active_jp_pool = runtime_proxy_pool(config, "jp")
active_us_pool = runtime_proxy_pool(config, "us")
checkout_candidates = active_jp_pool if active_jp_pool else req.checkout_proxy
if ideal_mode:
provider_candidates = active_us_pool if active_us_pool else req.provider_proxy
base_nl_proxy = (
select_proxy_from_pool(checkout_candidates, pool_index)
or select_proxy_from_pool(provider_candidates, pool_index)
or first_proxy_from_pool(req.checkout_proxy)
or first_proxy_from_pool(req.provider_proxy)
)
promo_candidates = runtime_proxy_pool(config, "ideal-promo") or req.promotion_proxy or base_nl_proxy
base_promo_proxy = select_proxy_from_pool(promo_candidates, pool_index) or base_nl_proxy
nl_seed = proxy_for_attempt(base_nl_proxy, attempt, "idealnl", force=dynamic_pool)
promo_seed = proxy_for_attempt(base_promo_proxy, attempt, "idealvn", force=dynamic_pool)
nl_proxy = proxy_for_required_country(nl_seed, "NL")
promotion_proxy = proxy_for_required_country(promo_seed, "VN")
if base_nl_proxy and not nl_proxy:
raise HTTPException(status_code=422, detail="iDEAL 主代理无法切换到 NL")
if base_promo_proxy and not promotion_proxy:
raise HTTPException(status_code=422, detail="iDEAL 优惠代理无法切换到 VN")
data = req.model_dump(by_alias=True)
data["checkoutProxy"] = nl_proxy
data["approveProxy"] = nl_proxy
data["providerProxy"] = nl_proxy
data["promotionProxy"] = promotion_proxy
data["billing_country"] = "NL"
data["pmCountry"] = "NL"
data["checkout_ui_mode"] = "custom"
log_info(
"api.long_link.retry_attempt.ideal_proxy_selected",
attempt=attempt,
pool_index=pool_index,
dynamic_pool=dynamic_pool,
checkout_proxy=nl_proxy,
promotion_proxy=promotion_proxy,
provider_proxy=nl_proxy,
approve_proxy=nl_proxy,
checkout_country=proxy_country_hint(nl_proxy),
promotion_country=proxy_country_hint(promotion_proxy),
)
return LongLinkRequest(**data)
if run_mode == RUN_MODE_US_CHECKOUT_JP_PAYPAL:
base_proxy = select_proxy_from_pool(checkout_candidates, pool_index) or first_proxy_from_pool(req.checkout_proxy)
shared_proxy = proxy_for_attempt(base_proxy, attempt, "shared", force=dynamic_pool)
data = req.model_dump(by_alias=True)
data["checkoutProxy"] = shared_proxy
data["approveProxy"] = shared_proxy
data["providerProxy"] = shared_proxy
log_info(
"api.long_link.retry_attempt.proxy_selected",
attempt=attempt,
pool_index=pool_index,
run_mode=run_mode,
checkout_proxy=data["checkoutProxy"],
provider_proxy=data["providerProxy"],
checkout_country=proxy_country_hint(data["checkoutProxy"]),
provider_country=proxy_country_hint(data["providerProxy"]),
checkout_auto_sid=proxy_supports_auto_sid(data["checkoutProxy"]),
provider_auto_sid=proxy_supports_auto_sid(data["providerProxy"]),
shared_proxy=True,
)
return LongLinkRequest(**data)
provider_candidates = active_us_pool if active_us_pool else req.provider_proxy
base_checkout_proxy = select_proxy_from_pool(checkout_candidates, pool_index) or first_proxy_from_pool(req.checkout_proxy)
base_provider_proxy = select_proxy_from_pool(provider_candidates, pool_index) or first_proxy_from_pool(req.provider_proxy)
# UPI is country-bound and PayPal should follow its billing profile. iDEAL
# itself is selected by the NL billing data; forcing the proxy to NL broke
# routes that had already succeeded through the configured provider lane.
provider_country = "IN" if upi_mode else (effective_pm_country(req) if not ideal_mode else "")
provider_source = base_provider_proxy or base_checkout_proxy
if provider_source and provider_country:
aligned_provider = proxy_for_required_country(provider_source, provider_country)
if not aligned_provider:
raise HTTPException(
status_code=422,
detail=f"provider proxy cannot switch to required {provider_country} country",
)
base_provider_proxy = aligned_provider
checkout_proxy = proxy_for_attempt(base_checkout_proxy, attempt, "checkout", force=dynamic_pool)
provider_proxy = proxy_for_attempt(base_provider_proxy, attempt, "provider", force=dynamic_pool)
if link_type == "paypal":
checkout_country = effective_country(req)
aligned_checkout = proxy_for_required_country(checkout_proxy, checkout_country)
if checkout_proxy and not aligned_checkout:
raise HTTPException(status_code=422, detail=f"PayPal Checkout 代理无法切换到账单国家 {checkout_country}")
checkout_proxy = aligned_checkout
if provider_proxy and provider_country:
verified_provider = proxy_for_required_country(provider_proxy, provider_country)
if not verified_provider:
raise HTTPException(
status_code=422,
detail=f"provider proxy country mismatch; required={provider_country}",
)
provider_proxy = verified_provider
data = req.model_dump(by_alias=True)
data["checkoutProxy"] = checkout_proxy
# Approval is part of the ChatGPT checkout. It must reuse the exact checkout
# proxy/SID instead of moving to the Stripe provider lane.
data["approveProxy"] = checkout_proxy
data["providerProxy"] = provider_proxy
if link_type == "paypal":
promo_base = first_proxy_from_pool(req.promotion_proxy) or base_checkout_proxy
promo_seed = proxy_for_attempt(promo_base, attempt, "paypalvn", force=dynamic_pool)
promotion_proxy = proxy_for_required_country(promo_seed, "VN")
if promo_base and not promotion_proxy:
raise HTTPException(status_code=422, detail="PayPal 优惠代理无法切换到 VN")
data["promotionProxy"] = promotion_proxy
log_info(
"api.long_link.retry_attempt.proxy_selected",
attempt=attempt,
pool_index=pool_index,
link_type=link_type,
provider_required_country=provider_country or "configured",
dynamic_pool=dynamic_pool,
checkout_proxy=data["checkoutProxy"],
approve_proxy=data["approveProxy"],
provider_proxy=data["providerProxy"],
checkout_country=proxy_country_hint(data["checkoutProxy"]),
approve_country=proxy_country_hint(data["approveProxy"]),
provider_country=proxy_country_hint(data["providerProxy"]),
checkout_auto_sid=proxy_supports_auto_sid(data["checkoutProxy"]),
approve_auto_sid=proxy_supports_auto_sid(data["approveProxy"]),
provider_auto_sid=proxy_supports_auto_sid(data["providerProxy"]),
)
return LongLinkRequest(**data)
def launch_long_link_task_worker(task_id: str, req: LongLinkRequest, owner: str, owner_role: str = "user") -> None:
Thread(target=run_long_link_task_retrying, args=(task_id, req, owner, owner_role), daemon=True).start()
def run_long_link_task_retrying(task_id: str, req: LongLinkRequest, owner: str, owner_role: str = "user") -> None:
request_id = f"ll_{task_id[-10:]}"
started = time.perf_counter()
max_attempts = 3 if owner_role == "cdk" else (ADMIN_LONG_LINK_MAX_ATTEMPTS if owner_role == "admin" else LONG_LINK_MAX_ATTEMPTS)
log_callback_token = TASK_LOG_CALLBACK.set(task_log_callback(task_id))
cancel_check_token = TASK_CANCEL_CHECK.set(lambda: task_cancel_requested(task_id))
set_task_state(
task_id,
status="running",
progress=3,
stage="排队",
message=f"任务已开始,最多连续尝试 {max_attempts} 次",
)
try:
last_response: LongLinkResponse | None = None
last_error = ""
last_attempt = 0
stopped_early = False
for attempt in range(1, max_attempts + 1):
if task_cancel_requested(task_id):
raise TaskCancelled("task cancelled")
resume_status = wait_for_task_resume(task_id)
if resume_status in {"done", "failed", "cancelled", "missing"}:
return
last_attempt = attempt
attempt_request_id = f"{request_id}_{attempt:02d}"
attempt_req = request_for_retry_attempt(req, attempt)
attempt_country = effective_country(attempt_req)
set_task_state(
task_id,
status="running",
progress=max(3, min(95, int(((attempt - 1) / max_attempts) * 100))),
stage=f"第 {attempt}/{max_attempts} 次",
message=f"正在第 {attempt} 次尝试,账单地区 {attempt_country}/{currency_for_country(attempt_country)}",
attempt=attempt,
)
log_info(
"api.long_link.retry_attempt.start",
attempt=attempt,
max_attempts=max_attempts,
owner=owner,
owner_role=owner_role,
billing_country=attempt_country,
pm_country=effective_pm_country(attempt_req),
currency=currency_for_country(attempt_country),
checkout_ui_mode=attempt_req.checkout_ui_mode,
provider_proxy=provider_stage_proxy(attempt_req),
)
try:
response = build_long_link_response(
attempt_req,
progress=task_progress_callback(task_id),
request_id=attempt_request_id,
should_stop=lambda: task_cancel_requested(task_id),
)
if task_cancel_requested(task_id):
return
last_response = response
provider_success = bool(not response.fallback and response.provider_redirect_url)
if owner_role == "cdk" and normalize_link_type(req.link_type) == "ideal":
provider_success = cdk_ideal_response_succeeded(response)
if provider_success:
if owner_role == "cdk":
require_cdk_user(req.cdk, consume=True)
record_user_success(owner, response)
record_proxy_success(owner, attempt_req)
response = response.model_copy(update={"success_attempt": attempt})
set_latest_result(task_id, response, success_attempt=attempt)
result_expires_at = result_expiry_timestamp(response)
set_task_state(
task_id,
status="done",
progress=100,
stage="完成",
message=f"第 {attempt} 次成功",
attempt=attempt,
elapsed_ms=elapsed_ms(started),
result=long_link_response_to_dict(response),
result_expires_at=result_expires_at,
error="",
)
log_info("api.long_link.retry_attempt.success", attempt=attempt, max_attempts=max_attempts)
return
last_error = response.provider_error or "PP 提取失败,已回退 hosted 长链"
log_warning(
"api.long_link.retry_attempt.fallback",
attempt=attempt,
max_attempts=max_attempts,
provider_error=last_error,
)
if not retryable_failure(last_error, fresh_checkout=True):
stopped_early = True
log_warning(
"api.long_link.retry_attempt.non_retryable",
attempt=attempt,
detail=last_error,
)
break
except HTTPException as exc:
if is_amount_guard_error(exc):
raise
last_error = str(exc.detail)
log_warning(
"api.long_link.retry_attempt.http_exception",
attempt=attempt,
max_attempts=max_attempts,
status_code=exc.status_code,
detail=last_error,
)
if not retryable_failure(last_error, exc.status_code, fresh_checkout=True):
raise
except Exception as exc:
last_error = repr(exc)
log_warning(
"api.long_link.retry_attempt.exception",
attempt=attempt,
max_attempts=max_attempts,
error=last_error,
)
if not retryable_failure(last_error, fresh_checkout=True):
raise HTTPException(status_code=500, detail=last_error)
if attempt < max_attempts:
resume_status = wait_for_task_resume(task_id)
if resume_status in {"done", "failed", "cancelled", "missing"}:
return
time.sleep(0.4)
if last_response is not None:
if owner_role == "cdk":
link_type = normalize_link_type(req.link_type)
if link_type == "ideal" and not cdk_ideal_response_succeeded(last_response):
detail = last_error or "iDEAL 提炼未成功,未获得 ideal.nl 支付链接"
else:
detail = last_error or "PayPal 提链未成功,未获得支付链接"
raise HTTPException(status_code=502, detail=detail)
if normalize_link_type(req.link_type) == "paypal":
raise HTTPException(
status_code=502,
detail=last_error or "PayPal 提链未成功,回退链接不作为成功结果",
)
if last_attempt:
last_response = last_response.model_copy(update={"success_attempt": last_attempt})
set_latest_result(task_id, last_response, success_attempt=last_attempt)
result_expires_at = result_expiry_timestamp(last_response)
set_task_state(
task_id,
status="done",
progress=100,
stage="完成",
message=(
f"第 {last_attempt} 次遇到不可重试的支付结果,已返回 hosted 回退链接"
if stopped_early
else f"连续 {last_attempt} 次未成功,已返回最后一次 hosted 回退结果"
),
attempt=last_attempt,
elapsed_ms=elapsed_ms(started),
result=long_link_response_to_dict(last_response),
result_expires_at=result_expires_at,
error=last_error,
)
return
raise HTTPException(status_code=502, detail=last_error or f"连续 {max_attempts} 次尝试均失败")
except HTTPException as exc:
set_task_state(
task_id,
status="failed",
progress=100,
stage="失败",
message=str(exc.detail),
elapsed_ms=elapsed_ms(started),
error=str(exc.detail),
)
except TaskCancelled:
set_task_state(task_id, status="cancelled", progress=0, stage="已重置", message="任务已停止", elapsed_ms=elapsed_ms(started), error="")
except Exception as exc:
set_task_state(
task_id,
status="failed",
progress=100,
stage="失败",
message=repr(exc),
elapsed_ms=elapsed_ms(started),
error=repr(exc),
)
finally:
TASK_LOG_CALLBACK.reset(log_callback_token)
TASK_CANCEL_CHECK.reset(cancel_check_token)
@app.post("/api/long-link-task", response_model=LongLinkTaskStartResponse)
def start_long_link_task(req: LongLinkRequest, request: Request) -> LongLinkTaskStartResponse:
user = link_request_user(req, request, consume_cdk=False)
req = apply_runtime_defaults(req)
task_id = f"llt_{uuid.uuid4().hex[:12]}"
token_fingerprint = access_token_fingerprint(req)
with TASK_LOCK:
active_task_id = active_task_for_token_locked(token_fingerprint)
if active_task_id:
raise HTTPException(status_code=409, detail=f"当前 token 已有任务运行:{active_task_id},请先停止或等待结束")
TASKS[task_id] = {
"task_id": task_id,
"status": "queued",
"progress": 1,
"stage": "排队",
"message": "任务已创建",
"attempt": 0,
"created_at": time.time(),
"updated_at": time.time(),
"elapsed_ms": 0,
"result": None,
"result_expires_at": 0,
"error": "",
"logs": [],
"probe_results": [],
"log_seq": 0,
"paused": False,
"owner": user["username"],
"owner_role": user["role"],
"request_payload": task_request_metadata(req),
"token_fingerprint": token_fingerprint,
"cancel_requested": False,
}
cleanup_tasks_locked()
launch_long_link_task_worker(task_id, req, user["username"], user["role"])
return LongLinkTaskStartResponse(ok=True, task_id=task_id)
@app.post("/api/ideal-long-link-task", response_model=LongLinkTaskStartResponse)
def start_ideal_long_link_task(req: LongLinkRequest, request: Request) -> LongLinkTaskStartResponse:
user = link_request_user(req, request, consume_cdk=False)
req = apply_runtime_defaults(req)
checkout_proxy = checkout_stage_proxy(req)
provider_proxy = normalize_proxy_url(provider_stage_proxy(req) or checkout_proxy)
req = req.model_copy(
update={
"link_type": "ideal",
"billing_country": "NL",
"pm_country": "NL",
"checkout_ui_mode": "custom",
"checkout_proxy": checkout_proxy,
"approve_proxy": checkout_proxy,
"provider_proxy": provider_proxy,
}
)
task_id = f"ilt_{uuid.uuid4().hex[:12]}"
token_fingerprint = access_token_fingerprint(req)
with TASK_LOCK:
active_task_id = active_task_for_token_locked(token_fingerprint)
if active_task_id:
raise HTTPException(status_code=409, detail=f"当前 token 已有任务运行:{active_task_id},请先停止或等待结束")
TASKS[task_id] = {
"task_id": task_id,
"status": "queued",
"progress": 1,
"stage": "queued",
"message": "iDEAL task created",
"created_at": time.time(),
"updated_at": time.time(),
"elapsed_ms": 0,
"result": None,
"result_expires_at": 0,
"error": "",
"logs": [],
"probe_results": [],
"log_seq": 0,
"paused": False,
"owner": user["username"],
"owner_role": user["role"],
"request_payload": task_request_metadata(req),
"token_fingerprint": token_fingerprint,
"cancel_requested": False,
}
cleanup_tasks_locked()
launch_long_link_task_worker(task_id, req, user["username"], user["role"])
return LongLinkTaskStartResponse(ok=True, task_id=task_id)
@app.post("/api/upi-long-link-task", response_model=LongLinkTaskStartResponse)
def start_upi_long_link_task(req: LongLinkRequest, request: Request) -> LongLinkTaskStartResponse:
user = link_request_user(req, request, consume_cdk=False)
if user.get("role") == "cdk":
raise HTTPException(status_code=403, detail="CDK only supports iDEAL extraction")
req = apply_runtime_defaults(req)
checkout_proxy = checkout_stage_proxy(req)
provider_proxy = proxy_with_region(provider_stage_proxy(req) or checkout_proxy, "IN")
req = req.model_copy(
update={
"link_type": "upi",
"billing_country": "IN",
"pm_country": "IN",
"checkout_ui_mode": "hosted",
"checkout_proxy": checkout_proxy,
"approve_proxy": checkout_proxy,
"provider_proxy": provider_proxy,
}
)
task_id = f"upi_{uuid.uuid4().hex[:12]}"
token_fingerprint = access_token_fingerprint(req)
with TASK_LOCK:
active_task_id = active_task_for_token_locked(token_fingerprint)
if active_task_id:
raise HTTPException(status_code=409, detail=f"当前 token 已有任务运行:{active_task_id},请先停止或等待结束")
TASKS[task_id] = {
"task_id": task_id,
"status": "queued",
"progress": 1,
"stage": "queued",
"message": "UPI task created",
"created_at": time.time(),
"updated_at": time.time(),
"elapsed_ms": 0,
"result": None,
"result_expires_at": 0,
"error": "",
"logs": [],
"probe_results": [],
"log_seq": 0,
"paused": False,
"owner": user["username"],
"owner_role": user["role"],
"request_payload": task_request_metadata(req),
"token_fingerprint": token_fingerprint,
"cancel_requested": False,
}
cleanup_tasks_locked()
launch_long_link_task_worker(task_id, req, user["username"], user["role"])
return LongLinkTaskStartResponse(ok=True, task_id=task_id)
@app.get("/api/long-link-task/{task_id}", response_model=LongLinkTaskStatusResponse)
def get_long_link_task(task_id: str, request: Request) -> LongLinkTaskStatusResponse:
with TASK_LOCK:
task = dict(TASKS.get(task_id) or {})
task["logs"] = list(task.get("logs") or [])
if not task:
raise HTTPException(status_code=404, detail="task not found")
require_task_access(task, request)
response_logs = task.get("logs") or []
response_probe_results = task.get("probe_results") or []
if not is_admin_request(request):
response_logs = []
response_probe_results = []
created_at = float(task.get("created_at") or time.time())
elapsed = int((time.time() - created_at) * 1000)
if task.get("elapsed_ms"):
elapsed = int(task["elapsed_ms"])
return LongLinkTaskStatusResponse(
ok=task.get("status") != "failed",
task_id=task_id,
status=str(task.get("status") or "unknown"),
progress=int(task.get("progress") or 0),
stage=str(task.get("stage") or ""),
message=str(task.get("message") or ""),
attempt=int(task.get("attempt") or 0),
paused=bool(task.get("paused") or False),
elapsed_ms=elapsed,
result=long_link_response_from_dict(task.get("result")),
error=str(task.get("error") or ""),
logs=response_logs,
probe_results=response_probe_results,
created_at=int(float(task.get("created_at") or 0)),
updated_at=int(float(task.get("updated_at") or 0)),
result_expires_at=int(task.get("result_expires_at") or 0),
)
@app.post("/api/long-link-task/{task_id}/pause")
def set_long_link_task_paused(task_id: str, payload: TaskPauseRequest, request: Request) -> dict[str, Any]:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
raise HTTPException(status_code=404, detail="task not found")
require_task_access(task, request)
status = str(task.get("status") or "")
if status in {"done", "failed", "cancelled"}:
return {"ok": True, "task_id": task_id, "paused": bool(task.get("paused") or False)}
task["paused"] = bool(payload.paused)
task["updated_at"] = time.time()
if task["paused"]:
task["status"] = "paused"
task["stage"] = "暂停"
task["message"] = "任务已暂停"
else:
task["status"] = "running"
if task.get("progress", 0) <= 0:
task["progress"] = 3
task["stage"] = str(task.get("stage") or "处理中")
task["message"] = "任务已恢复"
return {"ok": True, "task_id": task_id, "paused": bool(task.get("paused") or False)}
@app.post("/api/long-link-task/{task_id}/reset")
def reset_long_link_task(task_id: str, request: Request) -> dict[str, Any]:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
raise HTTPException(status_code=404, detail="task not found")
require_task_access(task, request)
token_fingerprint = str(task.get("token_fingerprint") or "")
cancelled = cancel_token_tasks_locked(token_fingerprint, "任务已停止,不会继续跑")
if task_id not in cancelled:
mark_task_cancelled_locked(task, "任务状态已重置")
preserve_probe_results = str(task.get("task_kind") or "") == "global_promo_probe"
if not preserve_probe_results:
task["elapsed_ms"] = 0
task["result"] = None
task["result_expires_at"] = 0
task["error"] = ""
if not preserve_probe_results:
task["logs"] = []
task["probe_results"] = []
task["log_seq"] = 0
task["paused"] = False
return {"ok": True, "task_id": task_id, "status": "cancelled", "cancelled": cancelled}
@app.post("/api/long-link-task/stop-token")
def stop_long_link_tasks_for_token(req: LongLinkRequest, request: Request) -> dict[str, Any]:
link_request_user(req, request, consume_cdk=False)
req = apply_runtime_defaults(req)
token_fingerprint = access_token_fingerprint(req)
with TASK_LOCK:
cancelled = cancel_token_tasks_locked(token_fingerprint, "当前 token 的任务已停止")
return {"ok": True, "status": "cancelled", "cancelled": cancelled}
@app.get("/api/long-link-latest", response_model=LongLinkTaskStatusResponse)
def get_latest_long_link(request: Request) -> LongLinkTaskStatusResponse:
require_admin(request)
with TASK_LOCK:
latest = dict(LATEST_RESULT)
latest["logs"] = list(latest.get("logs") or [])
result = long_link_response_from_dict(latest.get("result"))
if not result:
raise HTTPException(status_code=404, detail="latest result not found")
return LongLinkTaskStatusResponse(
ok=True,
task_id=str(latest.get("task_id") or "latest"),
status="done",
progress=100,
stage="最近结果",
message="已取回最近一次生成结果",
attempt=int((latest.get("result") or {}).get("success_attempt") or 0),
elapsed_ms=0,
result=result,
paused=bool(latest.get("paused") or False),
error="",
logs=latest.get("logs") or [],
probe_results=latest.get("probe_results") or [],
created_at=int(float(latest.get("updated_at") or 0)),
updated_at=int(float(latest.get("updated_at") or 0)),
result_expires_at=int(latest.get("result_expires_at") or 0),
)
from __future__ import annotations
import contextvars
import base64
import binascii
import hashlib
import json
import logging
import os
import random
import re
import secrets
import sqlite3
import time
import uuid
from collections import Counter, deque
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from pathlib import Path
from threading import Event, Lock, Thread, local
from typing import Any
from urllib.parse import parse_qsl, quote, unquote, urlencode, urljoin, urlsplit, urlunsplit
import requests
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, JSONResponse, Response
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, ConfigDict, Field
try:
from curl_cffi.requests import Session as CurlCffiSession # type: ignore
except ImportError: # pragma: no cover - optional dependency
CurlCffiSession = None # type: ignore
DEFAULT_STRIPE_PK = (
"pk_live_51HOrSwC6h1nxGoI3lTAgRjYVrz4dU3fVOabyCcKR3pbEJguCVAlqCxdxCUvoRh1XWwRac"
"ViovU3kLKvpkjh7IqkW00iXQsjo3n"
)
STRIPE_VERSION_FULL = (
os.getenv(
"OPENAI_PAY_STRIPE_VERSION",
"2025-03-31.basil; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1",
).strip()
or "2025-03-31.basil; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1"
)
UPI_STRIPE_VERSION_FULL = (
os.getenv(
"OPENAI_PAY_UPI_STRIPE_VERSION",
"2026-06-24.dahlia; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1",
).strip()
or "2026-06-24.dahlia; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1"
)
DEFAULT_TIMEOUT = 30
def env_int(name: str, default: int, minimum: int = 1, maximum: int = 10000) -> int:
try:
value = int(str(os.getenv(name, str(default))).strip())
except (TypeError, ValueError):
return default
return min(max(value, minimum), maximum)
def env_bool(name: str, default: bool) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return str(raw).strip().lower() not in {"0", "false", "no", "off", ""}
APPROVE_POOL_WORKERS = env_int("OPENAI_PAY_APPROVE_POOL_WORKERS", 50, minimum=1, maximum=100)
APPROVE_POOL_MAX_WORKERS = env_int(
"OPENAI_PAY_APPROVE_POOL_MAX_WORKERS",
max(APPROVE_POOL_WORKERS, 75),
minimum=1,
maximum=100,
)
APPROVE_POOL_MIN_WORKERS = env_int(
"OPENAI_PAY_APPROVE_POOL_MIN_WORKERS",
min(APPROVE_POOL_WORKERS, 25),
minimum=1,
maximum=100,
)
APPROVE_POOL_ADAPTIVE = env_bool("OPENAI_PAY_APPROVE_POOL_ADAPTIVE", True)
APPROVE_POOL_ADAPT_INTERVAL = env_int("OPENAI_PAY_APPROVE_POOL_ADAPT_INTERVAL", 100, minimum=10, maximum=1000)
APPROVE_POOL_RAMP_STEP = env_int("OPENAI_PAY_APPROVE_POOL_RAMP_STEP", 5, minimum=1, maximum=50)
APPROVE_POOL_LATENCY_LOW_MS = env_int("OPENAI_PAY_APPROVE_POOL_LATENCY_LOW_MS", 3500, minimum=100, maximum=30000)
APPROVE_POOL_LATENCY_HIGH_MS = env_int("OPENAI_PAY_APPROVE_POOL_LATENCY_HIGH_MS", 8000, minimum=500, maximum=60000)
APPROVE_POOL_ERROR_RATE_HIGH_PERCENT = env_int(
"OPENAI_PAY_APPROVE_POOL_ERROR_RATE_HIGH_PERCENT",
5,
minimum=1,
maximum=100,
)
APPROVE_POOL_EARLY_SHUTDOWN = env_bool("OPENAI_PAY_APPROVE_POOL_EARLY_SHUTDOWN", True)
APPROVE_MAX_ATTEMPTS = env_int("OPENAI_PAY_APPROVE_MAX_ATTEMPTS", 3, minimum=1, maximum=5)
APPROVE_RETRY_DELAY_MS = env_int("OPENAI_PAY_APPROVE_RETRY_DELAY_MS", 700, minimum=100, maximum=5000)
LONG_LINK_MAX_ATTEMPTS = env_int("OPENAI_PAY_LONG_LINK_MAX_ATTEMPTS", 10, minimum=1, maximum=50)
ADMIN_LONG_LINK_MAX_ATTEMPTS = env_int("OPENAI_PAY_ADMIN_LONG_LINK_MAX_ATTEMPTS", 10, minimum=1, maximum=100)
APPROVE_PROGRESS_INTERVAL = env_int("OPENAI_PAY_APPROVE_PROGRESS_INTERVAL", 50, minimum=1, maximum=1000)