axm0121 commited on
Commit
802dc45
·
verified ·
1 Parent(s): d89831c

Deploy Docker Space

Browse files
Files changed (9) hide show
  1. .dockerignore +8 -0
  2. .gitignore +4 -0
  3. .hfignore +10 -0
  4. Dockerfile +16 -0
  5. README.md +184 -5
  6. app.py +1302 -0
  7. docker-compose.yml +13 -0
  8. public/index.html +1315 -0
  9. requirements.txt +5 -0
.dockerignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ *.log
5
+ .git/
6
+ .gitignore
7
+ server.out.log
8
+ server.err.log
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__/
2
+ .venv/
3
+ *.pyc
4
+ *.log
.hfignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ .venv/
2
+ .venv-codex/
3
+ .vscode/
4
+ __pycache__/
5
+ *.pyc
6
+ *.log
7
+ *.bak-*
8
+ task_plan.md
9
+ findings.md
10
+ progress.md
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ ENV PYTHONDONTWRITEBYTECODE=1
4
+ ENV PYTHONUNBUFFERED=1
5
+
6
+ WORKDIR /app
7
+
8
+ COPY requirements.txt .
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+
11
+ COPY app.py .
12
+ COPY public ./public
13
+
14
+ EXPOSE 8787
15
+
16
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8787", "--no-access-log"]
README.md CHANGED
@@ -1,10 +1,189 @@
1
  ---
2
- title: Opllplus
3
- emoji: 🌍
4
- colorFrom: blue
5
- colorTo: yellow
6
  sdk: docker
 
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: OpenAI Pay Long Link
 
 
 
3
  sdk: docker
4
+ app_port: 8787
5
  pinned: false
6
  ---
7
 
