File size: 125,025 Bytes
3ec0f02 a13850f 3ec0f02 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 | from __future__ import annotations
import base64
import hashlib
import hmac
import json
import os
import re
import secrets
import shutil
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path
from urllib.parse import quote, unquote, urlencode, urlparse, urlsplit
from urllib.request import Request, urlopen
from flask import Flask, jsonify, redirect, render_template, request
def _load_local_env() -> None:
"""Load local deployment values without overwriting process variables."""
for filename in (".env", ".env.local"):
path = Path(__file__).resolve().parent / filename
if not path.is_file():
continue
try:
lines = path.read_text(encoding="utf-8").splitlines()
except OSError:
continue
for raw in lines:
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
name, value = line.split("=", 1)
name = name.strip()
value = value.strip().strip('"').strip("'")
if name and name not in os.environ:
os.environ[name] = value
_load_local_env()
# Worker stdout is parsed as UTF-8 JSON. Force child interpreters away from
# the Windows console code page so currency symbols remain serializable.
os.environ["PYTHONIOENCODING"] = "utf-8"
os.environ["PYTHONUTF8"] = "1"
async def sentinel_headers(
proxy: str = "",
action: str = "",
device_id: str = "",
did: str = "",
) -> dict[str, str]:
"""Return deployment-provided Sentinel headers, if configured.
The sanitized bundle does not contain a Sentinel token provider. Keeping
the hook asynchronous preserves the protocol worker contract while letting
an upstream deployment inject its own provider without embedding tokens.
"""
return {}
ROOT = Path(__file__).resolve().parent
app = Flask(__name__, template_folder="templates", static_folder="static")
app.json.ensure_ascii = False
REG_SESSION_SECRET = os.getenv("REG_SESSION_SECRET", "").strip()
REG_SESSION_COOKIE = os.getenv("REG_SESSION_COOKIE", "reg_access").strip() or "reg_access"
REG_INTERNAL_BASE = os.getenv("REG_INTERNAL_BASE", "http://127.0.0.1:18081").strip().rstrip("/")
PH_SHORT_BRIDGE_KEY = os.getenv("PH_SHORT_BRIDGE_KEY", "").strip()
JOB_TTL_SECONDS = max(1800, int(os.getenv("PH_PORTAL_JOB_TTL", "86400")))
MAX_JOBS = max(20, min(500, int(os.getenv("PH_PORTAL_MAX_JOBS", "120"))))
HARD_MAX_BATCH_CONCURRENCY = 200
MAX_BATCH_CONCURRENCY = max(
1,
min(
HARD_MAX_BATCH_CONCURRENCY,
int(os.getenv("PH_PORTAL_MAX_BATCH_CONCURRENCY", str(HARD_MAX_BATCH_CONCURRENCY))),
),
)
FLOW_JOB_CACHE_LIMIT = max(100, MAX_BATCH_CONCURRENCY)
def _resolve_helper_python() -> str:
configured = os.getenv("PAY153_PYTHON", "").strip()
candidates = [configured] if configured else []
# The sanitized bundle is also run directly on Windows. Prefer the
# workspace environment when it contains the helper dependencies, then
# fall back to the bundle environment and the current interpreter.
candidates.extend([
"/opt/pay153/venv/bin/python",
str(ROOT / ".venv" / "Scripts" / "python.exe"),
str(ROOT / ".venv" / "bin" / "python"),
str(ROOT.parent / ".venv" / "Scripts" / "python.exe"),
str(ROOT.parent / ".venv" / "bin" / "python"),
sys.executable,
])
seen = set()
for candidate in candidates:
value = str(candidate or "").strip()
if not value or value in seen:
continue
seen.add(value)
if Path(value).is_file() or shutil.which(value):
return value
return configured or sys.executable
PAY153_PYTHON = _resolve_helper_python()
PAY153_INTERNAL_BASE = os.getenv("PAY153_INTERNAL_BASE", "http://127.0.0.1:18096").strip().rstrip("/")
PAY153_INTERNAL_KEY = os.getenv("PAY153_INTERNAL_KEY", "").strip()
# Stripe publishable keys are public client configuration. This value was
# confirmed from the successful local HAR and avoids requiring PAY153 merely
# to initialize Stripe.js after payment_method returned a SetupIntent.
CARD_BIND_PUBLISHABLE_KEY = os.getenv(
"CARD_BIND_PUBLISHABLE_KEY",
"pk_live_51HOrSwC6h1nxGoI3lTAgRjYVrz4dU3fVOabyCcKR3pbEJguCVAlqCxdxCUvoRh1XWwRacViovU3kLKvpkjh7IqkW00iXQsjo3n",
).strip()
CARD_BIND_PROXY_REUSE_ATTEMPTS = max(
1, min(10, int(os.getenv("CARD_BIND_PROXY_REUSE_ATTEMPTS", "3")))
)
SET_DEFAULT_HELPER_TIMEOUT_SECONDS = max(
30, min(900, int(os.getenv("SET_DEFAULT_HELPER_TIMEOUT_SECONDS", "360")))
)
PROTOCOL_HELPER = str(ROOT / "ph_checkout_protocol.py")
CARD_BIND_HELPER = str(ROOT / "card_bind_session.py")
CARD_DEFAULT_HELPER = str(ROOT / "card_set_default.py")
CARD_CHECKOUT_CONTEXT_HELPER = str(ROOT / "card_checkout_context.py")
CARD_SERVER_TOKEN_HELPER = str(ROOT / "server_confirmation_token.py")
STANDALONE_PAY_HELPER = str(ROOT / "standalone_protocol_pay.py")
LOCAL_CHECKOUT_HELPER = str(ROOT / "local_checkout_bridge.py")
CHECKOUT_CONTEXT_PATH = ROOT / "data" / "checkout_contexts.jsonl"
PROXY_PREFLIGHT_HELPER = str(ROOT / "proxy_preflight.py")
CARD_BIND_ACCOUNT_EMAIL = os.getenv("CARD_BIND_ACCOUNT_EMAIL", "gosulasathish7420@gmail.com").strip().lower()
_jobs: dict[str, dict] = {}
_protocol_pay_jobs: dict[str, dict] = {}
_card_checkout_jobs: dict[str, dict] = {}
_unified_flow_jobs: dict[str, dict] = {}
_key_probe_jobs: dict[str, dict] = {}
_lock = threading.RLock()
_external_at_lock = threading.Lock()
class PrefixMiddleware:
def __init__(self, wrapped):
self.wrapped = wrapped
def __call__(self, environ, start_response):
prefix = str(environ.get("HTTP_X_SCRIPT_NAME") or "").rstrip("/")
if prefix:
path = str(environ.get("PATH_INFO") or "/")
if path == prefix:
path = "/"
elif path.startswith(prefix + "/"):
path = path[len(prefix):]
environ["SCRIPT_NAME"] = prefix
environ["PATH_INFO"] = path
return self.wrapped(environ, start_response)
app.wsgi_app = PrefixMiddleware(app.wsgi_app)
def shared_reg_session_valid() -> bool:
if not REG_SESSION_SECRET:
return True
expected = hmac.new(
REG_SESSION_SECRET.encode("utf-8"),
b"register-console-access",
hashlib.sha256,
).hexdigest()
provided = str(request.cookies.get(REG_SESSION_COOKIE) or "")
return bool(provided and hmac.compare_digest(provided, expected))
@app.before_request
def require_shared_reg_session():
public_mount = request.script_root in {"/card-link", "/protocol-pay"}
public_exact = {
"/",
"/card-flow/",
"/card-long/",
"/protocol-pay/",
"/api/card-bind/config",
"/api/card-bind/session",
"/api/card-bind/default",
"/api/card-flow/quick-checkout",
"/api/unified-flow/jobs",
"/static/card-flow.css",
"/static/card-flow.js",
"/api/protocol-pay/jobs",
"/api/protocol-pay/batch-confirm",
"/static/protocol-pay.css",
"/static/protocol-pay.js",
}
public_dynamic = request.path.startswith("/api/card-flow/task/") or request.path.startswith("/api/protocol-pay/jobs/") or request.path.startswith("/api/unified-flow/jobs/") or request.path.startswith("/api/card-bind/key-probe/")
if request.path == "/healthz":
return None
if public_mount and (request.path in public_exact or public_dynamic):
return None
if shared_reg_session_valid():
return None
if request.path.startswith("/api/"):
return jsonify({"ok": False, "error": "LOGIN_REQUIRED"}), 401
return redirect("/login")
def reg_console_request(path: str, method: str = "GET", payload: dict | None = None) -> tuple[int, dict]:
if not REG_SESSION_SECRET:
raise RuntimeError("REG_SESSION_SECRET_MISSING")
session_value = hmac.new(
REG_SESSION_SECRET.encode("utf-8"),
b"register-console-access",
hashlib.sha256,
).hexdigest()
data = None
headers = {
"Cookie": f"{REG_SESSION_COOKIE}={session_value}",
"Accept": "application/json",
}
if payload is not None:
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
headers["Content-Type"] = "application/json"
req = Request(
f"{REG_INTERNAL_BASE}{path}",
data=data,
headers=headers,
method=method.upper(),
)
try:
with urlopen(req, timeout=30) as response:
raw = response.read().decode("utf-8", errors="replace")
return int(response.status), json.loads(raw or "{}")
except Exception as exc:
status = int(getattr(exc, "code", 502) or 502)
raw = ""
if hasattr(exc, "read"):
try:
raw = exc.read().decode("utf-8", errors="replace")
except Exception:
raw = ""
try:
body = json.loads(raw or "{}")
except Exception:
body = {"ok": False, "error": raw[:300] or str(exc)}
return status, body
def reg_bridge_get(path: str, params: dict | None = None) -> dict:
if not PH_SHORT_BRIDGE_KEY:
raise RuntimeError("菲律宾短链账号桥接密钥尚未配置")
query = f"?{urlencode(params or {})}" if params else ""
req = Request(
f"{REG_INTERNAL_BASE}{path}{query}",
headers={"X-PH-Short-Bridge-Key": PH_SHORT_BRIDGE_KEY, "Accept": "application/json"},
)
try:
with urlopen(req, timeout=15) as response:
payload = json.loads(response.read().decode("utf-8", errors="replace"))
except Exception as exc:
detail = ""
if hasattr(exc, "read"):
try:
detail = exc.read().decode("utf-8", errors="replace")[:300]
except Exception:
detail = ""
raise RuntimeError(f"读取 APP.example 账号会话失败:{detail or exc}") from exc
if not isinstance(payload, dict) or payload.get("ok") is False or payload.get("error"):
raise RuntimeError(str((payload or {}).get("error") or "账号会话接口返回异常"))
return payload
def validate_short_url(raw: str) -> tuple[str, str, str]:
value = str(raw or "").strip()
parsed = urlparse(value)
if parsed.scheme != "https" or parsed.hostname != "chatgpt.com":
raise ValueError("短链必须使用 chatgpt.com 官方 HTTPS 地址")
parts = [part for part in parsed.path.split("/") if part]
if len(parts) != 3 or parts[0] != "checkout":
raise ValueError("短链路径格式不正确")
processor, session_id = parts[1], parts[2]
if processor not in {"openai_ie", "openai_llc"}:
raise ValueError("短链处理实体不正确")
if not re.fullmatch(r"(?:oaics_|cs_)[A-Za-z0-9_-]{12,}", session_id):
raise ValueError("Checkout Session ID 格式不正确")
return value, processor, session_id
def cleanup_jobs() -> None:
cutoff = time.time() - JOB_TTL_SECONDS
with _lock:
expired = [
key for key, value in _jobs.items()
if value.get("created_at", 0) < cutoff
and value.get("status") not in {"queued", "running", "verification_required"}
]
for key in expired:
_jobs.pop(key, None)
if len(_jobs) > MAX_JOBS:
finished = sorted(
(item for item in _jobs.values() if item.get("status") not in {"queued", "running", "verification_required"}),
key=lambda item: item.get("created_at", 0),
)
for item in finished[: max(0, len(_jobs) - MAX_JOBS)]:
_jobs.pop(str(item.get("id") or ""), None)
def public_job(job: dict) -> dict:
return {
"id": job["id"],
"task_id": job.get("task_id") or "",
"account_email": job.get("account_email") or "",
"status": job.get("status") or "queued",
"progress": int(job.get("progress") or 0),
"stage": job.get("stage") or "等待执行",
"message": job.get("message") or "",
"error": job.get("error") or "",
"result": dict(job.get("result") or {}),
"logs": list(job.get("logs") or []),
"cancel_requested": bool(job.get("cancel_requested")),
"created_at": job.get("created_at"),
"updated_at": job.get("updated_at"),
"finished_at": job.get("finished_at"),
}
def add_log(job_id: str, level: str, message: str) -> None:
text = str(message or "").strip()
if not text:
return
with _lock:
job = _jobs.get(job_id)
if not job:
return
logs = job.setdefault("logs", [])
if logs and logs[-1].get("message") == text:
return
logs.append({"time": time.strftime("%H:%M:%S"), "type": level, "message": text[:800]})
if len(logs) > 100:
del logs[:-100]
job["updated_at"] = time.time()
def parse_cards(raw) -> list[dict[str, str]]:
cards: list[dict[str, str]] = []
seen: set[tuple[str, str, str, str]] = set()
def luhn_ok(number: str) -> bool:
total = 0
parity = len(number) % 2
for index, char in enumerate(number):
digit = int(char)
if index % 2 == parity:
digit *= 2
if digit > 9:
digit -= 9
total += digit
return total % 10 == 0
def append_card(number: Any, month: Any, year: Any, cvc: Any) -> None:
number_text = re.sub(r"\D", "", str(number or ""))
month_text = re.sub(r"\D", "", str(month or ""))
year_text = re.sub(r"\D", "", str(year or ""))
cvc_text = re.sub(r"\D", "", str(cvc or ""))
if len(year_text) == 2:
year_text = "20" + year_text
if not (12 <= len(number_text) <= 19 and luhn_ok(number_text)
and 1 <= int(month_text or 0) <= 12 and len(year_text) == 4
and 3 <= len(cvc_text) <= 4):
return
key = (number_text, str(int(month_text)), year_text, cvc_text)
if key not in seen:
seen.add(key)
cards.append({"number": key[0], "exp_month": key[1], "exp_year": key[2], "cvc": key[3]})
if isinstance(raw, list):
for value in raw:
if isinstance(value, dict):
append_card(value.get("number"), value.get("exp_month") or value.get("month"),
value.get("exp_year") or value.get("year"),
value.get("cvc") or value.get("cvv") or value.get("csc"))
else:
parts = [item for item in re.split(r"[|,;\s]+", str(value or "").strip()) if item]
if len(parts) >= 4:
append_card(*parts[:4])
else:
text = str(raw or "")
for line in text.splitlines():
parts = [item for item in re.split(r"[|,;\s]+", line.strip()) if item]
if len(parts) >= 4:
append_card(*parts[:4])
number_pattern = re.compile(r"(?<!\d)(\d{12,19}|(?:\d{4}[ -]){3}\d{4}|(?:\d{4}[ -]){2}\d{3,4})(?!\d)")
expiry_pattern = re.compile(r"(?<!\d)(0?[1-9]|1[0-2])\s*[/|,-]\s*(\d{2}|\d{4})(?!\d)")
cvc_pattern = re.compile(r"(?:cvc|cvv|csc|verification|security(?:\s*code)?|\u5b89\u5168\u7801|\u9a8c\u8bc1\u7801)[^\d]{0,24}(\d{3,4})", re.I)
for match in number_pattern.finditer(text):
number = re.sub(r"\D", "", match.group(1))
if not (12 <= len(number) <= 19 and luhn_ok(number)):
continue
tail = text[match.end():match.end() + 240]
expiry = expiry_pattern.search(tail)
if not expiry:
continue
cvc_match = cvc_pattern.search(tail)
if cvc_match:
cvc = cvc_match.group(1)
else:
plain = re.search(r"(?<!\d)(\d{3,4})(?!\d)", tail[expiry.end():])
cvc = plain.group(1) if plain else ""
append_card(number, expiry.group(1), expiry.group(2), cvc)
if not cards:
raise ValueError("未识别到完整支付卡,请检查卡号、有效期和 CVC")
return cards[:20]
def parse_proxies(raw) -> list[str]:
values = raw if isinstance(raw, list) else re.split(r"[\r\n,]+", str(raw or ""))
result = []
for value in values:
item = str(value or "").strip()
if item and item not in result:
result.append(item)
return result[:100]
def update_job(job_id: str, **updates) -> dict | None:
with _lock:
job = _jobs.get(job_id)
if not job:
return None
job.update(updates)
job["updated_at"] = time.time()
return dict(job)
def job_cancelled(job_id: str) -> bool:
with _lock:
return bool((_jobs.get(job_id) or {}).get("cancel_requested"))
def stop_if_cancelled(job_id: str) -> None:
if job_cancelled(job_id):
raise InterruptedError("任务已停止")
def run_job(job_id: str) -> None:
with _lock:
job = _jobs.get(job_id)
if not job:
return
try:
update_job(job_id, status="running", progress=8, stage="读取账号任务", message="正在读取短链和原账号任务信息")
add_log(job_id, "info", "读取菲律宾短链与原账号会话")
stop_if_cancelled(job_id)
snapshot = reg_bridge_get("/api/internal/ph-short/session", {"task_id": job["task_id"]})
update_job(job_id, progress=20, stage="校验短链", message="正在核对 Checkout、币种和金额")
stop_if_cancelled(job_id)
short_url, processor, checkout_session_id = validate_short_url(snapshot.get("short_url"))
currency = str(snapshot.get("currency") or "PHP").upper()
if currency != "PHP":
raise RuntimeError(f"短链币种不匹配:{currency or '未知'}")
amount = int(snapshot.get("amount") or 0)
if amount < 0:
raise RuntimeError("短链金额不正确")
update_job(job_id, progress=28, stage="检查账号环境", message="正在确认原任务仍有可用账号环境")
stop_if_cancelled(job_id)
has_account_context = bool(
str(snapshot.get("access_token") or "").strip()
or str(snapshot.get("session_token") or "").strip()
or snapshot.get("session_cookies")
)
if not has_account_context:
raise RuntimeError("原任务账号环境已失效,请先在账号页刷新后重新提取短链")
user_proxy_pool = list(job.get("_proxies") or [])
proxy_candidates: list[str] = []
proxy_source = "user_pool" if user_proxy_pool else ""
if user_proxy_pool:
proxy_candidates.extend(user_proxy_pool)
else:
checkout_proxy = str(snapshot.get("checkout_proxy") or "").strip()
if checkout_proxy:
proxy_candidates.append(checkout_proxy)
proxy_source = "checkout_sticky_us"
add_log(job_id, "info", "Reusing the original US checkout session")
if not str(job.get("_confirmation_token") or "").strip():
for _ in range(2):
try:
generated = reg_bridge_get("/api/internal/ph-short/proxy", {"country": "US"})
candidate = str(generated.get("proxy") or "").strip()
if candidate and candidate not in proxy_candidates:
proxy_candidates.append(candidate)
except Exception as exc:
add_log(job_id, "warn", f"US fallback proxy fetch failed: {type(exc).__name__}")
else:
add_log(job_id, "info", "ConfirmationToken is locked to the original Checkout proxy")
if not proxy_candidates:
raise RuntimeError("No usable payment proxy is available")
proxy = proxy_candidates[0]
if not proxy_source:
proxy_source = "auto_us"
update_job(job_id, _selected_proxy=proxy, _proxy_source=proxy_source)
payload = {
"short_url": short_url,
"processor_entity": processor,
"checkout_session_id": checkout_session_id,
"access_token": snapshot.get("access_token"),
"chatgpt_account_id": str(snapshot.get("chatgpt_account_id") or ""),
"session_cookies": snapshot.get("session_cookies") or {},
"user_agent": str(snapshot.get("user_agent") or ""),
"checkout_device_id": str(snapshot.get("checkout_device_id") or ""),
"checkout_chatgpt_session_id": str(snapshot.get("checkout_chatgpt_session_id") or ""),
"email": str(snapshot.get("email") or job.get("account_email") or ""),
"proxy": proxy,
"proxies": proxy_candidates,
"cards": list(job.get("_cards") or []),
"saved_payment_method_id": str(job.get("_saved_payment_method_id") or ""),
"confirmation_token": str(job.get("_confirmation_token") or ""),
"preconfirmed_checkout": dict(job.get("_preconfirmed_checkout") or {}),
"card_retry_count": int(job.get("_card_retry_count", 2)),
"card_retry_delay": 1,
}
update_job(job_id, progress=36, stage="初始化 Stripe", message="正在初始化现有 PH Checkout")
process = subprocess.Popen(
[PAY153_PYTHON, PROTOCOL_HELPER],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
bufsize=1,
)
with _lock:
if job_id in _jobs:
_jobs[job_id]["_process"] = process
assert process.stdin is not None and process.stdout is not None
process.stdin.write(json.dumps(payload, ensure_ascii=False))
process.stdin.close()
result = {}
last_error = ""
for line in process.stdout:
stop_if_cancelled(job_id)
text = line.strip()
if not text:
continue
try:
event = json.loads(text)
except Exception:
add_log(job_id, "info", text)
continue
if event.get("type") == "log":
level = str(event.get("level") or "info")
message = str(event.get("message") or "")
add_log(job_id, level, message)
lower = message.lower()
if "oaics session resolved" in lower:
update_job(job_id, progress=48, stage="Resolve Checkout", message="Loading Stripe Elements context")
elif "elements session initialized" in lower or "billing snapshot" in lower:
update_job(job_id, progress=62, stage="Initialize payment", message="Preparing the saved PaymentMethod")
elif "paymentmethod created" in lower:
update_job(job_id, progress=74, stage="Prepare authorization", message="PaymentMethod is ready for Checkout")
elif "confirmationtoken created" in lower:
update_job(job_id, progress=82, stage="Submit payment", message="Submitting the Checkout confirmation")
elif "payment succeeded" in lower:
update_job(job_id, progress=96, stage="Payment complete", message="Payment succeeded; finalizing authorization")
elif "post-payment card binding status" in lower:
update_job(job_id, progress=98, stage="Finalize", message="Checking the final account binding")
elif "checkout confirm returned" in lower:
update_job(job_id, progress=90, stage="Checkout confirmed", message="Confirming the Stripe Intent")
elif "submit chatgpt checkout approval" in lower:
update_job(job_id, progress=94, stage="Checkout approval", message="Submitting final approval and confirming again")
elif event.get("type") == "result":
result = dict(event.get("result") or {})
elif event.get("type") == "error":
last_error = str(event.get("error") or "")
code = process.wait(timeout=10)
with _lock:
if job_id in _jobs:
_jobs[job_id]["_process"] = None
if code != 0 or not result:
clean_error = last_error or f"Protocol helper exited with code {code}"
if clean_error.startswith("RuntimeError: "):
clean_error = clean_error[len("RuntimeError: "):]
raise RuntimeError(clean_error)
result.update({
"short_url": short_url,
"processor_entity": processor,
"checkout_session_id": checkout_session_id,
"amount_minor": amount,
"currency": "PHP",
"billing_country": "PH",
"account_email": str(snapshot.get("email") or job.get("account_email") or ""),
"protocol_mode": "stripe_checkout_protocol",
})
if result.get("status") == "verification_required":
update_job(
job_id,
status="verification_required",
progress=92,
stage="等待支付验证",
message="支付方式需要额外验证,完成后点击继续确认",
result=result,
_resume_payload={
"mode": "resume",
"checkout_session_id": checkout_session_id,
"stripe_publishable_key": str(result.get("stripe_publishable_key") or ""),
"intent_type": str(result.get("intent_type") or ""),
"intent_client_secret": str(result.get("intent_client_secret") or ""),
"proxy": proxy,
"session_cookies": snapshot.get("session_cookies") or {},
},
)
else:
update_job(job_id, status="ready", progress=100, stage="支付完成", message="菲律宾 Checkout 协议支付完成", result=result, finished_at=time.time())
except InterruptedError as exc:
with _lock:
process = (_jobs.get(job_id) or {}).get("_process")
if process and process.poll() is None:
try:
process.terminate()
except Exception:
pass
update_job(
job_id,
status="cancelled",
progress=100,
stage="已停止",
message=str(exc),
finished_at=time.time(),
)
except Exception as exc:
add_log(job_id, "error", f"{type(exc).__name__}: {exc}")
update_job(
job_id,
status="error",
progress=100,
stage="执行失败",
error=str(exc),
message="任务执行失败",
finished_at=time.time(),
)
def run_resume_job(job_id: str) -> None:
with _lock:
job = _jobs.get(job_id)
payload = dict((job or {}).get("_resume_payload") or {})
previous_result = dict((job or {}).get("result") or {})
if not job or not payload:
return
try:
update_job(job_id, status="running", progress=94, stage="确认验证结果", message="正在轮询原 Checkout 的最终状态", error="")
process = subprocess.Popen(
[PAY153_PYTHON, PROTOCOL_HELPER],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
bufsize=1,
)
with _lock:
if job_id in _jobs:
_jobs[job_id]["_process"] = process
assert process.stdin is not None and process.stdout is not None
process.stdin.write(json.dumps(payload, ensure_ascii=False))
process.stdin.close()
result: dict = {}
last_error = ""
for line in process.stdout:
stop_if_cancelled(job_id)
text = line.strip()
if not text:
continue
try:
event = json.loads(text)
except Exception:
add_log(job_id, "info", text)
continue
if event.get("type") == "log":
add_log(job_id, str(event.get("level") or "info"), str(event.get("message") or ""))
elif event.get("type") == "result":
result = dict(event.get("result") or {})
elif event.get("type") == "error":
last_error = str(event.get("error") or "")
code = process.wait(timeout=10)
with _lock:
if job_id in _jobs:
_jobs[job_id]["_process"] = None
if code != 0 or not result:
raise RuntimeError(last_error or f"协议支付续跑进程退出:{code}")
merged = {**previous_result, **result}
if result.get("status") == "verification_required":
update_job(job_id, status="verification_required", progress=94, stage="等待支付验证", message="尚未检测到验证完成,可稍后再次继续确认", result=merged)
return
update_job(job_id, status="ready", progress=100, stage="支付完成", message="菲律宾 Checkout 已确认到账", result=merged, finished_at=time.time())
except InterruptedError as exc:
with _lock:
process = (_jobs.get(job_id) or {}).get("_process")
if process and process.poll() is None:
try:
process.terminate()
except Exception:
pass
update_job(job_id, status="cancelled", progress=100, stage="已停止", message=str(exc), finished_at=time.time())
except Exception as exc:
add_log(job_id, "error", f"{type(exc).__name__}: {exc}")
update_job(job_id, status="error", progress=100, stage="最终确认失败", error=str(exc), finished_at=time.time())
def request_script_root(value: str | None) -> str:
root = str(value or "").rstrip("/")
return root
def _decode_access_token_claims(access_token: str) -> dict:
token = str(access_token or "").strip()
parts = token.split(".")
if len(parts) < 2:
raise ValueError("AT_FORMAT_INVALID")
segment = parts[1] + "=" * (-len(parts[1]) % 4)
try:
claims = json.loads(base64.urlsafe_b64decode(segment.encode("ascii")).decode("utf-8"))
except Exception as exc:
raise ValueError("AT_PAYLOAD_INVALID") from exc
if not isinstance(claims, dict):
raise ValueError("AT_PAYLOAD_INVALID")
return claims
def _external_at_identity(access_token: str) -> tuple[str, str, str]:
claims = _decode_access_token_claims(access_token)
auth = claims.get("https://api.openai.com/auth") or {}
profile = claims.get("https://api.openai.com/profile") or {}
if not isinstance(auth, dict):
auth = {}
if not isinstance(profile, dict):
profile = {}
account_id = str(auth.get("chatgpt_account_id") or claims.get("chatgpt_account_id") or claims.get("account_id") or "").strip()
if not account_id:
raise ValueError("AT_ACCOUNT_ID_MISSING")
token_hash = hashlib.sha256(access_token.encode("utf-8")).hexdigest()
email = str(profile.get("email") or claims.get("email") or "").strip().lower()
if not email or "@" not in email:
email = f"external-{token_hash[:16]}@example.com"
record_id = hashlib.sha256(("external-at:" + account_id).encode("utf-8")).hexdigest()[:12]
return record_id, email, account_id
def ensure_external_at_account(access_token: str) -> str:
token = str(access_token or "").strip()
if len(token) < 300 or len(token) > 30000:
raise ValueError("AT_FORMAT_INVALID")
_record_id, email, _account_id = _external_at_identity(token)
# External ATs are decoded in memory only. They are never appended to the
# APP.example account archive.
return email
def resolve_card_bind_email(body: dict | None = None) -> str:
body = body or {}
requested_id = str(body.get("record_id") or request.args.get("record_id") or "").strip()
requested_email = str(body.get("email") or request.args.get("email") or "").strip().lower()
requested_at = str(body.get("access_token") or body.get("at") or request.args.get("access_token") or "").strip()
if not requested_id and not requested_email and not requested_at:
return CARD_BIND_ACCOUNT_EMAIL
matched_email = ""
account_file = Path("/opt/reg153/success_accounts.jsonl")
if account_file.exists():
with account_file.open(encoding="utf-8", errors="ignore") as handle:
for line in handle:
try:
item = json.loads(line)
except Exception:
continue
item_id = str(item.get("id") or "").strip()
item_email = str(item.get("email") or "").strip().lower()
item_at = str(item.get("access_token") or "").strip()
if ((requested_id and item_id == requested_id) or
(requested_email and item_email == requested_email) or
(requested_at and item_at and hmac.compare_digest(requested_at, item_at))):
matched_email = item_email
break
if matched_email:
return matched_email
if requested_at:
return ensure_external_at_account(requested_at)
raise ValueError("ACCOUNT_NOT_FOUND")
@app.get("/card-long/")
def card_long_page():
return render_template("card-long-flow.html")
def _find_protocol_publishable_key(value) -> str:
pattern = re.compile(r"pk_(?:live|test)_[A-Za-z0-9]{24,}")
if isinstance(value, dict):
for name in ("stripe_publishable_key", "publishable_key", "public_key", "key"):
candidate = str(value.get(name) or "").strip()
if pattern.fullmatch(candidate):
return candidate
for item in value.values():
found = _find_protocol_publishable_key(item)
if found:
return found
elif isinstance(value, list):
for item in value:
found = _find_protocol_publishable_key(item)
if found:
return found
elif isinstance(value, str):
match = pattern.search(value)
if match:
return match.group(0)
return ""
def initialize_card_stripe_via_checkout(record_id: str, proxy_pool: list[str], access_token: str = "") -> dict:
# Creating the temporary Checkout is the initialization side effect. Its
# response key is optional because a fresh payment_method call follows it.
token = str(access_token or "").strip()
if not token:
raise RuntimeError("AT_REQUIRED_FOR_CHECKOUT_KEY")
if not PAY153_INTERNAL_KEY:
if not proxy_pool:
raise RuntimeError("PROXY_POOL_REQUIRED")
initialized = _run_local_checkout_extractor(
token,
str(proxy_pool[0] or ""),
str(proxy_pool[0] or ""),
mode="initialize",
)
return {
"pay_job_id": "local",
"publishable_key": CARD_BIND_PUBLISHABLE_KEY,
"result": initialized,
}
status, created = _pay153_request("/api/checkout", "POST", {
"token": token, "plan": "plus", "link_type": "ph_short", "country": "US",
"entry_proxies": list(proxy_pool), "exit_proxies": list(proxy_pool),
"entry_proxy_country": "US", "exit_proxy_country": "US", "use_promo": False,
"promo_country": "US", "retry_count": 3, "use_sen": True, "use_so": True,
})
pay_job_id = str((created or {}).get("job_id") or "")
if status >= 400 or not pay_job_id:
raise RuntimeError(str((created or {}).get("error") or "CHECKOUT_KEY_TASK_CREATE_FAILED"))
observed_key = ""
for _ in range(720):
pstatus, progress = _pay153_request("/api/checkout-progress", params={"job_id": pay_job_id})
if pstatus >= 400:
raise RuntimeError(str((progress or {}).get("error") or "CHECKOUT_KEY_TASK_QUERY_FAILED"))
progress = progress if isinstance(progress, dict) else {}
state = str(progress.get("status") or "")
observed_key = observed_key or _find_protocol_publishable_key(progress)
if state == "done":
return {
"pay_job_id": pay_job_id,
"publishable_key": observed_key or _find_protocol_publishable_key(progress.get("result") or {}),
"result": progress.get("result") or {},
}
if state in {"error", "failed", "cancelled"}:
raise RuntimeError(str(progress.get("error") or progress.get("message") or "CHECKOUT_KEY_TASK_FAILED"))
time.sleep(1)
raise RuntimeError("CHECKOUT_INITIALIZATION_TIMEOUT")
def _run_card_bind_session_helper(account_email: str, selected_proxy: str, access_token: str) -> tuple[int, dict]:
try:
completed = subprocess.run(
[PAY153_PYTHON, CARD_BIND_HELPER, account_email, selected_proxy, access_token],
capture_output=True, text=True, timeout=70, check=False,
)
except FileNotFoundError as exc:
return 127, {
"ok": False,
"error": "CARD_BIND_HELPER_UNAVAILABLE",
"detail": f"Python helper executable is unavailable: {exc.filename or PAY153_PYTHON}",
}
except subprocess.TimeoutExpired:
return 124, {
"ok": False,
"error": "CARD_BIND_HELPER_TIMEOUT",
"detail": "Card session helper exceeded 70 seconds",
}
except OSError as exc:
return 126, {
"ok": False,
"error": "CARD_BIND_HELPER_START_FAILED",
"detail": f"Card session helper could not start: {exc}",
}
try:
payload = json.loads((completed.stdout or "{}").strip().splitlines()[-1])
except Exception:
stderr = str(completed.stderr or "").strip().splitlines()
payload = {
"ok": False,
"error": "BIND_SESSION_INVALID_RESPONSE",
"detail": (stderr[-1] if stderr else "helper returned no JSON")[:300],
}
return completed.returncode, payload
def _key_probe_public(job: dict) -> dict:
return {
"id": job.get("id"), "status": job.get("status"), "progress": int(job.get("progress") or 0),
"message": job.get("message") or "", "error": job.get("error") or "",
"publishable_key": job.get("publishable_key") or "",
"session": dict(job.get("session") or {}),
}
def _run_key_probe(probe_id: str):
with _lock: job = dict(_key_probe_jobs.get(probe_id) or {})
if not job: return
try:
token = str(job.get("_access_token") or "")
account_email = str(job.get("_account_email") or "")
selected_proxy = str(job.get("_selected_proxy") or "")
with _lock:
_key_probe_jobs[probe_id].update(status="running", progress=12, message="Creating temporary Checkout to initialize Stripe")
initialized = initialize_card_stripe_via_checkout(job.get("record_id") or "", list(job.get("_proxies") or []), token)
with _lock:
_key_probe_jobs[probe_id].update(progress=82, message="Checkout initialized; fetching a fresh SetupIntent and Stripe key")
refreshed = {}
last_detail = ""
for attempt in range(1, 13):
returncode, candidate = _run_card_bind_session_helper(account_email, selected_proxy, token)
if returncode == 0 and candidate.get("ok"):
refreshed = candidate
break
upstream = int(candidate.get("status") or 0)
detail = candidate.get("detail") or candidate.get("error") or "BIND_SESSION_REFETCH_FAILED"
last_detail = f"BIND_SESSION_REFETCH_FAILED[{upstream}]: {detail}"
if "no payment account exists" not in str(detail).lower() or attempt >= 12:
break
with _lock:
if probe_id in _key_probe_jobs:
_key_probe_jobs[probe_id].update(
progress=min(96, 82 + attempt),
message=f"Payment account initialization pending; SetupIntent retry {attempt}/12",
)
time.sleep(1)
if not refreshed.get("ok"):
raise RuntimeError(last_detail or "BIND_SESSION_REFETCH_FAILED")
key = _find_protocol_publishable_key(refreshed) or str(initialized.get("publishable_key") or "")
if not str(key).startswith("pk_"):
raise RuntimeError("CHECKOUT_INITIALIZED_BUT_KEY_NOT_RETURNED")
refreshed["publishable_key"] = key
refreshed["publishable_key_source"] = "checkout_then_refetch"
refreshed["pending"] = False
with _lock:
_key_probe_jobs[probe_id].update(
status="done", progress=100, message="Fresh SetupIntent and Stripe key resolved",
publishable_key=key, session=refreshed, _access_token="", finished_at=time.time(),
)
except Exception as exc:
with _lock:
if probe_id in _key_probe_jobs:
_key_probe_jobs[probe_id].update(status="error", progress=100, message="Stripe initialization/refetch failed", error=f"{type(exc).__name__}: {exc}"[:500], _access_token="", finished_at=time.time())
def _start_key_probe(record_id: str, account_email: str, selected_proxy: str, access_token: str, proxies: list[str], initial_session: dict | None = None) -> dict:
probe_id = secrets.token_hex(6); now = time.time()
job = {"id": probe_id, "record_id": record_id, "status": "queued", "progress": 2, "message": "Stripe initialization queued", "error": "", "publishable_key": "", "session": dict(initial_session or {}), "created_at": now, "finished_at": None, "_account_email": account_email, "_selected_proxy": selected_proxy, "_access_token": access_token, "_proxies": list(proxies)}
with _lock:
_key_probe_jobs[probe_id] = job
if len(_key_probe_jobs) > 100:
finished = sorted((x for x in _key_probe_jobs.values() if x.get("status") in {"done", "error"}), key=lambda x: x.get("created_at", 0))
for old in finished[:max(0, len(_key_probe_jobs)-100)]: _key_probe_jobs.pop(str(old.get("id") or ""), None)
threading.Thread(target=_run_key_probe, args=(probe_id,), daemon=True, name=f"key-probe-{probe_id}").start()
return job
@app.get("/api/card-bind/key-probe/<probe_id>")
def card_bind_key_probe(probe_id: str):
value = str(probe_id or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", value):
return jsonify({"ok": False, "error": "INVALID_KEY_PROBE_ID"}), 400
with _lock:
job = _key_probe_jobs.get(value)
payload = _key_probe_public(job) if job else None
if not payload:
return jsonify({"ok": False, "error": "KEY_PROBE_NOT_FOUND"}), 404
return jsonify({"ok": True, "probe": payload})
def normalize_user_proxy(raw: str) -> str:
value = str(raw or "").strip()
if not value:
raise ValueError("PROXY_REQUIRED")
if "://" in value:
parsed = urlsplit(value)
scheme = parsed.scheme.lower()
if scheme not in {"http", "https", "socks5", "socks5h"}:
raise ValueError("UNSUPPORTED_PROXY_SCHEME")
if not parsed.hostname or parsed.port is None:
raise ValueError("PROXY_HOST_OR_PORT_MISSING")
auth = ""
if parsed.username is not None:
auth = f"{quote(unquote(parsed.username), safe='')}:{quote(unquote(parsed.password or ''), safe='')}@"
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
return f"{scheme}://{auth}{host}:{parsed.port}"
if value.count("@") == 1:
left, right = value.split("@", 1)
if left.count(":") == 1 and right.count(":") >= 1:
username, password = left.split(":", 1)
host, port = right.rsplit(":", 1)
else:
host, port = left.rsplit(":", 1)
username, password = right.split(":", 1)
if not port.isdigit():
raise ValueError("PROXY_PORT_INVALID")
return f"http://{quote(username, safe='')}:{quote(password, safe='')}@{host}:{port}"
parts = value.split(":")
if len(parts) >= 4 and parts[1].isdigit():
host, port, username = parts[0], parts[1], parts[2]
password = ":".join(parts[3:])
return f"http://{quote(username, safe='')}:{quote(password, safe='')}@{host}:{port}"
if len(parts) == 2 and parts[1].isdigit():
return f"http://{value}"
raise ValueError("PROXY_FORMAT_INVALID")
def normalize_user_proxy_pool(raw) -> list[str]:
values = raw if isinstance(raw, list) else str(raw or "").replace("\r", "").split("\n")
result = []
seen = set()
for index, item in enumerate(values, 1):
text = str(item or "").strip()
if not text:
continue
try:
proxy = normalize_user_proxy(text)
except Exception as exc:
raise ValueError(f"PROXY_LINE_{index}: {exc}") from exc
if proxy not in seen:
seen.add(proxy); result.append(proxy)
if not result:
raise ValueError("PROXY_POOL_REQUIRED")
if len(result) > 500:
raise ValueError("PROXY_POOL_MAX_500")
return result
def card_helper_error_response(payload: dict, fallback_status: int = 502):
result = dict(payload or {})
if not result.get("error"):
result["error"] = "CARD_PROTOCOL_EMPTY_RESPONSE"
if result.get("error") in {
"CARD_BIND_HELPER_UNAVAILABLE",
"CARD_BIND_HELPER_TIMEOUT",
"CARD_BIND_HELPER_START_FAILED",
"CARD_BIND_DEPENDENCY_MISSING",
"CARD_BIND_RUNTIME_FILE_MISSING",
"CARD_BIND_UPSTREAM_NETWORK_ERROR",
"CARD_BIND_PROXY_POOL_EXHAUSTED",
"SET_DEFAULT_HELPER_UNAVAILABLE",
"SET_DEFAULT_HELPER_TIMEOUT",
"SET_DEFAULT_HELPER_START_FAILED",
"SET_DEFAULT_DEPENDENCY_MISSING",
"SET_DEFAULT_UPSTREAM_NETWORK_ERROR",
"SET_DEFAULT_TLS_CA_BUNDLE_ERROR",
"CARD_BIND_TLS_CA_BUNDLE_ERROR",
}:
return jsonify(result), 503
upstream = int(result.get("status") or 0)
if upstream == 401:
result["error"] = "AT_INVALIDATED_OR_EXPIRED"
result["upstream_status"] = upstream
return jsonify(result), 422
if upstream == 403:
result["error"] = "UPSTREAM_ROUTE_BLOCKED"
result["upstream_status"] = upstream
return jsonify(result), 503
if upstream == 429:
result["error"] = result.get("error") or "UPSTREAM_RATE_LIMITED"
return jsonify(result), 429
if upstream >= 500:
return jsonify(result), 503
return jsonify(result), fallback_status
def _run_card_set_default(
account_email: str,
payment_method_id: str,
selected_proxy: str,
access_token: str,
) -> tuple[int, dict]:
def safe_detail(value: object) -> str:
detail = str(value or "")
detail = re.sub(r"(?i)((?:https?|socks5h?)://)[^/@\s]+@", r"\1***@", detail)
detail = re.sub(
r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+",
"AT_REDACTED",
detail,
)
return detail[:500]
try:
completed = subprocess.run(
[PAY153_PYTHON, CARD_DEFAULT_HELPER, account_email, payment_method_id, selected_proxy, access_token],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=SET_DEFAULT_HELPER_TIMEOUT_SECONDS,
check=False,
)
except FileNotFoundError as exc:
return 127, {"ok": False, "error": "SET_DEFAULT_HELPER_UNAVAILABLE", "detail": safe_detail(exc)}
except subprocess.TimeoutExpired as exc:
return 124, {
"ok": False,
"error": "SET_DEFAULT_HELPER_TIMEOUT",
"detail": f"helper exceeded {SET_DEFAULT_HELPER_TIMEOUT_SECONDS}s",
}
except OSError as exc:
return 126, {"ok": False, "error": "SET_DEFAULT_HELPER_START_FAILED", "detail": safe_detail(exc)}
payload = None
stdout_lines = [line.strip() for line in str(completed.stdout or "").splitlines() if line.strip()]
for line in reversed(stdout_lines):
try:
candidate = json.loads(line)
except Exception:
continue
if isinstance(candidate, dict):
payload = candidate
break
stderr_lines = [line.strip() for line in str(completed.stderr or "").splitlines() if line.strip()]
if payload is None:
detail_source = stderr_lines[-1] if stderr_lines else (stdout_lines[-1] if stdout_lines else "helper returned no JSON")
payload = {
"ok": False,
"error": "SET_DEFAULT_HELPER_ERROR" if completed.returncode else "SET_DEFAULT_INVALID_RESPONSE",
"detail": safe_detail(detail_source),
}
elif completed.returncode and not payload.get("error"):
payload["error"] = "SET_DEFAULT_HELPER_ERROR"
if completed.returncode and not payload.get("detail") and stderr_lines:
payload["detail"] = safe_detail(stderr_lines[-1])
return completed.returncode, payload
@app.post("/api/card-bind/default")
def card_bind_default():
body = request.get_json(silent=True) or {}
payment_method_id = str(body.get("payment_method_id") or "").strip()
if not re.fullmatch(r"pm_[A-Za-z0-9]+", payment_method_id):
return jsonify({"ok": False, "error": "INVALID_PAYMENT_METHOD"}), 400
try:
account_email = resolve_card_bind_email(body)
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 404
try:
selected_proxy = normalize_user_proxy(body.get("proxy"))
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
submitted_at = str(body.get("access_token") or body.get("at") or "").strip()
returncode, payload = _run_card_set_default(
account_email, payment_method_id, selected_proxy, submitted_at
)
if returncode != 0 or not payload.get("ok"):
return card_helper_error_response(payload)
return jsonify(payload)
@app.post("/api/card-flow/context")
def card_flow_context():
body = request.get_json(silent=True) or {}
task_id = str(body.get("task_id") or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", task_id):
return jsonify({"ok": False, "error": "Checkout task ID is invalid"}), 400
try:
snapshot = reg_bridge_get("/api/internal/ph-short/session", {"task_id": task_id})
completed = subprocess.run(
[PAY153_PYTHON, CARD_CHECKOUT_CONTEXT_HELPER],
input=json.dumps(snapshot, ensure_ascii=False),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=90,
check=False,
)
try:
payload = json.loads((completed.stdout or "{}").strip().splitlines()[-1])
except Exception:
payload = {"ok": False, "error": "Checkout context response is invalid"}
if completed.returncode != 0 or not payload.get("ok"):
detail = (completed.stderr or "").strip().splitlines()
return jsonify({"ok": False, "error": payload.get("error") or (detail[-1] if detail else "Checkout context failed")}), 502
return jsonify(payload)
except Exception as exc:
return jsonify({"ok": False, "error": str(exc)}), 502
@app.post("/api/card-flow/server-token")
def card_flow_server_token():
body = request.get_json(silent=True) or {}
task_id = str(body.get("task_id") or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", task_id):
return jsonify({"ok": False, "error": "Checkout task ID is invalid"}), 400
try:
snapshot = reg_bridge_get("/api/internal/ph-short/session", {"task_id": task_id})
completed = subprocess.run(
[PAY153_PYTHON, CARD_SERVER_TOKEN_HELPER],
input=json.dumps(snapshot, ensure_ascii=False),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=120,
check=False,
)
lines = (completed.stdout or "").strip().splitlines()
try:
payload = json.loads(lines[-1] if lines else "{}")
except Exception:
payload = {"ok": False, "error": "Server ConfirmationToken response is invalid"}
if completed.returncode != 0 or not payload.get("ok"):
detail = (completed.stderr or "").strip().splitlines()
error_code = str(payload.get("error_code") or "")
status_code = 409 if error_code == "OFFER_NOT_ELIGIBLE" else 502
return jsonify({
"ok": False,
"error_code": error_code,
"error": payload.get("error") or (detail[-1] if detail else "Server ConfirmationToken failed"),
"offer_check_ok": payload.get("offer_check_ok"),
"offer_eligible": payload.get("offer_eligible"),
}), status_code
return jsonify(payload)
except Exception as exc:
return jsonify({"ok": False, "error": str(exc)}), 502
@app.get("/card-flow/")
def card_flow_page():
return render_template("card-flow.html")
def _checkout_result_context(result: dict, entry_proxies: list[str], source: str = "") -> dict:
session_id = str(result.get("checkout_session_id") or "").strip()
if not session_id:
return {}
try: attempt = max(1, int(result.get("attempt") or 1))
except Exception: attempt = 1
selected_proxy = str(result.get("checkout_proxy") or "").strip()
if entry_proxies:
selected_proxy = selected_proxy or str(entry_proxies[(attempt - 1) % len(entry_proxies)] or "").strip()
return {
"checkout_session_id": session_id,
"checkout_url": str(result.get("checkout_url") or result.get("short_link") or ""),
"processor_entity": str(result.get("processor_entity") or "openai_llc"),
"checkout_proxy": selected_proxy,
"checkout_device_id": str(result.get("checkout_device_id") or ""),
"checkout_chatgpt_session_id": str(result.get("checkout_chatgpt_session_id") or ""),
"checkout_user_agent": str(result.get("checkout_user_agent") or ""),
"session_cookies": {
str(name): str(value)
for name, value in dict(result.get("session_cookies") or {}).items()
if str(name) and str(value)
},
"created_at": time.time(),
"source": source,
}
def _persist_checkout_context(context: dict) -> None:
if not context or not context.get("checkout_session_id"):
return
CHECKOUT_CONTEXT_PATH.parent.mkdir(parents=True, exist_ok=True)
with _lock:
rows = []
if CHECKOUT_CONTEXT_PATH.exists():
for line in CHECKOUT_CONTEXT_PATH.read_text(encoding="utf-8", errors="ignore").splitlines():
try: item = json.loads(line)
except Exception: continue
if not isinstance(item, dict): continue
if str(item.get("checkout_session_id") or "") == str(context.get("checkout_session_id") or ""): continue
if float(item.get("created_at") or 0) < time.time() - 7 * 86400: continue
rows.append(item)
rows.append(dict(context))
CHECKOUT_CONTEXT_PATH.write_text("".join(json.dumps(item, ensure_ascii=False, separators=(",", ":")) + "\\n" for item in rows[-1000:]), encoding="utf-8")
def _lookup_checkout_context(session_id: str) -> dict:
target = str(session_id or "").strip()
if not target: return {}
candidates = []
pay153_contexts = Path("/opt/pay153/data/ph_short_contexts.jsonl")
if pay153_contexts.exists():
for line in pay153_contexts.read_text(encoding="utf-8", errors="ignore").splitlines():
try: item = json.loads(line)
except Exception: continue
if isinstance(item, dict) and str(item.get("checkout_session_id") or "") == target:
candidates.append(item)
if CHECKOUT_CONTEXT_PATH.exists():
for line in CHECKOUT_CONTEXT_PATH.read_text(encoding="utf-8", errors="ignore").splitlines():
try: item = json.loads(line)
except Exception: continue
if isinstance(item, dict) and str(item.get("checkout_session_id") or "") == target:
candidates.append(item)
# Backfill links created by the older reg quick-checkout path.
legacy_tasks = Path("/opt/reg153/account_tasks.jsonl")
if legacy_tasks.exists():
for line in legacy_tasks.read_text(encoding="utf-8", errors="ignore").splitlines():
try: task = json.loads(line)
except Exception: continue
result = task.get("result") if isinstance(task.get("result"), dict) else {}
if str(result.get("checkout_session_id") or "") != target: continue
options = task.get("options") if isinstance(task.get("options"), dict) else {}
entry = [str(item).strip() for item in (options.get("entry_proxies") or []) if str(item).strip()]
context = _checkout_result_context(result, entry, "legacy_reg_task")
context["created_at"] = float(task.get("finished_at") or task.get("created_at") or time.time())
candidates.append(context)
if not candidates: return {}
return dict(max(candidates, key=lambda item: float(item.get("created_at") or 0)))
def _lookup_reg_account_session(email: str, account_id: str) -> dict:
target_email = str(email or "").strip().lower()
target_account = str(account_id or "").strip()
source = Path("/opt/reg153/success_accounts.jsonl")
if not source.exists():
return {}
matches = []
for line in source.read_text(encoding="utf-8", errors="ignore").splitlines():
try:
row = json.loads(line)
except Exception:
continue
if not isinstance(row, dict):
continue
same_email = target_email and str(row.get("email") or "").strip().lower() == target_email
same_account = target_account and str(row.get("account_id") or "").strip() == target_account
if not (same_email or same_account):
continue
cookies = row.get("session_cookies") if isinstance(row.get("session_cookies"), dict) else {}
if cookies:
matches.append(row)
if not matches:
return {}
latest = max(matches, key=lambda row: str(row.get("last_checked_at") or row.get("created_at") or ""))
return {str(k): str(v) for k, v in dict(latest.get("session_cookies") or {}).items() if str(k) and str(v)}
def _pay153_request(path: str, method: str = "GET", payload: dict | None = None, params: dict | None = None) -> tuple[int, dict]:
if not PAY153_INTERNAL_KEY:
raise RuntimeError(
"PAY153_INTERNAL_KEY_MISSING: configure PAY153_INTERNAL_KEY in .env "
"and start the PAY153 bridge at " + PAY153_INTERNAL_BASE
)
query = f"?{urlencode(params or {})}" if params else ""
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
headers = {"X-Pay153-Internal-Key": PAY153_INTERNAL_KEY, "Accept": "application/json"}
if data is not None:
headers["Content-Type"] = "application/json"
req = Request(f"{PAY153_INTERNAL_BASE}{path}{query}", data=data, headers=headers, method=method)
try:
with urlopen(req, timeout=35) as response:
raw = response.read().decode("utf-8", errors="replace")
return int(response.status), json.loads(raw or "{}")
except Exception as exc:
status = int(getattr(exc, "code", 502) or 502)
raw = ""
if hasattr(exc, "read"):
try: raw = exc.read().decode("utf-8", errors="replace")
except Exception: raw = ""
try: body = json.loads(raw or "{}")
except Exception: body = {"error": raw[:300] or str(exc)}
return status, body
def _run_local_checkout_extractor(
access_token: str, entry_proxy: str, exit_proxy: str, mode: str = "extract"
) -> dict:
try:
completed = subprocess.run(
[PAY153_PYTHON, LOCAL_CHECKOUT_HELPER],
input=json.dumps(
{
"access_token": access_token,
"entry_proxy": entry_proxy,
"exit_proxy": exit_proxy,
"mode": mode,
},
ensure_ascii=False,
),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=15 * 60,
check=False,
)
except subprocess.TimeoutExpired as exc:
raise TimeoutError("LOCAL_CHECKOUT_TIMEOUT") from exc
lines = (completed.stdout or "").strip().splitlines()
try:
result = json.loads(lines[-1] if lines else "{}")
except Exception as exc:
raise RuntimeError("LOCAL_CHECKOUT_INVALID_RESPONSE") from exc
if completed.returncode != 0 or not result.get("ok"):
message = str(result.get("error") or f"LOCAL_CHECKOUT_EXIT_{completed.returncode}")
raw_trace = result.get("trace") if isinstance(result.get("trace"), list) else []
safe_trace = [
str(frame)
for frame in raw_trace[:6]
if re.fullmatch(r"[A-Za-z0-9_.-]+:\d+:[A-Za-z0-9_.<>-]+", str(frame))
]
if safe_trace:
message += " [trace: " + " <- ".join(safe_trace) + "]"
raise RuntimeError(message[:1200])
if not str(result.get("checkout_session_id") or "").startswith(("oaics_", "cs_")):
raise RuntimeError("LOCAL_CHECKOUT_SESSION_MISSING")
if not str(result.get("checkout_url") or "").startswith("https://chatgpt.com/checkout/"):
raise RuntimeError("LOCAL_CHECKOUT_URL_MISSING")
return result
def _extend_sticky_proxy_ttl(value: str, minutes: int = 120) -> str:
proxy = str(value or "").strip()
if not proxy:
return proxy
if re.search(r"-t-\d+", proxy):
return re.sub(r"-t-\d+", f"-t-{int(minutes)}", proxy, count=1)
return proxy
def _card_checkout_public(job: dict) -> dict:
return {
"id": job.get("id"), "task_id": job.get("id"), "status": job.get("status"),
"progress": int(job.get("progress") or 0), "message": job.get("message") or "",
"error": job.get("error") or "", "result": dict(job.get("result") or {}),
"created_at": job.get("created_at"), "finished_at": job.get("finished_at"),
}
def _run_isolated_card_checkout(task_id: str):
with _lock: job = dict(_card_checkout_jobs.get(task_id) or {})
if not job: return
try:
with _lock: _card_checkout_jobs[task_id].update(status="running", progress=5, message="Validating US/TR proxy pools")
preflight = subprocess.run(
[PAY153_PYTHON, PROXY_PREFLIGHT_HELPER],
input=json.dumps({
"entry": [_extend_sticky_proxy_ttl(item, 120) for item in job["_entry_proxies"]],
"exit": [_extend_sticky_proxy_ttl(item, 120) for item in job["_exit_proxies"]],
}, ensure_ascii=False),
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=45, check=False,
)
try: checked = json.loads((preflight.stdout or "{}").strip().splitlines()[-1])
except Exception: checked = {}
entry_valid = list(checked.get("entry") or [])
exit_valid = list(checked.get("exit") or [])
# A proxy that already completed card binding can be temporarily
# unobservable from Cloudflare's trace endpoint. Keep it usable when
# every probe is inconclusive, but never bypass a positive country
# mismatch.
entry_inconclusive = list(checked.get("entry_inconclusive") or [])
exit_inconclusive = list(checked.get("exit_inconclusive") or [])
entry_mismatch = list(checked.get("entry_mismatch") or [])
exit_mismatch = list(checked.get("exit_mismatch") or [])
preflight_note = ""
if not entry_valid and entry_inconclusive and not entry_mismatch:
entry_valid = entry_inconclusive
preflight_note = " US probe inconclusive; reused supplied binding proxy."
if not exit_valid and exit_inconclusive and not exit_mismatch:
exit_valid = exit_inconclusive
preflight_note += " TR probe inconclusive; reused supplied promo proxy."
if not entry_valid or not exit_valid:
mismatch_note = []
if entry_mismatch: mismatch_note.append("US country mismatch")
if exit_mismatch: mismatch_note.append("TR country mismatch")
raise RuntimeError(
f"PROXY_PREFLIGHT_FAILED: US {int(checked.get('entry_valid') or 0)}/{int(checked.get('entry_total') or 0)}, "
f"TR {int(checked.get('exit_valid') or 0)}/{int(checked.get('exit_total') or 0)}"
+ ("; " + ", ".join(mismatch_note) if mismatch_note else "")
)
with _lock: _card_checkout_jobs[task_id].update(status="running", progress=12, message=f"Proxy preflight passed: US {len(entry_valid)}, TR {len(exit_valid)}.{preflight_note}")
if not PAY153_INTERNAL_KEY:
with _lock:
_card_checkout_jobs[task_id].update(
progress=18,
message="PAY153 bridge not configured; using bundled local checkout extractor",
)
result = _run_local_checkout_extractor(
str(job.get("_access_token") or ""),
entry_valid[0],
exit_valid[0],
)
_persist_checkout_context(_checkout_result_context(result, entry_valid, "local_checkout_extractor"))
with _lock:
_card_checkout_jobs[task_id].update(
status="done",
progress=100,
message="Checkout completed by local extractor",
result=result,
finished_at=time.time(),
_access_token="",
)
return
payload = {
"token": job["_access_token"], "plan": "plus", "link_type": "ph_short", "country": "PH",
"entry_proxies": entry_valid, "exit_proxies": exit_valid,
"entry_proxy_country": "US", "exit_proxy_country": "TR", "use_promo": True,
"promo_country": "TR", "retry_count": 10, "paired_proxy_rotation": True,
"allow_missing_customer_session": True,
"use_sen": True, "use_so": True,
}
status, created = _pay153_request("/api/checkout", "POST", payload)
pay_job_id = str(created.get("job_id") or "")
if status >= 400 or not pay_job_id:
raise RuntimeError(str(created.get("error") or f"PAY153_HTTP_{status}"))
with _lock: _card_checkout_jobs[task_id].update(progress=18, message="Checkout extraction running", _pay_job_id=pay_job_id)
deadline = time.monotonic() + 15 * 60
while time.monotonic() < deadline:
status, progress = _pay153_request("/api/checkout-progress", params={"job_id": pay_job_id})
if status >= 400: raise RuntimeError(str(progress.get("error") or f"PAY153_PROGRESS_HTTP_{status}"))
state = str(progress.get("status") or "")
with _lock:
current = _card_checkout_jobs.get(task_id)
if not current: return
current.update(progress=min(96, max(18, int(progress.get("percent") or 0))), message=str(progress.get("text") or "Checkout extraction running"))
if state == "done":
result = progress.get("result") if isinstance(progress.get("result"), dict) else {}
_persist_checkout_context(_checkout_result_context(result, entry_valid, "isolated_card_flow"))
with _lock: _card_checkout_jobs[task_id].update(status="done", progress=100, message="Checkout completed", result=result, finished_at=time.time(), _access_token="")
return
if state in {"error", "cancelled"}: raise RuntimeError(str(progress.get("error") or progress.get("text") or "Checkout failed"))
time.sleep(2)
raise TimeoutError("CHECKOUT_TIMEOUT")
except Exception as exc:
with _lock:
child_job_id = str((_card_checkout_jobs.get(task_id) or {}).get("_pay_job_id") or "")
if child_job_id:
try:
_pay153_request("/api/checkout-cancel", "POST", {"job_id": child_job_id})
except Exception:
pass
with _lock:
if task_id in _card_checkout_jobs:
current = _card_checkout_jobs[task_id]
if current.get("status") != "cancelled":
current.update(status="error", progress=100, message="Checkout failed", error=f"{type(exc).__name__}: {exc}"[:500], finished_at=time.time(), _access_token="")
def _start_card_checkout_job(
access_token: str,
entry_proxy_pool: list[str],
exit_proxy_pool: list[str],
) -> dict:
task_id = secrets.token_hex(6); now = time.time()
job = {"id": task_id, "status": "queued", "progress": 0, "message": "Task created", "error": "", "result": {}, "created_at": now, "finished_at": None, "_access_token": access_token, "_entry_proxies": entry_proxy_pool, "_exit_proxies": exit_proxy_pool, "_pay_job_id": ""}
with _lock: _card_checkout_jobs[task_id] = job
threading.Thread(target=_run_isolated_card_checkout, args=(task_id,), daemon=True, name=f"card-checkout-{task_id}").start()
return job
@app.post("/api/card-flow/quick-checkout")
def public_card_flow_quick_checkout():
body = request.get_json(silent=True) or {}
try:
access_token = _extract_protocol_access_token(body.get("access_token") or body.get("at"))
entry_proxy_pool = normalize_user_proxy_pool(body.get("entry_proxy_pool") or body.get("bind_proxy_pool") or body.get("proxy_pool"))
exit_proxy_pool = normalize_user_proxy_pool(body.get("exit_proxy_pool") or body.get("promo_proxy_pool"))
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
job = _start_card_checkout_job(access_token, entry_proxy_pool, exit_proxy_pool)
task_id = str(job["id"])
return jsonify({"ok": True, "task_id": task_id, "status": "queued"}), 201
@app.get("/api/card-flow/task/<task_id>")
def public_card_flow_task(task_id: str):
value = str(task_id or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", value):
return jsonify({"ok": False, "error": "INVALID_TASK_ID"}), 400
with _lock:
isolated = _card_checkout_jobs.get(value)
if isolated:
return jsonify(_card_checkout_public(isolated))
status, payload = reg_console_request(f"/api/tasks/{value}", "GET")
if isinstance(payload, dict) and isinstance(payload.get("options"), dict):
payload = dict(payload)
payload["options"] = {
key: val for key, val in payload["options"].items()
if key not in {"entry_proxies", "exit_proxies", "proxies", "proxy_pool"}
}
return jsonify(payload), status
@app.post("/api/card-flow/task/<task_id>/cancel")
def public_card_flow_cancel(task_id: str):
value = str(task_id or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", value):
return jsonify({"ok": False, "error": "INVALID_TASK_ID"}), 400
with _lock:
job = _card_checkout_jobs.get(value)
child_job_id = str((job or {}).get("_pay_job_id") or "")
if job:
job.update(status="cancelled", progress=100, message="Task replaced by retry", error="", finished_at=time.time(), _access_token="")
if child_job_id:
try:
_pay153_request("/api/checkout-cancel", "POST", {"job_id": child_job_id})
except Exception:
pass
return jsonify({"ok": True, "task_id": value, "child_cancelled": bool(child_job_id)})
@app.get("/api/card-bind/config")
def card_bind_config():
return jsonify({
"ok": True,
"requires_access_token": True,
"max_batch_concurrency": MAX_BATCH_CONCURRENCY,
})
@app.post("/api/card-bind/session")
def card_bind_session():
body = request.get_json(silent=True) or {}
raw_at = body.get("access_token") or body.get("at")
if raw_at:
try:
body = dict(body)
body["access_token"] = _extract_protocol_access_token(raw_at)
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
try:
account_email = resolve_card_bind_email(body)
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 404
try:
proxy_pool = normalize_user_proxy_pool(body.get("proxy_pool") or [body.get("proxy")])
selected_proxy = normalize_user_proxy(body.get("proxy") or proxy_pool[0])
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
submitted_at = str(body.get("access_token") or "").strip()
if selected_proxy in proxy_pool:
selected_index = proxy_pool.index(selected_proxy)
proxy_candidates = proxy_pool[selected_index:] + proxy_pool[:selected_index]
else:
proxy_candidates = [selected_proxy] + proxy_pool
proxy_candidates = list(dict.fromkeys(proxy_candidates))[:5]
retryable_proxy_errors = {
"CARD_BIND_UPSTREAM_NETWORK_ERROR",
"CARD_BIND_HELPER_TIMEOUT",
}
returncode = 10
payload = {"ok": False, "error": "CARD_BIND_UPSTREAM_NETWORK_ERROR"}
attempted_proxies = 0
attempted_rounds = 0
stop_retrying = False
for proxy_round in range(1, CARD_BIND_PROXY_REUSE_ATTEMPTS + 1):
attempted_rounds = proxy_round
for candidate_proxy in proxy_candidates:
attempted_proxies += 1
returncode, payload = _run_card_bind_session_helper(account_email, candidate_proxy, submitted_at)
selected_proxy = candidate_proxy
if returncode == 0 and payload.get("ok"):
stop_retrying = True
break
if str(payload.get("error") or "") not in retryable_proxy_errors:
stop_retrying = True
break
if stop_retrying:
break
if proxy_round < CARD_BIND_PROXY_REUSE_ATTEMPTS:
time.sleep(0.5)
if returncode != 0 or not payload.get("ok"):
if str(payload.get("error") or "") in retryable_proxy_errors:
exhausted = (
attempted_rounds >= CARD_BIND_PROXY_REUSE_ATTEMPTS
and attempted_proxies >= len(proxy_candidates) * CARD_BIND_PROXY_REUSE_ATTEMPTS
)
payload = dict(payload)
payload.update({
"error": "CARD_BIND_PROXY_POOL_EXHAUSTED" if exhausted else payload.get("error"),
"detail": (
f"Tried {attempted_rounds} fresh connection round(s) across "
f"{len(proxy_candidates)} rotating endpoint(s) before reaching the upstream. "
f"Last: {str(payload.get('detail') or '')}"
)[:600],
"proxy_attempts": attempted_proxies,
"proxy_rounds": attempted_rounds,
"proxy_pool_size": len(proxy_candidates),
"proxy_pool_exhausted": exhausted,
})
upstream = int(payload.get("status") or 0)
detail = str(payload.get("detail") or payload.get("error") or "")
# New accounts can answer 403/5xx before any Checkout has initialized
# their Stripe context. Initialize once and then fetch a fresh session.
needs_payment_account = "no payment account exists" in detail.lower()
if submitted_at and (upstream in {403, 500, 502, 503, 504} or needs_payment_account):
probe = _start_key_probe("", account_email, selected_proxy, submitted_at, proxy_pool)
return jsonify({
"ok": True, "pending": True, "key_probe_id": str(probe.get("id") or ""),
"account_email": account_email, "publishable_key_source": "checkout_then_refetch",
"initialization_reason": "payment_account_missing" if needs_payment_account else "upstream_unavailable",
}), 202
return card_helper_error_response(payload)
if not str(payload.get("publishable_key") or "").startswith("pk_"):
if CARD_BIND_PUBLISHABLE_KEY.startswith("pk_"):
payload.update({
"publishable_key": CARD_BIND_PUBLISHABLE_KEY,
"publishable_key_source": "configured_protocol_fallback",
"pending": False,
})
return jsonify(payload)
probe = _start_key_probe(
str(payload.get("record_id") or ""), account_email, selected_proxy,
submitted_at, proxy_pool, initial_session=payload,
)
payload.update({
"pending": True,
"key_probe_id": str(probe.get("id") or ""),
"publishable_key_source": "checkout_then_refetch",
})
return jsonify(payload), 202
payload["publishable_key_source"] = "access_token_protocol"
return jsonify(payload)
@app.get("/")
def index():
if request.script_root == "/card-link":
return render_template("card-flow.html")
if request.script_root == "/protocol-pay":
return render_template("protocol-pay.html")
return render_template("index.html")
@app.get("/api/source/tasks")
def source_tasks():
try:
payload = reg_bridge_get("/api/internal/ph-short/tasks", {"limit": 100})
except (RuntimeError, ValueError) as exc:
return jsonify({"ok": False, "error": str(exc)}), 502
return jsonify({"ok": True, "items": payload.get("items") or []})
@app.get("/api/jobs")
def list_jobs():
cleanup_jobs()
with _lock:
items = sorted(_jobs.values(), key=lambda item: item.get("created_at", 0), reverse=True)
result = [public_job(item) for item in items]
return jsonify({"ok": True, "items": result})
@app.post("/api/jobs")
def create_job():
cleanup_jobs()
payload = request.get_json(silent=True) or {}
task_id = str(payload.get("task_id") or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", task_id):
return jsonify({"ok": False, "error": "请选择一个已完成的菲律宾短链任务"}), 400
try:
confirmation_token = str(payload.get("confirmation_token") or "").strip()
if confirmation_token and not re.fullmatch(r"ctoken_[A-Za-z0-9]+", confirmation_token):
raise ValueError("ConfirmationToken format is invalid")
preconfirmed_checkout = payload.get("preconfirmed_checkout") or {}
if not isinstance(preconfirmed_checkout, dict):
raise ValueError("Preconfirmed Checkout response is invalid")
saved_payment_method_id = str(payload.get("saved_payment_method_id") or "").strip()
if saved_payment_method_id and not re.fullmatch(r"pm_[A-Za-z0-9]+", saved_payment_method_id):
raise ValueError("Saved PaymentMethod format is invalid")
cards = [] if (confirmation_token or saved_payment_method_id) else parse_cards(payload.get("cards") or payload.get("card_pool"))
proxies = parse_proxies(payload.get("proxies") or payload.get("proxy_pool"))
try:
card_retry_count = int(payload.get("card_retry_count", 2))
except (TypeError, ValueError) as exc:
raise ValueError("\u91cd\u8bd5\u6b21\u6570\u5fc5\u987b\u662f\u6574\u6570") from exc
card_retry_count = max(0, min(10, card_retry_count))
source = reg_bridge_get("/api/internal/ph-short/tasks", {"limit": 100})
source_item = next((item for item in source.get("items") or [] if item.get("task_id") == task_id), None)
if not source_item:
raise RuntimeError("短链任务不存在或尚未完成")
except (RuntimeError, ValueError) as exc:
return jsonify({"ok": False, "error": str(exc)}), 409
with _lock:
active = next(
(
item for item in _jobs.values()
if item.get("task_id") == task_id and item.get("status") in {"queued", "running", "verification_required"}
),
None,
)
if active:
return jsonify({"ok": True, "job": public_job(active), "existing": True})
job_id = secrets.token_hex(6)
now = time.time()
job = {
"id": job_id,
"task_id": task_id,
"account_email": str(source_item.get("email") or ""),
"status": "queued",
"progress": 0,
"stage": "等待执行",
"message": "任务已创建",
"error": "",
"result": {},
"logs": [],
"cancel_requested": False,
"created_at": now,
"updated_at": now,
"finished_at": None,
"script_root": request.script_root,
"_cards": cards,
"_saved_payment_method_id": saved_payment_method_id,
"_confirmation_token": confirmation_token,
"_preconfirmed_checkout": preconfirmed_checkout,
"_proxies": proxies,
"_card_retry_count": card_retry_count,
"_process": None,
}
_jobs[job_id] = job
threading.Thread(target=run_job, args=(job_id,), name=f"ph-short-{job_id}", daemon=True).start()
return jsonify({"ok": True, "job": public_job(job)}), 201
@app.get("/api/jobs/<job_id>")
def get_job(job_id: str):
with _lock:
job = _jobs.get(job_id)
result = public_job(job) if job else None
if not result:
return jsonify({"ok": False, "error": "任务不存在或已过期"}), 404
return jsonify({"ok": True, "job": result})
@app.post("/api/jobs/<job_id>/cancel")
def cancel_job(job_id: str):
with _lock:
job = _jobs.get(job_id)
if not job:
return jsonify({"ok": False, "error": "任务不存在或已过期"}), 404
if job.get("status") in {"ready", "error", "cancelled"}:
return jsonify({"ok": True, "job": public_job(job)})
if job.get("status") == "verification_required" and not job.get("_process"):
job.update({
"status": "cancelled",
"progress": 100,
"stage": "已停止",
"message": "任务已停止",
"finished_at": time.time(),
"updated_at": time.time(),
})
return jsonify({"ok": True, "job": public_job(job)})
job["cancel_requested"] = True
job["message"] = "正在停止任务"
job["updated_at"] = time.time()
result = public_job(job)
return jsonify({"ok": True, "job": result})
@app.post("/api/jobs/<job_id>/resume")
def resume_job(job_id: str):
with _lock:
job = _jobs.get(job_id)
if not job:
return jsonify({"ok": False, "error": "任务不存在或已过期"}), 404
if job.get("status") != "verification_required":
return jsonify({"ok": False, "error": "当前任务不在等待验证状态"}), 409
if not job.get("_resume_payload"):
return jsonify({"ok": False, "error": "任务缺少验证续跑上下文"}), 409
job["cancel_requested"] = False
job["status"] = "queued"
job["stage"] = "准备确认验证结果"
job["message"] = "续跑任务已提交"
job["updated_at"] = time.time()
result = public_job(job)
threading.Thread(target=run_resume_job, args=(job_id,), name=f"ph-resume-{job_id}", daemon=True).start()
return jsonify({"ok": True, "job": result})
@app.delete("/api/jobs/<job_id>")
def delete_job(job_id: str):
with _lock:
job = _jobs.get(job_id)
if not job:
return jsonify({"ok": True})
if job.get("status") in {"queued", "running", "verification_required"}:
return jsonify({"ok": False, "error": "运行中的任务请先停止"}), 409
_jobs.pop(job_id, None)
return jsonify({"ok": True})
@app.get("/jobs/<job_id>/open")
def open_checkout(job_id: str):
with _lock:
job = _jobs.get(job_id)
result = dict((job or {}).get("result") or {})
short_url = str(result.get("short_url") or "")
if not short_url:
return redirect(f"{request.script_root}/?error=job_not_ready")
return redirect(short_url, code=302)
@app.get("/healthz")
def healthz():
cleanup_jobs()
with _lock:
active = sum(1 for item in _jobs.values() if item.get("status") in {"queued", "running", "verification_required"})
return jsonify({
"ok": True,
"service": "reg153-ph-short-protocol",
"mode": "stripe_checkout_protocol",
"temporary_browser": False,
"active_jobs": active,
"jobs": len(_jobs),
})
# --- Standalone saved-card payment: headless bootstrap, then protocol confirmation ---
def _extract_protocol_access_token(raw) -> str:
value = str(raw or "").strip()
if not value:
raise ValueError("AT_REQUIRED")
candidates: list[str] = []
if value.startswith(("{", "[")):
try:
obj = json.loads(value)
except Exception as exc:
raise ValueError("AT_JSON_INVALID") from exc
def collect_tokens(item) -> None:
if isinstance(item, dict):
for key in ("accessToken", "access_token", "token", "at"):
candidate = str(item.get(key) or "").strip()
if candidate.count(".") == 2 and candidate.startswith("eyJ"):
candidates.append(candidate)
for child in item.values():
collect_tokens(child)
elif isinstance(item, list):
for child in item:
collect_tokens(child)
collect_tokens(obj)
else:
if value.lower().startswith("bearer "):
value = value[7:].strip()
candidates.extend(
re.findall(r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", value)
)
if value.count(".") == 2 and value.startswith("eyJ"):
candidates.append(value)
candidates = list(dict.fromkeys(candidates))
if not candidates:
raise ValueError("AT_FORMAT_INVALID")
def token_rank(token: str) -> tuple[int, int, int]:
try:
claims = _decode_access_token_claims(token)
now = int(time.time())
exp = int(claims.get("exp") or 0)
issued = int(claims.get("iat") or 0)
return int(not exp or exp > now), issued, exp
except (TypeError, ValueError):
return 0, 0, 0
return max(candidates, key=token_rank)
def _protocol_token_identity(token: str) -> dict:
try:
segment = token.split(".")[1]
segment += "=" * (-len(segment) % 4)
claims = json.loads(base64.urlsafe_b64decode(segment.encode()).decode("utf-8"))
except Exception as exc:
raise ValueError("AT_PAYLOAD_INVALID") from exc
auth = claims.get("https://api.openai.com/auth") or {}
profile = claims.get("https://api.openai.com/profile") or {}
account_id = str(auth.get("chatgpt_account_id") or auth.get("account_id") or "").strip()
email = str(profile.get("email") or claims.get("email") or "").strip().lower()
if not account_id:
raise ValueError("AT_ACCOUNT_ID_MISSING")
exp = int(claims.get("exp") or 0)
if exp and exp <= int(time.time()):
raise ValueError("AT_EXPIRED")
return {"account_id": account_id, "email": email}
def _normalize_protocol_checkout_url(raw: str) -> tuple[str, str, str]:
value = str(raw or "").strip()
parsed = urlparse(value)
if parsed.scheme != "https":
raise ValueError("CHECKOUT_HTTPS_REQUIRED")
if parsed.hostname == "chatgpt.com":
return validate_short_url(value)
if parsed.hostname == "pay.openai.com":
parts = [part for part in parsed.path.split("/") if part]
if len(parts) >= 3 and parts[0] == "c" and parts[1] == "pay" and re.fullmatch(r"cs_[A-Za-z0-9_-]{12,}", parts[2]):
session_id = parts[2]
return f"https://chatgpt.com/checkout/openai_llc/{session_id}", "openai_llc", session_id
raise ValueError("CHECKOUT_URL_UNSUPPORTED")
def _protocol_public_job(job: dict) -> dict:
return {
"id": job.get("id"), "status": job.get("status"), "progress": int(job.get("progress") or 0),
"stage": job.get("stage"), "message": job.get("message"), "error": job.get("error"),
"result": dict(job.get("result") or {}), "logs": list(job.get("logs") or []),
"account_email": job.get("account_email") or "", "checkout_url": job.get("checkout_url") or "",
"created_at": job.get("created_at"), "updated_at": job.get("updated_at"), "finished_at": job.get("finished_at"),
}
def _protocol_update(job_id: str, **updates):
with _lock:
job = _protocol_pay_jobs.get(job_id)
if not job:
return
job.update(updates); job["updated_at"] = time.time()
def _protocol_log(job_id: str, level: str, message: str):
text = str(message or "").strip()
if not text:
return
with _lock:
job = _protocol_pay_jobs.get(job_id)
if not job:
return
logs = job.setdefault("logs", [])
logs.append({"time": time.strftime("%H:%M:%S"), "type": level, "message": text[:600]})
if len(logs) > 24:
del logs[:-24]
job["updated_at"] = time.time()
def _protocol_helper_error(stdout: str, fallback: str) -> str:
"""Extract a structured helper error, preserving non-JSON diagnostics."""
last_plain = ""
last_error = ""
for line in str(stdout or "").splitlines():
text = line.strip()
if not text:
continue
try:
event = json.loads(text)
except Exception:
last_plain = text[:500]
continue
if isinstance(event, dict) and event.get("type") == "error":
last_error = str(event.get("error") or "")
return last_error or last_plain or fallback
def _run_standalone_protocol_pay(job_id: str):
with _lock:
job = dict(_protocol_pay_jobs.get(job_id) or {})
if not job:
return
try:
_protocol_update(job_id, status="running", progress=8, stage="\u6821\u9a8c\u8d26\u53f7", message="\u6b63\u5728\u89e3\u6790 AT \u4e0e Checkout")
origin = dict(job.get("_origin_context") or {})
origin_cookies = dict(origin.get("session_cookies") or {})
account_cookies = _lookup_reg_account_session(job.get("account_email") or "", job.get("account_id") or "")
merged_cookies = dict(account_cookies)
merged_cookies.update(origin_cookies)
_protocol_log(job_id, "info", f"Session context merged: account={len(account_cookies)} checkout={len(origin_cookies)} total={len(merged_cookies)}")
snapshot = {
"short_url": job["checkout_url"], "processor_entity": job["processor_entity"],
"checkout_session_id": job["checkout_session_id"], "access_token": job["_access_token"],
"chatgpt_account_id": job["account_id"], "session_cookies": merged_cookies,
"user_agent": str(origin.get("checkout_user_agent") or "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:144.0) Gecko/20100101 Firefox/144.0"),
"checkout_device_id": str(origin.get("checkout_device_id") or uuid.uuid4()),
"checkout_chatgpt_session_id": str(origin.get("checkout_chatgpt_session_id") or ""),
"email": job.get("account_email") or "", "proxy": job["_proxies"][0],
"checkout_proxy": job["_proxies"][0],
"saved_payment_method_id": str(job.get("_saved_payment_method_id") or ""),
"preserve_checkout_identity": bool(origin),
"context_source": str(origin.get("source") or "generated"),
}
proc = subprocess.Popen(
[PAY153_PYTHON, STANDALONE_PAY_HELPER], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", bufsize=1,
)
with _lock:
if job_id in _protocol_pay_jobs:
_protocol_pay_jobs[job_id]["_process"] = proc
assert proc.stdin is not None and proc.stdout is not None
helper_mode = "prepare" if job.get("_defer_confirm") else "run"
proc.stdin.write(json.dumps({"mode": helper_mode, "snapshot": snapshot, "proxies": job["_proxies"]}, ensure_ascii=False)); proc.stdin.close()
result = {}; last_error = ""; last_plain = ""
for line in proc.stdout:
text = line.strip()
if not text: continue
try: event = json.loads(text)
except Exception:
last_plain = text[:500]
_protocol_log(job_id, "info", text); continue
if event.get("type") == "log":
message = str(event.get("message") or ""); phase = str(event.get("phase") or "")
_protocol_log(job_id, str(event.get("level") or "info"), message)
if phase == "validate": _protocol_update(job_id, progress=18, stage="\u68c0\u67e5\u5df2\u7ed1\u5361", message=message)
elif phase == "headless": _protocol_update(job_id, progress=38, stage="Checkout \u521d\u59cb\u5316", message=message)
elif phase == "headless_done": _protocol_update(job_id, progress=66, stage="\u534f\u8bae\u4e0a\u4e0b\u6587\u5c31\u7eea", message=message)
elif phase == "protocol": _protocol_update(job_id, progress=76, stage="\u534f\u8bae\u786e\u8ba4", message=message)
else:
lower = message.lower()
if "checkout confirm" in lower: _protocol_update(job_id, progress=84, stage="Checkout \u786e\u8ba4", message=message)
elif "stripe" in lower and "status=" in lower: _protocol_update(job_id, progress=93, stage="Stripe \u6700\u7ec8\u72b6\u6001", message=message)
elif event.get("type") == "result": result = dict(event.get("result") or {})
elif event.get("type") == "error": last_error = str(event.get("error") or "")
code = proc.wait(timeout=10)
if code != 0 or not result:
raise RuntimeError(last_error or last_plain or f"PAY_HELPER_EXIT_{code}")
status = str(result.get("status") or "").lower()
if status == "prepared" and job.get("_defer_confirm"):
private_prepared = dict(result.get("prepared") or {})
safe_result = dict(result.get("safe") or {})
if not private_prepared:
raise RuntimeError("PREPARED_CONTEXT_MISSING")
_protocol_update(job_id, status="prepared", progress=72, stage="\u51c6\u5907\u5b8c\u6210", message="\u5df2\u5c31\u7eea\uff0c\u7b49\u5f85\u6240\u6709\u4efb\u52a1\u540c\u65f6\u63d0\u4ea4", result=safe_result, _prepared=private_prepared)
return
if status == "verification_required":
_protocol_update(job_id, status="verification_required", progress=94, stage="\u7b49\u5f85\u9a8c\u8bc1", message="\u652f\u4ed8\u9700\u8981\u989d\u5916\u9a8c\u8bc1", result=result)
elif status == "pending_verification":
_protocol_update(job_id, status="pending_verification", progress=98, stage="\u7b49\u5f85\u8ba2\u9605\u540c\u6b65", message="Stripe \u5df2\u5b8c\u6210\uff0c\u6b63\u5728\u7b49\u5f85\u8ba2\u9605\u7ec8\u6001", result=result)
else:
_protocol_update(job_id, status="ready", progress=100, stage="\u652f\u4ed8\u5b8c\u6210", message="\u7eaf\u534f\u8bae\u76f4\u5361\u652f\u4ed8\u5df2\u5b8c\u6210", result=result, finished_at=time.time())
except Exception as exc:
message = str(exc)
if message.startswith("RuntimeError: "):
message = message[14:]
_protocol_log(job_id, "error", message)
_protocol_update(job_id, status="error", progress=100, stage="\u6267\u884c\u5931\u8d25", message=message, error=message, finished_at=time.time())
finally:
with _lock:
if job_id in _protocol_pay_jobs:
_protocol_pay_jobs[job_id]["_process"] = None
_protocol_pay_jobs[job_id].pop("_access_token", None)
_protocol_pay_jobs[job_id].pop("_cards", None)
_protocol_pay_jobs[job_id].pop("_saved_payment_method_id", None)
def _unified_public_job(job: dict) -> dict:
return {
"id": job.get("id"), "status": job.get("status"),
"progress": int(job.get("progress") or 0), "stage": job.get("stage") or "",
"message": job.get("message") or "", "error": job.get("error") or "",
"result": dict(job.get("result") or {}),
"account_email": job.get("account_email") or "",
"checkout_url": job.get("checkout_url") or "",
"created_at": job.get("created_at"), "updated_at": job.get("updated_at"),
"finished_at": job.get("finished_at"),
}
def _unified_update(job_id: str, **updates) -> None:
with _lock:
job = _unified_flow_jobs.get(job_id)
if not job:
return
job.update(updates)
job["updated_at"] = time.time()
def _unified_cancelled(job_id: str) -> bool:
with _lock:
return str((_unified_flow_jobs.get(job_id) or {}).get("status") or "") == "cancelled"
def _start_unified_protocol_child(parent: dict, checkout_result: dict) -> tuple[str, str]:
parent_job_id = str(parent.get("id") or "")
if _unified_cancelled(parent_job_id):
raise InterruptedError("任务已停止")
entry_proxies = list(parent.get("_entry_proxies") or [])
context = _checkout_result_context(checkout_result, entry_proxies, "unified_card_flow")
raw_url = str(context.get("checkout_url") or "")
checkout_url, processor, session_id = _normalize_protocol_checkout_url(raw_url)
context.update({
"checkout_url": checkout_url,
"processor_entity": processor,
"checkout_session_id": session_id,
"source": "unified_card_flow",
})
_persist_checkout_context(context)
origin_context = _lookup_checkout_context(session_id) or context
origin_proxy = str(origin_context.get("checkout_proxy") or "").strip()
selected_proxy = normalize_user_proxy(origin_proxy or entry_proxies[0])
protocol_job_id = secrets.token_hex(6)
now = time.time()
protocol_job = {
"id": protocol_job_id, "status": "queued", "progress": 0,
"stage": "等待执行", "message": "统一流程已交接到协议支付", "error": "",
"result": {}, "logs": [], "account_email": parent.get("account_email") or "",
"account_id": parent.get("account_id") or "", "checkout_url": checkout_url,
"processor_entity": processor, "checkout_session_id": session_id,
"created_at": now, "updated_at": now, "finished_at": None,
"_access_token": parent.get("_access_token") or "", "_proxies": [selected_proxy],
"_cards": [], "_saved_payment_method_id": parent.get("_payment_method_id") or "",
"_origin_context": origin_context, "_process": None,
"_defer_confirm": True, "_prepared": None,
}
with _lock:
parent_job = _unified_flow_jobs.get(parent_job_id)
if not parent_job or parent_job.get("status") == "cancelled":
raise InterruptedError("任务已停止")
_protocol_pay_jobs[protocol_job_id] = protocol_job
parent_job.update(_protocol_job_id=protocol_job_id, checkout_url=checkout_url, updated_at=time.time())
threading.Thread(
target=_run_standalone_protocol_pay,
args=(protocol_job_id,),
daemon=True,
name=f"unified-protocol-{protocol_job_id}",
).start()
return protocol_job_id, checkout_url
def _run_unified_flow(job_id: str) -> None:
with _lock:
job = dict(_unified_flow_jobs.get(job_id) or {})
if not job:
return
try:
_unified_update(job_id, status="running", progress=5, stage="设置默认卡", message="正在确认本次绑定的支付方式")
default_result = None
default_error = ""
for index, candidate in enumerate(list(job.get("_entry_proxies") or [])[:3], 1):
if _unified_cancelled(job_id):
raise InterruptedError("任务已停止")
_unified_update(job_id, progress=5 + index * 3, message=f"正在通过绑卡线路 {index} 设置默认卡")
try:
returncode, payload = _run_card_set_default(
str(job.get("account_email") or ""),
str(job.get("_payment_method_id") or ""),
candidate,
str(job.get("_access_token") or ""),
)
if returncode == 0 and payload.get("ok"):
default_result = payload
break
default_error = str(payload.get("error") or f"SET_DEFAULT_EXIT_{returncode}")
default_detail = str(payload.get("detail") or "").strip()
if default_detail and default_detail not in default_error:
default_error = f"{default_error}: {default_detail}"
if int(payload.get("status") or 0) in {401, 422}:
break
except Exception as exc:
default_error = f"{type(exc).__name__}: {exc}"
if default_result is None:
raise RuntimeError(default_error or "SET_DEFAULT_FAILED")
_unified_update(job_id, progress=18, stage="创建 Checkout", message="绑卡已确认,正在提取 Checkout")
checkout_job = _start_card_checkout_job(
str(job.get("_access_token") or ""),
list(job.get("_entry_proxies") or []),
list(job.get("_exit_proxies") or []),
)
checkout_task_id = str(checkout_job.get("id") or "")
_unified_update(job_id, _checkout_task_id=checkout_task_id)
checkout_result = {}
while True:
if _unified_cancelled(job_id):
raise InterruptedError("任务已停止")
with _lock:
child = dict(_card_checkout_jobs.get(checkout_task_id) or {})
if not child:
raise RuntimeError("CHECKOUT_CHILD_MISSING")
child_status = str(child.get("status") or "")
child_progress = int(child.get("progress") or 0)
_unified_update(
job_id,
progress=min(58, 18 + round(child_progress * 0.40)),
stage="创建 Checkout",
message=str(child.get("message") or "正在提取 Checkout"),
)
if child_status == "done":
checkout_result = dict(child.get("result") or {})
break
if child_status in {"error", "failed", "cancelled"}:
raise RuntimeError(str(child.get("error") or child.get("message") or "CHECKOUT_FAILED"))
time.sleep(0.5)
_unified_update(job_id, progress=60, stage="协议支付", message="Checkout 已生成,正在复用原始会话执行支付")
protocol_job_id, checkout_url = _start_unified_protocol_child(job, checkout_result)
_unified_update(job_id, checkout_url=checkout_url)
while True:
if _unified_cancelled(job_id):
raise InterruptedError("任务已停止")
with _lock:
child = dict(_protocol_pay_jobs.get(protocol_job_id) or {})
if not child:
raise RuntimeError("PROTOCOL_CHILD_MISSING")
child_status = str(child.get("status") or "")
child_progress = int(child.get("progress") or 0)
_unified_update(
job_id,
status="prepared" if child_status == "prepared" else "running",
progress=min(99, 60 + round(child_progress * 0.39)),
stage=str(child.get("stage") or "协议支付"),
message=str(child.get("message") or "正在执行协议支付"),
)
if child_status in {"ready", "verification_required", "pending_verification"}:
result = dict(child.get("result") or {})
result["checkout_url"] = checkout_url
if child_status == "ready":
_unified_update(
job_id, status="ready", progress=100, stage="完成",
message="绑卡、提链与协议支付已完成", result=result,
finished_at=time.time(),
)
else:
_unified_update(
job_id, status=child_status, progress=96,
stage=str(child.get("stage") or "等待验证"),
message=str(child.get("message") or "等待最终状态确认"),
result=result,
)
return
if child_status in {"error", "cancelled"}:
raise RuntimeError(str(child.get("error") or child.get("message") or "PROTOCOL_PAY_FAILED"))
time.sleep(0.5)
except InterruptedError as exc:
_unified_update(job_id, status="cancelled", progress=100, stage="已停止", message=str(exc), finished_at=time.time())
except Exception as exc:
if not _unified_cancelled(job_id):
message = str(exc)
if message.startswith("RuntimeError: "):
message = message[14:]
_unified_update(
job_id, status="error", progress=100, stage="执行失败",
message=message, error=message, finished_at=time.time(),
)
finally:
with _lock:
current = _unified_flow_jobs.get(job_id)
if current:
current.pop("_access_token", None)
current.pop("_payment_method_id", None)
current.pop("_entry_proxies", None)
current.pop("_exit_proxies", None)
@app.post("/api/unified-flow/jobs")
def create_unified_flow_job():
body = request.get_json(silent=True) or {}
try:
token = _extract_protocol_access_token(body.get("access_token") or body.get("at"))
identity = _protocol_token_identity(token)
payment_method_id = str(body.get("payment_method_id") or "").strip()
if not re.fullmatch(r"pm_[A-Za-z0-9]+", payment_method_id):
raise ValueError("INVALID_PAYMENT_METHOD")
entry_proxy_pool = normalize_user_proxy_pool(
body.get("entry_proxy_pool") or body.get("bind_proxy_pool") or body.get("proxy_pool")
)
exit_proxy_pool = normalize_user_proxy_pool(
body.get("exit_proxy_pool") or body.get("promo_proxy_pool")
)
account_email = str(identity.get("email") or "").strip().lower()
if not account_email:
account_email = resolve_card_bind_email({"access_token": token})
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
job_id = secrets.token_hex(6)
now = time.time()
job = {
"id": job_id, "status": "queued", "progress": 0, "stage": "等待执行",
"message": "统一任务已创建", "error": "", "result": {},
"account_email": account_email, "account_id": identity.get("account_id") or "",
"checkout_url": "", "created_at": now, "updated_at": now, "finished_at": None,
"_access_token": token, "_payment_method_id": payment_method_id,
"_entry_proxies": entry_proxy_pool, "_exit_proxies": exit_proxy_pool,
"_checkout_task_id": "", "_protocol_job_id": "",
}
with _lock:
_unified_flow_jobs[job_id] = job
if len(_unified_flow_jobs) > FLOW_JOB_CACHE_LIMIT:
finished = sorted(
(item for item in _unified_flow_jobs.values() if item.get("status") in {"ready", "error", "cancelled", "pending_verification"}),
key=lambda item: item.get("created_at", 0),
)
for old in finished[:max(0, len(_unified_flow_jobs) - FLOW_JOB_CACHE_LIMIT)]:
_unified_flow_jobs.pop(str(old.get("id") or ""), None)
threading.Thread(target=_run_unified_flow, args=(job_id,), daemon=True, name=f"unified-flow-{job_id}").start()
return jsonify({"ok": True, "job": _unified_public_job(job)}), 201
@app.post("/api/unified-flow/batch-confirm")
def confirm_unified_flow_batch():
body = request.get_json(silent=True) or {}
job_ids = []
for raw in body.get("job_ids") or []:
value = str(raw or "").strip().lower()
if value and value not in job_ids:
job_ids.append(value)
if (
not job_ids
or len(job_ids) > MAX_BATCH_CONCURRENCY
or any(not re.fullmatch(r"[a-f0-9]{12}", value) for value in job_ids)
):
return jsonify({"ok": False, "error": "JOB_IDS_INVALID"}), 400
with _lock:
missing = [value for value in job_ids if value not in _unified_flow_jobs]
protocol_ids = {
value: str((_unified_flow_jobs.get(value) or {}).get("_protocol_job_id") or "")
for value in job_ids
}
unready = [
value for value in job_ids
if (_unified_flow_jobs.get(value) or {}).get("status") != "prepared"
or not protocol_ids[value]
or (_protocol_pay_jobs.get(protocol_ids[value]) or {}).get("status") != "prepared"
]
if not missing and not unready:
for value in job_ids:
child = _protocol_pay_jobs[protocol_ids[value]]
child.update(
status="releasing", progress=78,
stage="\u7b49\u5f85\u540c\u6b65\u5c4f\u969c",
message="\u652f\u4ed8\u5df2\u5c31\u7eea\uff0c\u7b49\u5f85\u5e76\u53d1\u653e\u884c",
updated_at=time.time(),
)
_unified_flow_jobs[value].update(
status="running", progress=90,
stage="\u5e76\u53d1\u652f\u4ed8\u653e\u884c",
message="\u6240\u6709\u51c6\u5907\u4efb\u52a1\u5df2\u5230\u8fbe\u5c4f\u969c",
updated_at=time.time(),
)
if missing:
return jsonify({"ok": False, "error": "TASK_NOT_FOUND", "job_ids": missing}), 404
if unready:
return jsonify({"ok": False, "error": "TASKS_NOT_PREPARED", "job_ids": unready}), 409
gate = threading.Event()
for value in job_ids:
protocol_job_id = protocol_ids[value]
threading.Thread(
target=_run_prepared_protocol_confirm,
args=(protocol_job_id, gate),
daemon=True,
name=f"unified-confirm-{protocol_job_id}",
).start()
time.sleep(0.08)
gate.set()
with _lock:
jobs = [_unified_public_job(_unified_flow_jobs[value]) for value in job_ids]
return jsonify({"ok": True, "jobs": jobs, "released": len(jobs), "mode": "simultaneous"})
@app.get("/api/unified-flow/jobs/<job_id>")
def get_unified_flow_job(job_id: str):
value = str(job_id or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", value):
return jsonify({"ok": False, "error": "INVALID_TASK_ID"}), 400
with _lock:
job = _unified_flow_jobs.get(value)
payload = _unified_public_job(job) if job else None
if not payload:
return jsonify({"ok": False, "error": "TASK_NOT_FOUND"}), 404
return jsonify({"ok": True, "job": payload})
@app.post("/api/unified-flow/jobs/<job_id>/cancel")
def cancel_unified_flow_job(job_id: str):
value = str(job_id or "").strip().lower()
if not re.fullmatch(r"[a-f0-9]{12}", value):
return jsonify({"ok": False, "error": "INVALID_TASK_ID"}), 400
with _lock:
job = _unified_flow_jobs.get(value)
if not job:
return jsonify({"ok": False, "error": "TASK_NOT_FOUND"}), 404
checkout_task_id = str(job.get("_checkout_task_id") or "")
protocol_job_id = str(job.get("_protocol_job_id") or "")
job.update(status="cancelled", progress=100, stage="已停止", message="用户停止任务", finished_at=time.time())
job.pop("_access_token", None)
job.pop("_payment_method_id", None)
job.pop("_entry_proxies", None)
job.pop("_exit_proxies", None)
checkout_child = _card_checkout_jobs.get(checkout_task_id)
pay153_job_id = str((checkout_child or {}).get("_pay_job_id") or "")
if checkout_child:
checkout_child.update(status="cancelled", progress=100, message="Parent task cancelled", _access_token="")
protocol_child = _protocol_pay_jobs.get(protocol_job_id)
process = (protocol_child or {}).get("_process")
if pay153_job_id:
try:
_pay153_request("/api/checkout-cancel", "POST", {"job_id": pay153_job_id})
except Exception:
pass
if process and process.poll() is None:
try:
process.terminate()
except Exception:
pass
with _lock:
payload = _unified_public_job(_unified_flow_jobs[value])
return jsonify({"ok": True, "job": payload})
@app.get("/protocol-pay/")
def standalone_protocol_pay_page():
return render_template("protocol-pay.html")
@app.post("/api/protocol-pay/jobs")
def create_standalone_protocol_pay_job():
body = request.get_json(silent=True) or {}
try:
token = _extract_protocol_access_token(body.get("access_token") or body.get("at"))
identity = _protocol_token_identity(token)
payment_method_id = str(body.get("payment_method_id") or "").strip()
if payment_method_id and not re.fullmatch(r"pm_[A-Za-z0-9]+", payment_method_id):
raise ValueError("INVALID_PAYMENT_METHOD")
raw_cards = body.get("cards") or body.get("card") or []
cards = parse_cards(raw_cards) if raw_cards else []
checkout_url, processor, session_id = _normalize_protocol_checkout_url(body.get("checkout_url") or body.get("url"))
origin_context = _lookup_checkout_context(session_id)
origin_proxy_raw = str(origin_context.get("checkout_proxy") or "")
ttl_match = re.search(r"-t-(\d+)", origin_proxy_raw)
origin_created = float(origin_context.get("created_at") or 0)
if ttl_match and origin_created:
ttl_seconds = max(60, int(ttl_match.group(1)) * 60)
age_seconds = max(0, time.time() - origin_created)
if age_seconds > max(60, ttl_seconds - 30):
raise ValueError(
f"CHECKOUT_PROXY_SESSION_EXPIRED: link age {int(age_seconds // 60)}m exceeds sticky session {int(ttl_seconds // 60)}m; regenerate the Checkout link"
)
proxies = []
origin_proxy = str(origin_context.get("checkout_proxy") or "").strip()
if origin_proxy:
proxies.append(normalize_user_proxy(origin_proxy))
proxy_errors = []
for _ in range(3):
try:
generated = reg_bridge_get("/api/internal/ph-short/proxy", {"country": "US"})
candidate = normalize_user_proxy(str(generated.get("proxy") or ""))
if candidate not in proxies:
proxies.append(candidate)
except Exception as exc:
proxy_errors.append(str(exc))
if not proxies:
raise RuntimeError("AUTO_PROXY_FAILED: " + (proxy_errors[-1] if proxy_errors else "NO_PROXY_RETURNED"))
preflight = subprocess.run(
[PAY153_PYTHON, PROXY_PREFLIGHT_HELPER],
input=json.dumps({"proxies": proxies, "expected": "US", "limit": 3}, ensure_ascii=False),
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=45, check=False,
)
try:
checked = json.loads((preflight.stdout or "{}").strip().splitlines()[-1])
except Exception:
checked = {}
proxies = list(checked.get("proxies") or [])
if not proxies:
raise RuntimeError(
f"US_PROXY_PREFLIGHT_FAILED: {int(checked.get('valid') or 0)}/{int(checked.get('total') or 0)}"
)
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
except RuntimeError as exc:
return jsonify({"ok": False, "error": str(exc)}), 502
job_id = secrets.token_hex(6); now = time.time()
job = {
"id": job_id, "status": "queued", "progress": 0, "stage": "\u7b49\u5f85\u6267\u884c", "message": "\u4efb\u52a1\u5df2\u521b\u5efa",
"error": "", "result": {}, "logs": [], "account_email": identity.get("email") or "",
"account_id": identity["account_id"], "checkout_url": checkout_url, "processor_entity": processor,
"checkout_session_id": session_id, "created_at": now, "updated_at": now, "finished_at": None,
"_access_token": token, "_proxies": proxies, "_cards": cards, "_origin_context": origin_context, "_process": None,
"_saved_payment_method_id": payment_method_id,
"_defer_confirm": bool(body.get("defer_confirm")), "_prepared": None,
}
with _lock:
_protocol_pay_jobs[job_id] = job
if len(_protocol_pay_jobs) > FLOW_JOB_CACHE_LIMIT:
finished = sorted((x for x in _protocol_pay_jobs.values() if x.get("status") in {"ready","error","cancelled","pending_verification"}), key=lambda x:x.get("created_at",0))
for old in finished[:max(0,len(_protocol_pay_jobs)-FLOW_JOB_CACHE_LIMIT)]: _protocol_pay_jobs.pop(str(old.get("id")),None)
threading.Thread(target=_run_standalone_protocol_pay, args=(job_id,), daemon=True, name=f"protocol-pay-{job_id}").start()
return jsonify({"ok": True, "job": _protocol_public_job(job)}), 201
def _run_prepared_protocol_confirm(job_id: str, gate: threading.Event) -> None:
with _lock:
job = dict(_protocol_pay_jobs.get(job_id) or {})
if not job or not job.get("_prepared"):
return
try:
_protocol_update(job_id, status="queued", progress=78, stage="\u7b49\u5f85\u540c\u6b65\u5c4f\u969c", message="\u6240\u6709\u4efb\u52a1\u5df2\u5c31\u7eea")
gate.wait(timeout=30)
_protocol_update(job_id, status="running", progress=82, stage="\u540c\u65f6\u63d0\u4ea4\u8ba2\u9605", message="\u5c4f\u969c\u5df2\u91ca\u653e")
proc = subprocess.Popen([PAY153_PYTHON, STANDALONE_PAY_HELPER], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", bufsize=1)
with _lock:
if job_id in _protocol_pay_jobs: _protocol_pay_jobs[job_id]["_process"] = proc
assert proc.stdin is not None and proc.stdout is not None
proc.stdin.write(json.dumps({"mode":"confirm","prepared":job["_prepared"]},ensure_ascii=False));proc.stdin.close()
result={};last_error=""
for line in proc.stdout:
text=line.strip()
if not text:continue
try:event=json.loads(text)
except Exception:_protocol_log(job_id,"info",text);continue
if event.get("type")=="log":
message=str(event.get("message") or "");_protocol_log(job_id,str(event.get("level") or "info"),message)
if "checkout confirm" in message.lower():_protocol_update(job_id,progress=90,stage="Checkout \u786e\u8ba4",message=message)
elif event.get("type")=="result":result=dict(event.get("result") or {})
elif event.get("type")=="error":last_error=str(event.get("error") or "")
code=proc.wait(timeout=10)
if code!=0 or not result:raise RuntimeError(last_error or f"PAY_HELPER_EXIT_{code}")
result_status=str(result.get("status") or "").lower()
if result_status=="verification_required":_protocol_update(job_id,status="verification_required",progress=94,stage="\u7b49\u5f85\u9a8c\u8bc1",message="\u652f\u4ed8\u9700\u8981\u989d\u5916\u9a8c\u8bc1",result=result)
elif result_status=="pending_verification":_protocol_update(job_id,status="pending_verification",progress=98,stage="\u7b49\u5f85\u8ba2\u9605\u540c\u6b65",message="Stripe \u5df2\u5b8c\u6210\uff0c\u6b63\u5728\u7b49\u5f85\u8ba2\u9605\u7ec8\u6001",result=result)
else:_protocol_update(job_id,status="ready",progress=100,stage="\u8ba2\u9605\u5b8c\u6210",message="\u540c\u6b65\u534f\u8bae\u8ba2\u9605\u5df2\u5b8c\u6210",result=result,finished_at=time.time())
except Exception as exc:
message=str(exc);_protocol_log(job_id,"error",message);_protocol_update(job_id,status="error",progress=100,stage="\u6267\u884c\u5931\u8d25",message=message,error=message,finished_at=time.time())
finally:
with _lock:
if job_id in _protocol_pay_jobs:
_protocol_pay_jobs[job_id]["_process"]=None;_protocol_pay_jobs[job_id].pop("_prepared",None)
@app.post("/api/protocol-pay/batch-confirm")
def confirm_protocol_pay_batch():
body=request.get_json(silent=True) or {};job_ids=[]
for value in body.get("job_ids") or []:
jid=str(value or "").strip()
if jid and jid not in job_ids:job_ids.append(jid)
if not job_ids or len(job_ids)>MAX_BATCH_CONCURRENCY:return jsonify({"ok":False,"error":"JOB_IDS_INVALID"}),400
with _lock:
missing=[jid for jid in job_ids if jid not in _protocol_pay_jobs]
unready=[jid for jid in job_ids if jid in _protocol_pay_jobs and _protocol_pay_jobs[jid].get("status")!="prepared"]
if missing:return jsonify({"ok":False,"error":"TASK_NOT_FOUND","job_ids":missing}),404
if unready:return jsonify({"ok":False,"error":"TASKS_NOT_PREPARED","job_ids":unready}),409
gate=threading.Event()
for jid in job_ids:
threading.Thread(target=_run_prepared_protocol_confirm,args=(jid,gate),daemon=True,name=f"protocol-confirm-{jid}").start()
time.sleep(0.08);gate.set()
with _lock:jobs=[_protocol_public_job(_protocol_pay_jobs[jid]) for jid in job_ids]
return jsonify({"ok":True,"jobs":jobs,"released":len(jobs),"mode":"simultaneous"})
@app.get("/api/protocol-pay/jobs/<job_id>")
def get_standalone_protocol_pay_job(job_id: str):
with _lock:
job = _protocol_pay_jobs.get(str(job_id or ""))
payload = _protocol_public_job(job) if job else None
if not payload:
return jsonify({"ok": False, "error": "TASK_NOT_FOUND"}), 404
return jsonify({"ok": True, "job": payload})
if __name__ == "__main__":
app.run(host="127.0.0.1", port=int(os.getenv("PORT", "5088")), debug=False)
|