8
+ # OpenAI Pay Long Link
9
+
10
+ Standalone tool for generating a hosted payment long link from a ChatGPT access token.
11
+
12
+ ## 📚 文档导航
13
+
14
+ - 🚀 **[快速启动](QUICK_START.md)** - 5 分钟快速上手
15
+ - 📖 **[API 参考](API_REFERENCE.md)** - 完整 API 文档
16
+ - 💡 **[PayPal 原理](PAYPAL_PRINCIPLE.md)** - 提链原理详解
17
+ - 📝 **[文档索引](DOCS_INDEX.md)** - 所有文档列表
18
+
19
+ ## PayPal 提链原理
20
+
21
+ 当前实测跑通的推荐模式是 **US/USD + 美国账单 + 全程 US 代理 + 关闭 promo + 自动轮换 sid**。
22
+
23
+ 1. **checkout 阶段使用 US 出口**
24
+ 通过 ChatGPT 后端创建 `US/USD` checkout,得到 `cs_live_*`、`processor_entity=openai_llc` 和动态 `publishable_key`。
25
+
26
+ 2. **provider / Stripe 阶段继续使用 US 出口**
27
+ `stripe init`、`payment_methods`、`confirm`、`payment_page` 轮询使用同一个 US 代理链路。
28
+
29
+ 3. **approve 阶段仍然使用 US 出口**
30
+ 当 Stripe confirm 返回 `requires_approval` 时,调用 ChatGPT `/backend-api/payments/checkout/approve`,实测可返回 `approved`。
31
+
32
+ 4. **billing_details 使用 US 地址**
33
+ PayPal payment method 的账单国家必须与 checkout 国家一致。当前有效组合是 `US/USD checkout + US billing + US provider/approve`。
34
+
35
+ 5. **关闭默认 promo**
36
+ 默认 promo 在实测账号上会返回 `Discount code is not eligible`。推荐请求里设置 `use_promo: false`,并把 `promo_code` 留空。
37
+
38
+ 6. **代理 sid 轮换**
39
+ 同一代理池可能出现 checkout 403 challenge。请求里设置 `rotate_proxy_sid: true` 后,服务端会把代理用户名里的 `sid-xxxx` 每次替换成新的随机 sid;实测第二次轮换后成功拿到 BA 链。
40
+
41
+ 关键注意:**不要固定使用内置默认 Stripe publishable key**。checkout 会返回自己的 `publishable_key`,后续 Stripe init 必须使用这个动态 key,否则容易出现:
42
+
43
+ ```text
44
+ stripe init failed: No such checkout.session
45
+ ```
46
+
47
+ 最终跑通组合:
48
+
49
+ ```text
50
+ US checkout proxy -> US/USD checkout -> dynamic publishable_key -> US provider/Stripe proxy -> US approve proxy -> US billing_details -> PayPal approve/BA link
51
+ ```
52
+
53
+ `pm-redirects.stripe.com/authorize/...` 是 Stripe 中间跳转授权链接;正常情况下会 302 跳转到最终的 PayPal 链:
54
+
55
+ ```text
56
+ https://www.paypal.com/agreements/approve?ba_token=...
57
+ ```
58
+
59
+ 本次失败路径记录:
60
+
61
+ - `AU/AUD + US approve` 容易在 checkout 阶段返回 403 HTML challenge。
62
+ - `AU/AUD + 默认 promo` 可能返回 `Discount code is not eligible`。
63
+ - 同一 US 代理 sid 连续请求也可能触发 403,建议开启自动轮换 sid。
64
+
65
+
66
+ ## Run
67
+
68
+ ```powershell
69
+ cd openai_pay_long_link
70
+ py -m venv .venv
71
+ .\.venv\Scripts\Activate.ps1
72
+ pip install -r requirements.txt
73
+ uvicorn app:app --host 127.0.0.1 --port 8787
74
+ ```
75
+
76
+ Open:
77
+
78
+ ```text
79
+ http://127.0.0.1:8787
80
+ ```
81
+
82
+ ## Docker
83
+
84
+ ```bash
85
+ cd openai_pay_long_link
86
+ docker compose up -d --build
87
+ ```
88
+
89
+ Open:
90
+
91
+ ```text
92
+ http://127.0.0.1:8787
93
+ ```
94
+
95
+ Stop:
96
+
97
+ ```bash
98
+ docker compose down
99
+ ```
100
+
101
+ The server uses a built-in default outbound proxy when the page does not submit
102
+ one. Override it at deploy time with `OPENAI_PAY_DEFAULT_PROXY`; set it to an
103
+ empty value to use direct outbound network.
104
+
105
+ For PP provider extraction, the current verified flow uses one US proxy for the whole PayPal path:
106
+
107
+ - checkout stage: `region-US`
108
+ - Stripe/provider stage: same `region-US`
109
+ - approve stage: same `region-US`
110
+ - billing country/currency: `US/USD`
111
+ - PayPal billing details: US address
112
+ - promo: disabled
113
+ - proxy sid: rotate when the proxy username contains `sid-xxxx`
114
+
115
+ If the submitted proxy contains a `region-XX` segment, keep it as `region-US` for this verified mode. The `checkout_proxy_region` field can override the checkout proxy region without changing the billing country.
116
+
117
+ `OPENAI_PAY_PROVIDER_PROXY` is kept for compatibility with other provider flows. The verified PayPal mode should leave provider routing on the same US proxy. GoPay switches the post-checkout provider stage to the Indonesia proxy; override with `OPENAI_PAY_GOPAY_PROVIDER_PROXY`.
118
+
119
+ ## API
120
+
121
+ ```http
122
+ POST /api/long-link
123
+ Content-Type: application/json
124
+
125
+ {
126
+ "accessToken": "eyJ...",
127
+ "proxy": "socks5h://user-region-US-sid-xxxx:pass@example.com:1000",
128
+ "link_type": "paypal",
129
+ "billing_country": "US",
130
+ "country": "US",
131
+ "currency": "USD",
132
+ "checkout_proxy_region": "US",
133
+ "approve_proxy_region": "US",
134
+ "payment_locale": "en",
135
+ "use_promo": false,
136
+ "promo_code": "",
137
+ "rotate_proxy_sid": true,
138
+ "redirect_poll_timeout_seconds": 120,
139
+ "stripe_publishable_key": ""
140
+ }
141
+ ```
142
+
143
+ The server creates a ChatGPT checkout and stores the dynamic `publishable_key` from the checkout response, then calls:
144
+
145
+ ```text
146
+ https://api.stripe.com/v1/payment_pages/{cs_id}/init
147
+ ```
148
+
149
+ Then it reads `stripe_hosted_url` and changes:
150
+
151
+ ```text
152
+ https://checkout.stripe.com -> https://pay.openai.com
153
+ ```
154
+
155
+ ### PayPal 推荐参数
156
+
157
+ - `checkout_proxy_region`: checkout 阶段使用的代理区域。为空时沿用账单国家;本次实测推荐 `US`。
158
+ - `approve_proxy_region`: provider / Stripe / approve 阶段使用的代理区域;本次实测推荐 `US`。
159
+ - `rotate_proxy_sid`: 为 `true` 时,如果代理用户名含 `sid-xxxx`,每次请求自动替换为随机 sid。
160
+ - `proxy_sid`: 手动指定 sid;为空且 `rotate_proxy_sid=true` 时自动生成。
161
+ - `redirect_poll_timeout_seconds`: PayPal approve 后等待 Stripe provider redirect 的秒数。推荐 `90` 到 `120`,最大限制为 `300`。
162
+ - `use_promo`: 推荐 `false`。如果设为 `true`,需要确认当前账号和地区可用对应 `promo_code`。
163
+
164
+ ## Link Types
165
+
166
+ - `hosted`: normal payment long link; country remains selectable.
167
+ - `paypal`: PayPal redirect extraction, current recommended default is `US/USD`, no promo, one US proxy for checkout, Stripe/provider, and approve, with a US billing address.
168
+ - `gopay`: GoPay redirect extraction, defaults to `ID/IDR`, uses an Indonesia billing address. Accounts with active USD checkout/subscription state may be blocked by Stripe from creating an IDR checkout.
169
+
170
+ For `paypal` and `gopay`, if Stripe provider redirect extraction fails but the hosted checkout URL exists, the API falls back to the hosted long link and returns `fallback: true` plus `provider_error`.
171
+
172
+ For PayPal, prefer `long_url` or `provider_redirect_url` for user-facing output. `stripe_redirect_url` may be a `pm-redirects.stripe.com` intermediate URL, which is useful for debugging and normally redirects to PayPal.
173
+
174
+ ## Testing
175
+
176
+ 测试 PayPal 提链功能:
177
+
178
+ ```bash
179
+ python test_paypal_api.py <your_access_token> [proxy]
180
+ ```
181
+
182
+ 示例:
183
+ ```bash
184
+ # 使用默认代理
185
+ python test_paypal_api.py eyJhbGci...
186
+
187
+ # 使用自定义代理
188
+ python test_paypal_api.py eyJhbGci... http://127.0.0.1:7890
189
+ ```
app.py ADDED
@@ -0,0 +1,1302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import random
6
+ import re
7
+ import time
8
+ import uuid
9
+ from pathlib import Path
10
+ from typing import Any
11
+ from urllib.parse import parse_qsl, quote, urlencode, urljoin, urlsplit, urlunsplit
12
+
13
+ import requests
14
+ from fastapi import FastAPI, HTTPException
15
+ from fastapi.responses import FileResponse
16
+ from fastapi.staticfiles import StaticFiles
17
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
18
+
19
+ try:
20
+ from curl_cffi.requests import Session as CurlCffiSession # type: ignore
21
+ except ImportError: # pragma: no cover - optional dependency
22
+ CurlCffiSession = None # type: ignore
23
+
24
+
25
+ DEFAULT_STRIPE_PK = (
26
+ "pk_live_51HOrSwC6h1nxGoI3lTAgRjYVrz4dU3fVOabyCcKR3pbEJguCVAlqCxdxCUvoRh1XWwRac"
27
+ "ViovU3kLKvpkjh7IqkW00iXQsjo3n"
28
+ )
29
+ STRIPE_VERSION_FULL = "2025-03-31.basil; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1"
30
+ DEFAULT_TIMEOUT = 30
31
+ BASE_DIR = Path(__file__).resolve().parent
32
+ PUBLIC_DIR = BASE_DIR / "public"
33
+ DEFAULT_PROXY = os.getenv(
34
+ "OPENAI_PAY_DEFAULT_PROXY",
35
+ "", # 默认为空,用户需要提供有效代理
36
+ ).strip()
37
+ PROVIDER_STAGE_PROXY = os.getenv("OPENAI_PAY_PROVIDER_PROXY", "").strip()
38
+ GOPAY_PROVIDER_STAGE_PROXY = os.getenv(
39
+ "OPENAI_PAY_GOPAY_PROVIDER_PROXY",
40
+ "", # 默认为空
41
+ ).strip()
42
+ DEFAULT_USER_AGENT = (
43
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
44
+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36"
45
+ )
46
+ DEFAULT_STRIPE_RUNTIME_VERSION = "6f8494a281"
47
+ US_BILLING_NAMES = [
48
+ ("James", "Smith"),
49
+ ("John", "Brown"),
50
+ ("Michael", "Johnson"),
51
+ ("Robert", "Miller"),
52
+ ("David", "Davis"),
53
+ ("William", "Wilson"),
54
+ ]
55
+ US_BILLING_STREETS = [
56
+ ("3110 Sunset Boulevard", "Los Angeles", "CA", "90026"),
57
+ ("1200 Market Street", "San Francisco", "CA", "94102"),
58
+ ("500 Main Street", "Austin", "TX", "78701"),
59
+ ("88 Broadway", "New York", "NY", "10007"),
60
+ ("1200 Peachtree St", "Atlanta", "GA", "30309"),
61
+ ]
62
+ JAPAN_BILLING_NAMES = [
63
+ ("Taro", "Yamada"),
64
+ ("Hanako", "Sato"),
65
+ ("Ken", "Suzuki"),
66
+ ("Yui", "Takahashi"),
67
+ ("Haruto", "Tanaka"),
68
+ ]
69
+ JAPAN_BILLING_STREETS = [
70
+ ("1-2-3 Shibuya", "Shibuya-ku", "Tokyo", "150-0002"),
71
+ ("2-1-1 Namba", "Chuo-ku", "Osaka", "542-0076"),
72
+ ("3-4-5 Sakae", "Naka-ku", "Aichi", "460-0008"),
73
+ ("4-2-8 Hakata", "Hakata-ku", "Fukuoka", "812-0011"),
74
+ ]
75
+ INDONESIA_BILLING_NAMES = [
76
+ ("Budi", "Santoso"),
77
+ ("Agus", "Wijaya"),
78
+ ("Siti", "Rahma"),
79
+ ("Dewi", "Lestari"),
80
+ ("Rizky", "Pratama"),
81
+ ]
82
+ INDONESIA_BILLING_STREETS = [
83
+ ("Jl. Jend. Sudirman No. 1", "Jakarta", "DKI Jakarta", "10210"),
84
+ ("Jl. MH Thamrin No. 10", "Jakarta", "DKI Jakarta", "10350"),
85
+ ("Jl. Asia Afrika No. 8", "Bandung", "Jawa Barat", "40111"),
86
+ ("Jl. Basuki Rahmat No. 5", "Surabaya", "Jawa Timur", "60271"),
87
+ ]
88
+ AUSTRALIA_BILLING_NAMES = [
89
+ ("Oliver", "Wilson"),
90
+ ("Jack", "Taylor"),
91
+ ("Charlotte", "Brown"),
92
+ ("Amelia", "Martin"),
93
+ ("Noah", "Anderson"),
94
+ ]
95
+ AUSTRALIA_BILLING_STREETS = [
96
+ ("200 George Street", "Sydney", "NSW", "2000"),
97
+ ("360 Collins Street", "Melbourne", "VIC", "3000"),
98
+ ("123 Queen Street", "Brisbane", "QLD", "4000"),
99
+ ("77 King William Street", "Adelaide", "SA", "5000"),
100
+ ("100 St Georges Terrace", "Perth", "WA", "6000"),
101
+ ]
102
+ COUNTRY_CURRENCY = {
103
+ "AT": "EUR",
104
+ "AU": "AUD",
105
+ "BE": "EUR",
106
+ "BR": "BRL",
107
+ "CA": "CAD",
108
+ "CH": "CHF",
109
+ "CZ": "CZK",
110
+ "DE": "EUR",
111
+ "DK": "DKK",
112
+ "ES": "EUR",
113
+ "FI": "EUR",
114
+ "FR": "EUR",
115
+ "GB": "GBP",
116
+ "HK": "HKD",
117
+ "ID": "IDR",
118
+ "IE": "EUR",
119
+ "IN": "INR",
120
+ "IT": "EUR",
121
+ "JP": "JPY",
122
+ "KR": "KRW",
123
+ "MX": "MXN",
124
+ "MY": "MYR",
125
+ "NL": "EUR",
126
+ "NO": "NOK",
127
+ "NZ": "NZD",
128
+ "PH": "PHP",
129
+ "PL": "PLN",
130
+ "PT": "EUR",
131
+ "SE": "SEK",
132
+ "SG": "SGD",
133
+ "TH": "THB",
134
+ "TW": "TWD",
135
+ "US": "USD",
136
+ "VN": "VND",
137
+ }
138
+ LOCALE_MAP = {
139
+ "de": ("de-DE", "de"),
140
+ "en": ("en-US", "en"),
141
+ "en-US": ("en-US", "en"),
142
+ "es": ("es-ES", "es"),
143
+ "fr": ("fr-FR", "fr"),
144
+ "id": ("id-ID", "id"),
145
+ "it": ("it-IT", "it"),
146
+ "ja": ("ja-JP", "ja"),
147
+ "ko": ("ko-KR", "ko"),
148
+ "pt-BR": ("pt-BR", "pt-BR"),
149
+ "zh-CN": ("zh-CN", "zh-CN"),
150
+ "zh-TW": ("zh-TW", "zh-TW"),
151
+ }
152
+
153
+
154
+ class LongLinkRequest(BaseModel):
155
+ model_config = ConfigDict(populate_by_name=True)
156
+
157
+ @model_validator(mode="before")
158
+ @classmethod
159
+ def normalize_har_fields(cls, data: Any) -> Any:
160
+ if not isinstance(data, dict):
161
+ return data
162
+ normalized = dict(data)
163
+ if not normalized.get("accessToken") and not normalized.get("access_token") and normalized.get("token"):
164
+ normalized["accessToken"] = normalized.get("token")
165
+ if not normalized.get("billing_country") and normalized.get("country"):
166
+ normalized["billing_country"] = normalized.get("country")
167
+ if not normalized.get("payment_locale") and normalized.get("ui_language"):
168
+ normalized["payment_locale"] = normalized.get("ui_language")
169
+ if not normalized.get("approve_proxy_region") and normalized.get("approve_proxy_mode"):
170
+ normalized["approve_proxy_region"] = normalized.get("approve_proxy_mode")
171
+ if not normalized.get("checkout_proxy_region") and normalized.get("checkout_proxy_mode"):
172
+ normalized["checkout_proxy_region"] = normalized.get("checkout_proxy_mode")
173
+ return normalized
174
+
175
+ access_token: str = Field(..., alias="accessToken")
176
+ plan: str = "plus"
177
+ proxy: str = ""
178
+ checkout_proxy_region: str = ""
179
+ rotate_proxy_sid: bool = False
180
+ proxy_sid: str = ""
181
+ default_proxy_id: str = ""
182
+ stripe_proxy_id: str = ""
183
+ stripe_proxy: str = ""
184
+ stripe_publishable_key: str = ""
185
+ billing_country: str = "AU"
186
+ country: str = "AU"
187
+ currency: str = "AUD"
188
+ checkout_ui_mode: str = "hosted"
189
+ payment_locale: str = "en"
190
+ ui_language: str = "en"
191
+ link_type: str = "paypal"
192
+ approve_proxy_region: str = ""
193
+ approve_proxy_mode: str = "us"
194
+ use_promo: bool = True
195
+ skip_stripe_page: bool = True
196
+ skip_cdk: str = ""
197
+ promo_code: str = "STRIPEATLASGPT4BIZ050126"
198
+ workspace_name: str = "linux-do"
199
+ seat_quantity: int = 2
200
+ device_id: str = ""
201
+ user_agent: str = ""
202
+ redirect_poll_timeout_seconds: int = 0
203
+
204
+
205
+ class LongLinkResponse(BaseModel):
206
+ ok: bool
207
+ cs_id: str
208
+ processor_entity: str
209
+ billing_country: str
210
+ currency: str
211
+ payment_locale: str
212
+ link_type: str
213
+ payment_method_type: str
214
+ payment_method_id: str
215
+ stripe_redirect_url: str
216
+ provider_redirect_url: str
217
+ fallback: bool = False
218
+ provider_error: str = ""
219
+ stripe_hosted_url: str
220
+ long_url: str
221
+ approve_proxy_region: str = ""
222
+ diagnostics: list[dict[str, Any]] = Field(default_factory=list)
223
+
224
+
225
+ def new_session() -> Any:
226
+ if CurlCffiSession is not None:
227
+ return CurlCffiSession(impersonate="chrome136")
228
+ return requests.Session()
229
+
230
+
231
+ def effective_default_proxy(proxy: str = "") -> str:
232
+ return str(proxy or "").strip() or DEFAULT_PROXY
233
+
234
+
235
+ def random_proxy_sid() -> str:
236
+ return uuid.uuid4().hex[:8]
237
+
238
+
239
+ def normalize_proxy_sid(value: str) -> str:
240
+ return re.sub(r"[^A-Za-z0-9]", "", str(value or ""))[:32]
241
+
242
+
243
+ def replace_proxy_sid(proxy: str, sid: str) -> str:
244
+ proxy = str(proxy or "").strip()
245
+ sid = normalize_proxy_sid(sid) or random_proxy_sid()
246
+ if not proxy or "sid-" not in proxy:
247
+ return proxy
248
+ return re.sub(r"sid-[A-Za-z0-9]+", f"sid-{sid}", proxy, count=1)
249
+
250
+
251
+ def materialize_request_proxy(req: LongLinkRequest) -> str:
252
+ if not req.rotate_proxy_sid and not str(req.proxy_sid or "").strip():
253
+ return ""
254
+ base_proxy = str(req.proxy or "").strip() or DEFAULT_PROXY
255
+ if not base_proxy or "sid-" not in base_proxy:
256
+ return ""
257
+ sid = normalize_proxy_sid(req.proxy_sid) or random_proxy_sid()
258
+ req.proxy = replace_proxy_sid(base_proxy, sid)
259
+ return sid
260
+
261
+
262
+ def set_proxy_url(session: Any, proxy: str) -> None:
263
+ proxy = str(proxy or "").strip()
264
+ if proxy:
265
+ session.proxies = {"http": proxy, "https": proxy}
266
+
267
+
268
+ def set_proxy(session: Any, proxy: str) -> None:
269
+ set_proxy_url(session, effective_default_proxy(proxy))
270
+
271
+
272
+ def proxy_for_region(proxy: str, region: str) -> str:
273
+ proxy = str(proxy or "").strip()
274
+ region = str(region or "").strip().upper()
275
+ if proxy and region and "region-" in proxy:
276
+ return re.sub(r"region-[A-Za-z]{2}", f"region-{region}", proxy)
277
+ return proxy
278
+
279
+
280
+ def normalize_proxy_region(region: str) -> str:
281
+ value = str(region or "").strip().upper()
282
+ return value if re.fullmatch(r"[A-Z]{2}", value) else ""
283
+
284
+
285
+ def effective_approve_proxy_region(req: LongLinkRequest) -> str:
286
+ explicit = normalize_proxy_region(req.approve_proxy_region)
287
+ if explicit:
288
+ return explicit
289
+ mode = normalize_proxy_region(req.approve_proxy_mode)
290
+ if mode:
291
+ return mode
292
+ return "ID" if normalize_link_type(req.link_type) == "gopay" else "US"
293
+
294
+
295
+ def effective_checkout_proxy_region(req: LongLinkRequest) -> str:
296
+ explicit = normalize_proxy_region(req.checkout_proxy_region)
297
+ return explicit or effective_country(req)
298
+
299
+
300
+ def checkout_stage_proxy(req: LongLinkRequest) -> str:
301
+ base_proxy = str(req.proxy or "").strip() or DEFAULT_PROXY
302
+ region = effective_checkout_proxy_region(req)
303
+ return proxy_for_region(base_proxy, region)
304
+
305
+
306
+ def provider_stage_proxy(req: LongLinkRequest) -> str:
307
+ link_type = normalize_link_type(req.link_type)
308
+ if link_type == "paypal":
309
+ if str(req.stripe_proxy or "").strip():
310
+ return str(req.stripe_proxy or "").strip()
311
+ base_proxy = str(req.proxy or "").strip() or DEFAULT_PROXY
312
+ return proxy_for_region(base_proxy, effective_approve_proxy_region(req))
313
+ region = effective_country(req)
314
+ base_proxy = str(req.proxy or "").strip() or DEFAULT_PROXY
315
+ if link_type == "gopay" and GOPAY_PROVIDER_STAGE_PROXY:
316
+ base_proxy = GOPAY_PROVIDER_STAGE_PROXY
317
+ elif PROVIDER_STAGE_PROXY:
318
+ base_proxy = PROVIDER_STAGE_PROXY
319
+ return proxy_for_region(base_proxy, region)
320
+
321
+
322
+ def approve_stage_proxy(req: LongLinkRequest) -> str:
323
+ base_proxy = str(req.proxy or "").strip() or DEFAULT_PROXY
324
+ return proxy_for_region(base_proxy, effective_approve_proxy_region(req))
325
+
326
+
327
+ def currency_for_country(country: str) -> str:
328
+ return COUNTRY_CURRENCY.get(str(country or "").upper(), "USD")
329
+
330
+
331
+ def normalize_currency(currency: str, country: str) -> str:
332
+ requested = str(currency or "").strip().upper()
333
+ expected = currency_for_country(country)
334
+ return requested if requested == expected else expected
335
+
336
+
337
+ def normalize_country(country: str) -> str:
338
+ country = str(country or "").strip().upper()
339
+ return country if country in COUNTRY_CURRENCY else "US"
340
+
341
+
342
+ def normalize_link_type(link_type: str) -> str:
343
+ value = str(link_type or "hosted").strip().lower()
344
+ aliases = {
345
+ "payment": "hosted",
346
+ "pay": "hosted",
347
+ "long": "hosted",
348
+ "pp": "paypal",
349
+ "paypal": "paypal",
350
+ "gopy": "gopay",
351
+ "gopay": "gopay",
352
+ }
353
+ return aliases.get(value, "hosted")
354
+
355
+
356
+ def safe_excerpt(value: Any, limit: int = 360) -> str:
357
+ if isinstance(value, (dict, list)):
358
+ text = json.dumps(value, ensure_ascii=False)
359
+ else:
360
+ text = str(value or "")
361
+ text = re.sub(r"Bearer\s+[A-Za-z0-9._-]+", "Bearer [redacted]", text, flags=re.I)
362
+ text = re.sub(r"eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}", "[redacted-jwt]", text)
363
+ text = re.sub(r"(access[_-]?token[\"'=:\s]*)([^\"'\\s<>,}]+)", r"\1[redacted]", text, flags=re.I)
364
+ text = re.sub(r"(authorization[\"'=:\s]*)(Bearer\s+)?([^\"'\\s<>,}]+)", r"\1[redacted]", text, flags=re.I)
365
+ text = re.sub(r"(cookie[\"'=:\s]*)([^\"'\\n\\r]+)", r"\1[redacted]", text, flags=re.I)
366
+ text = re.sub(r"(ba_token=)[A-Za-z0-9_-]+", r"\1[redacted]", text, flags=re.I)
367
+ text = re.sub(r"\s+", " ", text).strip()
368
+ return text[: max(1, int(limit or 360))]
369
+
370
+
371
+ def short_id(value: Any) -> str:
372
+ text = str(value or "")
373
+ if len(text) <= 14:
374
+ return text
375
+ return f"{text[:6]}...{text[-4:]}"
376
+
377
+
378
+ def add_diagnostic(
379
+ diagnostics: list[dict[str, Any]],
380
+ stage: str,
381
+ status: str,
382
+ region: str = "",
383
+ message: Any = "",
384
+ http_status: int | None = None,
385
+ ) -> None:
386
+ item: dict[str, Any] = {
387
+ "stage": str(stage or "-"),
388
+ "status": str(status or "-"),
389
+ "region": str(region or "-"),
390
+ "message": safe_excerpt(message, 420),
391
+ }
392
+ if http_status is not None:
393
+ item["http_status"] = int(http_status)
394
+ diagnostics.append(item)
395
+
396
+
397
+ def diagnostic_http_exception(exc: HTTPException, diagnostics: list[dict[str, Any]]) -> HTTPException:
398
+ return HTTPException(
399
+ status_code=exc.status_code,
400
+ detail={
401
+ "message": safe_excerpt(exc.detail),
402
+ "diagnostics": diagnostics,
403
+ },
404
+ )
405
+
406
+
407
+ def effective_country(req: LongLinkRequest) -> str:
408
+ return normalize_country(req.country or req.billing_country)
409
+
410
+
411
+ def effective_currency(req: LongLinkRequest, country: str = "") -> str:
412
+ resolved_country = normalize_country(country or effective_country(req))
413
+ return normalize_currency(req.currency, resolved_country)
414
+
415
+
416
+ def effective_payment_locale(req: LongLinkRequest) -> str:
417
+ return str(req.ui_language or req.payment_locale or "en").strip() or "en"
418
+
419
+
420
+ def locale_parts(locale: str) -> tuple[str, str]:
421
+ return LOCALE_MAP.get(str(locale or "").strip(), LOCALE_MAP["en"])
422
+
423
+
424
+ def find_token(value: Any) -> str:
425
+ if isinstance(value, dict):
426
+ for key in ("accessToken", "access_token", "token"):
427
+ token = str(value.get(key) or "").strip()
428
+ if token:
429
+ return token
430
+ for item in value.values():
431
+ token = find_token(item)
432
+ if token:
433
+ return token
434
+ if isinstance(value, list):
435
+ for item in value:
436
+ token = find_token(item)
437
+ if token:
438
+ return token
439
+ return ""
440
+
441
+
442
+ def normalize_access_token(raw: str) -> str:
443
+ token = str(raw or "").strip()
444
+ if not token:
445
+ return ""
446
+ if token.startswith("{") or token.startswith("["):
447
+ try:
448
+ return find_token(json.loads(token)) or token
449
+ except json.JSONDecodeError:
450
+ return token
451
+ return token
452
+
453
+
454
+ def extract_processor_entity(data: Any) -> str:
455
+ if not isinstance(data, dict):
456
+ return ""
457
+ direct = data.get("processor_entity") or data.get("processorEntity")
458
+ if direct:
459
+ return str(direct).strip()
460
+ for key in ("checkout_session", "session", "checkout", "data"):
461
+ nested = data.get(key)
462
+ if isinstance(nested, dict):
463
+ found = extract_processor_entity(nested)
464
+ if found:
465
+ return found
466
+ return ""
467
+
468
+
469
+ def build_chatgpt_session(req: LongLinkRequest) -> Any:
470
+ access_token = normalize_access_token(req.access_token)
471
+ if not access_token:
472
+ raise HTTPException(status_code=400, detail="accessToken is required")
473
+
474
+ device_id = req.device_id.strip() or str(uuid.uuid4())
475
+ user_agent = req.user_agent.strip() or DEFAULT_USER_AGENT
476
+ browser_locale, _ = locale_parts(effective_payment_locale(req))
477
+ session = new_session()
478
+ session.headers.update(
479
+ {
480
+ "User-Agent": user_agent,
481
+ "Accept": "*/*",
482
+ "Accept-Language": f"{browser_locale},en;q=0.9",
483
+ "Authorization": f"Bearer {access_token}",
484
+ "Origin": "https://chatgpt.com",
485
+ "Referer": "https://chatgpt.com/",
486
+ "Content-Type": "application/json",
487
+ "oai-device-id": device_id,
488
+ "oai-language": browser_locale,
489
+ "sec-ch-ua": '"Google Chrome";v="147", "Not.A/Brand";v="8", "Chromium";v="147"',
490
+ "sec-ch-ua-mobile": "?0",
491
+ "sec-ch-ua-platform": '"Windows"',
492
+ "sec-fetch-dest": "empty",
493
+ "sec-fetch-mode": "cors",
494
+ "sec-fetch-site": "same-origin",
495
+ "Cookie": f"oai-did={device_id}",
496
+ }
497
+ )
498
+ set_proxy_url(session, checkout_stage_proxy(req))
499
+ return session
500
+
501
+
502
+ def create_checkout(req: LongLinkRequest, chatgpt_session: Any | None = None) -> dict[str, Any]:
503
+ billing_country = effective_country(req)
504
+ currency = effective_currency(req, billing_country)
505
+ checkout_ui_mode = (req.checkout_ui_mode or "hosted").strip() or "hosted"
506
+ plan = str(req.plan or "plus").strip().lower()
507
+ plan_name = "chatgptplusplan" if plan == "plus" else plan
508
+ body = {
509
+ "entry_point": "all_plans_pricing_modal",
510
+ "plan_name": plan_name,
511
+ "billing_details": {
512
+ "country": billing_country,
513
+ "currency": currency,
514
+ },
515
+ "promo_campaign": {
516
+ "promo_campaign_id": "plus-1-month-free",
517
+ "is_coupon_from_query_param": False,
518
+ },
519
+ "checkout_ui_mode": checkout_ui_mode,
520
+ }
521
+ if req.use_promo:
522
+ promo_code = str(req.promo_code or "").strip()
523
+ workspace_name = str(req.workspace_name or "").strip()
524
+ if promo_code:
525
+ body["promo_code"] = promo_code
526
+ if workspace_name:
527
+ body["workspace_name"] = workspace_name
528
+ body["seat_quantity"] = max(1, int(req.seat_quantity or 1))
529
+ body["use_promo"] = True
530
+ if req.skip_stripe_page:
531
+ body["skip_stripe_page"] = True
532
+ headers = {
533
+ "Referer": "https://chatgpt.com/",
534
+ "x-openai-target-path": "/backend-api/payments/checkout",
535
+ "x-openai-target-route": "/backend-api/payments/checkout",
536
+ }
537
+ response = (chatgpt_session or build_chatgpt_session(req)).post(
538
+ "https://chatgpt.com/backend-api/payments/checkout",
539
+ json=body,
540
+ headers=headers,
541
+ timeout=DEFAULT_TIMEOUT,
542
+ )
543
+ if response.status_code >= 400:
544
+ body_text = response.text[:500] if response.text else ""
545
+ if "cannot combine currencies" in body_text.lower():
546
+ raise HTTPException(
547
+ status_code=409,
548
+ detail=(
549
+ "GoPay needs an IDR checkout, but this Stripe customer already has active USD "
550
+ "checkout/subscription state. Use a fresh account/customer or wait for the USD "
551
+ "checkout state to expire; this cannot be bypassed in code."
552
+ ),
553
+ )
554
+ raise HTTPException(
555
+ status_code=response.status_code,
556
+ detail=f"checkout create failed: {body_text}",
557
+ )
558
+
559
+ try:
560
+ data = response.json() or {}
561
+ except ValueError:
562
+ body_text = response.text[:500] if response.text else ""
563
+ raise HTTPException(
564
+ status_code=502,
565
+ detail=f"checkout returned non-json response: status={response.status_code}, body={body_text}",
566
+ )
567
+ cs_id = data.get("checkout_session_id") or data.get("session_id") or data.get("id")
568
+ if not cs_id or not str(cs_id).startswith("cs_"):
569
+ raise HTTPException(status_code=502, detail=f"checkout response missing cs_id: {data}")
570
+ return {
571
+ "cs_id": str(cs_id),
572
+ "processor_entity": extract_processor_entity(data),
573
+ "billing_country": billing_country,
574
+ "currency": currency,
575
+ "stripe_publishable_key": str(data.get("publishable_key") or "").strip(),
576
+ }
577
+
578
+
579
+ def stripe_init(cs_id: str, req: LongLinkRequest, proxy_override: str = "") -> dict[str, Any]:
580
+ stripe_pk = req.stripe_publishable_key.strip() or DEFAULT_STRIPE_PK
581
+ browser_locale, elements_locale = locale_parts(effective_payment_locale(req))
582
+ stripe = new_session()
583
+ stripe.headers.update(
584
+ {
585
+ "User-Agent": req.user_agent.strip() or DEFAULT_USER_AGENT,
586
+ "Accept-Language": "en-US,en;q=0.9",
587
+ }
588
+ )
589
+ if proxy_override:
590
+ set_proxy_url(stripe, proxy_override)
591
+ else:
592
+ set_proxy_url(stripe, checkout_stage_proxy(req))
593
+ body = {
594
+ "browser_locale": browser_locale,
595
+ "browser_timezone": "Asia/Shanghai",
596
+ "elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
597
+ "elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
598
+ "elements_session_client[elements_init_source]": "custom_checkout",
599
+ "elements_session_client[referrer_host]": "chatgpt.com",
600
+ "elements_session_client[stripe_js_id]": str(uuid.uuid4()),
601
+ "elements_session_client[locale]": elements_locale,
602
+ "elements_session_client[is_aggregation_expected]": "false",
603
+ "elements_options_client[saved_payment_method][enable_save]": "never",
604
+ "elements_options_client[saved_payment_method][enable_redisplay]": "never",
605
+ "key": stripe_pk,
606
+ "_stripe_version": STRIPE_VERSION_FULL,
607
+ }
608
+ response = stripe.post(
609
+ f"https://api.stripe.com/v1/payment_pages/{cs_id}/init",
610
+ data=body,
611
+ timeout=DEFAULT_TIMEOUT,
612
+ )
613
+ if response.status_code >= 400:
614
+ raise HTTPException(
615
+ status_code=response.status_code,
616
+ detail=f"stripe init failed: {response.text[:500]}",
617
+ )
618
+ return response.json() or {}
619
+
620
+
621
+ def stripe_init_gopay_checksum(stripe: Any, cs_id: str, stripe_pk: str, req: LongLinkRequest) -> str:
622
+ browser_locale, elements_locale = locale_parts(effective_payment_locale(req))
623
+ body = {
624
+ "browser_locale": browser_locale,
625
+ "browser_timezone": "Asia/Shanghai",
626
+ "elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
627
+ "elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
628
+ "elements_session_client[elements_init_source]": "custom_checkout",
629
+ "elements_session_client[referrer_host]": "chatgpt.com",
630
+ "elements_session_client[stripe_js_id]": str(uuid.uuid4()),
631
+ "elements_session_client[locale]": elements_locale,
632
+ "elements_session_client[is_aggregation_expected]": "false",
633
+ "key": stripe_pk,
634
+ }
635
+ response = stripe.post(
636
+ f"https://api.stripe.com/v1/payment_pages/{cs_id}/init",
637
+ data=body,
638
+ timeout=DEFAULT_TIMEOUT,
639
+ )
640
+ if response.status_code >= 400:
641
+ raise HTTPException(status_code=response.status_code, detail=f"stripe gopay init failed: {response.text[:500]}")
642
+ checksum = str((response.json() or {}).get("init_checksum") or "").strip()
643
+ if not checksum:
644
+ raise HTTPException(status_code=502, detail=f"stripe gopay init missing init_checksum: {response.text[:300]}")
645
+ return checksum
646
+
647
+
648
+ def to_openai_pay_url(stripe_hosted_url: str) -> str:
649
+ url = str(stripe_hosted_url or "").strip()
650
+ if not url:
651
+ return ""
652
+ if url.startswith("https://checkout.stripe.com"):
653
+ return "https://pay.openai.com" + url[len("https://checkout.stripe.com") :]
654
+
655
+ parsed = urlsplit(url)
656
+ if parsed.netloc.lower() == "checkout.stripe.com":
657
+ return urlunsplit((parsed.scheme or "https", "pay.openai.com", parsed.path, parsed.query, parsed.fragment))
658
+ return url
659
+
660
+
661
+ def processor_entity_for_country(country: str, processor_entity: str = "") -> str:
662
+ entity = str(processor_entity or "").strip()
663
+ if entity:
664
+ return entity
665
+ return "openai_llc" if str(country or "").upper() == "US" else "openai_ie"
666
+
667
+
668
+ def chatgpt_success_return_url(cs_id: str, country: str, processor_entity: str = "") -> str:
669
+ entity = processor_entity_for_country(country, processor_entity)
670
+ return f"https://chatgpt.com/checkout/verify?stripe_session_id={cs_id}&processor_entity={entity}&plan_type=plus"
671
+
672
+
673
+ def stripe_checkout_long_url(cs_id: str, country: str, processor_entity: str = "") -> str:
674
+ return (
675
+ f"https://checkout.stripe.com/c/pay/{cs_id}"
676
+ f"?returned_from_redirect=true&ui_mode=custom&return_url="
677
+ f"{quote(chatgpt_success_return_url(cs_id, country, processor_entity), safe='')}"
678
+ )
679
+
680
+
681
+ def stripe_confirm_return_url(cs_id: str, checkout: dict[str, Any], stripe_hosted_url: str) -> str:
682
+ hosted_url = to_openai_pay_url(stripe_hosted_url) or stripe_checkout_long_url(
683
+ cs_id,
684
+ checkout["billing_country"],
685
+ checkout.get("processor_entity", ""),
686
+ )
687
+ if "pay.openai.com/" in hosted_url or "checkout.stripe.com/" in hosted_url:
688
+ parsed = urlsplit(hosted_url)
689
+ query = dict(parse_qsl(parsed.query, keep_blank_values=True))
690
+ query.setdefault(
691
+ "success_return_url",
692
+ chatgpt_success_return_url(
693
+ cs_id,
694
+ checkout["billing_country"],
695
+ checkout.get("processor_entity", ""),
696
+ ),
697
+ )
698
+ return urlunsplit((parsed.scheme, parsed.netloc, parsed.path, urlencode(query), parsed.fragment))
699
+ return hosted_url
700
+
701
+
702
+ def expected_amount(init_payload: Any) -> str:
703
+ if not isinstance(init_payload, dict):
704
+ return "0"
705
+ total_summary = init_payload.get("total_summary")
706
+ if isinstance(total_summary, dict) and total_summary.get("due") is not None:
707
+ return str(total_summary.get("due"))
708
+ invoice = init_payload.get("invoice")
709
+ if isinstance(invoice, dict) and invoice.get("amount_due") is not None:
710
+ return str(invoice.get("amount_due"))
711
+ line_items = init_payload.get("line_items")
712
+ if isinstance(line_items, list):
713
+ total = 0
714
+ found = False
715
+ for item in line_items:
716
+ if isinstance(item, dict) and item.get("amount") is not None:
717
+ try:
718
+ total += int(item.get("amount") or 0)
719
+ found = True
720
+ except Exception:
721
+ pass
722
+ if found:
723
+ return str(total)
724
+ return "0"
725
+
726
+
727
+ def stripe_context(cs_id: str, init_payload: dict[str, Any], req: LongLinkRequest) -> dict[str, Any]:
728
+ _, elements_locale = locale_parts(effective_payment_locale(req))
729
+ return {
730
+ "stripe_js_id": str(uuid.uuid4()),
731
+ "elements_session_id": f"elements_session_{uuid.uuid4().hex[:11]}",
732
+ "elements_session_config_id": str(init_payload.get("config_id") or uuid.uuid4()),
733
+ "config_id": init_payload.get("config_id") or "",
734
+ "init_checksum": init_payload.get("init_checksum") or "",
735
+ "currency": str(init_payload.get("currency") or currency_for_country(effective_country(req))).lower(),
736
+ "checkout_amount": expected_amount(init_payload),
737
+ "locale": elements_locale,
738
+ }
739
+
740
+
741
+ def billing_for_country(country: str) -> dict[str, str]:
742
+ country = normalize_country(country)
743
+ if country == "ID":
744
+ first_name, last_name = random.choice(INDONESIA_BILLING_NAMES)
745
+ line1, city, state, postal_code = random.choice(INDONESIA_BILLING_STREETS)
746
+ elif country == "JP":
747
+ first_name, last_name = random.choice(JAPAN_BILLING_NAMES)
748
+ line1, city, state, postal_code = random.choice(JAPAN_BILLING_STREETS)
749
+ elif country == "DE":
750
+ first_name, last_name = random.choice([
751
+ ("Max", "Mueller"),
752
+ ("Felix", "Schmidt"),
753
+ ("Anna", "Schneider"),
754
+ ("Lukas", "Fischer"),
755
+ ])
756
+ line1, city, state, postal_code = random.choice([
757
+ ("Friedrichstrasse 100", "Berlin", "", "10117"),
758
+ ("Leopoldstrasse 50", "Munich", "", "80802"),
759
+ ("Zeil 106", "Frankfurt", "", "60313"),
760
+ ("Koenigsallee 60", "Duesseldorf", "", "40212"),
761
+ ])
762
+ elif country == "AU":
763
+ first_name, last_name = random.choice(AUSTRALIA_BILLING_NAMES)
764
+ line1, city, state, postal_code = random.choice(AUSTRALIA_BILLING_STREETS)
765
+ elif country in {"FR", "ES", "IT", "NL", "IE", "PT", "BE", "FI", "AT"}:
766
+ first_name, last_name = random.choice([
767
+ ("Alex", "Martin"),
768
+ ("Lucas", "Rossi"),
769
+ ("Emma", "Garcia"),
770
+ ("Sofia", "Jansen"),
771
+ ])
772
+ line1, city, state, postal_code = random.choice([
773
+ ("10 Rue de Rivoli", "Paris", "", "75001"),
774
+ ("Calle Mayor 10", "Madrid", "", "28013"),
775
+ ("Via Roma 20", "Milan", "", "20121"),
776
+ ("Damrak 1", "Amsterdam", "", "1012 LG"),
777
+ ])
778
+ else:
779
+ first_name, last_name = random.choice(US_BILLING_NAMES)
780
+ line1, city, state, postal_code = random.choice(US_BILLING_STREETS)
781
+ country = "US" if country == "US" else country
782
+ suffix = random.randint(1000, 9999)
783
+ return {
784
+ "name": f"{first_name} {last_name}",
785
+ "email": f"{first_name.lower()}.{last_name.lower()}{suffix}@example.com",
786
+ "country": country,
787
+ "line1": line1,
788
+ "city": city,
789
+ "state": state,
790
+ "postal_code": postal_code,
791
+ }
792
+
793
+
794
+ def billing_for_link_type(link_type: str, country: str) -> dict[str, str]:
795
+ normalized = normalize_link_type(link_type)
796
+ if normalized in {"paypal", "gopay"}:
797
+ return billing_for_country(country)
798
+ return billing_for_country(country)
799
+
800
+
801
+ def build_stripe_session(req: LongLinkRequest, proxy_override: str = "") -> Any:
802
+ stripe = new_session()
803
+ stripe.headers.update(
804
+ {
805
+ "User-Agent": req.user_agent.strip() or DEFAULT_USER_AGENT,
806
+ "Accept-Language": "en-US,en;q=0.9",
807
+ }
808
+ )
809
+ if proxy_override:
810
+ set_proxy_url(stripe, proxy_override)
811
+ else:
812
+ set_proxy_url(stripe, checkout_stage_proxy(req))
813
+ return stripe
814
+
815
+
816
+ def stripe_create_payment_method(
817
+ stripe: Any,
818
+ cs_id: str,
819
+ stripe_pk: str,
820
+ billing: dict[str, str],
821
+ payment_method_type: str,
822
+ ctx: dict[str, Any],
823
+ ) -> str:
824
+ payment_method_type = normalize_link_type(payment_method_type)
825
+ if payment_method_type == "gopay":
826
+ body = {
827
+ "billing_details[name]": billing.get("name") or "Budi Santoso",
828
+ "billing_details[email]": billing.get("email") or "buyer@example.com",
829
+ "billing_details[address][country]": billing.get("country") or "ID",
830
+ "billing_details[address][line1]": billing.get("line1") or "Jl. Jend. Sudirman No. 1",
831
+ "billing_details[address][city]": billing.get("city") or "Jakarta",
832
+ "billing_details[address][postal_code]": billing.get("postal_code") or "10210",
833
+ "billing_details[address][state]": billing.get("state") or "DKI Jakarta",
834
+ "type": "gopay",
835
+ "client_attribution_metadata[checkout_session_id]": cs_id,
836
+ "key": stripe_pk,
837
+ }
838
+ else:
839
+ runtime_version = str(ctx.get("runtime_version") or DEFAULT_STRIPE_RUNTIME_VERSION)
840
+ body = {
841
+ "billing_details[name]": billing.get("name") or "John Doe",
842
+ "billing_details[email]": billing.get("email") or "buyer@example.com",
843
+ "billing_details[address][country]": billing.get("country") or "US",
844
+ "billing_details[address][line1]": billing.get("line1") or "3110 Sunset Boulevard",
845
+ "billing_details[address][city]": billing.get("city") or "Los Angeles",
846
+ "billing_details[address][postal_code]": billing.get("postal_code") or "90026",
847
+ "billing_details[address][state]": billing.get("state") or "CA",
848
+ "type": "paypal",
849
+ "payment_user_agent": f"stripe.js/{runtime_version}; stripe-js-v3/{runtime_version}; payment-element; deferred-intent",
850
+ "referrer": "https://chatgpt.com",
851
+ "time_on_page": str(random.randint(25000, 55000)),
852
+ "client_attribution_metadata[checkout_session_id]": cs_id,
853
+ "client_attribution_metadata[client_session_id]": ctx["stripe_js_id"],
854
+ "client_attribution_metadata[checkout_config_id]": ctx.get("config_id") or "",
855
+ "client_attribution_metadata[elements_session_id]": ctx["elements_session_id"],
856
+ "client_attribution_metadata[elements_session_config_id]": ctx["elements_session_config_id"],
857
+ "client_attribution_metadata[merchant_integration_source]": "elements",
858
+ "client_attribution_metadata[merchant_integration_subtype]": "payment-element",
859
+ "client_attribution_metadata[merchant_integration_version]": "2021",
860
+ "client_attribution_metadata[payment_intent_creation_flow]": "deferred",
861
+ "client_attribution_metadata[payment_method_selection_flow]": "automatic",
862
+ "client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
863
+ "client_attribution_metadata[merchant_integration_additional_elements][1]": "address",
864
+ "key": stripe_pk,
865
+ "_stripe_version": STRIPE_VERSION_FULL,
866
+ }
867
+ response = stripe.post("https://api.stripe.com/v1/payment_methods", data=body, timeout=DEFAULT_TIMEOUT)
868
+ if response.status_code >= 400:
869
+ raise HTTPException(status_code=response.status_code, detail=f"stripe payment_methods failed: {response.text[:500]}")
870
+ pm_id = str((response.json() or {}).get("id") or "")
871
+ if not pm_id.startswith("pm_"):
872
+ raise HTTPException(status_code=502, detail=f"stripe payment_methods bad response: {response.text[:300]}")
873
+ return pm_id
874
+
875
+
876
+ def stripe_confirm(
877
+ stripe: Any,
878
+ cs_id: str,
879
+ pm_id: str,
880
+ stripe_pk: str,
881
+ payment_method_type: str,
882
+ init_payload: dict[str, Any],
883
+ ctx: dict[str, Any],
884
+ checkout: dict[str, Any],
885
+ req: LongLinkRequest,
886
+ stripe_hosted_url: str,
887
+ ) -> dict[str, Any]:
888
+ payment_method_type = normalize_link_type(payment_method_type)
889
+ return_url = stripe_confirm_return_url(cs_id, checkout, stripe_hosted_url)
890
+ if payment_method_type == "gopay":
891
+ init_checksum = stripe_init_gopay_checksum(stripe, cs_id, stripe_pk, req)
892
+ body = {
893
+ "guid": uuid.uuid4().hex,
894
+ "muid": uuid.uuid4().hex,
895
+ "sid": uuid.uuid4().hex,
896
+ "payment_method": pm_id,
897
+ "init_checksum": init_checksum,
898
+ "version": "fed52f3bc6",
899
+ "expected_amount": "0",
900
+ "expected_payment_method_type": "gopay",
901
+ "return_url": return_url,
902
+ "elements_session_client[session_id]": f"elements_session_{uuid.uuid4().hex[:11]}",
903
+ "elements_session_client[locale]": locale_parts(effective_payment_locale(req))[1],
904
+ "elements_session_client[referrer_host]": "chatgpt.com",
905
+ "elements_session_client[is_aggregation_expected]": "false",
906
+ "client_attribution_metadata[client_session_id]": str(uuid.uuid4()),
907
+ "client_attribution_metadata[merchant_integration_source]": "elements",
908
+ "client_attribution_metadata[merchant_integration_subtype]": "payment-element",
909
+ "client_attribution_metadata[payment_intent_creation_flow]": "deferred",
910
+ "consent[terms_of_service]": "accepted",
911
+ "key": stripe_pk,
912
+ }
913
+ else:
914
+ runtime_version = str(ctx.get("runtime_version") or DEFAULT_STRIPE_RUNTIME_VERSION)
915
+ body = {
916
+ "guid": uuid.uuid4().hex,
917
+ "muid": uuid.uuid4().hex,
918
+ "sid": uuid.uuid4().hex,
919
+ "payment_method": pm_id,
920
+ "init_checksum": str(init_payload.get("init_checksum") or ctx.get("init_checksum") or ""),
921
+ "version": runtime_version,
922
+ "expected_amount": str(ctx.get("checkout_amount") or expected_amount(init_payload)),
923
+ "expected_payment_method_type": "paypal",
924
+ "return_url": return_url,
925
+ "elements_session_client[session_id]": ctx["elements_session_id"],
926
+ "elements_session_client[locale]": str(ctx.get("locale") or "en"),
927
+ "elements_session_client[referrer_host]": "chatgpt.com",
928
+ "elements_session_client[is_aggregation_expected]": "false",
929
+ "elements_session_client[elements_init_source]": "custom_checkout",
930
+ "elements_session_client[stripe_js_id]": ctx["stripe_js_id"],
931
+ "elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
932
+ "elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
933
+ "elements_options_client[saved_payment_method][enable_save]": "never",
934
+ "elements_options_client[saved_payment_method][enable_redisplay]": "never",
935
+ "client_attribution_metadata[client_session_id]": ctx["stripe_js_id"],
936
+ "client_attribution_metadata[checkout_session_id]": cs_id,
937
+ "client_attribution_metadata[checkout_config_id]": ctx.get("config_id") or "",
938
+ "client_attribution_metadata[elements_session_id]": ctx["elements_session_id"],
939
+ "client_attribution_metadata[elements_session_config_id]": ctx["elements_session_config_id"],
940
+ "client_attribution_metadata[merchant_integration_source]": "checkout",
941
+ "client_attribution_metadata[merchant_integration_subtype]": "payment-element",
942
+ "client_attribution_metadata[merchant_integration_version]": "custom",
943
+ "client_attribution_metadata[payment_intent_creation_flow]": "deferred",
944
+ "client_attribution_metadata[payment_method_selection_flow]": "automatic",
945
+ "client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
946
+ "client_attribution_metadata[merchant_integration_additional_elements][1]": "address",
947
+ "consent[terms_of_service]": "accepted",
948
+ "key": stripe_pk,
949
+ "_stripe_version": STRIPE_VERSION_FULL,
950
+ }
951
+ response = stripe.post(f"https://api.stripe.com/v1/payment_pages/{cs_id}/confirm", data=body, timeout=DEFAULT_TIMEOUT)
952
+ if response.status_code >= 400:
953
+ raise HTTPException(status_code=response.status_code, detail=f"stripe confirm failed: {response.text[:500]}")
954
+ return response.json() or {}
955
+
956
+
957
+ def extract_redirect_to_url(payload: Any) -> str:
958
+ if not isinstance(payload, dict):
959
+ return ""
960
+ next_action = payload.get("next_action")
961
+ if isinstance(next_action, dict) and next_action.get("type") == "redirect_to_url":
962
+ redirect_to_url = next_action.get("redirect_to_url") or {}
963
+ if isinstance(redirect_to_url, dict):
964
+ url = str(redirect_to_url.get("url") or "").strip()
965
+ if url:
966
+ return url
967
+ for key in ("setup_intent", "payment_intent"):
968
+ nested = payload.get(key)
969
+ if isinstance(nested, dict):
970
+ found = extract_redirect_to_url(nested)
971
+ if found:
972
+ return found
973
+ return ""
974
+
975
+
976
+ def stripe_payment_page_redirect_url(stripe: Any, cs_id: str, stripe_pk: str, req: LongLinkRequest, timeout_seconds: float = 30) -> str:
977
+ deadline = time.time() + max(1.0, float(timeout_seconds or 30))
978
+ last_err = ""
979
+ params = {
980
+ "elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
981
+ "elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
982
+ "elements_session_client[elements_init_source]": "custom_checkout",
983
+ "elements_session_client[referrer_host]": "chatgpt.com",
984
+ "elements_session_client[session_id]": f"elements_session_{uuid.uuid4().hex[:11]}",
985
+ "elements_session_client[stripe_js_id]": str(uuid.uuid4()),
986
+ "elements_session_client[locale]": locale_parts(effective_payment_locale(req))[1],
987
+ "elements_session_client[is_aggregation_expected]": "false",
988
+ "elements_options_client[saved_payment_method][enable_save]": "never",
989
+ "elements_options_client[saved_payment_method][enable_redisplay]": "never",
990
+ "key": stripe_pk,
991
+ "_stripe_version": STRIPE_VERSION_FULL,
992
+ }
993
+ while time.time() < deadline:
994
+ response = stripe.get(f"https://api.stripe.com/v1/payment_pages/{cs_id}", params=params, timeout=DEFAULT_TIMEOUT)
995
+ if response.status_code == 200:
996
+ payload = response.json() or {}
997
+ redirect_url = extract_redirect_to_url(payload)
998
+ if redirect_url:
999
+ return redirect_url
1000
+ last_err = f"keys=[{','.join(sorted(payload.keys())[:8])}]"
1001
+ else:
1002
+ last_err = f"http {response.status_code}: {response.text[:120]}"
1003
+ time.sleep(1)
1004
+ raise HTTPException(status_code=504, detail=f"redirect url resolution timeout: {last_err}")
1005
+
1006
+
1007
+ def redirect_poll_timeout(req: LongLinkRequest, default_seconds: int) -> int:
1008
+ try:
1009
+ configured = int(req.redirect_poll_timeout_seconds or 0)
1010
+ except Exception:
1011
+ configured = 0
1012
+ if configured <= 0 and normalize_link_type(req.link_type) == "paypal":
1013
+ configured = 90
1014
+ if configured <= 0:
1015
+ configured = int(default_seconds or 30)
1016
+ return max(5, min(configured, 300))
1017
+
1018
+
1019
+ def chatgpt_approve(chatgpt: Any, cs_id: str, checkout: dict[str, Any], approve_proxy: str = "") -> str:
1020
+ if approve_proxy:
1021
+ set_proxy_url(chatgpt, approve_proxy)
1022
+ country = checkout["billing_country"]
1023
+ processor_entity = processor_entity_for_country(country, checkout.get("processor_entity", ""))
1024
+ try:
1025
+ chatgpt.post(
1026
+ "https://chatgpt.com/backend-api/sentinel/ping",
1027
+ json={},
1028
+ headers={
1029
+ "Referer": "https://chatgpt.com/",
1030
+ "x-openai-target-path": "/backend-api/sentinel/ping",
1031
+ "x-openai-target-route": "/backend-api/sentinel/ping",
1032
+ },
1033
+ timeout=DEFAULT_TIMEOUT,
1034
+ )
1035
+ except Exception:
1036
+ pass
1037
+ response = chatgpt.post(
1038
+ "https://chatgpt.com/backend-api/payments/checkout/approve",
1039
+ json={"checkout_session_id": cs_id, "processor_entity": processor_entity},
1040
+ headers={
1041
+ "Referer": f"https://chatgpt.com/checkout/{processor_entity}/{cs_id}",
1042
+ "x-openai-target-path": "/backend-api/payments/checkout/approve",
1043
+ "x-openai-target-route": "/backend-api/payments/checkout/approve",
1044
+ },
1045
+ timeout=DEFAULT_TIMEOUT,
1046
+ )
1047
+ if response.status_code >= 400:
1048
+ raise HTTPException(status_code=response.status_code, detail=f"chatgpt approve failed: {response.text[:500]}")
1049
+ try:
1050
+ result = (response.json() or {}).get("result")
1051
+ except Exception:
1052
+ result = ""
1053
+ # 对于 blocked 状态,不抛出异常,继续尝试获取 redirect URL
1054
+ # 某些情况下即使 blocked,Stripe 仍可能已经生成了 PayPal redirect
1055
+ if result not in ("approved", "blocked"):
1056
+ raise HTTPException(status_code=502, detail=f"chatgpt approve unexpected result: {result!r}")
1057
+ # blocked 状态也返回,让调用者决定是否继续
1058
+ return str(result)
1059
+
1060
+
1061
+ def redirect_url_after_confirm(
1062
+ chatgpt: Any,
1063
+ stripe: Any,
1064
+ confirm_payload: dict[str, Any],
1065
+ cs_id: str,
1066
+ stripe_pk: str,
1067
+ checkout: dict[str, Any],
1068
+ req: LongLinkRequest,
1069
+ diagnostics: list[dict[str, Any]] | None = None,
1070
+ ) -> str:
1071
+ redirect_url = extract_redirect_to_url(confirm_payload)
1072
+ if redirect_url:
1073
+ if diagnostics is not None:
1074
+ add_diagnostic(diagnostics, "redirect", "ok", effective_approve_proxy_region(req), "confirm returned redirect_to_url")
1075
+ return redirect_url
1076
+ submission = confirm_payload.get("submission_attempt") if isinstance(confirm_payload, dict) else None
1077
+ if isinstance(submission, dict) and submission.get("state") == "requires_approval":
1078
+ if diagnostics is not None:
1079
+ add_diagnostic(diagnostics, "approve", "running", effective_approve_proxy_region(req), "confirm requires approval")
1080
+ result = chatgpt_approve(chatgpt, cs_id, checkout, approve_proxy=approve_stage_proxy(req))
1081
+ if diagnostics is not None:
1082
+ add_diagnostic(diagnostics, "approve", "ok", effective_approve_proxy_region(req), f"result={result}")
1083
+ add_diagnostic(diagnostics, "redirect_poll", "running", effective_approve_proxy_region(req), "waiting for provider redirect")
1084
+ return stripe_payment_page_redirect_url(
1085
+ stripe,
1086
+ cs_id,
1087
+ stripe_pk,
1088
+ req,
1089
+ timeout_seconds=redirect_poll_timeout(req, 45),
1090
+ )
1091
+ if diagnostics is not None:
1092
+ state = submission.get("state") if isinstance(submission, dict) else ""
1093
+ add_diagnostic(diagnostics, "redirect_poll", "running", effective_approve_proxy_region(req), f"confirm state={state or 'unknown'}")
1094
+ return stripe_payment_page_redirect_url(
1095
+ stripe,
1096
+ cs_id,
1097
+ stripe_pk,
1098
+ req,
1099
+ timeout_seconds=redirect_poll_timeout(req, 30),
1100
+ )
1101
+
1102
+
1103
+ def resolve_external_redirect(stripe: Any, redirect_url: str, preferred_hosts: tuple[str, ...] = (), max_hops: int = 5) -> str:
1104
+ current = str(redirect_url or "").strip()
1105
+ preferred = tuple(host.lower().lstrip(".") for host in preferred_hosts if host)
1106
+ for _ in range(max(1, int(max_hops or 1))):
1107
+ if not current:
1108
+ return ""
1109
+ host = (urlsplit(current).netloc or "").lower()
1110
+ if preferred and any(host == item or host.endswith(f".{item}") for item in preferred):
1111
+ return current
1112
+ try:
1113
+ response = stripe.get(current, allow_redirects=False, timeout=DEFAULT_TIMEOUT)
1114
+ except Exception:
1115
+ return current
1116
+ if response.status_code not in (301, 302, 303, 307, 308):
1117
+ return current
1118
+ location = str(response.headers.get("Location") or "").strip()
1119
+ if not location:
1120
+ return current
1121
+ current = urljoin(current, location)
1122
+ return current
1123
+
1124
+
1125
+ def create_provider_link(
1126
+ chatgpt: Any,
1127
+ checkout: dict[str, Any],
1128
+ init_payload: dict[str, Any],
1129
+ stripe_hosted_url: str,
1130
+ req: LongLinkRequest,
1131
+ provider_proxy: str = "",
1132
+ diagnostics: list[dict[str, Any]] | None = None,
1133
+ ) -> dict[str, str]:
1134
+ link_type = normalize_link_type(req.link_type)
1135
+ stripe_pk = req.stripe_publishable_key.strip() or DEFAULT_STRIPE_PK
1136
+ stripe = build_stripe_session(req, proxy_override=provider_proxy)
1137
+ ctx = stripe_context(checkout["cs_id"], init_payload, req)
1138
+ billing = billing_for_link_type(link_type, checkout["billing_country"])
1139
+ provider_region = effective_approve_proxy_region(req) if link_type == "paypal" else checkout["billing_country"]
1140
+ if diagnostics is not None:
1141
+ add_diagnostic(diagnostics, "pm_create", "running", provider_region, f"type={link_type}, billing={billing.get('country') or '-'}")
1142
+ pm_id = stripe_create_payment_method(stripe, checkout["cs_id"], stripe_pk, billing, link_type, ctx)
1143
+ if diagnostics is not None:
1144
+ add_diagnostic(diagnostics, "pm_create", "ok", provider_region, f"payment_method={short_id(pm_id)}")
1145
+ confirm_payload = stripe_confirm(
1146
+ stripe,
1147
+ checkout["cs_id"],
1148
+ pm_id,
1149
+ stripe_pk,
1150
+ link_type,
1151
+ init_payload,
1152
+ ctx,
1153
+ checkout,
1154
+ req,
1155
+ stripe_hosted_url,
1156
+ )
1157
+ if diagnostics is not None:
1158
+ submission = confirm_payload.get("submission_attempt") if isinstance(confirm_payload, dict) else None
1159
+ state = submission.get("state") if isinstance(submission, dict) else ""
1160
+ redirect_state = "has_redirect" if extract_redirect_to_url(confirm_payload) else "no_redirect"
1161
+ add_diagnostic(diagnostics, "confirm", "ok", provider_region, f"state={state or 'unknown'}, {redirect_state}")
1162
+ stripe_redirect_url = redirect_url_after_confirm(
1163
+ chatgpt,
1164
+ stripe,
1165
+ confirm_payload,
1166
+ checkout["cs_id"],
1167
+ stripe_pk,
1168
+ checkout,
1169
+ req,
1170
+ diagnostics=diagnostics,
1171
+ )
1172
+ if diagnostics is not None:
1173
+ add_diagnostic(diagnostics, "stripe_redirect", "ok", provider_region, "stripe redirect resolved")
1174
+ preferred_hosts = ("paypal.com",) if link_type == "paypal" else ()
1175
+ provider_url = resolve_external_redirect(stripe, stripe_redirect_url, preferred_hosts=preferred_hosts)
1176
+ if diagnostics is not None:
1177
+ host = urlsplit(provider_url or stripe_redirect_url).netloc or "-"
1178
+ status = "ok" if provider_url else "failed"
1179
+ add_diagnostic(diagnostics, "provider_redirect", status, provider_region, f"host={host}")
1180
+ return {
1181
+ "payment_method_id": pm_id,
1182
+ "stripe_redirect_url": stripe_redirect_url,
1183
+ "provider_redirect_url": provider_url,
1184
+ "long_url": provider_url or stripe_redirect_url,
1185
+ }
1186
+
1187
+
1188
+ app = FastAPI(title="OpenAI Pay Long Link")
1189
+ app.mount("/public", StaticFiles(directory=PUBLIC_DIR), name="public")
1190
+
1191
+
1192
+ @app.get("/")
1193
+ def index() -> FileResponse:
1194
+ return FileResponse(PUBLIC_DIR / "index.html")
1195
+
1196
+
1197
+ @app.get("/api/health")
1198
+ def health() -> dict[str, bool]:
1199
+ return {"ok": True}
1200
+
1201
+
1202
+ @app.post("/api/long-link", response_model=LongLinkResponse)
1203
+ def generate_long_link(req: LongLinkRequest) -> LongLinkResponse:
1204
+ link_type = normalize_link_type(req.link_type)
1205
+ diagnostics: list[dict[str, Any]] = []
1206
+ checkout_region = effective_country(req)
1207
+ checkout_proxy_region = effective_checkout_proxy_region(req)
1208
+ provider_region = effective_approve_proxy_region(req) if link_type == "paypal" else checkout_region
1209
+ currency = effective_currency(req, checkout_region)
1210
+ proxy_sid = materialize_request_proxy(req)
1211
+ if proxy_sid:
1212
+ add_diagnostic(diagnostics, "proxy", "ok", checkout_proxy_region, f"proxy sid rotated, suffix={proxy_sid[-4:]}")
1213
+ add_diagnostic(diagnostics, "session", "running", checkout_proxy_region, "prepare ChatGPT session")
1214
+ try:
1215
+ chatgpt = build_chatgpt_session(req)
1216
+ add_diagnostic(diagnostics, "session", "ok", checkout_proxy_region, "session headers ready")
1217
+ except HTTPException as exc:
1218
+ add_diagnostic(diagnostics, "session", "failed", checkout_proxy_region, exc.detail, exc.status_code)
1219
+ raise diagnostic_http_exception(exc, diagnostics) from exc
1220
+
1221
+ add_diagnostic(
1222
+ diagnostics,
1223
+ "checkout",
1224
+ "running",
1225
+ checkout_proxy_region,
1226
+ f"country={checkout_region}, currency={currency}, proxy={checkout_proxy_region}",
1227
+ )
1228
+ try:
1229
+ checkout = create_checkout(req, chatgpt)
1230
+ add_diagnostic(diagnostics, "checkout", "ok", checkout_proxy_region, f"cs_id={short_id(checkout.get('cs_id'))}")
1231
+ except HTTPException as exc:
1232
+ add_diagnostic(diagnostics, "checkout", "failed", checkout_proxy_region, exc.detail, exc.status_code)
1233
+ raise diagnostic_http_exception(exc, diagnostics) from exc
1234
+
1235
+ if not req.stripe_publishable_key.strip() and checkout.get("stripe_publishable_key"):
1236
+ req.stripe_publishable_key = checkout["stripe_publishable_key"]
1237
+ provider_proxy = provider_stage_proxy(req) if link_type in {"paypal", "gopay"} else ""
1238
+ add_diagnostic(diagnostics, "stripe_init", "running", provider_region, "request Stripe init")
1239
+ try:
1240
+ init_payload = stripe_init(checkout["cs_id"], req, proxy_override=provider_proxy)
1241
+ add_diagnostic(diagnostics, "stripe_init", "ok", provider_region, "Stripe init returned payload")
1242
+ except HTTPException as exc:
1243
+ add_diagnostic(diagnostics, "stripe_init", "failed", provider_region, exc.detail, exc.status_code)
1244
+ raise diagnostic_http_exception(exc, diagnostics) from exc
1245
+
1246
+ stripe_hosted_url = str(init_payload.get("stripe_hosted_url") or "").strip()
1247
+ if not stripe_hosted_url:
1248
+ exc = HTTPException(
1249
+ status_code=502,
1250
+ detail=f"stripe init response missing stripe_hosted_url, keys={sorted(init_payload.keys())}",
1251
+ )
1252
+ add_diagnostic(diagnostics, "stripe_init", "failed", provider_region, exc.detail, exc.status_code)
1253
+ raise diagnostic_http_exception(exc, diagnostics) from exc
1254
+ hosted_long_url = to_openai_pay_url(stripe_hosted_url)
1255
+ add_diagnostic(diagnostics, "hosted_url", "ok", checkout_region, "hosted checkout URL ready")
1256
+ provider = {
1257
+ "payment_method_id": "",
1258
+ "stripe_redirect_url": "",
1259
+ "provider_redirect_url": "",
1260
+ "long_url": hosted_long_url,
1261
+ }
1262
+ fallback = False
1263
+ provider_error = ""
1264
+ if link_type in {"paypal", "gopay"}:
1265
+ try:
1266
+ provider = create_provider_link(
1267
+ chatgpt,
1268
+ checkout,
1269
+ init_payload,
1270
+ stripe_hosted_url,
1271
+ req,
1272
+ provider_proxy=provider_proxy,
1273
+ diagnostics=diagnostics,
1274
+ )
1275
+ except HTTPException as exc:
1276
+ fallback = True
1277
+ provider_error = safe_excerpt(exc.detail)
1278
+ add_diagnostic(diagnostics, "provider_link", "failed", provider_region, exc.detail, exc.status_code)
1279
+ except Exception as exc:
1280
+ fallback = True
1281
+ provider_error = safe_excerpt(exc)
1282
+ add_diagnostic(diagnostics, "provider_link", "failed", provider_region, exc)
1283
+
1284
+ return LongLinkResponse(
1285
+ ok=True,
1286
+ cs_id=checkout["cs_id"],
1287
+ processor_entity=checkout["processor_entity"],
1288
+ billing_country=checkout["billing_country"],
1289
+ currency=checkout["currency"],
1290
+ payment_locale=locale_parts(effective_payment_locale(req))[0],
1291
+ link_type=link_type,
1292
+ payment_method_type=link_type if link_type in {"paypal", "gopay"} else "",
1293
+ payment_method_id=provider["payment_method_id"],
1294
+ stripe_redirect_url=provider["stripe_redirect_url"],
1295
+ provider_redirect_url=provider["provider_redirect_url"],
1296
+ fallback=fallback,
1297
+ provider_error=provider_error,
1298
+ stripe_hosted_url=stripe_hosted_url,
1299
+ long_url=provider["long_url"] or hosted_long_url,
1300
+ approve_proxy_region=effective_approve_proxy_region(req),
1301
+ diagnostics=diagnostics,
1302
+ )
docker-compose.yml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ openai-pay-long-link:
3
+ build: .
4
+ container_name: openai-pay-long-link
5
+ restart: unless-stopped
6
+ ports:
7
+ - "8787:8787"
8
+ healthcheck:
9
+ test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8787/api/health', timeout=5).read()"]
10
+ interval: 30s
11
+ timeout: 10s
12
+ retries: 3
13
+ start_period: 10s
public/index.html ADDED
@@ -0,0 +1,1315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>小鸡毛の公益支付长链生成器</title>
7
+ <style>
8
+ :root {
9
+ color-scheme: light;
10
+ --ink: #101827;
11
+ --muted: #667085;
12
+ --line: rgba(148, 163, 184, 0.28);
13
+ --line-strong: rgba(148, 163, 184, 0.42);
14
+ --panel: rgba(255, 255, 255, 0.72);
15
+ --panel-solid: #ffffff;
16
+ --soft: rgba(255, 255, 255, 0.58);
17
+ --navy: #111827;
18
+ --navy-2: #1f2937;
19
+ --accent: #7c3aed;
20
+ --accent-2: #06b6d4;
21
+ --warn-bg: rgba(255, 249, 219, 0.78);
22
+ --warn-line: rgba(250, 204, 21, 0.45);
23
+ --ok: #16a34a;
24
+ --bad: #dc2626;
25
+ --shadow: 0 26px 80px rgba(31, 41, 55, 0.14);
26
+ }
27
+
28
+ * { box-sizing: border-box; }
29
+
30
+ body {
31
+ margin: 0;
32
+ min-height: 100vh;
33
+ color: var(--ink);
34
+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif;
35
+ font-size: 14px;
36
+ background:
37
+ radial-gradient(circle at 14% 10%, rgba(125, 211, 252, 0.62), transparent 32%),
38
+ radial-gradient(circle at 86% 0%, rgba(249, 168, 212, 0.62), transparent 38%),
39
+ radial-gradient(circle at 66% 68%, rgba(216, 180, 254, 0.42), transparent 36%),
40
+ linear-gradient(135deg, #d8f3ff 0%, #f8fbff 44%, #ffe2f2 100%);
41
+ background-attachment: fixed;
42
+ }
43
+
44
+ button, input, select, textarea { font: inherit; }
45
+
46
+ button, a.button {
47
+ display: inline-flex;
48
+ align-items: center;
49
+ justify-content: center;
50
+ min-height: 42px;
51
+ border: 1px solid rgba(255, 255, 255, 0.62);
52
+ border-radius: 16px;
53
+ padding: 0 18px;
54
+ background: rgba(255, 255, 255, 0.76);
55
+ color: #111827;
56
+ font-weight: 900;
57
+ text-decoration: none;
58
+ cursor: pointer;
59
+ white-space: nowrap;
60
+ box-shadow: 0 10px 28px rgba(15, 23, 42, 0.08);
61
+ transition: transform 160ms ease, box-shadow 160ms ease, background 160ms ease;
62
+ }
63
+
64
+ button:hover, a.button:hover {
65
+ background: rgba(255, 255, 255, 0.94);
66
+ box-shadow: 0 16px 34px rgba(15, 23, 42, 0.12);
67
+ transform: translateY(-1px);
68
+ }
69
+
70
+ button.primary, a.button.primary {
71
+ border-color: var(--navy);
72
+ background: var(--navy);
73
+ color: #fff;
74
+ }
75
+
76
+ button.primary:hover, a.button.primary:hover { background: var(--navy-2); }
77
+ button:disabled, a.button.disabled { pointer-events: none; opacity: 0.58; cursor: wait; transform: none; }
78
+
79
+ .page {
80
+ width: min(1560px, calc(100vw - 32px));
81
+ margin: 34px auto 72px;
82
+ position: relative;
83
+ }
84
+
85
+ .shell {
86
+ border: 1px solid rgba(255, 255, 255, 0.74);
87
+ border-radius: 28px;
88
+ background: var(--panel);
89
+ box-shadow: var(--shadow);
90
+ backdrop-filter: blur(22px);
91
+ padding: 28px;
92
+ position: relative;
93
+ overflow: hidden;
94
+ }
95
+
96
+ .top-nav {
97
+ display: inline-flex;
98
+ align-items: center;
99
+ gap: 8px;
100
+ padding: 8px;
101
+ border-radius: 26px;
102
+ background: rgba(255, 255, 255, 0.7);
103
+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.76), 0 12px 32px rgba(15, 23, 42, 0.08);
104
+ }
105
+
106
+ .nav-item {
107
+ min-height: 36px;
108
+ border-radius: 20px;
109
+ padding: 0 17px;
110
+ display: inline-flex;
111
+ align-items: center;
112
+ color: #334155;
113
+ font-weight: 900;
114
+ }
115
+
116
+ .nav-item.active {
117
+ background: #111827;
118
+ color: #fff;
119
+ }
120
+
121
+ .hero {
122
+ padding: 26px 0 18px;
123
+ }
124
+
125
+ .title-row {
126
+ display: flex;
127
+ align-items: center;
128
+ gap: 16px;
129
+ flex-wrap: wrap;
130
+ }
131
+
132
+ .brand-mark {
133
+ width: 42px;
134
+ height: 42px;
135
+ border: 3px solid #111827;
136
+ border-radius: 50%;
137
+ display: grid;
138
+ place-items: center;
139
+ font-size: 24px;
140
+ font-weight: 950;
141
+ line-height: 1;
142
+ }
143
+
144
+ h1 {
145
+ margin: 0;
146
+ font-size: clamp(34px, 5vw, 48px);
147
+ line-height: 1.08;
148
+ letter-spacing: 0;
149
+ font-weight: 950;
150
+ }
151
+
152
+ .update-pill {
153
+ width: fit-content;
154
+ max-width: 100%;
155
+ margin-top: 14px;
156
+ padding: 9px 16px;
157
+ border-radius: 999px;
158
+ background: rgba(255, 255, 255, 0.76);
159
+ color: #334155;
160
+ font-size: 13px;
161
+ box-shadow: 0 10px 26px rgba(15, 23, 42, 0.06);
162
+ }
163
+
164
+ .privacy {
165
+ margin: 16px 0 20px;
166
+ padding: 15px 17px;
167
+ border: 1px solid var(--warn-line);
168
+ border-radius: 18px;
169
+ background: var(--warn-bg);
170
+ color: #6b4f00;
171
+ line-height: 1.65;
172
+ }
173
+
174
+ .stats {
175
+ display: grid;
176
+ grid-template-columns: repeat(3, 104px);
177
+ justify-content: end;
178
+ gap: 10px;
179
+ margin: -4px 0 18px;
180
+ z-index: 5;
181
+ }
182
+
183
+ .stat {
184
+ width: 104px;
185
+ min-height: 52px;
186
+ padding: 10px 13px;
187
+ border: 1px solid rgba(255, 255, 255, 0.68);
188
+ border-radius: 17px;
189
+ background: rgba(255, 255, 255, 0.66);
190
+ box-shadow: 0 16px 34px rgba(15, 23, 42, 0.11);
191
+ backdrop-filter: blur(16px);
192
+ }
193
+
194
+ .stat-label {
195
+ color: #667085;
196
+ font-size: 11px;
197
+ font-weight: 800;
198
+ }
199
+
200
+ .stat-value {
201
+ margin-top: 4px;
202
+ font-size: 16px;
203
+ font-weight: 950;
204
+ }
205
+
206
+ .card {
207
+ background: rgba(255, 255, 255, 0.68);
208
+ border: 1px solid rgba(255, 255, 255, 0.72);
209
+ border-radius: 22px;
210
+ box-shadow: 0 18px 48px rgba(15, 23, 42, 0.08);
211
+ }
212
+
213
+ .main-form {
214
+ display: grid;
215
+ gap: 20px;
216
+ min-width: 0;
217
+ }
218
+
219
+ .layout-grid {
220
+ display: grid;
221
+ grid-template-columns: minmax(560px, 0.98fr) minmax(480px, 0.72fr);
222
+ gap: 20px;
223
+ align-items: start;
224
+ }
225
+
226
+ .field-row {
227
+ display: flex;
228
+ align-items: center;
229
+ justify-content: space-between;
230
+ gap: 12px;
231
+ margin-bottom: 10px;
232
+ }
233
+
234
+ label, .field-label {
235
+ display: block;
236
+ color: #111827;
237
+ font-size: 15px;
238
+ font-weight: 950;
239
+ }
240
+
241
+ .hint, .token-meta {
242
+ color: var(--muted);
243
+ font-size: 12px;
244
+ line-height: 1.45;
245
+ }
246
+
247
+ textarea, input, select {
248
+ width: 100%;
249
+ min-height: 46px;
250
+ border: 1px solid rgba(226, 232, 240, 0.86);
251
+ border-radius: 18px;
252
+ background: rgba(255, 255, 255, 0.78);
253
+ color: var(--ink);
254
+ padding: 12px 15px;
255
+ outline: none;
256
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8);
257
+ }
258
+
259
+ textarea {
260
+ min-height: 210px;
261
+ resize: vertical;
262
+ font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
263
+ font-size: 12.5px;
264
+ line-height: 1.6;
265
+ }
266
+
267
+ textarea:focus, input:focus, select:focus {
268
+ border-color: rgba(124, 58, 237, 0.42);
269
+ box-shadow: 0 0 0 4px rgba(124, 58, 237, 0.12);
270
+ }
271
+
272
+ .config-grid {
273
+ display: grid;
274
+ grid-template-columns: repeat(2, minmax(0, 1fr));
275
+ gap: 18px 20px;
276
+ }
277
+
278
+ .wide { grid-column: 1 / -1; }
279
+
280
+ .toolbar {
281
+ display: flex;
282
+ align-items: center;
283
+ justify-content: space-between;
284
+ gap: 12px;
285
+ flex-wrap: wrap;
286
+ }
287
+
288
+ .action-left, .action-right, .result-actions, .log-actions {
289
+ display: flex;
290
+ align-items: center;
291
+ gap: 10px;
292
+ flex-wrap: wrap;
293
+ }
294
+
295
+ .result-card .card-head {
296
+ align-items: flex-start;
297
+ flex-direction: column;
298
+ }
299
+
300
+ .result-actions {
301
+ margin-top: 4px;
302
+ }
303
+
304
+ .result-actions button,
305
+ .result-actions a.button {
306
+ min-height: 58px;
307
+ border: 0;
308
+ border-radius: 19px;
309
+ padding: 0 28px;
310
+ background: linear-gradient(135deg, #5b5ff4, #7c3aed);
311
+ color: #fff;
312
+ box-shadow: 0 18px 42px rgba(124, 58, 237, 0.28);
313
+ font-size: 16px;
314
+ }
315
+
316
+ .status-text {
317
+ min-height: 42px;
318
+ display: inline-flex;
319
+ align-items: center;
320
+ border-radius: 16px;
321
+ padding: 0 16px;
322
+ background: rgba(255, 255, 255, 0.72);
323
+ color: #475467;
324
+ font-weight: 850;
325
+ }
326
+
327
+ .status-text.error {
328
+ color: var(--bad);
329
+ background: rgba(254, 242, 242, 0.86);
330
+ }
331
+
332
+ details {
333
+ border-radius: 20px;
334
+ background: rgba(255, 255, 255, 0.54);
335
+ border: 1px solid rgba(255, 255, 255, 0.7);
336
+ }
337
+
338
+ summary {
339
+ cursor: pointer;
340
+ padding: 15px 17px;
341
+ font-weight: 950;
342
+ color: #1f2937;
343
+ }
344
+
345
+ .advanced-grid {
346
+ display: grid;
347
+ grid-template-columns: repeat(3, minmax(0, 1fr));
348
+ gap: 16px;
349
+ padding: 0 17px 17px;
350
+ }
351
+
352
+ .checkline {
353
+ min-height: 46px;
354
+ display: flex;
355
+ align-items: center;
356
+ gap: 10px;
357
+ padding: 12px 15px;
358
+ border: 1px solid rgba(226, 232, 240, 0.86);
359
+ border-radius: 18px;
360
+ background: rgba(255, 255, 255, 0.78);
361
+ font-size: 13px;
362
+ font-weight: 850;
363
+ }
364
+
365
+ .checkline input {
366
+ width: auto;
367
+ min-height: auto;
368
+ padding: 0;
369
+ box-shadow: none;
370
+ }
371
+
372
+ .progress-card {
373
+ padding: 18px;
374
+ }
375
+
376
+ .progress-head {
377
+ display: flex;
378
+ align-items: center;
379
+ justify-content: space-between;
380
+ gap: 12px;
381
+ }
382
+
383
+ .progress-title {
384
+ margin: 0;
385
+ font-size: 18px;
386
+ font-weight: 950;
387
+ }
388
+
389
+ .progress-percent {
390
+ font-size: 26px;
391
+ line-height: 1;
392
+ font-weight: 950;
393
+ color: #111827;
394
+ }
395
+
396
+ .progress-track {
397
+ height: 12px;
398
+ margin: 16px 0 14px;
399
+ border-radius: 999px;
400
+ background: rgba(226, 232, 240, 0.78);
401
+ overflow: hidden;
402
+ }
403
+
404
+ .progress-fill {
405
+ width: 0%;
406
+ height: 100%;
407
+ border-radius: inherit;
408
+ background: linear-gradient(90deg, #06b6d4, #7c3aed, #db2777);
409
+ transition: width 320ms ease;
410
+ }
411
+
412
+ .progress-card.error .progress-fill {
413
+ background: linear-gradient(90deg, #fb7185, #dc2626);
414
+ }
415
+
416
+ .steps {
417
+ display: grid;
418
+ grid-template-columns: repeat(5, minmax(0, 1fr));
419
+ gap: 8px;
420
+ }
421
+
422
+ .step {
423
+ min-height: 34px;
424
+ border-radius: 999px;
425
+ display: inline-flex;
426
+ align-items: center;
427
+ justify-content: center;
428
+ padding: 0 10px;
429
+ background: rgba(255, 255, 255, 0.62);
430
+ color: #667085;
431
+ font-size: 12px;
432
+ font-weight: 900;
433
+ text-align: center;
434
+ }
435
+
436
+ .step.active {
437
+ background: #111827;
438
+ color: #fff;
439
+ }
440
+
441
+ .step.done {
442
+ background: rgba(22, 163, 74, 0.14);
443
+ color: #166534;
444
+ }
445
+
446
+ .below-grid {
447
+ display: grid;
448
+ grid-template-columns: 1fr;
449
+ gap: 18px;
450
+ min-width: 0;
451
+ }
452
+
453
+ .card-head {
454
+ padding: 18px 20px;
455
+ display: flex;
456
+ align-items: center;
457
+ justify-content: space-between;
458
+ gap: 12px;
459
+ border-bottom: 1px solid rgba(226, 232, 240, 0.62);
460
+ }
461
+
462
+ .card-title {
463
+ margin: 0;
464
+ font-size: 18px;
465
+ line-height: 1.2;
466
+ font-weight: 950;
467
+ }
468
+
469
+ .card-subtitle {
470
+ margin-top: 4px;
471
+ color: var(--muted);
472
+ font-size: 12px;
473
+ }
474
+
475
+ .card-body {
476
+ padding: 18px 20px 20px;
477
+ display: grid;
478
+ gap: 14px;
479
+ }
480
+
481
+ .log-table-wrap {
482
+ height: 430px;
483
+ overflow: auto;
484
+ background: rgba(17, 24, 39, 0.94);
485
+ border-radius: 0 0 22px 22px;
486
+ }
487
+
488
+ table {
489
+ width: 100%;
490
+ border-collapse: collapse;
491
+ table-layout: fixed;
492
+ }
493
+
494
+ th, td {
495
+ padding: 9px 11px;
496
+ border-bottom: 1px solid rgba(71, 85, 105, 0.48);
497
+ vertical-align: top;
498
+ }
499
+
500
+ th {
501
+ position: sticky;
502
+ top: 0;
503
+ z-index: 2;
504
+ background: #111827;
505
+ color: #dbeafe;
506
+ text-align: left;
507
+ font-size: 12px;
508
+ }
509
+
510
+ td {
511
+ color: #dbeafe;
512
+ font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
513
+ font-size: 12.5px;
514
+ line-height: 1.35;
515
+ }
516
+
517
+ .col-time { width: 88px; }
518
+ .col-level { width: 64px; }
519
+ .col-message { width: auto; }
520
+ .col-stage { width: 96px; }
521
+ .col-status { width: 72px; }
522
+ .col-cost { width: 62px; }
523
+ .level { color: #93c5fd; font-weight: 950; }
524
+ .ok { color: #4ade80; font-weight: 950; }
525
+ .bad { color: #fca5a5; font-weight: 950; }
526
+ .muted-cell { color: #9ca3af; }
527
+ .final-row td { background: rgba(22, 163, 74, 0.16); }
528
+
529
+ code {
530
+ display: block;
531
+ min-height: 42px;
532
+ padding: 12px;
533
+ border: 1px solid rgba(226, 232, 240, 0.86);
534
+ border-radius: 16px;
535
+ background: rgba(241, 245, 249, 0.86);
536
+ color: #101827;
537
+ overflow-wrap: anywhere;
538
+ font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
539
+ line-height: 1.5;
540
+ }
541
+
542
+ .result-label {
543
+ margin: 8px 0 9px;
544
+ color: #111827;
545
+ font-size: 16px;
546
+ font-weight: 950;
547
+ }
548
+
549
+ .raw-result {
550
+ margin-top: 4px;
551
+ background: rgba(255, 255, 255, 0.42);
552
+ }
553
+
554
+ .raw-result-body {
555
+ display: grid;
556
+ gap: 14px;
557
+ padding: 0 17px 17px;
558
+ }
559
+
560
+ .dot {
561
+ width: 8px;
562
+ height: 8px;
563
+ border-radius: 50%;
564
+ background: var(--ok);
565
+ display: inline-block;
566
+ }
567
+
568
+ .dot.idle { background: #94a3b8; }
569
+ .dot.error { background: var(--bad); }
570
+ .success-num { color: var(--ok); }
571
+ .fail-num { color: var(--bad); }
572
+
573
+ @media (max-width: 1180px) {
574
+ .stats {
575
+ grid-template-columns: repeat(3, minmax(0, 1fr));
576
+ margin: 14px 0 0;
577
+ }
578
+ .stat { width: auto; }
579
+ .layout-grid { grid-template-columns: 1fr; }
580
+ .below-grid { grid-template-columns: 1fr; }
581
+ }
582
+
583
+ @media (max-width: 760px) {
584
+ .page { width: calc(100vw - 18px); margin-top: 12px; }
585
+ .shell { padding: 18px; border-radius: 22px; }
586
+ .config-grid, .advanced-grid, .steps { grid-template-columns: 1fr; }
587
+ .card-head, .field-row, .progress-head { align-items: flex-start; flex-direction: column; }
588
+ .col-stage, .col-cost { display: none; }
589
+ h1 { font-size: 32px; }
590
+ }
591
+ </style>
592
+ </head>
593
+ <body>
594
+ <div class="page">
595
+ <section class="shell">
596
+ <nav class="top-nav" aria-label="功能导航">
597
+ <span class="nav-item active">转长链</span>
598
+ <span class="nav-item">转CPA文件</span>
599
+ <span class="nav-item">接码</span>
600
+ </nav>
601
+
602
+ <header class="hero">
603
+ <div class="title-row">
604
+ <div class="brand-mark" aria-hidden="true">⌁</div>
605
+ <h1>小鸡毛の公益支付长链生成器</h1>
606
+ </div>
607
+ <div class="update-pill">6月8日更新:已支持邮箱注册的 GPT 账户跳过 Stripe 支付页提取日区 PP 链功能</div>
608
+ </header>
609
+
610
+ <div class="privacy">
611
+ 隐私说明:本工具不在服务端保存 token、代理或生成结果;代理仅保存在用户自己的浏览器 localStorage;页面统计仅保存本次浏览器会话数字。
612
+ </div>
613
+
614
+ <div class="stats" aria-label="运行统计">
615
+ <div class="stat">
616
+ <div class="stat-label">在线人数</div>
617
+ <div class="stat-value" id="onlineCount">--</div>
618
+ </div>
619
+ <div class="stat">
620
+ <div class="stat-label">累计生成</div>
621
+ <div class="stat-value success-num" id="successCount">0</div>
622
+ </div>
623
+ <div class="stat">
624
+ <div class="stat-label">失败次数</div>
625
+ <div class="stat-value fail-num" id="failCount">0</div>
626
+ </div>
627
+ </div>
628
+
629
+ <div class="layout-grid">
630
+ <section class="main-form">
631
+ <div>
632
+ <div class="field-row">
633
+ <label for="accessToken">Access Token 或 session JSON</label>
634
+ <button id="copySessionUrl" type="button">复制 Session 地址</button>
635
+ </div>
636
+ <textarea id="accessToken" autocomplete="off" spellcheck="false" placeholder="可粘贴 accessToken,或 https://chatgpt.com/api/auth/session 返回的整段 JSON"></textarea>
637
+ <div id="tokenMeta" class="token-meta">暂未识别 token。</div>
638
+ </div>
639
+
640
+ <div class="config-grid">
641
+ <div class="field">
642
+ <label for="linkType">链类型</label>
643
+ <select id="linkType">
644
+ <option value="hosted">支付长链</option>
645
+ <option value="paypal" selected>PP 链提取(美国账单)</option>
646
+ <option value="gopay">GoPay 链提取(印尼地址)</option>
647
+ </select>
648
+ </div>
649
+ <div class="field">
650
+ <label for="paymentLocale">支付页语言</label>
651
+ <select id="paymentLocale">
652
+ <option value="en" selected>英文</option>
653
+ <option value="zh-CN">简体中文</option>
654
+ <option value="zh-TW">繁体中文</option>
655
+ <option value="ja">日文</option>
656
+ <option value="ko">韩文</option>
657
+ <option value="de">德文</option>
658
+ <option value="fr">法文</option>
659
+ <option value="es">西文</option>
660
+ <option value="id">印尼文</option>
661
+ <option value="pt-BR">葡语</option>
662
+ </select>
663
+ <div class="hint">只影响支付页显示语言。</div>
664
+ </div>
665
+ <div class="field">
666
+ <label for="billingCountry">地区</label>
667
+ <select id="billingCountry"></select>
668
+ <div class="hint">选择地区后,币种会自动切换。</div>
669
+ </div>
670
+ <div class="field">
671
+ <label for="currency">币种</label>
672
+ <input id="currency" readonly />
673
+ <div class="hint">币种跟随地区自动填充。</div>
674
+ </div>
675
+ <div class="field wide">
676
+ <label for="proxy">生成/支付代理</label>
677
+ <input id="proxy" placeholder="自动选择默认线路,或填写 socks5h://user-region-US-sid-xxxx:pass@host:port" />
678
+ <div class="hint">PP 链推荐 US/USD、关闭 promo、US checkout/provider/approve,并自动轮换 sid。</div>
679
+ </div>
680
+ </div>
681
+
682
+ <details>
683
+ <summary>高级选项</summary>
684
+ <div class="advanced-grid">
685
+ <div>
686
+ <label for="pmBillingCountry">计费国家/地区</label>
687
+ <select id="pmBillingCountry"></select>
688
+ </div>
689
+ <div>
690
+ <label for="checkoutProxyRegion">Checkout 出口区域</label>
691
+ <select id="checkoutProxyRegion"></select>
692
+ </div>
693
+ <div>
694
+ <label for="approveProxyRegion">Approve 出口区域</label>
695
+ <select id="approveProxyRegion"></select>
696
+ </div>
697
+ <div>
698
+ <label for="redirectPollTimeout">PP 跳转轮询秒数</label>
699
+ <input id="redirectPollTimeout" type="number" min="5" max="300" step="5" value="120" />
700
+ </div>
701
+ <div>
702
+ <label for="rotateProxySid">代理 sid</label>
703
+ <label class="checkline"><input id="rotateProxySid" type="checkbox" checked /> 每次请求自动轮换</label>
704
+ </div>
705
+ <div>
706
+ <label for="usePromo">Promo</label>
707
+ <label class="checkline"><input id="usePromo" type="checkbox" /> 使用 promo code</label>
708
+ </div>
709
+ <div>
710
+ <label for="checkoutMode">支付页模式</label>
711
+ <select id="checkoutMode">
712
+ <option value="hosted" selected>hosted</option>
713
+ </select>
714
+ </div>
715
+ <div>
716
+ <label for="stripeKey">Stripe Publishable Key</label>
717
+ <input id="stripeKey" placeholder="留空使用 checkout 动态 key" />
718
+ </div>
719
+ <div>
720
+ <label for="deviceId">Device ID</label>
721
+ <input id="deviceId" placeholder="留空自动生成" />
722
+ </div>
723
+ <div>
724
+ <label for="userAgent">User Agent</label>
725
+ <input id="userAgent" placeholder="留空使用默认 Chrome UA" />
726
+ </div>
727
+ </div>
728
+ </details>
729
+
730
+ <div class="toolbar">
731
+ <div class="action-left">
732
+ <button id="generate" class="primary" type="button">提取 PP 链</button>
733
+ <button id="checkProxy" type="button">检测代理</button>
734
+ <button id="saveProxy" type="button">保存代理</button>
735
+ <button id="clearProxy" type="button">清除保存</button>
736
+ </div>
737
+ <div class="action-right">
738
+ <span id="status" class="status-text">等待开始</span>
739
+ </div>
740
+ </div>
741
+
742
+ <section class="card progress-card" id="progressCard">
743
+ <div class="progress-head">
744
+ <div>
745
+ <h2 class="progress-title">提取进度</h2>
746
+ <div class="hint" id="progressLabel">等待开始</div>
747
+ </div>
748
+ <div class="progress-percent" id="progressPercent">0%</div>
749
+ </div>
750
+ <div class="progress-track" aria-hidden="true">
751
+ <div class="progress-fill" id="progressFill"></div>
752
+ </div>
753
+ <div class="steps" id="progressSteps">
754
+ <span class="step">读取 Token</span>
755
+ <span class="step">检测代理</span>
756
+ <span class="step">OpenAI Checkout</span>
757
+ <span class="step">Stripe init</span>
758
+ <span class="step">重写长链</span>
759
+ </div>
760
+ </section>
761
+ </section>
762
+ <div class="below-grid">
763
+ <section class="card log-card">
764
+ <div class="card-head">
765
+ <div>
766
+ <h2 class="card-title">运行日志</h2>
767
+ <div class="card-subtitle">按阶段记录 checkout、Stripe/provider、approve 和 BA 链结果。</div>
768
+ </div>
769
+ <div class="log-actions">
770
+ <button id="clearLog" type="button">清空日志</button>
771
+ <button id="exportLog" type="button">导出日志</button>
772
+ </div>
773
+ </div>
774
+ <div class="log-table-wrap" id="logWrap">
775
+ <table>
776
+ <thead>
777
+ <tr>
778
+ <th class="col-time">时间</th>
779
+ <th class="col-level">级别</th>
780
+ <th class="col-message">消息</th>
781
+ <th class="col-stage">组合</th>
782
+ <th class="col-status">状态</th>
783
+ <th class="col-cost">耗时</th>
784
+ </tr>
785
+ </thead>
786
+ <tbody id="logBody"></tbody>
787
+ </table>
788
+ </div>
789
+ </section>
790
+
791
+ <section class="card result-card">
792
+ <div class="card-head">
793
+ <div>
794
+ <h2 class="card-title">生成结果</h2>
795
+ </div>
796
+ <div class="result-actions">
797
+ <a id="openLink" class="button primary disabled" target="_blank" rel="noopener">跳转PP链</a>
798
+ <button id="copy" type="button" disabled>复制PP链</button>
799
+ </div>
800
+ </div>
801
+ <div class="card-body">
802
+ <div>
803
+ <div class="result-label">PayPal支付链接</div>
804
+ <code id="longUrl">等待提取结果。</code>
805
+ </div>
806
+ <div>
807
+ <div class="result-label">CS ID / 地区 / 币种</div>
808
+ <code id="summary">-</code>
809
+ </div>
810
+ <div>
811
+ <div class="result-label">提取状态</div>
812
+ <code id="extractStatus">待机</code>
813
+ </div>
814
+ <details class="raw-result">
815
+ <summary>原始返回</summary>
816
+ <div class="raw-result-body">
817
+ <div>
818
+ <div class="result-label">Stripe Redirect URL</div>
819
+ <code id="stripeRedirectUrl">-</code>
820
+ </div>
821
+ <div>
822
+ <div class="result-label">原始 Stripe URL</div>
823
+ <code id="stripeUrl">-</code>
824
+ </div>
825
+ <code id="providerUrl" hidden>-</code>
826
+ </div>
827
+ </details>
828
+ </div>
829
+ </section>
830
+ </div>
831
+ </div>
832
+ </section>
833
+ </div>
834
+
835
+ <script>
836
+ const COUNTRIES = [
837
+ ["JP", "日本 JP", "JPY"], ["US", "美国 US", "USD"], ["ID", "印度尼西亚 ID", "IDR"], ["DE", "德国 DE", "EUR"],
838
+ ["FR", "法国 FR", "EUR"], ["GB", "英国 GB", "GBP"], ["CA", "加拿大 CA", "CAD"], ["AU", "澳大利亚 AU", "AUD"],
839
+ ["KR", "韩国 KR", "KRW"], ["SG", "新加坡 SG", "SGD"], ["HK", "中国香港 HK", "HKD"], ["TW", "中国台湾 TW", "TWD"],
840
+ ["IN", "印度 IN", "INR"], ["BR", "巴西 BR", "BRL"], ["MX", "墨西哥 MX", "MXN"], ["TH", "泰国 TH", "THB"],
841
+ ["MY", "马来西亚 MY", "MYR"], ["PH", "菲律宾 PH", "PHP"], ["VN", "越南 VN", "VND"], ["AE", "阿联酋 AE", "AED"],
842
+ ["CH", "瑞士 CH", "CHF"], ["SE", "瑞典 SE", "SEK"], ["NO", "挪威 NO", "NOK"], ["DK", "丹麦 DK", "DKK"],
843
+ ["PL", "波兰 PL", "PLN"], ["CZ", "捷克 CZ", "CZK"], ["NZ", "新西兰 NZ", "NZD"],
844
+ ];
845
+ const APPROVE_PROXY_REGIONS = [["JP", "JP"], ["US", "US"], ["DE", "DE"], ["GB", "GB"], ["CA", "CA"], ["AU", "AU"], ["SG", "SG"], ["HK", "HK"], ["TW", "TW"], ["KR", "KR"], ["ID", "ID"]];
846
+ const DEFAULT_COUNTRY_BY_TYPE = { hosted: "AU", paypal: "US", gopay: "ID" };
847
+ const PROGRESS_STAGES = [
848
+ { percent: 8, label: "读取 Token", text: "正在读取 Token" },
849
+ { percent: 20, label: "检测代理", text: "正在准备代理线路" },
850
+ { percent: 44, label: "OpenAI Checkout", text: "正在创建 OpenAI Checkout" },
851
+ { percent: 68, label: "Stripe init", text: "正在初始化 Stripe 支付页" },
852
+ { percent: 88, label: "重写长链", text: "正在提取并重写长链" },
853
+ ];
854
+ const $ = (id) => document.getElementById(id);
855
+ const generateButton = $("generate");
856
+ const copyButton = $("copy");
857
+ const openLink = $("openLink");
858
+ const statusLine = $("status");
859
+ const logBody = $("logBody");
860
+ const logWrap = $("logWrap");
861
+ let currentLongUrl = "";
862
+ let successCount = 0;
863
+ let failCount = 0;
864
+ let currentRunStart = 0;
865
+ let logRows = [];
866
+ let progressTimer = null;
867
+
868
+ function setStatus(text, isError) {
869
+ statusLine.textContent = text;
870
+ statusLine.classList.toggle("error", Boolean(isError));
871
+ }
872
+
873
+ function updateCounts() {
874
+ $("successCount").textContent = String(successCount);
875
+ $("failCount").textContent = String(failCount);
876
+ $("onlineCount").textContent = "1";
877
+ }
878
+
879
+ function setProgress(percent, label, activeIndex, mode) {
880
+ const bounded = Math.max(0, Math.min(100, Math.round(percent)));
881
+ $("progressPercent").textContent = bounded + "%";
882
+ $("progressFill").style.width = bounded + "%";
883
+ $("progressLabel").textContent = label;
884
+ $("progressCard").classList.toggle("error", mode === "error");
885
+ const steps = Array.from($("progressSteps").children);
886
+ steps.forEach(function (step, index) {
887
+ step.classList.toggle("done", index < activeIndex || bounded === 100);
888
+ step.classList.toggle("active", index === activeIndex && bounded < 100 && mode !== "error");
889
+ });
890
+ }
891
+
892
+ function startProgress() {
893
+ clearInterval(progressTimer);
894
+ setProgress(4, "准备开始", 0);
895
+ let index = 0;
896
+ progressTimer = setInterval(function () {
897
+ const stage = PROGRESS_STAGES[Math.min(index, PROGRESS_STAGES.length - 1)];
898
+ setProgress(stage.percent, stage.text, Math.min(index, PROGRESS_STAGES.length - 1));
899
+ if (index < PROGRESS_STAGES.length - 1) index += 1;
900
+ }, 950);
901
+ }
902
+
903
+ function finishProgress(success, label) {
904
+ clearInterval(progressTimer);
905
+ progressTimer = null;
906
+ setProgress(100, label || (success ? "提取完成" : "提取失败"), PROGRESS_STAGES.length - 1, success ? "ok" : "error");
907
+ }
908
+
909
+ function nowTime() {
910
+ const now = new Date();
911
+ return [now.getHours(), now.getMinutes(), now.getSeconds()].map(function (item) { return String(item).padStart(2, "0"); }).join(":");
912
+ }
913
+
914
+ function elapsedText() {
915
+ if (!currentRunStart) return "-";
916
+ return Math.max(0, Math.round((Date.now() - currentRunStart) / 1000)) + "s";
917
+ }
918
+
919
+ function escapeHtml(value) {
920
+ return String(value == null ? "" : value)
921
+ .replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
922
+ .replace(/"/g, "&quot;").replace(/'/g, "&#039;");
923
+ }
924
+
925
+ function statusHtml(status) {
926
+ if (status === "成功") return '<span class="ok">成功</span>';
927
+ if (status === "失败") return '<span class="bad">失败</span>';
928
+ return '<span class="muted-cell">' + escapeHtml(status || "-") + "</span>";
929
+ }
930
+
931
+ function addLog(message, status, stage, level) {
932
+ const row = { time: nowTime(), level: level || "INFO", message: message, stage: stage || "-", status: status || "-", cost: elapsedText() };
933
+ logRows.push(row);
934
+ const tr = document.createElement("tr");
935
+ if (message.indexOf("运行完成") >= 0) tr.className = "final-row";
936
+ tr.innerHTML =
937
+ '<td class="col-time">' + row.time + '</td>' +
938
+ '<td class="col-level"><span class="level">' + row.level + '</span></td>' +
939
+ '<td class="col-message">' + escapeHtml(row.message) + '</td>' +
940
+ '<td class="col-stage muted-cell">' + escapeHtml(row.stage) + '</td>' +
941
+ '<td class="col-status">' + statusHtml(row.status) + '</td>' +
942
+ '<td class="col-cost">' + row.cost + '</td>';
943
+ logBody.appendChild(tr);
944
+ logWrap.scrollTop = logWrap.scrollHeight;
945
+ }
946
+
947
+ function createJobId() {
948
+ if (window.crypto && typeof window.crypto.randomUUID === "function") return window.crypto.randomUUID();
949
+ return "job-" + Date.now() + "-" + Math.random().toString(16).slice(2);
950
+ }
951
+
952
+ function base64UrlDecode(value) {
953
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
954
+ const padded = normalized + "=".repeat((4 - (normalized.length % 4)) % 4);
955
+ return decodeURIComponent(atob(padded).split("").map(function (char) {
956
+ return "%" + ("00" + char.charCodeAt(0).toString(16)).slice(-2);
957
+ }).join(""));
958
+ }
959
+
960
+ function findToken(value) {
961
+ if (!value) return "";
962
+ if (typeof value === "string") return value.trim();
963
+ if (Array.isArray(value)) {
964
+ for (const item of value) {
965
+ const token = findToken(item);
966
+ if (token) return token;
967
+ }
968
+ }
969
+ if (typeof value === "object") {
970
+ for (const key of ["accessToken", "access_token", "token"]) {
971
+ if (typeof value[key] === "string" && value[key].trim()) return value[key].trim();
972
+ }
973
+ const values = Object.values(value);
974
+ for (const item of values) {
975
+ const token = findToken(item);
976
+ if (token) return token;
977
+ }
978
+ }
979
+ return "";
980
+ }
981
+
982
+ function readAccessTokenInput() {
983
+ const raw = $("accessToken").value.trim();
984
+ if (!raw) return "";
985
+ if (raw.startsWith("{") || raw.startsWith("[")) {
986
+ try { return findToken(JSON.parse(raw)) || raw; } catch (error) { return raw; }
987
+ }
988
+ return raw;
989
+ }
990
+
991
+ function updateTokenMeta() {
992
+ const token = readAccessTokenInput();
993
+ if (!token.includes(".")) {
994
+ $("tokenMeta").textContent = token ? "已输入内容,未识别 JWT 信息。" : "暂未识别 token。";
995
+ return;
996
+ }
997
+ try {
998
+ const payload = JSON.parse(base64UrlDecode(token.split(".")[1] || ""));
999
+ const profile = payload["https://api.openai.com/profile"] || {};
1000
+ const email = profile.email || payload.email || "";
1001
+ $("tokenMeta").textContent = email ? "已识别 token,可能关联邮箱:" + email : "已识别 token。";
1002
+ } catch (error) {
1003
+ $("tokenMeta").textContent = "已识别 JWT 格式,无法解析邮箱。";
1004
+ }
1005
+ }
1006
+
1007
+ function fillCountrySelect(selectId, selectedCode) {
1008
+ const select = $(selectId);
1009
+ select.innerHTML = "";
1010
+ for (const item of COUNTRIES) {
1011
+ const option = document.createElement("option");
1012
+ option.value = item[0];
1013
+ option.textContent = item[1];
1014
+ if (item[0] === selectedCode) option.selected = true;
1015
+ select.appendChild(option);
1016
+ }
1017
+ }
1018
+
1019
+ function fillApproveProxyRegions() {
1020
+ const select = $("approveProxyRegion");
1021
+ select.innerHTML = "";
1022
+ for (const item of APPROVE_PROXY_REGIONS) {
1023
+ const option = document.createElement("option");
1024
+ option.value = item[0];
1025
+ option.textContent = item[1];
1026
+ if (item[0] === "JP") option.selected = true;
1027
+ select.appendChild(option);
1028
+ }
1029
+ }
1030
+
1031
+ function countryCurrency(code) {
1032
+ const selected = COUNTRIES.find(function (item) { return item[0] === code; });
1033
+ return selected ? selected[2] : "USD";
1034
+ }
1035
+
1036
+ function updateProviderProxyPreview() {
1037
+ return;
1038
+ }
1039
+
1040
+ function updateCurrency() {
1041
+ $("currency").value = countryCurrency($("billingCountry").value);
1042
+ if ($("pmBillingCountry").value !== $("billingCountry").value) $("pmBillingCountry").value = $("billingCountry").value;
1043
+ updateProviderProxyPreview();
1044
+ }
1045
+
1046
+ function updateCountryForLinkType() {
1047
+ const linkType = $("linkType").value;
1048
+ const defaultCountry = DEFAULT_COUNTRY_BY_TYPE[linkType] || "AU";
1049
+ $("billingCountry").value = defaultCountry;
1050
+ $("pmBillingCountry").value = defaultCountry;
1051
+ $("checkoutProxyRegion").value = linkType === "paypal" ? "US" : defaultCountry;
1052
+ if (linkType === "gopay") $("approveProxyRegion").value = "ID";
1053
+ if (linkType === "paypal") $("approveProxyRegion").value = "US";
1054
+ $("redirectPollTimeout").value = linkType === "paypal" ? "120" : "90";
1055
+ $("rotateProxySid").checked = linkType === "paypal";
1056
+ $("usePromo").checked = false;
1057
+ updateCurrency();
1058
+ generateButton.textContent = linkType === "paypal" ? "提取 PP 链" : linkType === "gopay" ? "提取 GoPay 链" : "生成支付长链";
1059
+ }
1060
+
1061
+ function loadProxy() {
1062
+ const saved = localStorage.getItem("openai_pay_long_link_proxy") || "";
1063
+ $("proxy").value = saved;
1064
+ updateProviderProxyPreview();
1065
+ }
1066
+
1067
+ function setLinkEnabled(enabled) {
1068
+ copyButton.disabled = !enabled;
1069
+ openLink.classList.toggle("disabled", !enabled);
1070
+ openLink.href = enabled ? currentLongUrl : "";
1071
+ }
1072
+
1073
+ function resetResult() {
1074
+ currentLongUrl = "";
1075
+ setLinkEnabled(false);
1076
+ $("longUrl").textContent = "等待提取结果。";
1077
+ $("summary").textContent = "-";
1078
+ $("extractStatus").textContent = "运行中";
1079
+ $("providerUrl").textContent = "-";
1080
+ $("stripeRedirectUrl").textContent = "-";
1081
+ $("stripeUrl").textContent = "-";
1082
+ }
1083
+
1084
+ async function parseApiResponse(response) {
1085
+ const raw = await response.text();
1086
+ const contentType = response.headers.get("content-type") || "";
1087
+ if (raw && contentType.includes("application/json")) {
1088
+ try {
1089
+ return JSON.parse(raw);
1090
+ } catch (error) {
1091
+ return { detail: "接口返回了无法解析的 JSON:" + raw.slice(0, 300) };
1092
+ }
1093
+ }
1094
+ if (raw) {
1095
+ try {
1096
+ return JSON.parse(raw);
1097
+ } catch (error) {
1098
+ return { detail: "HTTP " + response.status + " " + response.statusText + ":" + raw.slice(0, 500) };
1099
+ }
1100
+ }
1101
+ return { detail: "HTTP " + response.status + " " + response.statusText };
1102
+ }
1103
+
1104
+ function detailMessage(value) {
1105
+ if (!value) return "";
1106
+ if (typeof value === "string") return value;
1107
+ if (typeof value === "object") {
1108
+ if (typeof value.message === "string") return value.message;
1109
+ if (typeof value.detail === "string") return value.detail;
1110
+ try {
1111
+ return JSON.stringify(value);
1112
+ } catch (error) {
1113
+ return String(value);
1114
+ }
1115
+ }
1116
+ return String(value);
1117
+ }
1118
+
1119
+ function diagnosticsFrom(payload) {
1120
+ if (!payload || typeof payload !== "object") return [];
1121
+ if (Array.isArray(payload.diagnostics)) return payload.diagnostics;
1122
+ if (payload.detail && typeof payload.detail === "object" && Array.isArray(payload.detail.diagnostics)) {
1123
+ return payload.detail.diagnostics;
1124
+ }
1125
+ return [];
1126
+ }
1127
+
1128
+ function renderDiagnostics(items) {
1129
+ items.forEach(function (item) {
1130
+ const stage = item && item.stage ? String(item.stage) : "-";
1131
+ const region = item && item.region ? String(item.region) : "-";
1132
+ const rawStatus = item && item.status ? String(item.status) : "-";
1133
+ const displayStatus = rawStatus === "ok" ? "成功" : rawStatus === "failed" ? "失败" : "-";
1134
+ const level = rawStatus === "failed" ? "ERROR" : rawStatus === "running" ? "INFO" : "INFO";
1135
+ const httpStatus = item && item.http_status ? " HTTP " + item.http_status : "";
1136
+ const message = "诊断 " + stage + httpStatus + ":" + detailMessage(item && item.message ? item.message : rawStatus);
1137
+ addLog(message, displayStatus, region, level);
1138
+ });
1139
+ }
1140
+
1141
+ async function generate() {
1142
+ const accessToken = readAccessTokenInput();
1143
+ if (!accessToken) {
1144
+ setStatus("Access Token 不能为空。", true);
1145
+ setProgress(0, "Access Token 不能为空", 0, "error");
1146
+ addLog("Access Token 不能为空。", "失败", "input", "ERROR");
1147
+ return;
1148
+ }
1149
+ currentRunStart = Date.now();
1150
+ generateButton.disabled = true;
1151
+ resetResult();
1152
+ startProgress();
1153
+ setStatus("正在提取链接...");
1154
+
1155
+ const region = $("billingCountry").value;
1156
+ const checkoutProxyRegion = $("checkoutProxyRegion").value;
1157
+ const approveRegion = $("approveProxyRegion").value;
1158
+ const providerRegion = approveRegion;
1159
+ const combo = checkoutProxyRegion + "+" + providerRegion;
1160
+ addLog("步骤 1 checkout 开始:" + checkoutProxyRegion + " 出口创建 " + region + "/" + $("currency").value + " checkout", "-", combo);
1161
+ addLog("步骤 2 Stripe init 等待:provider 切换 " + providerRegion + " 出口", "-", providerRegion);
1162
+ addLog("步骤 3 PM 创建等待:billing_details=" + $("pmBillingCountry").value, "-", providerRegion);
1163
+
1164
+ try {
1165
+ const currency = $("currency").value;
1166
+ const response = await fetch("/api/long-link", {
1167
+ method: "POST",
1168
+ headers: { "Content-Type": "application/json" },
1169
+ body: JSON.stringify({
1170
+ job_id: createJobId(),
1171
+ token: accessToken,
1172
+ accessToken: accessToken,
1173
+ plan: "plus",
1174
+ link_type: $("linkType").value,
1175
+ ui_language: $("paymentLocale").value,
1176
+ country: region,
1177
+ currency: currency,
1178
+ approve_proxy_mode: approveRegion.toLowerCase(),
1179
+ checkout_proxy_region: checkoutProxyRegion,
1180
+ proxy: $("proxy").value.trim(),
1181
+ default_proxy_id: "",
1182
+ stripe_proxy_id: "",
1183
+ stripe_proxy: "",
1184
+ rotate_proxy_sid: $("rotateProxySid").checked,
1185
+ redirect_poll_timeout_seconds: Number($("redirectPollTimeout").value) || 0,
1186
+ use_promo: $("usePromo").checked,
1187
+ skip_stripe_page: true,
1188
+ skip_cdk: "",
1189
+ promo_code: $("usePromo").checked ? "STRIPEATLASGPT4BIZ050126" : "",
1190
+ workspace_name: "linux-do",
1191
+ seat_quantity: 2,
1192
+ billing_country: region,
1193
+ approve_proxy_region: approveRegion,
1194
+ checkout_ui_mode: $("checkoutMode").value,
1195
+ payment_locale: $("paymentLocale").value,
1196
+ stripe_publishable_key: $("stripeKey").value.trim(),
1197
+ device_id: $("deviceId").value.trim(),
1198
+ user_agent: $("userAgent").value.trim(),
1199
+ }),
1200
+ });
1201
+ const data = await parseApiResponse(response);
1202
+ renderDiagnostics(diagnosticsFrom(data));
1203
+ if (!response.ok) throw new Error(detailMessage(data.detail) || "请求失败");
1204
+
1205
+ addLog("步骤 4 confirm 完成", data.fallback ? "-" : "成功", providerRegion);
1206
+ addLog("步骤 5 approve 完成:" + approveRegion + " 出口", data.fallback ? "-" : "成功", approveRegion);
1207
+ addLog("步骤 6 BA 链完成", data.long_url ? "成功" : "失败", providerRegion);
1208
+
1209
+ currentLongUrl = data.long_url || "";
1210
+ $("longUrl").textContent = currentLongUrl || "未返回长链。";
1211
+ $("summary").textContent = (data.cs_id || "-") + " / " + (data.billing_country || "-") + " / " + (data.currency || "-") + " / " + (data.link_type || $("linkType").value);
1212
+ $("extractStatus").textContent = data.fallback ? "已回退 hosted:" + (data.provider_error || "provider redirect 提取失败") : "OK";
1213
+ $("providerUrl").textContent = data.provider_redirect_url || "-";
1214
+ $("stripeRedirectUrl").textContent = data.stripe_redirect_url || "-";
1215
+ $("stripeUrl").textContent = data.stripe_hosted_url || "-";
1216
+ setLinkEnabled(Boolean(currentLongUrl));
1217
+
1218
+ if (data.long_url && !data.fallback) {
1219
+ successCount += 1;
1220
+ setStatus("提取完成。");
1221
+ finishProgress(true, "提取完成");
1222
+ addLog("运行完成:成功 1,失败 0,总计 1", "成功", "-");
1223
+ } else {
1224
+ failCount += 1;
1225
+ setStatus("提取完成,但未拿到最终 PP 链。", true);
1226
+ finishProgress(false, "未拿到最终 PP 链");
1227
+ addLog("运行完成:成功 0,失败 1,总计 1", "失败", "-", "WARN");
1228
+ }
1229
+ updateCounts();
1230
+ } catch (error) {
1231
+ failCount += 1;
1232
+ updateCounts();
1233
+ currentLongUrl = "";
1234
+ setLinkEnabled(false);
1235
+ $("extractStatus").textContent = error instanceof Error ? error.message : String(error);
1236
+ const message = error instanceof Error ? error.message : String(error);
1237
+ setStatus(message, true);
1238
+ finishProgress(false, message);
1239
+ addLog(message, "失败", "error", "ERROR");
1240
+ addLog("运行完成:成功 0,失败 1,总计 1", "失败", "-", "WARN");
1241
+ } finally {
1242
+ generateButton.disabled = false;
1243
+ }
1244
+ }
1245
+
1246
+ async function copyLink() {
1247
+ if (!currentLongUrl) return;
1248
+ await navigator.clipboard.writeText(currentLongUrl);
1249
+ setStatus("已复制长链。");
1250
+ addLog("长链已复制到剪贴板", "成功", "ui");
1251
+ }
1252
+
1253
+ function exportLog() {
1254
+ const text = logRows.map(function (row) {
1255
+ return [row.time, row.level, row.message, row.stage, row.status, row.cost].join("\t");
1256
+ }).join("\n");
1257
+ const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
1258
+ const link = document.createElement("a");
1259
+ link.href = URL.createObjectURL(blob);
1260
+ link.download = "pp-link-extractor-log-" + new Date().toISOString().slice(0, 10) + ".txt";
1261
+ link.click();
1262
+ URL.revokeObjectURL(link.href);
1263
+ }
1264
+
1265
+ fillCountrySelect("billingCountry", "US");
1266
+ fillCountrySelect("pmBillingCountry", "US");
1267
+ fillCountrySelect("checkoutProxyRegion", "US");
1268
+ fillApproveProxyRegions();
1269
+ loadProxy();
1270
+ updateCountryForLinkType();
1271
+ updateTokenMeta();
1272
+ updateCounts();
1273
+ setProgress(0, "等待开始", 0);
1274
+ addLog("系统就绪:默认 PP 链提取,US/USD 美国账单,US checkout/provider/approve,无 promo,自动轮换 sid", "-", "US+US");
1275
+
1276
+ $("accessToken").addEventListener("input", updateTokenMeta);
1277
+ $("billingCountry").addEventListener("change", updateCurrency);
1278
+ $("pmBillingCountry").addEventListener("change", function () { $("billingCountry").value = $("pmBillingCountry").value; updateCurrency(); });
1279
+ $("checkoutProxyRegion").addEventListener("change", updateProviderProxyPreview);
1280
+ $("linkType").addEventListener("change", updateCountryForLinkType);
1281
+ $("proxy").addEventListener("input", updateProviderProxyPreview);
1282
+ $("copySessionUrl").addEventListener("click", async function () {
1283
+ await navigator.clipboard.writeText("https://chatgpt.com/api/auth/session");
1284
+ setStatus("已复制 Session 地址。");
1285
+ });
1286
+ $("saveProxy").addEventListener("click", function () {
1287
+ localStorage.setItem("openai_pay_long_link_proxy", $("proxy").value.trim());
1288
+ setStatus("代理已保存在本机浏览器。");
1289
+ addLog("代理配置已保存", "成功", "ui");
1290
+ });
1291
+ $("clearProxy").addEventListener("click", function () {
1292
+ localStorage.removeItem("openai_pay_long_link_proxy");
1293
+ $("proxy").value = "";
1294
+ updateProviderProxyPreview();
1295
+ setStatus("已清除保存的代理。");
1296
+ addLog("已清除保存代理", "成功", "ui");
1297
+ });
1298
+ $("checkProxy").addEventListener("click", function () {
1299
+ updateProviderProxyPreview();
1300
+ const ok = Boolean($("proxy").value.trim());
1301
+ setStatus(ok ? "代理格式已填入,运行时检测出口。" : "未填写代理,将使用服务器默认线路。", false);
1302
+ addLog(ok ? "代理已填入:运行时检测出口" : "代理为空:使用默认线路", ok ? "成功" : "-", "proxy");
1303
+ setProgress(ok ? 20 : 12, ok ? "代理已填入" : "使用默认线路", 1);
1304
+ });
1305
+ $("clearLog").addEventListener("click", function () {
1306
+ logRows = [];
1307
+ logBody.innerHTML = "";
1308
+ addLog("日志已清空", "成功", "ui");
1309
+ });
1310
+ $("exportLog").addEventListener("click", exportLog);
1311
+ generateButton.addEventListener("click", generate);
1312
+ copyButton.addEventListener("click", copyLink);
1313
+ </script>
1314
+ </body>
1315
+ </html>
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi>=0.110.0
2
+ uvicorn>=0.29.0
3
+ requests>=2.31.0
4
+ curl_cffi>=0.6.0
5
+ pydantic>=2.0.0