Spaces:
Paused
Paused
File size: 296,002 Bytes
b391298 8e6b7e4 b391298 8e6b7e4 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 8e6b7e4 b391298 aa43ba6 b391298 aa43ba6 b391298 aa43ba6 b391298 aa43ba6 b391298 aa43ba6 b391298 aa43ba6 b391298 aa43ba6 b391298 aa43ba6 b391298 aa43ba6 b391298 aa43ba6 b391298 aa43ba6 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 aa43ba6 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 aa43ba6 b391298 aa43ba6 b391298 8e6b7e4 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 8e6b7e4 2e90a67 8e6b7e4 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 8e6b7e4 b391298 2e90a67 b391298 8e6b7e4 b391298 8e6b7e4 b391298 2e90a67 b391298 8e6b7e4 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 8e6b7e4 b391298 2e90a67 b391298 2e90a67 b391298 8e6b7e4 b391298 8e6b7e4 b391298 8e6b7e4 b391298 8e6b7e4 b391298 8e6b7e4 b391298 8e6b7e4 b391298 8e6b7e4 b391298 8e6b7e4 b391298 aa43ba6 b391298 2e90a67 b391298 aa43ba6 b391298 8e6b7e4 b391298 8e6b7e4 b391298 2e90a67 8e6b7e4 b391298 8e6b7e4 b391298 8e6b7e4 2e90a67 b391298 8e6b7e4 b391298 8e6b7e4 b391298 8e6b7e4 b391298 8e6b7e4 b391298 2e90a67 b391298 8e6b7e4 b391298 2e90a67 b391298 8e6b7e4 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 8e6b7e4 b391298 8e6b7e4 b391298 8e6b7e4 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 8e6b7e4 b391298 8e6b7e4 b391298 8e6b7e4 b391298 2e90a67 b391298 2e90a67 b391298 8e6b7e4 b391298 8e6b7e4 b391298 8e6b7e4 b391298 8e6b7e4 b391298 2e90a67 b391298 2e90a67 b391298 aa43ba6 b391298 aa43ba6 b391298 8e6b7e4 b391298 2e90a67 b391298 8e6b7e4 b391298 2e90a67 b391298 aa43ba6 b391298 8e6b7e4 b391298 2e90a67 b391298 2e90a67 b391298 8e6b7e4 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 8e6b7e4 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 8e6b7e4 b391298 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 8e6b7e4 b391298 8e6b7e4 2e90a67 b391298 2e90a67 b391298 2e90a67 b391298 | 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 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 | from __future__ import annotations
import contextvars
import base64
import binascii
import hashlib
import json
import logging
import os
import random
import re
import secrets
import sqlite3
import time
import uuid
from collections import Counter, deque
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from pathlib import Path
from threading import Event, Lock, Thread, local
from typing import Any
from urllib.parse import parse_qsl, quote, unquote, urlencode, urljoin, urlsplit, urlunsplit
import requests
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, JSONResponse, Response
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, ConfigDict, Field
try:
from curl_cffi.requests import Session as CurlCffiSession # type: ignore
except ImportError: # pragma: no cover - optional dependency
CurlCffiSession = None # type: ignore
DEFAULT_STRIPE_PK = (
"pk_live_51HOrSwC6h1nxGoI3lTAgRjYVrz4dU3fVOabyCcKR3pbEJguCVAlqCxdxCUvoRh1XWwRac"
"ViovU3kLKvpkjh7IqkW00iXQsjo3n"
)
STRIPE_VERSION_FULL = (
os.getenv(
"OPENAI_PAY_STRIPE_VERSION",
"2025-03-31.basil; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1",
).strip()
or "2025-03-31.basil; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1"
)
UPI_STRIPE_VERSION_FULL = (
os.getenv(
"OPENAI_PAY_UPI_STRIPE_VERSION",
"2026-06-24.dahlia; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1",
).strip()
or "2026-06-24.dahlia; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1"
)
DEFAULT_TIMEOUT = 30
def env_int(name: str, default: int, minimum: int = 1, maximum: int = 10000) -> int:
try:
value = int(str(os.getenv(name, str(default))).strip())
except (TypeError, ValueError):
return default
return min(max(value, minimum), maximum)
def env_bool(name: str, default: bool) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return str(raw).strip().lower() not in {"0", "false", "no", "off", ""}
APPROVE_POOL_WORKERS = env_int("OPENAI_PAY_APPROVE_POOL_WORKERS", 50, minimum=1, maximum=100)
APPROVE_POOL_MAX_WORKERS = env_int(
"OPENAI_PAY_APPROVE_POOL_MAX_WORKERS",
max(APPROVE_POOL_WORKERS, 75),
minimum=1,
maximum=100,
)
APPROVE_POOL_MIN_WORKERS = env_int(
"OPENAI_PAY_APPROVE_POOL_MIN_WORKERS",
min(APPROVE_POOL_WORKERS, 25),
minimum=1,
maximum=100,
)
APPROVE_POOL_ADAPTIVE = env_bool("OPENAI_PAY_APPROVE_POOL_ADAPTIVE", True)
APPROVE_POOL_ADAPT_INTERVAL = env_int("OPENAI_PAY_APPROVE_POOL_ADAPT_INTERVAL", 100, minimum=10, maximum=1000)
APPROVE_POOL_RAMP_STEP = env_int("OPENAI_PAY_APPROVE_POOL_RAMP_STEP", 5, minimum=1, maximum=50)
APPROVE_POOL_LATENCY_LOW_MS = env_int("OPENAI_PAY_APPROVE_POOL_LATENCY_LOW_MS", 3500, minimum=100, maximum=30000)
APPROVE_POOL_LATENCY_HIGH_MS = env_int("OPENAI_PAY_APPROVE_POOL_LATENCY_HIGH_MS", 8000, minimum=500, maximum=60000)
APPROVE_POOL_ERROR_RATE_HIGH_PERCENT = env_int(
"OPENAI_PAY_APPROVE_POOL_ERROR_RATE_HIGH_PERCENT",
5,
minimum=1,
maximum=100,
)
APPROVE_POOL_EARLY_SHUTDOWN = env_bool("OPENAI_PAY_APPROVE_POOL_EARLY_SHUTDOWN", True)
APPROVE_MAX_ATTEMPTS = env_int("OPENAI_PAY_APPROVE_MAX_ATTEMPTS", 3, minimum=1, maximum=5)
APPROVE_RETRY_DELAY_MS = env_int("OPENAI_PAY_APPROVE_RETRY_DELAY_MS", 700, minimum=100, maximum=5000)
LONG_LINK_MAX_ATTEMPTS = env_int("OPENAI_PAY_LONG_LINK_MAX_ATTEMPTS", 10, minimum=1, maximum=50)
ADMIN_LONG_LINK_MAX_ATTEMPTS = env_int("OPENAI_PAY_ADMIN_LONG_LINK_MAX_ATTEMPTS", 10, minimum=1, maximum=100)
APPROVE_PROGRESS_INTERVAL = env_int("OPENAI_PAY_APPROVE_PROGRESS_INTERVAL", 50, minimum=1, maximum=1000)
APPROVE_BLOCKED_RESTART_AFTER = env_int("OPENAI_PAY_APPROVE_BLOCKED_RESTART_AFTER", 600, minimum=0, maximum=10000)
APPROVE_BLOCKED_RESTART_MIN_BLOCKED = env_int("OPENAI_PAY_APPROVE_BLOCKED_RESTART_MIN_BLOCKED", 480, minimum=1, maximum=10000)
APPROVE_BLOCKED_RESTART_RATIO = env_int("OPENAI_PAY_APPROVE_BLOCKED_RESTART_RATIO", 80, minimum=1, maximum=100)
APPROVE_IP_SAMPLE_INTERVAL = env_int("OPENAI_PAY_APPROVE_IP_SAMPLE_INTERVAL", 50, minimum=0, maximum=10000)
APPROVE_IP_SAMPLE_ENABLED = env_bool("OPENAI_PAY_APPROVE_IP_SAMPLE", True)
APPROVE_STICKY_PER_PROXY_CONCURRENCY = env_int(
"OPENAI_PAY_APPROVE_STICKY_PER_PROXY_CONCURRENCY",
50,
minimum=1,
maximum=200,
)
APPROVE_STICKY_MAX_WORKERS = env_int("OPENAI_PAY_APPROVE_STICKY_MAX_WORKERS", 300, minimum=1, maximum=500)
APPROVE_STICKY_FAIL_WINDOW = env_int("OPENAI_PAY_APPROVE_STICKY_FAIL_WINDOW", 50, minimum=1, maximum=500)
APPROVE_STICKY_FAIL_DELETE = env_bool("OPENAI_PAY_APPROVE_STICKY_FAIL_DELETE", True)
AUTO_PROXY_COUNTRY_REWRITE = env_bool("OPENAI_PAY_AUTO_PROXY_COUNTRY", False)
PROXY_SESSION_KEY = re.sub(
r"[^a-z0-9]",
"",
os.getenv("OPENAI_PAY_PROXY_SESSION_KEY", "session").strip().lower(),
) or "session"
if PROXY_SESSION_KEY not in {"session", "sid", "sessid"}:
PROXY_SESSION_KEY = "session"
STRIPE_REDIRECT_POLL_MAX_ATTEMPTS = env_int("OPENAI_PAY_STRIPE_REDIRECT_POLL_MAX_ATTEMPTS", 3, minimum=1, maximum=3)
STRIPE_REDIRECT_POLL_WORKERS = env_int("OPENAI_PAY_STRIPE_REDIRECT_POLL_WORKERS", 20, minimum=1, maximum=100)
UPI_CONFIRM_TIMEOUT_SECONDS = env_int("OPENAI_PAY_UPI_CONFIRM_TIMEOUT_SECONDS", 60, minimum=30, maximum=120)
STRIPE_INIT_RESOURCE_MISSING_ATTEMPTS = env_int(
"OPENAI_PAY_STRIPE_INIT_RESOURCE_MISSING_ATTEMPTS",
4,
minimum=1,
maximum=10,
)
STRIPE_INIT_RESOURCE_MISSING_DELAY_MS = env_int(
"OPENAI_PAY_STRIPE_INIT_RESOURCE_MISSING_DELAY_MS",
1000,
minimum=100,
maximum=10000,
)
BASE_DIR = Path(__file__).resolve().parent
PUBLIC_DIR = BASE_DIR / "public"
PAYPAL_HOST_SUFFIXES = ("paypal.com", "paypalobjects.com")
IDEAL_HOST_SUFFIXES = ("ideal.nl",)
UPI_HOST_SUFFIXES = ("stripe.com", "stripe.network")
LOG_LEVEL = os.getenv("OPENAI_PAY_LOG_LEVEL", "INFO").strip().upper() or "INFO"
logging.basicConfig(
level=getattr(logging, LOG_LEVEL, logging.INFO),
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
LOG = logging.getLogger("openai_pay")
REQUEST_ID: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="-")
TASK_LOG_CALLBACK: contextvars.ContextVar[Any | None] = contextvars.ContextVar("task_log_callback", default=None)
TASK_CANCEL_CHECK: contextvars.ContextVar[Any | None] = contextvars.ContextVar("task_cancel_check", default=None)
APP_USERNAME = os.getenv("APP_USERNAME", "admin")
APP_PASSWORD = os.getenv("APP_PASSWORD", "anxiaomo294")
APP_API_KEY = (os.getenv("APP_API_KEY") or os.getenv("OPENAI_PAY_API_KEY") or "").strip()
DEFAULT_USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36"
)
DEFAULT_STRIPE_RUNTIME_VERSION = "6f8494a281"
DEFAULT_CHECKOUT_PROXY = ""
DEFAULT_APPROVE_PROXY = ""
DEFAULT_PROVIDER_PROXY = ""
RUN_MODE_SPLIT = "jp-us"
RUN_MODE_CHECKOUT_JP_REST_PROVIDER = "checkout-jp-rest-provider"
RUN_MODE_UIAI_STYLE = "uiai-style"
RUN_MODE_US_CHECKOUT_JP_PAYPAL = "us-checkout-jp-paypal"
SUPPORTED_RUN_MODES = {
RUN_MODE_SPLIT,
RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
}
DEFAULT_PROBE_COUNTRIES_RAW = os.getenv(
"OPENAI_PAY_PROBE_COUNTRIES",
"US,CA,MX,BR,GB,IE,AU,NZ,DE,FR,IT,ES,NL,AT,BE,CH,PT,SE,NO,DK,FI,"
"PL,CZ,RO,HU,GR,BG,HR,SI,SK,LT,LV,EE,CY,MT,LU,IS,LI,JP,KR,SG,HK,"
"TW,ID,MY,TH,IN,TR,UA,ZA",
)
US_BILLING_PROFILES = [
{
"first_name": "James",
"last_name": "Miller",
"line1": "123 Market St",
"city": "San Francisco",
"state": "CA",
"postal_code": "94105",
},
{
"first_name": "Emily",
"last_name": "Walker",
"line1": "456 Grant Ave",
"city": "San Jose",
"state": "CA",
"postal_code": "95112",
},
{
"first_name": "Daniel",
"last_name": "Hughes",
"line1": "789 Mission Blvd",
"city": "Seattle",
"state": "WA",
"postal_code": "98101",
},
{
"first_name": "Sophia",
"last_name": "Johnson",
"line1": "512 Oak Court",
"city": "Austin",
"state": "TX",
"postal_code": "73301",
},
{
"first_name": "Michael",
"last_name": "Brown",
"line1": "188 Cedar Lane",
"city": "Chicago",
"state": "IL",
"postal_code": "60601",
},
{
"first_name": "Olivia",
"last_name": "Davis",
"line1": "44 Madison Avenue",
"city": "New York",
"state": "NY",
"postal_code": "10001",
},
{
"first_name": "Noah",
"last_name": "Miller",
"line1": "901 Lake Street",
"city": "Denver",
"state": "CO",
"postal_code": "80202",
},
{
"first_name": "Emma",
"last_name": "Martinez",
"line1": "760 Palm Drive",
"city": "Miami",
"state": "FL",
"postal_code": "33101",
},
{
"first_name": "Ethan",
"last_name": "Garcia",
"line1": "27 River Bend",
"city": "Boston",
"state": "MA",
"postal_code": "02108",
},
{
"first_name": "Ava",
"last_name": "White",
"line1": "66 West End Road",
"city": "Portland",
"state": "OR",
"postal_code": "97205",
},
{
"first_name": "Liam",
"last_name": "Clark",
"line1": "318 Mountain View",
"city": "Phoenix",
"state": "AZ",
"postal_code": "85001",
},
{
"first_name": "Isabella",
"last_name": "Moore",
"line1": "90 Harbor Point",
"city": "Houston",
"state": "TX",
"postal_code": "77002",
},
{
"first_name": "Lucas",
"last_name": "Taylor",
"line1": "230 Jefferson Ave",
"city": "Detroit",
"state": "MI",
"postal_code": "48201",
},
{
"first_name": "Mia",
"last_name": "Anderson",
"line1": "15 Pine Grove",
"city": "Atlanta",
"state": "GA",
"postal_code": "30301",
},
{
"first_name": "James",
"last_name": "Wilson",
"line1": "250 Broadway",
"city": "Minneapolis",
"state": "MN",
"postal_code": "55401",
},
]
BILLING_PROFILES = {
"US": US_BILLING_PROFILES,
"GB": {
"first_name": "George",
"last_name": "Taylor",
"line1": "221 Baker Street",
"city": "London",
"state": "",
"postal_code": "NW1 6XE",
},
"CA": {
"first_name": "Noah",
"last_name": "Wilson",
"line1": "100 King St W",
"city": "Toronto",
"state": "ON",
"postal_code": "M5X 1A9",
},
"BR": {
"first_name": "Pedro",
"last_name": "Silva",
"line1": "Avenida Paulista 1000",
"city": "Sao Paulo",
"state": "SP",
"postal_code": "01310-100",
},
"NZ": {
"first_name": "Jack",
"last_name": "Williams",
"line1": "188 Quay Street",
"city": "Auckland",
"state": "",
"postal_code": "1010",
},
"DE": {
"first_name": "Lukas",
"last_name": "Schneider",
"line1": "Friedrichstrasse 68",
"city": "Berlin",
"state": "",
"postal_code": "10117",
},
"JP": {
"first_name": "Haruto",
"last_name": "Sato",
"line1": "1-1-2 Marunouchi",
"city": "Chiyoda-ku",
"state": "Tokyo",
"postal_code": "100-0005",
},
"AU": {
"first_name": "Oliver",
"last_name": "Brown",
"line1": "200 George St",
"city": "Sydney",
"state": "NSW",
"postal_code": "2000",
},
"IE": {
"first_name": "Liam",
"last_name": "Murphy",
"line1": "1 Grand Canal Square",
"city": "Dublin",
"state": "D",
"postal_code": "D02 P820",
},
"ZA": {
"first_name": "Ethan",
"last_name": "Botha",
"line1": "1 Adderley Street",
"city": "Cape Town",
"state": "WC",
"postal_code": "8000",
},
"TR": {
"first_name": "Can",
"last_name": "Demir",
"line1": "Marmara Caddesi 12",
"city": "Istanbul",
"state": "IST",
"postal_code": "34000",
},
"IN": {
"first_name": "Ravi",
"last_name": "Sharma",
"line1": "221B Nehru Marg",
"city": "New Delhi",
"state": "DL",
"postal_code": "110001",
},
}
COUNTRY_NAME_SEEDS = [
("Alex", "Morgan"),
("Daniel", "Evans"),
("Mason", "Clark"),
("Lucas", "Walker"),
("Henry", "Scott"),
("Oscar", "Hall"),
]
COUNTRY_CITY_SEEDS = {
"AT": ("Vienna", "", "1010", "Karntner Strasse 12"),
"BE": ("Brussels", "", "1000", "Rue Neuve 25"),
"BR": ("Sao Paulo", "SP", "01310-100", "Avenida Paulista 1000"),
"BG": ("Sofia", "", "1000", "Vitosha Boulevard 18"),
"CH": ("Zurich", "", "8001", "Bahnhofstrasse 20"),
"CY": ("Nicosia", "", "1010", "Ledra Street 14"),
"CZ": ("Prague", "", "110 00", "Narodni 12"),
"DK": ("Copenhagen", "", "1050", "Ostergade 22"),
"EE": ("Tallinn", "", "10111", "Viru Street 8"),
"ES": ("Madrid", "", "28013", "Gran Via 28"),
"FI": ("Helsinki", "", "00100", "Mannerheimintie 10"),
"FR": ("Paris", "", "75001", "Rue de Rivoli 99"),
"GR": ("Athens", "", "105 63", "Ermou Street 15"),
"HR": ("Zagreb", "", "10000", "Ilica 21"),
"HU": ("Budapest", "", "1051", "Vaci utca 10"),
"IS": ("Reykjavik", "", "101", "Laugavegur 18"),
"IT": ("Rome", "", "00186", "Via del Corso 30"),
"LI": ("Vaduz", "", "9490", "Stadtle 17"),
"LT": ("Vilnius", "", "01100", "Gedimino pr. 16"),
"LU": ("Luxembourg", "", "L-2449", "Boulevard Royal 20"),
"LV": ("Riga", "", "LV-1050", "Brivibas iela 12"),
"MT": ("Valletta", "", "VLT 1111", "Republic Street 22"),
"NL": ("Amsterdam", "", "1012 LG", "Damrak 40"),
"NO": ("Oslo", "", "0159", "Karl Johans gate 14"),
"PL": ("Warsaw", "", "00-001", "Marszalkowska 20"),
"PT": ("Lisbon", "", "1100-148", "Rua Augusta 25"),
"RO": ("Bucharest", "", "010011", "Calea Victoriei 30"),
"SE": ("Stockholm", "", "111 22", "Drottninggatan 15"),
"SI": ("Ljubljana", "", "1000", "Slovenska cesta 12"),
"SK": ("Bratislava", "", "811 01", "Obchodna 10"),
}
COUNTRY_TIMEZONE = {
"AU": "Australia/Sydney",
"BR": "America/Sao_Paulo",
"CA": "America/Toronto",
"DE": "Europe/Berlin",
"IE": "Europe/Dublin",
"JP": "Asia/Tokyo",
"ZA": "Africa/Johannesburg",
"US": "America/New_York",
}
COUNTRY_CURRENCY = {
"AD": "EUR",
"AL": "ALL",
"AT": "EUR",
"AU": "AUD",
"BE": "EUR",
"BG": "BGN",
"BA": "BAM",
"BY": "BYN",
"BR": "BRL",
"CA": "CAD",
"CH": "CHF",
"CY": "EUR",
"CZ": "CZK",
"DE": "EUR",
"DK": "DKK",
"EE": "EUR",
"ES": "EUR",
"FI": "EUR",
"FR": "EUR",
"GB": "GBP",
"GR": "EUR",
"HR": "EUR",
"HK": "HKD",
"HU": "HUF",
"ID": "IDR",
"IE": "EUR",
"IS": "ISK",
"IN": "INR",
"IT": "EUR",
"JP": "JPY",
"KR": "KRW",
"LI": "CHF",
"LT": "EUR",
"LU": "EUR",
"LV": "EUR",
"MC": "EUR",
"MD": "MDL",
"ME": "EUR",
"MK": "MKD",
"MT": "EUR",
"MX": "MXN",
"MY": "MYR",
"NL": "EUR",
"NO": "NOK",
"NZ": "NZD",
"PL": "PLN",
"PT": "EUR",
"RO": "RON",
"RS": "RSD",
"SE": "SEK",
"SI": "EUR",
"SK": "EUR",
"SM": "EUR",
"SG": "SGD",
"TH": "THB",
"TR": "TRY",
"TW": "TWD",
"UA": "UAH",
"US": "USD",
"VA": "EUR",
"VN": "VND",
"ZA": "ZAR",
}
LOCALE_MAP = {
"de": ("de-DE", "de"),
"en": ("en-US", "en"),
"en-US": ("en-US", "en"),
"es": ("es-ES", "es"),
"fr": ("fr-FR", "fr"),
"id": ("id-ID", "id"),
"it": ("it-IT", "it"),
"ja": ("ja-JP", "ja"),
"ko": ("ko-KR", "ko"),
"pt-BR": ("pt-BR", "pt-BR"),
"zh-CN": ("zh-CN", "zh-CN"),
"zh-TW": ("zh-TW", "zh-TW"),
}
class LongLinkRequest(BaseModel):
model_config = ConfigDict(populate_by_name=True)
access_token: str = Field(..., alias="accessToken")
cdk: str = ""
proxy: str = ""
checkout_proxy: str = Field("", alias="checkoutProxy")
approve_proxy: str = Field("", alias="approveProxy")
provider_proxy: str = Field("", alias="providerProxy")
promotion_proxy: str = Field("", alias="promotionProxy")
stripe_publishable_key: str = ""
billing_country: str = "US"
pm_country: str = Field("AU", alias="pmCountry")
checkout_ui_mode: str = "custom"
payment_locale: str = "en"
link_type: str = "paypal"
proxy_pool_mode: str = Field("", alias="proxyPoolMode")
device_id: str = ""
user_agent: str = ""
auto_probe: bool = Field(True, alias="autoProbe")
probe_countries: str = Field("", alias="probeCountries")
class LongLinkResponse(BaseModel):
ok: bool
cs_id: str
processor_entity: str
billing_country: str
currency: str
checkout_amount: str = ""
payment_locale: str
link_type: str
payment_method_type: str
payment_method_id: str
stripe_redirect_url: str
provider_redirect_url: str
fallback: bool = False
provider_error: str = ""
stripe_hosted_url: str
long_url: str
ideal_qr_url: str = ""
success_attempt: int = 0
class LongLinkTaskStartResponse(BaseModel):
ok: bool
task_id: str
class LongLinkTaskStatusResponse(BaseModel):
ok: bool
task_id: str
status: str
progress: int = 0
stage: str = ""
message: str = ""
paused: bool = False
elapsed_ms: int = 0
attempt: int = 0
result: LongLinkResponse | None = None
error: str = ""
logs: list[dict[str, Any]] = Field(default_factory=list)
probe_results: list[dict[str, Any]] = Field(default_factory=list)
created_at: int = 0
updated_at: int = 0
result_expires_at: int = 0
class TaskPauseRequest(BaseModel):
paused: bool = True
class TaskCancelled(RuntimeError):
pass
class AuthRequest(BaseModel):
username: str
password: str
class RegisterRequest(BaseModel):
username: str
password: str
invite_code: str = Field(..., alias="inviteCode")
class UserResponse(BaseModel):
ok: bool
authenticated: bool
username: str = ""
role: str = ""
class MemberResponse(BaseModel):
username: str
role: str
created_at: int
disabled_at: int = 0
active_sessions: int = 0
success_count: int = 0
class MemberListResponse(BaseModel):
ok: bool
members: list[MemberResponse]
class ApiExtractRequest(BaseModel):
model_config = ConfigDict(populate_by_name=True)
access_token: str = Field("", alias="accessToken")
session_json: Any | None = Field(None, alias="sessionJson")
token: str = ""
cdk: str = ""
class BusinessCheckoutRequest(BaseModel):
"""Independent Business checkout creator.
Business uses a different plan/promotion payload from the normal PP flow.
"""
model_config = ConfigDict(populate_by_name=True)
access_token: str = Field("", alias="accessToken")
session_json: Any | None = Field(None, alias="sessionJson")
token: str = ""
checkout_url: str = Field("", alias="checkoutUrl")
promo_code: str = Field("", alias="promoCode")
promo_campaign_id: str = Field("", alias="promoCampaignId")
plan_name: str = Field("chatgptteamplan", alias="planName")
seat_quantity: int = Field(5, alias="seatQuantity", ge=2, le=100)
price_interval: str = Field("month", alias="priceInterval")
billing_country: str = Field("US", alias="billingCountry")
proxy: str = ""
class BusinessCheckoutResponse(BaseModel):
ok: bool
checkout_url: str = Field("", alias="checkoutUrl")
external_url: str = Field("", alias="externalUrl")
processor_entity: str = Field("", alias="processorEntity")
cs_id: str = Field("", alias="csId")
plan_name: str = Field("", alias="planName")
promo_code: str = Field("", alias="promoCode")
seat_quantity: int = Field(5, alias="seatQuantity")
message: str = ""
class CdkCheckRequest(BaseModel):
cdk: str = ""
class CdkCheckResponse(BaseModel):
model_config = ConfigDict(populate_by_name=True)
ok: bool
code: str
max_uses: int = Field(10, alias="maxUses")
use_count: int = Field(0, alias="useCount")
remaining_uses: int = Field(0, alias="remainingUses")
class InviteResponse(BaseModel):
code: str
created_by: str
created_at: int
used_by: str = ""
used_at: int = 0
revoked_at: int = 0
max_uses: int = 10
use_count: int = 0
remaining_uses: int = 10
last_used_at: int = 0
class InviteListResponse(BaseModel):
ok: bool
invites: list[InviteResponse]
class InviteCreateRequest(BaseModel):
count: int = Field(1, ge=1, le=50)
max_uses: int = Field(10, ge=1, le=100, alias="maxUses")
request_id: str = Field("", alias="requestId")
class InviteCreateResponse(BaseModel):
ok: bool
invite: InviteResponse
invites: list[InviteResponse] = Field(default_factory=list)
class ProxyCheckRequest(BaseModel):
model_config = ConfigDict(populate_by_name=True)
checkout_proxy: str = Field("", alias="checkoutProxy")
provider_proxy: str = Field("", alias="providerProxy")
class RuntimeConfigRequest(BaseModel):
model_config = ConfigDict(populate_by_name=True)
run_mode: str = Field(RUN_MODE_CHECKOUT_JP_REST_PROVIDER, alias="runMode")
proxy_pool_mode: str = Field("dynamic", alias="proxyPoolMode")
billing_country: str = Field("US", alias="billingCountry")
pm_country: str = Field("AU", alias="pmCountry")
payment_locale: str = Field("en", alias="paymentLocale")
jp_proxy: str = Field("", alias="jpProxy")
us_proxy: str = Field("", alias="usProxy")
sticky_jp_proxy: str = Field("", alias="stickyJpProxy")
sticky_us_proxy: str = Field("", alias="stickyUsProxy")
ideal_promo_proxy: str = Field("", alias="idealPromoProxy")
sticky_ideal_promo_proxy: str = Field("", alias="stickyIdealPromoProxy")
checkout_proxy: str = Field("", alias="checkoutProxy")
approve_proxy: str = Field("", alias="approveProxy")
provider_proxy: str = Field("", alias="providerProxy")
def elapsed_ms(start: float) -> int:
return int((time.perf_counter() - start) * 1000)
def mask_identifier(value: Any, keep_start: int = 8, keep_end: int = 4) -> str:
text = str(value or "").strip()
if not text:
return ""
if len(text) <= keep_start + keep_end + 3:
return text
return f"{text[:keep_start]}…{text[-keep_end:]}"
def redact_text(value: Any, max_len: int = 300) -> str:
text = str(value or "")
if not text:
return ""
text = re.sub(r"Bearer\s+[A-Za-z0-9._~+/=-]+", "Bearer <redacted>", text, flags=re.IGNORECASE)
text = re.sub(r"[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}", "<jwt-redacted>", text)
text = re.sub(r"(https?://)([^:/@\s]+):([^@\s]+)@", r"\1\2:***@", text)
text = re.sub(
r'("(?:accessToken|access_token|sessionToken|Authorization|authorization|token|proxy|password|secret|key)"\s*:\s*")([^"]+)(")',
r"\1<redacted>\3",
text,
flags=re.IGNORECASE,
)
if len(text) > max_len:
return f"{text[:max_len]}…<{len(text)} chars>"
return text
def safe_url(url: Any) -> str:
raw = str(url or "").strip()
if not raw:
return ""
try:
parsed = urlsplit(raw)
except Exception:
return redact_text(raw, max_len=180)
if not parsed.scheme or not parsed.netloc:
return redact_text(mask_identifier(raw, keep_start=24, keep_end=8), max_len=180)
try:
port_value = parsed.port
except ValueError:
port_value = None
port = f":{port_value}" if port_value else ""
segments = [mask_identifier(segment, keep_start=10, keep_end=4) for segment in parsed.path.split("/")]
path = "/".join(segments)
query_keys = [key for key, _ in parse_qsl(parsed.query, keep_blank_values=True)]
query = f"?query_keys={','.join(query_keys[:8])}" if query_keys else ""
if len(query_keys) > 8:
query += f",+{len(query_keys) - 8}"
return f"{parsed.scheme}://{parsed.hostname or ''}{port}{path}{query}"
def normalize_proxy_url(proxy: str) -> str:
proxy = str(proxy or "").strip()
if not proxy:
return ""
if "://" not in proxy:
parts = proxy.split(":")
if len(parts) >= 4:
host = parts[0].strip()
port = parts[1].strip()
username = ":".join(parts[2:-1]).strip()
password = parts[-1].strip()
if host and port and username and password:
proxy = f"http://{quote(username, safe='')}:{quote(password, safe='')}@{host}:{port}"
else:
proxy = f"http://{proxy}"
else:
proxy = f"http://{proxy}"
return proxy
def proxy_pool(value: Any) -> list[str]:
raw = str(value or "").strip()
if not raw:
return []
proxies: list[str] = []
for item in re.split(r"[\r\n,;|\s]+", raw):
proxy = normalize_proxy_url(item)
if proxy and proxy not in proxies:
proxies.append(proxy)
return proxies
def normalize_proxy_pool_value(value: Any) -> str:
return "\n".join(proxy_pool(value))
def select_proxy_from_pool(value: Any, index: int = 0) -> str:
# A configured pool may intentionally contain mixed countries. Preserve
# its order and use exactly the selected entry; country is not a filter.
proxies = proxy_pool(value)
if not proxies:
return ""
return proxies[max(0, int(index or 0)) % len(proxies)]
def first_proxy_from_pool(value: Any) -> str:
return select_proxy_from_pool(value, 0)
def ordered_proxy_pool(value: Any, preferred: Any = "") -> list[str]:
proxies = proxy_pool(value)
preferred_proxy = normalize_proxy_url(str(preferred or ""))
if preferred_proxy:
if preferred_proxy in proxies:
index = proxies.index(preferred_proxy)
proxies = proxies[index:] + proxies[:index]
else:
proxies.insert(0, preferred_proxy)
ordered: list[str] = []
for proxy in proxies:
if proxy and proxy not in ordered:
ordered.append(proxy)
return ordered
def proxy_country_hint(proxy: Any) -> str:
proxy_url = normalize_proxy_url(str(proxy or ""))
if not proxy_url:
return ""
try:
username = unquote(urlsplit(proxy_url).username or "")
except Exception:
return ""
# Country is controlled by the proxy account itself. Support common
# vendor formats such as "region-BR", "res-BR", and "country-BR";
# never rewrite the country later.
match = re.search(r"(?:^|[-_])(?:region|res|country|cc)-([A-Za-z]{2})(?:[-_]|$)", username)
return match.group(1).upper() if match else ""
def proxy_pool_primary_country(proxies: list[str]) -> str:
for proxy in proxies:
country = proxy_country_hint(proxy)
if country:
return country
return ""
def filter_proxy_pool_same_country(proxies: list[str], country: str = "") -> list[str]:
country = str(country or "").strip().upper()
if not proxies:
return []
if not country:
country = proxy_pool_primary_country(proxies)
if not country:
return proxies
filtered: list[str] = []
for proxy in proxies:
hint = proxy_country_hint(proxy)
if hint and hint != country:
continue
if proxy not in filtered:
filtered.append(proxy)
return filtered or proxies[:1]
def proxy_with_region(proxy: Any, country: str) -> str:
proxy_url = normalize_proxy_url(str(proxy or ""))
target_country = supported_country(country, "")
if not proxy_url or not target_country:
return proxy_url
if proxy_supports_country_rewrite(proxy_url):
return proxy_for_probe_country(proxy_url, target_country)
current_country = proxy_country_hint(proxy_url)
if current_country and current_country != target_country:
return ""
return proxy_url
PROXY_COUNTRY_MARKER_RE = re.compile(
r"((?:^|[-_])(?:region|res|country|cc)-)([A-Za-z]{2})(?=[-_]|$)",
re.IGNORECASE,
)
def proxy_supports_country_rewrite(proxy: Any) -> bool:
proxy_url = normalize_proxy_url(str(proxy or ""))
if not proxy_url:
return False
try:
username = unquote(urlsplit(proxy_url).username or "")
except Exception:
return False
return bool(PROXY_COUNTRY_MARKER_RE.search(username))
def proxy_for_probe_country(proxy: Any, country: str, sid: str = "") -> str:
"""Rewrite only an explicit proxy country marker for the isolated promo probe."""
proxy_url = normalize_proxy_url(str(proxy or ""))
target_country = supported_country(country, "")
if not proxy_url or not target_country:
return ""
try:
parsed = urlsplit(proxy_url)
username = unquote(parsed.username or "")
password = unquote(parsed.password or "")
def replace_country(match: re.Match[str]) -> str:
previous = match.group(2)
replacement = target_country.lower() if previous.islower() else target_country.upper()
return f"{match.group(1)}{replacement}"
username, replaced = PROXY_COUNTRY_MARKER_RE.subn(replace_country, username, count=1)
if not replaced:
return ""
netloc = parsed.hostname or ""
if parsed.port:
netloc = f"{netloc}:{parsed.port}"
auth = quote(username, safe="")
if password:
auth = f"{auth}:{quote(password, safe='')}"
rewritten = urlunsplit((parsed.scheme, f"{auth}@{netloc}", parsed.path, parsed.query, parsed.fragment))
return proxy_with_sid(rewritten, sid) if sid else rewritten
except Exception:
return ""
def proxy_for_payment_country(proxy: Any, country: str, sid: str = "") -> str:
"""Keep a payment-stage proxy in the requested country and optionally pin its session."""
proxy_url = normalize_proxy_url(str(proxy or ""))
target_country = supported_country(country, "")
if not proxy_url:
return ""
if not target_country:
return proxy_with_sid(proxy_url, sid) if sid else proxy_url
if proxy_supports_country_rewrite(proxy_url):
return proxy_for_probe_country(proxy_url, target_country, sid)
current_country = proxy_country_hint(proxy_url)
if current_country and current_country != target_country:
return ""
return proxy_with_sid(proxy_url, sid) if sid else proxy_url
def proxy_for_required_country(proxy: Any, country: str) -> str:
"""Return the configured proxy unchanged.
The country argument is retained for call-site compatibility and logging,
but a proxy's country must never be rewritten or rejected based on it.
Each configured lane is authoritative: whatever the operator enters is
the proxy used for that stage.
"""
return normalize_proxy_url(str(proxy or ""))
def proxy_without_sid(proxy: Any) -> str:
proxy_url = normalize_proxy_url(str(proxy or ""))
if not proxy_url:
return ""
try:
parsed = urlsplit(proxy_url)
username = unquote(parsed.username or "")
password = unquote(parsed.password or "")
username = re.sub(r"(^|-)(?:sid|session|sessid)-[^-:@]+", "", username, count=1).strip("-")
netloc = parsed.hostname or ""
if parsed.port:
netloc = f"{netloc}:{parsed.port}"
if username:
auth = quote(username, safe="")
if password:
auth = f"{auth}:{quote(password, safe='')}"
netloc = f"{auth}@{netloc}"
return urlunsplit((parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment))
except Exception:
return proxy_url
def proxies_compatible(saved_proxy: Any, base_proxy: Any) -> bool:
saved = normalize_proxy_url(str(saved_proxy or ""))
base = normalize_proxy_url(str(base_proxy or ""))
if not saved or not base:
return False
try:
saved_parts = urlsplit(saved)
base_parts = urlsplit(base)
if (saved_parts.hostname or "").lower() != (base_parts.hostname or "").lower():
return False
if saved_parts.port != base_parts.port:
return False
saved_country = proxy_country_hint(saved)
base_country = proxy_country_hint(base)
if saved_country and base_country and saved_country != base_country:
return False
return proxy_without_sid(saved) == proxy_without_sid(base)
except Exception:
return False
def proxy_supports_auto_sid(proxy: Any) -> bool:
proxy_url = normalize_proxy_url(str(proxy or ""))
if not proxy_url:
return False
try:
username = unquote(urlsplit(proxy_url).username or "")
except Exception:
return False
return bool(
re.search(r"(?:^|-)(?:sid|session|sessid)-[^-:@]+", username)
or re.search(r"(?:^|[-_])(?:region|res|country|cc)-[A-Za-z]{2}(?:[-_]|$)", username)
)
def proxy_with_sid(proxy: Any, sid: str) -> str:
proxy_url = normalize_proxy_url(str(proxy or ""))
sid = re.sub(r"[^A-Za-z0-9]", "", str(sid or ""))[:16]
if not proxy_url or not sid or not proxy_supports_auto_sid(proxy_url):
return proxy_url
try:
parsed = urlsplit(proxy_url)
username = unquote(parsed.username or "")
password = unquote(parsed.password or "")
session_pattern = r"(^|-)(?:sid|session|sessid)-[^-:@]+"
if re.search(session_pattern, username):
username = re.sub(session_pattern, rf"\1{PROXY_SESSION_KEY}-{sid}", username, count=1)
else:
username = f"{username}-{PROXY_SESSION_KEY}-{sid}"
netloc = parsed.hostname or ""
if parsed.port:
netloc = f"{netloc}:{parsed.port}"
auth = quote(username, safe="")
if password:
auth = f"{auth}:{quote(password, safe='')}"
netloc = f"{auth}@{netloc}"
return urlunsplit((parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment))
except Exception:
return proxy_url
def proxy_for_attempt(proxy: Any, attempt: int, stage: str = "", force: bool = False) -> str:
proxy_url = normalize_proxy_url(str(proxy or ""))
if not proxy_url:
return proxy_url
attempt_no = max(1, int(attempt or 1))
if attempt_no <= 1 and not force:
return proxy_url
sid = f"{stage[:1] or 'p'}{attempt_no:02d}{secrets.token_hex(4)}"
return proxy_with_sid(proxy_url, sid)
def redact_proxy(proxy: Any) -> str:
proxy_url = normalize_proxy_url(str(proxy or ""))
if not proxy_url:
return ""
try:
parsed = urlsplit(proxy_url)
host = parsed.hostname or ""
try:
port_value = parsed.port
except ValueError:
port_value = None
port = f":{port_value}" if port_value else ""
auth = ""
if parsed.username:
auth = f"{mask_identifier(parsed.username, keep_start=6, keep_end=3)}:***@"
return f"{parsed.scheme}://{auth}{host}{port}"
except Exception:
return "<proxy-redacted>"
def redact_proxy_pool(value: Any) -> str:
proxies = proxy_pool(value)
if not proxies:
return ""
labels = [redact_proxy(proxy) for proxy in proxies[:3]]
if len(proxies) > 3:
labels.append(f"+{len(proxies) - 3}")
return " | ".join(labels)
def response_keys(payload: Any, limit: int = 12) -> str:
if not isinstance(payload, dict):
return type(payload).__name__
keys = sorted(str(key) for key in payload.keys())
suffix = f",+{len(keys) - limit}" if len(keys) > limit else ""
return ",".join(keys[:limit]) + suffix
def interesting_payload_fields(payload: Any, limit: int = 18) -> str:
interesting_names = (
"paypal",
"redirect",
"url",
"next_action",
"submission",
"state",
"status",
"error",
"message",
"payment_method",
)
found: list[str] = []
def visit(value: Any, path: str, depth: int) -> None:
if len(found) >= limit or depth > 5:
return
if isinstance(value, dict):
for key, item in value.items():
if len(found) >= limit:
return
key_text = str(key)
child_path = f"{path}.{key_text}" if path else key_text
lowered = key_text.lower()
if any(name in lowered for name in interesting_names):
if isinstance(item, (str, int, float, bool)) or item is None:
if "url" in lowered or "redirect" in lowered:
rendered = safe_url(item)
elif "error" in lowered or "message" in lowered:
rendered = redact_text(item, max_len=120)
else:
rendered = mask_identifier(item) if isinstance(item, str) and len(item) > 24 else str(item)
found.append(f"{child_path}={rendered}")
else:
found.append(f"{child_path}<{type(item).__name__}>")
visit(item, child_path, depth + 1)
elif isinstance(value, list):
for index, item in enumerate(value[:8]):
if len(found) >= limit:
return
visit(item, f"{path}[{index}]", depth + 1)
elif isinstance(value, str) and ("http://" in value or "https://" in value):
found.append(f"{path}={safe_url(value)}")
visit(payload, "", 0)
return " | ".join(found)
def approve_result_value(payload: Any) -> str:
if not isinstance(payload, dict):
return ""
for key in ("result", "status", "state", "approval_status"):
value = payload.get(key)
if value is not None:
return str(value).strip()
return ""
def is_approved_result(result: Any) -> bool:
return str(result or "").strip().lower() in {
"approved",
"already_approved",
"success",
"succeeded",
}
def approve_outcome(item: dict[str, Any]) -> str:
if item.get("skipped"):
return "skipped"
result = str(item.get("result") or "").strip().lower()
status_code = int(item.get("status_code") or 0)
if is_approved_result(result):
return "approved"
if status_code == 0:
return "exception"
if status_code in {401, 403}:
return "auth_error"
if status_code == 404:
return "missing"
if status_code == 408:
return "timeout"
if status_code == 409:
return "conflict"
if status_code == 429:
return "rate_limited"
if status_code >= 500:
return "server_error"
if result == "blocked":
return "blocked"
if result:
return f"pending_{result}"[:48]
return "pending_empty"
def log_event(level: int, event: str, **fields: Any) -> None:
safe_fields: dict[str, Any] = {}
for key, value in fields.items():
lowered = key.lower()
if value is None:
continue
# Only redact actual proxy URL fields. Counters/modes/indices such as
# proxy_pool_count and proxy_pool_mode are ordinary metadata; passing
# them through redact_proxy turns values like 1/dynamic into http://1
# and http://dynamic in the logs.
is_proxy_value = (
"proxy" in lowered
and not lowered.endswith(("_count", "_index", "_mode"))
)
if is_proxy_value:
safe_fields[key] = value if isinstance(value, bool) else (redact_proxy(value) if value else "")
elif "url" in lowered or "location" in lowered:
safe_fields[key] = safe_url(value)
elif "token" in lowered or "authorization" in lowered or "secret" in lowered or "password" in lowered:
safe_fields[key] = value if isinstance(value, bool) else ("<redacted>" if value else "")
elif lowered.endswith("_id") or lowered in {"cs_id", "pm_id", "checkout_session"}:
safe_fields[key] = value if isinstance(value, bool) else mask_identifier(value)
elif "body" in lowered or "error" in lowered or "detail" in lowered:
safe_fields[key] = redact_text(value)
else:
safe_fields[key] = value
suffix = " ".join(f"{key}={safe_fields[key]!r}" for key in sorted(safe_fields))
LOG.log(level, "[req=%s] %s%s", REQUEST_ID.get(), event, f" {suffix}" if suffix else "")
callback = TASK_LOG_CALLBACK.get()
if callback:
try:
# Task logs are returned through an API. Store the same redacted
# fields that are written to journald so proxy credentials, tokens,
# secrets and full payment URLs never enter the task response.
raw_fields: dict[str, Any] = {
key: value if isinstance(value, (str, int, float, bool)) else str(value)
for key, value in safe_fields.items()
}
callback(
{
"time": time.strftime("%H:%M:%S"),
"level": logging.getLevelName(level).lower(),
"event": event,
"fields": raw_fields,
}
)
except Exception:
pass
def log_info(event: str, **fields: Any) -> None:
log_event(logging.INFO, event, **fields)
def log_warning(event: str, **fields: Any) -> None:
log_event(logging.WARNING, event, **fields)
def http_error_detail(label: str, response: Any) -> str:
body_text = redact_text(getattr(response, "text", "") or "", max_len=500)
return f"{label}: status={getattr(response, 'status_code', '')} body={body_text}"
def percentile_ms(values: list[int] | tuple[int, ...], percent: int = 95) -> int:
clean = sorted(int(value) for value in values if int(value) >= 0)
if not clean:
return 0
index = max(0, min(len(clean) - 1, ((len(clean) * percent + 99) // 100) - 1))
return clean[index]
def compact_counts(counter: Counter[str]) -> str:
return ",".join(f"{name}:{count}" for name, count in sorted(counter.items()) if count)
def new_session() -> Any:
if CurlCffiSession is not None:
return CurlCffiSession(impersonate="chrome136")
return requests.Session()
def clone_session(source: Any) -> Any:
session = new_session()
try:
session.headers.update(dict(getattr(source, "headers", {}) or {}))
except Exception:
pass
try:
proxies = dict(getattr(source, "proxies", {}) or {})
if proxies:
session.proxies = proxies
except Exception:
pass
try:
session.cookies.update(getattr(source, "cookies", {}) or {})
except Exception:
pass
return session
def set_proxy_url(session: Any, proxy: str) -> None:
proxy = normalize_proxy_url(proxy)
if proxy:
session.proxies = {"http": proxy, "https": proxy}
# 动态代理:不要复用同一条 TCP 连接,让代理商有机会在下一次请求/重试切换出口 IP。
try:
session.headers.update({"Connection": "close", "Proxy-Connection": "close"})
except Exception:
pass
def clear_proxy_url(session: Any) -> None:
try:
session.proxies = {}
except Exception:
pass
def session_proxy_url(session: Any) -> str:
try:
proxies = dict(getattr(session, "proxies", {}) or {})
except Exception:
return ""
return normalize_proxy_url(str(proxies.get("https") or proxies.get("http") or ""))
def sample_session_exit_ip(session: Any) -> tuple[str, str]:
try:
started = time.perf_counter()
response = session.get("https://api.ipify.org?format=json", timeout=8)
elapsed = elapsed_ms(started)
ip = ""
try:
data = response.json()
ip = str(data.get("ip") or "")
except Exception:
ip = str(getattr(response, "text", "") or "").strip()[:80]
return ip, str(elapsed)
except Exception as exc:
return "", repr(exc)
def requested_checkout_proxy(req: LongLinkRequest) -> str:
return first_proxy_from_pool(req.checkout_proxy or req.proxy)
def checkout_stage_proxy(req: LongLinkRequest) -> str:
return (
first_proxy_from_pool(req.checkout_proxy or req.proxy)
or first_proxy_from_pool(os.getenv("OPENAI_PAY_CHECKOUT_PROXY", ""))
)
def provider_stage_proxy(req: LongLinkRequest) -> str:
explicit_provider = first_proxy_from_pool(req.provider_proxy)
if explicit_provider:
return explicit_provider
explicit_checkout = requested_checkout_proxy(req)
if explicit_checkout:
return explicit_checkout
return first_proxy_from_pool(os.getenv("OPENAI_PAY_PROVIDER_PROXY", ""))
def promotion_stage_proxy(req: LongLinkRequest) -> str:
return (
first_proxy_from_pool(req.promotion_proxy)
or first_proxy_from_pool(os.getenv("OPENAI_PAY_PROMOTION_PROXY", ""))
)
def redirect_poll_proxy_pool(req: LongLinkRequest, stripe_session: Any) -> list[str]:
current_proxy = session_proxy_url(stripe_session) or provider_stage_proxy(req)
return [current_proxy] if current_proxy else []
def approve_stage_proxy(req: LongLinkRequest) -> str:
return (
first_proxy_from_pool(req.approve_proxy)
or requested_checkout_proxy(req)
or first_proxy_from_pool(os.getenv("OPENAI_PAY_APPROVE_PROXY", ""))
or checkout_stage_proxy(req)
)
def apply_approve_proxy(session: Any, proxy: str) -> None:
proxy = normalize_proxy_url(proxy)
if proxy:
set_proxy_url(session, proxy)
else:
clear_proxy_url(session)
log_info(
"session.approve_proxy.apply",
route="approve_proxy" if proxy else "direct",
proxy_configured=bool(proxy),
approve_proxy=proxy,
)
def host_matches_suffixes(host: str, suffixes: tuple[str, ...]) -> bool:
host = str(host or "").lower().strip(".")
return any(host == suffix or host.endswith(f".{suffix}") for suffix in suffixes)
def currency_for_country(country: str) -> str:
return COUNTRY_CURRENCY.get(str(country or "").upper(), "USD")
def supported_country(value: str, default: str = "DE") -> str:
country = str(value or "").strip().upper()
return country if country in COUNTRY_CURRENCY else default
def timezone_for_country(country: str) -> str:
return COUNTRY_TIMEZONE.get(supported_country(country), "Europe/Berlin")
def normalize_link_type(link_type: str) -> str:
value = str(link_type or "paypal").strip().lower()
aliases = {
"ideal": "ideal",
"idealpay": "ideal",
"i-deal": "ideal",
"upi": "upi",
"payment": "paypal",
"pay": "paypal",
"long": "paypal",
"pp": "paypal",
"paypal": "paypal",
}
return aliases.get(value, "paypal")
def stripe_version_for(link_type: str) -> str:
# Keep the API version that has already been proven against the existing
# PayPal/iDEAL Checkout schema. UPI's hosted QR action was added later and
# therefore uses the newer schema in isolation.
return UPI_STRIPE_VERSION_FULL if normalize_link_type(link_type) == "upi" else STRIPE_VERSION_FULL
def effective_country(req: LongLinkRequest) -> str:
return supported_country(req.billing_country, "DE")
def effective_pm_country(req: LongLinkRequest) -> str:
return supported_country(req.pm_country, effective_country(req))
def locale_parts(locale: str) -> tuple[str, str]:
return LOCALE_MAP.get(str(locale or "").strip(), LOCALE_MAP["en"])
def find_token(value: Any) -> str:
if isinstance(value, dict):
for key in ("accessToken", "access_token", "token"):
token = str(value.get(key) or "").strip()
if token:
return token
for item in value.values():
token = find_token(item)
if token:
return token
if isinstance(value, list):
for item in value:
token = find_token(item)
if token:
return token
return ""
def normalize_access_token(raw: str) -> str:
token = str(raw or "").strip()
if not token:
return ""
if token.startswith("{") or token.startswith("["):
try:
return find_token(json.loads(token)) or token
except json.JSONDecodeError:
return token
return token
def extract_processor_entity(data: Any) -> str:
if not isinstance(data, dict):
return ""
direct = data.get("processor_entity") or data.get("processorEntity")
if direct:
return str(direct).strip()
for key in ("checkout_session", "session", "checkout", "data"):
nested = data.get(key)
if isinstance(nested, dict):
found = extract_processor_entity(nested)
if found:
return found
return ""
def extract_stripe_publishable_key(data: Any) -> str:
if isinstance(data, dict):
preferred_keys = (
"stripe_publishable_key",
"stripePublishableKey",
"publishable_key",
"publishableKey",
"stripe_key",
)
for key in preferred_keys:
value = str(data.get(key) or "").strip()
if value.startswith(("pk_live_", "pk_test_")):
return value
for value in data.values():
found = extract_stripe_publishable_key(value)
if found:
return found
elif isinstance(data, list):
for value in data:
found = extract_stripe_publishable_key(value)
if found:
return found
elif isinstance(data, str):
match = re.search(r"\bpk_(?:live|test)_[A-Za-z0-9]+\b", data)
if match:
return match.group(0)
return ""
def extract_checkout_url(data: Any) -> str:
if isinstance(data, dict):
for key in (
"url",
"stripe_hosted_url",
"checkout_url",
"checkoutUrl",
"hosted_url",
):
value = str(data.get(key) or "").strip()
if value.startswith(("https://", "http://")):
return value
for value in data.values():
found = extract_checkout_url(value)
if found:
return found
elif isinstance(data, list):
for value in data:
found = extract_checkout_url(value)
if found:
return found
return ""
def extract_checkout_session_id(data: Any) -> str:
if isinstance(data, dict):
for key in (
"checkout_session_id",
"checkoutSessionId",
"stripe_checkout_session_id",
"stripeCheckoutSessionId",
"stripe_session_id",
"stripeSessionId",
"session_id",
"id",
"client_secret",
):
found = extract_checkout_session_id(data.get(key))
if found:
return found
for value in data.values():
found = extract_checkout_session_id(value)
if found:
return found
elif isinstance(data, list):
for value in data:
found = extract_checkout_session_id(value)
if found:
return found
elif isinstance(data, str):
value = data.strip()
for candidate in (value, unquote(value)):
if candidate.startswith(("cs_live_", "cs_test_", "oaics_")):
return candidate.split("_secret_", 1)[0]
match = re.search(r"(?:cs_(?:live|test)_[A-Za-z0-9_]+|oaics_[A-Za-z0-9_]+)", candidate)
if match:
return match.group(0)
return ""
def checkout_debug_value(value: Any) -> str:
if value is None:
return "null"
if isinstance(value, (dict, list)):
return f"{type(value).__name__}(len={len(value)})"
text = str(value)
return f"{type(value).__name__}(len={len(text)}, value={redact_text(text, max_len=130)})"
def checkout_response_summary(data: Any) -> str:
if not isinstance(data, dict):
return checkout_debug_value(data)
interesting = (
"checkout_session_id",
"checkoutSessionId",
"session_id",
"id",
"client_secret",
"customer_session_client_secret",
"confirm_return_url",
"checkout_provider",
"checkout_kind",
"checkout_state",
"checkout_ui_mode",
)
parts: list[str] = []
for key in interesting:
if key in data:
parts.append(f"{key}={checkout_debug_value(data.get(key))}")
hits: list[str] = []
def walk(value: Any, path: str = "$") -> None:
if len(hits) >= 8:
return
if isinstance(value, dict):
for key, item in value.items():
walk(item, f"{path}.{key}")
elif isinstance(value, list):
for index, item in enumerate(value[:20]):
walk(item, f"{path}[{index}]")
elif isinstance(value, str):
text = value.strip()
lowered = text.lower()
if any(marker in lowered for marker in ("cs_", "checkout", "stripe", "session", "secret", "pay.openai.com")):
hits.append(f"{path}={checkout_debug_value(text)}")
walk(data)
if hits:
parts.append("hits=" + " | ".join(hits))
return "; ".join(parts) or f"keys={response_keys(data)}"
def stripe_key_fingerprint(value: str) -> str:
key = str(value or "").strip()
if not key:
return ""
return mask_identifier(key, keep_start=15, keep_end=6)
def stripe_key_env_name(processor_entity: str) -> str:
normalized = re.sub(r"[^A-Za-z0-9]+", "_", str(processor_entity or "").upper()).strip("_")
return f"OPENAI_PAY_STRIPE_PK_{normalized}" if normalized else ""
def resolve_stripe_publishable_key(
req: LongLinkRequest,
checkout: dict[str, Any],
) -> tuple[str, str]:
explicit = req.stripe_publishable_key.strip()
if explicit:
return explicit, "request"
checkout_key = str(checkout.get("stripe_publishable_key") or "").strip()
if checkout_key:
return checkout_key, "checkout_response"
processor_entity = processor_entity_for_country(
str(checkout.get("billing_country") or ""),
str(checkout.get("processor_entity") or ""),
)
entity_env = stripe_key_env_name(processor_entity)
if entity_env:
entity_key = str(os.getenv(entity_env, "") or "").strip()
if entity_key:
return entity_key, entity_env
generic_key = str(os.getenv("OPENAI_PAY_STRIPE_PUBLISHABLE_KEY", "") or "").strip()
if generic_key:
return generic_key, "OPENAI_PAY_STRIPE_PUBLISHABLE_KEY"
if processor_entity == "openai_llc":
return DEFAULT_STRIPE_PK, "legacy_openai_llc_default"
return "", ""
def discover_stripe_key_from_hosted_page(
checkout: dict[str, Any],
req: LongLinkRequest,
provider_proxy: str,
) -> str:
hosted_url = str(checkout.get("checkout_url") or "").strip()
if not hosted_url:
hosted_url = f"https://checkout.stripe.com/c/pay/{checkout['cs_id']}"
session = build_stripe_session(req, proxy_override=provider_proxy)
try:
started = time.perf_counter()
response = session.get(hosted_url, allow_redirects=True, timeout=10)
found = extract_stripe_publishable_key(getattr(response, "text", "") or "")
log_info(
"stripe.key_discovery.hosted_page",
status_code=getattr(response, "status_code", ""),
elapsed_ms=elapsed_ms(started),
hosted_url=hosted_url,
key_found=bool(found),
key_fingerprint=stripe_key_fingerprint(found),
)
return found
except Exception as exc:
log_warning(
"stripe.key_discovery.hosted_page_error",
hosted_url=hosted_url,
error=repr(exc),
)
return ""
def build_chatgpt_session(req: LongLinkRequest) -> Any:
access_token = normalize_access_token(req.access_token)
if not access_token:
raise HTTPException(status_code=400, detail="accessToken is required")
device_id = req.device_id.strip() or str(uuid.uuid4())
user_agent = req.user_agent.strip() or DEFAULT_USER_AGENT
checkout_proxy = checkout_stage_proxy(req)
log_info(
"session.chatgpt.create",
route="checkout_proxy" if checkout_proxy else "direct",
proxy_configured=bool(checkout_proxy),
checkout_proxy=checkout_proxy,
access_token_present=bool(access_token),
device_id=device_id,
custom_user_agent=bool(req.user_agent.strip()),
)
session = new_session()
session.headers.update(
{
"User-Agent": user_agent,
"Accept": "*/*",
"Accept-Language": "en-US,en;q=0.9",
"Authorization": f"Bearer {access_token}",
"Origin": "https://chatgpt.com",
"Referer": "https://chatgpt.com/",
"Content-Type": "application/json",
"oai-device-id": device_id,
"oai-language": "en-US",
"sec-ch-ua": '"Google Chrome";v="147", "Not.A/Brand";v="8", "Chromium";v="147"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"Cookie": f"oai-did={device_id}",
}
)
if checkout_proxy:
set_proxy_url(session, checkout_proxy)
# The ChatGPT session is used only for checkout and approve. Stripe provider
# requests use their own US-routed session.
return session
def create_checkout(
req: LongLinkRequest,
chatgpt_session: Any | None = None,
allow_openai_checkout: bool = False,
include_promo: bool = True,
) -> dict[str, Any]:
billing_country = effective_country(req)
currency = currency_for_country(billing_country)
checkout_ui_mode = (req.checkout_ui_mode or "hosted").strip() or "hosted"
checkout_proxy_configured = bool(
getattr(chatgpt_session, "proxies", {}) if chatgpt_session is not None else checkout_stage_proxy(req)
)
log_info(
"chatgpt.checkout.start",
route="checkout_proxy" if checkout_proxy_configured else "direct",
checkout_proxy_configured=checkout_proxy_configured,
billing_country=billing_country,
currency=currency,
checkout_ui_mode=checkout_ui_mode,
)
body = {
"entry_point": "all_plans_pricing_modal",
"plan_name": "chatgptplusplan",
"billing_details": {
"country": billing_country,
"currency": currency,
},
"checkout_ui_mode": checkout_ui_mode,
}
if include_promo:
body["promo_campaign"] = {
"promo_campaign_id": "plus-1-month-free",
"is_coupon_from_query_param": False,
}
headers = {
"Referer": "https://chatgpt.com/",
"x-openai-target-path": "/backend-api/payments/checkout",
"x-openai-target-route": "/backend-api/payments/checkout",
}
started = time.perf_counter()
response = (chatgpt_session or build_chatgpt_session(req)).post(
"https://chatgpt.com/backend-api/payments/checkout",
json=body,
headers=headers,
timeout=DEFAULT_TIMEOUT,
)
log_info(
"chatgpt.checkout.http",
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
url="https://chatgpt.com/backend-api/payments/checkout",
)
if response.status_code >= 400:
detail = http_error_detail("checkout create failed", response)
log_warning("chatgpt.checkout.error", status_code=response.status_code, detail=detail)
raise HTTPException(
status_code=response.status_code,
detail=detail,
)
data = response.json() or {}
cs_id = extract_checkout_session_id(data)
id_ok = bool(cs_id and (str(cs_id).startswith("cs_") or (allow_openai_checkout and str(cs_id).startswith("oaics_"))))
if not id_ok:
summary = checkout_response_summary(data)
detail = f"checkout response missing cs_id: keys={response_keys(data)} summary={summary}"
log_warning("chatgpt.checkout.missing_cs_id", detail=detail, summary=summary)
raise HTTPException(status_code=502, detail=detail)
processor_entity = extract_processor_entity(data) or processor_entity_for_country(billing_country)
stripe_publishable_key = extract_stripe_publishable_key(data)
checkout_url = extract_checkout_url(data)
confirm_return_url = str(data.get("confirm_return_url") or "").strip()
checkout_provider = str(data.get("checkout_provider") or "").strip()
log_info(
"chatgpt.checkout.done",
cs_id=str(cs_id),
checkout_provider=checkout_provider,
processor_entity=processor_entity,
billing_country=billing_country,
currency=currency,
checkout_url_present=bool(checkout_url),
confirm_return_url_present=bool(confirm_return_url),
stripe_key_present=bool(stripe_publishable_key),
stripe_key_fingerprint=stripe_key_fingerprint(stripe_publishable_key),
response_keys=response_keys(data),
)
return {
"cs_id": str(cs_id),
"processor_entity": processor_entity,
"billing_country": billing_country,
"currency": currency,
"stripe_publishable_key": stripe_publishable_key,
"checkout_url": checkout_url,
"confirm_return_url": confirm_return_url,
"checkout_provider": checkout_provider,
"raw_checkout": data,
}
def update_checkout_promotion(chatgpt: Any, checkout: dict[str, Any], promotion_proxy: str) -> dict[str, Any]:
path = "/backend-api/payments/checkout/update"
original_proxy = session_proxy_url(chatgpt)
promotion_proxy = normalize_proxy_url(promotion_proxy)
if promotion_proxy:
set_proxy_url(chatgpt, promotion_proxy)
else:
clear_proxy_url(chatgpt)
body = {
"checkout_session_id": checkout["cs_id"],
"processor_entity": checkout["processor_entity"],
"plan_name": "chatgptplusplan",
"price_interval": "month",
"seat_quantity": 1,
"promo_campaign": {
"promo_campaign_id": "plus-1-month-free",
"is_coupon_from_query_param": False,
},
}
started = time.perf_counter()
try:
response = chatgpt.post(
f"https://chatgpt.com{path}",
json=body,
headers={
"Referer": f"https://chatgpt.com/checkout/{checkout['processor_entity']}/{checkout['cs_id']}",
"x-openai-target-path": path,
"x-openai-target-route": path,
},
timeout=DEFAULT_TIMEOUT,
)
log_info(
"chatgpt.checkout.promotion_update.http",
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
promotion_proxy=promotion_proxy,
)
if response.status_code >= 400:
raise HTTPException(status_code=response.status_code, detail=http_error_detail("checkout promotion update failed", response))
try:
payload = response.json() or {}
except Exception:
payload = {}
if isinstance(payload, dict) and payload.get("success") is False:
raise HTTPException(status_code=502, detail=f"checkout promotion update rejected: {redact_text(payload)}")
log_info("chatgpt.checkout.promotion_update.done", cs_id=checkout["cs_id"], response_keys=response_keys(payload))
return payload if isinstance(payload, dict) else {}
finally:
if original_proxy:
set_proxy_url(chatgpt, original_proxy)
else:
clear_proxy_url(chatgpt)
def update_ideal_tax_context(
chatgpt: Any,
checkout: dict[str, Any],
req: LongLinkRequest,
stripe_pk: str,
provider_proxy: str,
) -> None:
billing = billing_for_link_type("ideal", "NL")
path = "/backend-api/payments/checkout/taxes"
response = chatgpt.post(
f"https://chatgpt.com{path}",
json={
"checkout_session_id": checkout["cs_id"],
"checkout_email": billing["email"],
"billing_country": "NL",
"billing_name": billing["name"],
"currency": "EUR",
"tax_id": None,
"processor_entity": checkout["processor_entity"],
"billing_address": {
"line1": billing["line1"],
"city": billing["city"],
"country": "NL",
"postal_code": billing["postal_code"],
},
},
headers={
"Referer": f"https://chatgpt.com/checkout/{checkout['processor_entity']}/{checkout['cs_id']}",
"x-openai-target-path": path,
"x-openai-target-route": path,
},
timeout=DEFAULT_TIMEOUT,
)
if response.status_code >= 400:
raise HTTPException(status_code=response.status_code, detail=http_error_detail("iDEAL checkout taxes failed", response))
stripe = build_stripe_session(req, proxy_override=provider_proxy)
tax_response = stripe.post(
f"https://api.stripe.com/v1/payment_pages/{checkout['cs_id']}",
data={
"eid": "NA",
"tax_region[country]": "NL",
"tax_region[postal_code]": billing["postal_code"],
"tax_region[line1]": billing["line1"],
"tax_region[city]": billing["city"],
"key": stripe_pk,
},
timeout=DEFAULT_TIMEOUT,
)
if tax_response.status_code >= 400:
raise HTTPException(status_code=tax_response.status_code, detail=http_error_detail("iDEAL Stripe tax region failed", tax_response))
log_info("ideal.tax_context.done", cs_id=checkout["cs_id"], country="NL")
def stripe_error_fields(response: Any) -> dict[str, str]:
try:
payload = response.json() or {}
except Exception:
payload = {}
error = payload.get("error") if isinstance(payload, dict) else None
error = error if isinstance(error, dict) else {}
return {
"code": str(error.get("code") or ""),
"param": str(error.get("param") or ""),
"type": str(error.get("type") or ""),
"message": str(error.get("message") or ""),
}
def stripe_init(
cs_id: str,
req: LongLinkRequest,
proxy_override: str = "",
stripe_pk_override: str = "",
stripe_key_source: str = "",
processor_entity: str = "",
) -> dict[str, Any]:
stripe_pk = str(stripe_pk_override or req.stripe_publishable_key).strip()
if not stripe_pk:
raise HTTPException(
status_code=422,
detail=(
f"missing Stripe publishable key for processor_entity={processor_entity or 'unknown'}; "
"supply stripe_publishable_key or configure the matching processor environment variable"
),
)
browser_locale, elements_locale = locale_parts(req.payment_locale)
browser_timezone = timezone_for_country(effective_country(req))
proxy_override = normalize_proxy_url(proxy_override)
log_info(
"stripe.init.start",
route="provider_proxy" if proxy_override else "direct",
cs_id=cs_id,
browser_locale=browser_locale,
browser_timezone=browser_timezone,
elements_locale=elements_locale,
custom_stripe_pk=bool(req.stripe_publishable_key.strip()),
stripe_key_source=stripe_key_source,
stripe_key_fingerprint=stripe_key_fingerprint(stripe_pk),
processor_entity=processor_entity,
provider_proxy=proxy_override,
)
stripe = new_session()
stripe.headers.update(
{
"User-Agent": req.user_agent.strip() or DEFAULT_USER_AGENT,
"Accept-Language": "en-US,en;q=0.9",
}
)
if proxy_override:
set_proxy_url(stripe, proxy_override)
body = {
"browser_locale": browser_locale,
"browser_timezone": browser_timezone,
"elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
"elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
"elements_session_client[elements_init_source]": "custom_checkout",
"elements_session_client[referrer_host]": "chatgpt.com",
"elements_session_client[stripe_js_id]": str(uuid.uuid4()),
"elements_session_client[locale]": elements_locale,
"elements_session_client[is_aggregation_expected]": "false",
"elements_options_client[saved_payment_method][enable_save]": "never",
"elements_options_client[saved_payment_method][enable_redisplay]": "never",
"key": stripe_pk,
"_stripe_version": stripe_version_for(req.link_type),
}
response = None
error_fields: dict[str, str] = {}
for attempt in range(1, STRIPE_INIT_RESOURCE_MISSING_ATTEMPTS + 1):
started = time.perf_counter()
response = stripe.post(
f"https://api.stripe.com/v1/payment_pages/{cs_id}/init",
data=body,
timeout=DEFAULT_TIMEOUT,
)
error_fields = stripe_error_fields(response)
log_info(
"stripe.init.http",
attempt=attempt,
max_attempts=STRIPE_INIT_RESOURCE_MISSING_ATTEMPTS,
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
stripe_error_code=error_fields["code"],
stripe_error_param=error_fields["param"],
url=f"https://api.stripe.com/v1/payment_pages/{cs_id}/init",
)
if response.status_code < 400:
break
is_resource_missing = (
response.status_code == 404
and error_fields["code"] == "resource_missing"
and error_fields["param"] == "payment_page"
)
if not is_resource_missing or attempt >= STRIPE_INIT_RESOURCE_MISSING_ATTEMPTS:
break
time.sleep(STRIPE_INIT_RESOURCE_MISSING_DELAY_MS / 1000)
assert response is not None
if response.status_code >= 400:
if (
response.status_code == 404
and error_fields["code"] == "resource_missing"
and error_fields["param"] == "payment_page"
):
detail = (
f"Stripe checkout session is not visible to the selected publishable key "
f"(processor_entity={processor_entity or 'unknown'}, key_source={stripe_key_source or 'unknown'}, "
f"key={stripe_key_fingerprint(stripe_pk)}). Configure the matching key via "
f"{stripe_key_env_name(processor_entity) or 'stripe_publishable_key'} or submit stripe_publishable_key."
)
else:
detail = http_error_detail("stripe init failed", response)
log_warning(
"stripe.init.error",
status_code=response.status_code,
stripe_error_code=error_fields["code"],
stripe_error_param=error_fields["param"],
detail=detail,
)
raise HTTPException(status_code=response.status_code, detail=detail)
payload = response.json() or {}
log_info(
"stripe.init.done",
response_keys=response_keys(payload),
hosted_url=payload.get("stripe_hosted_url", ""),
currency=payload.get("currency", ""),
init_checksum_present=bool(payload.get("init_checksum")),
)
return payload
def to_openai_pay_url(stripe_hosted_url: str) -> str:
url = str(stripe_hosted_url or "").strip()
if not url:
return ""
if url.startswith("https://checkout.stripe.com"):
return "https://pay.openai.com" + url[len("https://checkout.stripe.com") :]
parsed = urlsplit(url)
if parsed.netloc.lower() == "checkout.stripe.com":
return urlunsplit((parsed.scheme or "https", "pay.openai.com", parsed.path, parsed.query, parsed.fragment))
return url
def hosted_checkout_referrer(cs_id: str, init_payload: dict[str, Any], stripe_hosted_url: str) -> str:
raw = (
to_openai_pay_url(stripe_hosted_url)
or to_openai_pay_url(str(init_payload.get("hosted_checkout_url") or ""))
or to_openai_pay_url(str(init_payload.get("stripe_hosted_url") or ""))
or to_openai_pay_url(str(init_payload.get("url") or ""))
or f"https://pay.openai.com/c/pay/{cs_id}"
)
return raw.split("#", 1)[0]
def processor_entity_for_country(country: str, processor_entity: str = "") -> str:
entity = str(processor_entity or "").strip()
if entity:
return entity
return "openai_llc" if str(country or "").upper() == "US" else "openai_ie"
def chatgpt_success_return_url(cs_id: str, country: str, processor_entity: str = "") -> str:
entity = processor_entity_for_country(country, processor_entity)
return f"https://chatgpt.com/checkout/verify?stripe_session_id={cs_id}&processor_entity={entity}&plan_type=plus"
def stripe_checkout_long_url(cs_id: str, country: str, processor_entity: str = "") -> str:
return (
f"https://checkout.stripe.com/c/pay/{cs_id}"
f"?returned_from_redirect=true&ui_mode=custom&return_url="
f"{quote(chatgpt_success_return_url(cs_id, country, processor_entity), safe='')}"
)
def stripe_confirm_return_url(cs_id: str, checkout: dict[str, Any], stripe_hosted_url: str, payment_method_type: str = "paypal") -> str:
hosted_url = to_openai_pay_url(stripe_hosted_url) or stripe_checkout_long_url(
cs_id,
checkout["billing_country"],
checkout.get("processor_entity", ""),
)
if "pay.openai.com/" in hosted_url or "checkout.stripe.com/" in hosted_url:
parsed = urlsplit(hosted_url)
query = dict(parse_qsl(parsed.query, keep_blank_values=True))
query.setdefault("redirect_pm_type", normalize_link_type(payment_method_type))
query.setdefault("lid", "".join(random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") for _ in range(24)))
query.setdefault("ui_mode", "hosted")
query.setdefault(
"success_return_url",
chatgpt_success_return_url(
cs_id,
checkout["billing_country"],
checkout.get("processor_entity", ""),
),
)
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path, urlencode(query), parsed.fragment))
return hosted_url
def expected_amount(init_payload: Any) -> str:
if not isinstance(init_payload, dict):
return "0"
total_summary = init_payload.get("total_summary")
if isinstance(total_summary, dict) and total_summary.get("due") is not None:
return str(total_summary.get("due"))
invoice = init_payload.get("invoice")
if isinstance(invoice, dict) and invoice.get("amount_due") is not None:
return str(invoice.get("amount_due"))
line_items = init_payload.get("line_items")
if isinstance(line_items, list):
total = 0
found = False
for item in line_items:
if isinstance(item, dict) and item.get("amount") is not None:
try:
total += int(item.get("amount") or 0)
found = True
except Exception:
pass
if found:
return str(total)
preferred_keys = (
"amount_due",
"amount_total",
"total_amount",
"checkout_amount",
"due",
"total",
"amount",
"unit_amount",
)
def scan_amount(value: Any, depth: int = 0) -> str:
if depth > 8:
return ""
if isinstance(value, dict):
for key in preferred_keys:
if key in value:
amount = value.get(key)
if isinstance(amount, bool):
continue
if isinstance(amount, (int, float)) and amount >= 0:
return str(int(amount))
text = str(amount if amount is not None else "").strip()
if re.fullmatch(r"\d+(?:\.\d+)?", text):
return text
for item in value.values():
found = scan_amount(item, depth + 1)
if found:
return found
elif isinstance(value, list):
for item in value:
found = scan_amount(item, depth + 1)
if found:
return found
return ""
scanned = scan_amount(init_payload)
if scanned:
return scanned
return "0"
def int_amount(value: Any, default: int = 0) -> int:
if isinstance(value, bool):
return default
if isinstance(value, int):
return value
text = str(value if value is not None else "").strip()
if re.fullmatch(r"-?\d+", text):
return int(text)
return default
def display_amounts(init_payload: Any) -> dict[str, int]:
if not isinstance(init_payload, dict):
return {
"subtotal": 0,
"total_exclusive_tax": 0,
"total_inclusive_tax": 0,
"total_discount_amount": 0,
"shipping_rate_amount": 0,
"due": 0,
}
invoice = init_payload.get("invoice") if isinstance(init_payload.get("invoice"), dict) else {}
total_summary = init_payload.get("total_summary") if isinstance(init_payload.get("total_summary"), dict) else {}
line_item_group = init_payload.get("line_item_group") if isinstance(init_payload.get("line_item_group"), dict) else {}
lines = invoice.get("lines") if isinstance(invoice.get("lines"), dict) else {}
line_items = lines.get("data") if isinstance(lines.get("data"), list) else []
line_subtotal = sum(int_amount(item.get("amount")) for item in line_items if isinstance(item, dict))
subtotal = int_amount(total_summary.get("subtotal"), line_subtotal)
total = int_amount(total_summary.get("total"), int_amount(line_item_group.get("total"), int_amount(invoice.get("amount_due"), 0)))
due = int_amount(total_summary.get("due"), int_amount(invoice.get("amount_due"), total))
return {
"subtotal": subtotal,
"total_exclusive_tax": int_amount(total_summary.get("total_exclusive_tax"), 0),
"total_inclusive_tax": int_amount(total_summary.get("total_inclusive_tax"), total),
"total_discount_amount": max(subtotal - total, 0),
"shipping_rate_amount": 0,
"due": due,
}
def stripe_checksum_plaintext(raw: str) -> str:
if not raw:
return ""
xored = bytearray(ch ^ 5 for ch in raw.encode("utf-8"))
pad = 3 - (len(raw) % 3)
if pad > 0:
xored.extend((ord(" ") ^ 5) for _ in range(pad))
return quote(base64.b64encode(bytes(xored)).decode("ascii"), safe="")
def stripe_shift_checksum(value: dict[str, str]) -> str:
raw = json.dumps(value, separators=(",", ":"))
encoded = stripe_checksum_plaintext(raw)
if not encoded:
return ""
out: list[str] = []
for ch in encoded:
code = ord(ch)
if code < 32 or code > 126:
out.append(ch)
else:
out.append(chr((code - 32 + 11) % 95 + 32))
return "".join(out)
def stripe_checkout_payment_user_agent() -> str:
stripe_js_build = "0711c6012f"
return f"stripe.js/{stripe_js_build}; stripe-js-v3/{stripe_js_build}; checkout"
def merge_stripe_context(target: dict[str, Any], payload: Any) -> dict[str, Any]:
if not isinstance(target, dict) or not isinstance(payload, dict):
return target
for key in (
"init_checksum",
"total_summary",
"invoice",
"line_item_group",
"line_items",
"payment_method_types",
"ordered_payment_method_types",
"payment_method_specs",
"customer_email",
"geocoding",
"config_id",
):
if payload.get(key) is not None:
target[key] = payload[key]
return target
def stripe_pre_confirm_paypal(
stripe: Any,
cs_id: str,
stripe_pk: str,
init_payload: dict[str, Any],
stripe_hosted_url: str,
) -> dict[str, Any]:
referer = to_openai_pay_url(stripe_hosted_url) or str(init_payload.get("stripe_hosted_url") or "")
referer = referer or f"https://pay.openai.com/c/pay/{cs_id}"
body = {
"eid": "NA",
"payment_method_type": "paypal",
"key": stripe_pk,
}
log_info(
"stripe.pre_confirm.start",
route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
cs_id=cs_id,
referer=referer,
)
started = time.perf_counter()
response = stripe.post(
f"https://api.stripe.com/v1/payment_pages/{cs_id}/pre_confirm",
data=body,
headers={
"Origin": "https://pay.openai.com",
"Referer": referer.split("#", 1)[0],
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
timeout=DEFAULT_TIMEOUT,
)
log_info(
"stripe.pre_confirm.http",
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
url=f"https://api.stripe.com/v1/payment_pages/{cs_id}/pre_confirm",
)
if response.status_code >= 400:
detail = http_error_detail("stripe pre_confirm failed", response)
log_warning("stripe.pre_confirm.error", status_code=response.status_code, detail=detail)
return init_payload
try:
payload = response.json() or {}
except Exception:
log_warning("stripe.pre_confirm.bad_json", body=redact_text(response.text, max_len=300))
return init_payload
merge_stripe_context(init_payload, payload)
log_info(
"stripe.pre_confirm.done",
response_keys=response_keys(payload),
init_checksum_present=bool(init_payload.get("init_checksum")),
expected_amount=expected_amount(init_payload),
interesting_fields=interesting_payload_fields(payload),
)
return init_payload
def stripe_prepare_paypal(
stripe: Any,
cs_id: str,
stripe_pk: str,
init_payload: dict[str, Any],
req: LongLinkRequest,
stripe_hosted_url: str,
) -> dict[str, Any]:
referer = to_openai_pay_url(stripe_hosted_url) or str(init_payload.get("stripe_hosted_url") or "")
referer = referer or f"https://pay.openai.com/c/pay/{cs_id}"
route = "provider_proxy" if getattr(stripe, "proxies", {}) else "direct"
def request_json(method: str, url: str, *, params: dict[str, Any] | None = None, data: dict[str, Any] | None = None, step: str) -> dict[str, Any]:
started = time.perf_counter()
try:
response = stripe.request(
method,
url,
params=params,
data=data,
headers={
"Origin": "https://pay.openai.com",
"Referer": referer.split("#", 1)[0],
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
timeout=DEFAULT_TIMEOUT,
)
except Exception as exc:
log_warning("stripe.prepare.exception", step=step, route=route, error=repr(exc))
return {}
log_info(
"stripe.prepare.http",
step=step,
route=route,
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
url=url,
)
if response.status_code >= 400:
log_warning("stripe.prepare.error", step=step, status_code=response.status_code, detail=http_error_detail("stripe prepare failed", response))
return {}
try:
payload = response.json() or {}
except Exception:
log_warning("stripe.prepare.bad_json", step=step, body=redact_text(response.text, max_len=300))
return {}
merge_stripe_context(init_payload, payload)
found_redirect = extract_redirect_to_url(payload)
if found_redirect:
init_payload["_prepared_redirect_url"] = found_redirect
log_info(
"stripe.prepare.done",
step=step,
response_keys=response_keys(payload),
redirect_present=bool(found_redirect),
init_checksum_present=bool(init_payload.get("init_checksum")),
expected_amount=expected_amount(init_payload),
)
return payload
log_info("stripe.prepare.start", route=route, cs_id=cs_id)
request_json(
"GET",
"https://api.stripe.com/v1/payment_pages/allowed_origins",
params={"key": stripe_pk, "session_id": cs_id},
step="allowed_origins",
)
_, elements_locale = locale_parts(req.payment_locale)
request_json(
"GET",
"https://api.stripe.com/v1/elements/sessions",
params={
"client_betas[0]": "google_pay_beta_1",
"client_betas[1]": "disable_deferred_intent_client_validation_beta_1",
"client_betas[2]": "blocked_card_brands_beta_2",
"deferred_intent[mode]": "subscription",
"deferred_intent[amount]": expected_amount(init_payload),
"deferred_intent[currency]": str(init_payload.get("currency") or currency_for_country(effective_country(req))).lower(),
"deferred_intent[setup_future_usage]": "off_session",
"deferred_intent[payment_method_types][0]": "card",
"currency": str(init_payload.get("currency") or currency_for_country(effective_country(req))).lower(),
"key": stripe_pk,
"elements_init_source": "checkout",
"hosted_surface": "checkout",
"referrer_host": "pay.openai.com",
"stripe_js_id": str(uuid.uuid4()),
"locale": elements_locale,
"type": "deferred_intent",
"checkout_session_id": cs_id,
},
step="elements_sessions",
)
for tax_country in [effective_country(req), "US"]:
request_json(
"POST",
f"https://api.stripe.com/v1/payment_pages/{cs_id}",
data={"eid": "NA", "tax_region[country]": tax_country, "key": stripe_pk},
step=f"tax_region_{tax_country}",
)
break
log_info(
"stripe.prepare.finish",
cs_id=cs_id,
init_checksum_present=bool(init_payload.get("init_checksum")),
expected_amount=expected_amount(init_payload),
prepared_redirect_present=bool(init_payload.get("_prepared_redirect_url")),
)
return init_payload
def amount_is_zero(value: Any) -> bool:
text = str(value if value is not None else "").strip()
if not text:
return False
try:
return float(text) == 0
except Exception:
digits = re.sub(r"[^\d.-]+", "", text)
try:
return bool(digits) and float(digits) == 0
except Exception:
return text in {"0", "0.0", "0.00"}
def enforce_zero_checkout_amount(init_payload: dict[str, Any], req: LongLinkRequest, cs_id: str) -> None:
amount = expected_amount(init_payload)
currency = str(init_payload.get("currency") or currency_for_country(effective_country(req))).upper()
if amount_is_zero(amount):
log_info(
"stripe.amount_guard.ok",
cs_id=cs_id,
amount=amount,
currency=currency,
billing_country=effective_country(req),
pm_country=effective_pm_country(req),
)
return
detail = f"付款金额不是 0,已停止:amount={amount} {currency}"
log_warning(
"stripe.amount_guard.blocked",
cs_id=cs_id,
amount=amount,
currency=currency,
billing_country=effective_country(req),
pm_country=effective_pm_country(req),
detail=detail,
)
raise HTTPException(status_code=402, detail=detail)
def is_amount_guard_error(exc: Exception) -> bool:
if not isinstance(exc, HTTPException):
return False
detail = str(exc.detail or "")
return exc.status_code == 402 and ("付款金额不是 0" in detail or "amount not zero" in detail.lower())
NON_RETRYABLE_ERROR_MARKERS = (
"could not parse your authentication token",
"invalid cdk",
"cdk exhausted",
"cdk revoked",
"payment_method_types_mismatch",
"does not offer paypal",
"does not offer ideal",
"does not offer upi",
"payment method is not available",
"payment_method_not_available",
"payment_method_unsupported_type",
"setup_attempt_failed",
"generic_decline",
"requires a new payment method",
"付款金额不是 0",
"amount not zero",
)
FRESH_CHECKOUT_RETRYABLE_MARKERS = (
"setup_attempt_failed",
"generic_decline",
"requires a new payment method",
"checkout_not_active_session",
)
def retryable_failure(detail: Any, status_code: int = 0, fresh_checkout: bool = False) -> bool:
text = str(detail or "").strip().lower()
# These are terminal for the current Stripe/Checkout object, but historical
# successes show that a new CS plus a fresh proxy SID can recover. Never
# repeat them inside the same checkout; only the bounded outer loop opts in.
if fresh_checkout and any(marker in text for marker in FRESH_CHECKOUT_RETRYABLE_MARKERS):
return True
if any(marker in text for marker in NON_RETRYABLE_ERROR_MARKERS):
return False
if status_code in {400, 401, 402, 422}:
return False
if status_code in {403, 408, 409, 425, 429, 500, 502, 503, 504}:
return True
transient_markers = (
"timeout",
"timed out",
"tls connect error",
"proxy",
"connection",
"checkout_not_active_session",
"approve blocked",
"result: 'blocked'",
"server error",
)
return any(marker in text for marker in transient_markers)
def provider_error_diagnostic(
detail: Any,
link_type: str,
checkout: dict[str, Any],
req: LongLinkRequest,
) -> str:
original = str(detail or "").strip()
lowered = original.lower()
method = normalize_link_type(link_type)
if method == "paypal" and ("setup_attempt_failed" in lowered or "generic_decline" in lowered):
return (
"PayPal SetupIntent 被 Stripe/PayPal 拒绝(当前 Checkout 已终止,需切换新 CS/代理会话);"
f"processor={checkout.get('processor_entity') or 'unknown'}, "
f"billing={effective_country(req)}, pm={effective_pm_country(req)}, "
f"checkout_proxy_country={proxy_country_hint(checkout_stage_proxy(req)) or 'unknown'}, "
f"provider_proxy_country={proxy_country_hint(provider_stage_proxy(req)) or 'unknown'}; "
f"upstream={original}"
)
if method == "upi" and "payment_method_types_mismatch" in lowered:
return (
"当前 Checkout 未向 UPI 开放该支付流程;"
f"billing={effective_country(req)}, provider_proxy_country="
f"{proxy_country_hint(provider_stage_proxy(req)) or 'unknown'}; upstream={original}"
)
return original
KNOWN_PAYMENT_METHOD_TYPES = {
"card",
"link",
"paypal",
"ideal",
"upi",
"google_pay",
"apple_pay",
}
def available_payment_method_types(payload: Any) -> set[str]:
"""Read only Stripe's explicit method lists/specs, avoiding loose key-name matches."""
found: set[str] = set()
def add(value: Any) -> None:
method = str(value or "").strip().lower()
if method in KNOWN_PAYMENT_METHOD_TYPES:
found.add(method)
def visit(value: Any, depth: int = 0, in_specs: bool = False) -> None:
if depth > 9:
return
if isinstance(value, dict):
for key, item in value.items():
key_text = str(key).strip().lower()
if key_text in {"payment_method_types", "ordered_payment_method_types"}:
if isinstance(item, list):
for method in item:
add(method)
else:
add(item)
elif key_text in {"payment_method_type", "expected_payment_method_type"}:
add(item)
elif in_specs and key_text == "type":
add(item)
visit(item, depth + 1, in_specs or key_text == "payment_method_specs")
elif isinstance(value, list):
for item in value[:200]:
visit(item, depth + 1, in_specs)
visit(payload)
return found
def payload_has_paypal(value: Any, depth: int = 0) -> bool:
del depth # compatibility with the former recursive signature
return "paypal" in available_payment_method_types(value)
def payment_method_is_available(payload: Any, link_type: str) -> bool:
return normalize_link_type(link_type) in available_payment_method_types(payload)
def require_payment_method_available(payload: Any, link_type: str) -> None:
method = normalize_link_type(link_type)
methods = available_payment_method_types(payload)
if method in methods:
return
available = ",".join(sorted(methods)) or "none"
raise HTTPException(
status_code=422,
detail=(
f"Stripe Checkout does not offer {method} for this country/currency/flow; "
f"available={available}"
),
)
def stripe_context(cs_id: str, init_payload: dict[str, Any], req: LongLinkRequest) -> dict[str, Any]:
_, elements_locale = locale_parts(req.payment_locale)
return {
"stripe_js_id": str(uuid.uuid4()),
"elements_session_id": f"elements_session_{uuid.uuid4().hex[:11]}",
"elements_session_config_id": str(init_payload.get("config_id") or uuid.uuid4()),
"config_id": init_payload.get("config_id") or "",
"init_checksum": init_payload.get("init_checksum") or "",
"currency": str(init_payload.get("currency") or currency_for_country(effective_country(req))).lower(),
"checkout_amount": expected_amount(init_payload),
"locale": elements_locale,
"checkout_ui_mode": (req.checkout_ui_mode or "hosted").strip() or "hosted",
"stripe_version": stripe_version_for(req.link_type),
}
def generated_billing_profile(country: str) -> dict[str, str]:
billing_country = supported_country(country, "US")
if billing_country in BILLING_PROFILES:
profile_entry = BILLING_PROFILES[billing_country]
if isinstance(profile_entry, list):
return random.choice(profile_entry)
return profile_entry
city, state, postal_code, line1 = COUNTRY_CITY_SEEDS.get(
billing_country,
("Capital City", billing_country, "1000", "Central Avenue 10"),
)
first_name, last_name = COUNTRY_NAME_SEEDS[sum(ord(ch) for ch in billing_country) % len(COUNTRY_NAME_SEEDS)]
return {
"first_name": first_name,
"last_name": last_name,
"line1": line1,
"city": city,
"state": state,
"postal_code": postal_code,
}
def billing_for_link_type(link_type: str, country: str = "US") -> dict[str, str]:
billing_country = supported_country(country, "US")
profile = generated_billing_profile(billing_country)
first_name = profile["first_name"]
last_name = profile["last_name"]
suffix = random.randint(1000, 9999)
return {
"name": f"{first_name} {last_name}",
"email": f"{first_name.lower()}.{last_name.lower()}{suffix}@example.com",
"country": billing_country,
"line1": profile["line1"],
"city": profile["city"],
"state": profile["state"],
"postal_code": profile["postal_code"],
}
def build_stripe_session(req: LongLinkRequest, proxy_override: str = "") -> Any:
proxy_override = normalize_proxy_url(proxy_override)
log_info(
"session.stripe.create",
route="provider_proxy" if proxy_override else "direct",
proxy_configured=bool(proxy_override),
provider_proxy=proxy_override,
)
stripe = new_session()
stripe.headers.update(
{
"User-Agent": req.user_agent.strip() or DEFAULT_USER_AGENT,
"Accept-Language": "en-US,en;q=0.9",
}
)
if proxy_override:
set_proxy_url(stripe, proxy_override)
return stripe
def stripe_create_payment_method(
stripe: Any,
cs_id: str,
stripe_pk: str,
billing: dict[str, str],
payment_method_type: str,
ctx: dict[str, Any],
init_payload: dict[str, Any] | None = None,
stripe_hosted_url: str = "",
) -> str:
payment_method_type = normalize_link_type(payment_method_type)
runtime_version = str(ctx.get("runtime_version") or DEFAULT_STRIPE_RUNTIME_VERSION)
log_info(
"stripe.payment_method.start",
route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
cs_id=cs_id,
payment_method_type=payment_method_type,
billing_country=billing.get("country") or "US",
billing_name=billing.get("name") or "",
billing_city=billing.get("city") or "",
billing_state=billing.get("state") or "",
billing_postal_code=billing.get("postal_code") or "",
currency=ctx.get("currency", ""),
checkout_amount=ctx.get("checkout_amount", ""),
)
hosted_mode = str(ctx.get("checkout_ui_mode") or "").lower() == "hosted"
if hosted_mode:
body = {
"billing_details[name]": billing.get("name") or "John Doe",
"billing_details[email]": billing.get("email") or "buyer@example.com",
"billing_details[address][country]": billing.get("country") or "US",
"billing_details[address][line1]": billing.get("line1") or "123 Market St",
"billing_details[address][city]": billing.get("city") or "San Francisco",
"billing_details[address][postal_code]": billing.get("postal_code") or "94105",
"billing_details[address][state]": billing.get("state") or "CA",
"type": payment_method_type,
"payment_user_agent": stripe_checkout_payment_user_agent(),
"client_attribution_metadata[checkout_session_id]": cs_id,
"client_attribution_metadata[merchant_integration_source]": "checkout",
"client_attribution_metadata[merchant_integration_subtype]": "hosted",
"client_attribution_metadata[merchant_integration_version]": "hosted_checkout",
"client_attribution_metadata[payment_method_selection_flow]": "automatic",
"key": stripe_pk,
"_stripe_version": str(ctx.get("stripe_version") or stripe_version_for(payment_method_type)),
}
if ctx.get("config_id"):
body["client_attribution_metadata[checkout_config_id]"] = str(ctx.get("config_id") or "")
else:
body = {
"billing_details[name]": billing.get("name") or "John Doe",
"billing_details[email]": billing.get("email") or "buyer@example.com",
"billing_details[address][country]": billing.get("country") or "US",
"billing_details[address][line1]": billing.get("line1") or "123 Market St",
"billing_details[address][city]": billing.get("city") or "San Francisco",
"billing_details[address][postal_code]": billing.get("postal_code") or "94105",
"billing_details[address][state]": billing.get("state") or "CA",
"type": payment_method_type,
"payment_user_agent": f"stripe.js/{runtime_version}; stripe-js-v3/{runtime_version}; payment-element; deferred-intent",
"referrer": "https://chatgpt.com",
"time_on_page": str(random.randint(25000, 55000)),
"client_attribution_metadata[checkout_session_id]": cs_id,
"client_attribution_metadata[client_session_id]": ctx["stripe_js_id"],
"client_attribution_metadata[checkout_config_id]": ctx.get("config_id") or "",
"client_attribution_metadata[elements_session_id]": ctx["elements_session_id"],
"client_attribution_metadata[elements_session_config_id]": ctx["elements_session_config_id"],
"client_attribution_metadata[merchant_integration_source]": "elements",
"client_attribution_metadata[merchant_integration_subtype]": "payment-element",
"client_attribution_metadata[merchant_integration_version]": "2021",
"client_attribution_metadata[payment_intent_creation_flow]": "deferred",
"client_attribution_metadata[payment_method_selection_flow]": "automatic",
"client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
"client_attribution_metadata[merchant_integration_additional_elements][1]": "address",
"key": stripe_pk,
"_stripe_version": str(ctx.get("stripe_version") or stripe_version_for(payment_method_type)),
}
started = time.perf_counter()
headers = None
if hosted_mode:
headers = {
"Origin": "https://pay.openai.com",
"Referer": hosted_checkout_referrer(cs_id, init_payload or {}, stripe_hosted_url),
}
response = stripe.post("https://api.stripe.com/v1/payment_methods", data=body, headers=headers, timeout=DEFAULT_TIMEOUT)
log_info(
"stripe.payment_method.http",
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
url="https://api.stripe.com/v1/payment_methods",
)
if response.status_code >= 400:
detail = http_error_detail("stripe payment_methods failed", response)
log_warning("stripe.payment_method.error", status_code=response.status_code, detail=detail)
raise HTTPException(status_code=response.status_code, detail=detail)
payload = response.json() or {}
pm_id = str(payload.get("id") or "")
if not pm_id.startswith("pm_"):
detail = f"stripe payment_methods bad response: keys={response_keys(payload)} body={redact_text(response.text, max_len=300)}"
log_warning("stripe.payment_method.bad_response", detail=detail)
raise HTTPException(status_code=502, detail=detail)
log_info("stripe.payment_method.done", payment_method_id=pm_id, response_keys=response_keys(payload))
return pm_id
def stripe_confirm(
stripe: Any,
cs_id: str,
pm_id: str,
stripe_pk: str,
payment_method_type: str,
init_payload: dict[str, Any],
ctx: dict[str, Any],
checkout: dict[str, Any],
req: LongLinkRequest,
stripe_hosted_url: str,
) -> dict[str, Any]:
payment_method_type = normalize_link_type(payment_method_type)
return_url = stripe_confirm_return_url(cs_id, checkout, stripe_hosted_url, payment_method_type)
runtime_version = str(ctx.get("runtime_version") or DEFAULT_STRIPE_RUNTIME_VERSION)
hosted_mode = str(ctx.get("checkout_ui_mode") or "").lower() == "hosted"
log_info(
"stripe.confirm.start",
route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
cs_id=cs_id,
payment_method_id=pm_id,
expected_amount=str(ctx.get("checkout_amount") or expected_amount(init_payload)),
payment_method_type=payment_method_type,
return_url=return_url,
mode="hosted" if hosted_mode else "custom",
)
if hosted_mode:
amounts = display_amounts(init_payload)
body = {
"eid": "NA",
"payment_method": pm_id,
"init_checksum": str(init_payload.get("init_checksum") or ctx.get("init_checksum") or ""),
"expected_amount": str(ctx.get("checkout_amount") or expected_amount(init_payload)),
"expected_payment_method_type": payment_method_type,
"consent[terms_of_service]": "accepted",
"last_displayed_line_item_group_details[subtotal]": str(amounts["subtotal"]),
"last_displayed_line_item_group_details[total_exclusive_tax]": str(amounts["total_exclusive_tax"]),
"last_displayed_line_item_group_details[total_inclusive_tax]": str(amounts["total_inclusive_tax"]),
"last_displayed_line_item_group_details[total_discount_amount]": str(amounts["total_discount_amount"]),
"last_displayed_line_item_group_details[shipping_rate_amount]": str(amounts["shipping_rate_amount"]),
"return_url": return_url,
"js_checksum": stripe_shift_checksum({"id": pm_id}),
"rv_timestamp": stripe_shift_checksum(
{
"rvTs": "2024-01-01 00:00:00 -0000",
"rv": "0711c6012fed57bca21a1857e407d89e5745e3df",
"sv": "d616dee94d164fb10d46843aec403d3beeb078d097c08dd8d77451247f21d924",
}
),
"client_attribution_metadata[checkout_session_id]": cs_id,
"client_attribution_metadata[merchant_integration_source]": "checkout",
"client_attribution_metadata[merchant_integration_subtype]": "hosted",
"client_attribution_metadata[merchant_integration_version]": "hosted_checkout",
"client_attribution_metadata[payment_method_selection_flow]": "automatic",
"key": stripe_pk,
"_stripe_version": str(ctx.get("stripe_version") or stripe_version_for(payment_method_type)),
}
if ctx.get("config_id"):
body["client_attribution_metadata[checkout_config_id]"] = str(ctx.get("config_id") or "")
else:
body = {
"guid": uuid.uuid4().hex,
"muid": uuid.uuid4().hex,
"sid": uuid.uuid4().hex,
"payment_method": pm_id,
"init_checksum": str(init_payload.get("init_checksum") or ctx.get("init_checksum") or ""),
"version": runtime_version,
"expected_amount": str(ctx.get("checkout_amount") or expected_amount(init_payload)),
"expected_payment_method_type": payment_method_type,
"return_url": return_url,
"elements_session_client[session_id]": ctx["elements_session_id"],
"elements_session_client[locale]": str(ctx.get("locale") or "en"),
"elements_session_client[referrer_host]": "chatgpt.com",
"elements_session_client[is_aggregation_expected]": "false",
"elements_session_client[elements_init_source]": "custom_checkout",
"elements_session_client[stripe_js_id]": ctx["stripe_js_id"],
"elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
"elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
"elements_options_client[saved_payment_method][enable_save]": "never",
"elements_options_client[saved_payment_method][enable_redisplay]": "never",
"client_attribution_metadata[client_session_id]": ctx["stripe_js_id"],
"client_attribution_metadata[checkout_session_id]": cs_id,
"client_attribution_metadata[checkout_config_id]": ctx.get("config_id") or "",
"client_attribution_metadata[elements_session_id]": ctx["elements_session_id"],
"client_attribution_metadata[elements_session_config_id]": ctx["elements_session_config_id"],
"client_attribution_metadata[merchant_integration_source]": "checkout",
"client_attribution_metadata[merchant_integration_subtype]": "payment-element",
"client_attribution_metadata[merchant_integration_version]": "custom",
"client_attribution_metadata[payment_intent_creation_flow]": "deferred",
"client_attribution_metadata[payment_method_selection_flow]": "automatic",
"client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
"client_attribution_metadata[merchant_integration_additional_elements][1]": "address",
"consent[terms_of_service]": "accepted",
"key": stripe_pk,
"_stripe_version": str(ctx.get("stripe_version") or stripe_version_for(payment_method_type)),
}
started = time.perf_counter()
headers = None
if hosted_mode:
headers = {
"Origin": "https://pay.openai.com",
"Referer": hosted_checkout_referrer(cs_id, init_payload, stripe_hosted_url),
}
confirm_timeout = UPI_CONFIRM_TIMEOUT_SECONDS if payment_method_type == "upi" else DEFAULT_TIMEOUT
response = stripe.post(
f"https://api.stripe.com/v1/payment_pages/{cs_id}/confirm",
data=body,
headers=headers,
timeout=confirm_timeout,
)
log_info(
"stripe.confirm.http",
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
timeout_seconds=confirm_timeout,
url=f"https://api.stripe.com/v1/payment_pages/{cs_id}/confirm",
)
if response.status_code >= 400:
detail = http_error_detail("stripe confirm failed", response)
log_warning("stripe.confirm.error", status_code=response.status_code, detail=detail)
raise HTTPException(status_code=response.status_code, detail=detail)
payload = response.json() or {}
submission = payload.get("submission_attempt") if isinstance(payload, dict) else None
submission_state = submission.get("state") if isinstance(submission, dict) else ""
intent_state = stripe_intent_state(payload)
log_info(
"stripe.confirm.done",
response_keys=response_keys(payload),
interesting_fields=interesting_payload_fields(payload),
has_redirect=bool(extract_redirect_to_url(payload)),
submission_state=submission_state,
checkout_status=payload.get("status", "") if isinstance(payload, dict) else "",
checkout_state=payload.get("state", "") if isinstance(payload, dict) else "",
payment_intent_present=bool(payload.get("payment_intent")) if isinstance(payload, dict) else False,
setup_intent_present=bool(payload.get("setup_intent")) if isinstance(payload, dict) else False,
next_action_present=bool(payload.get("next_action")) if isinstance(payload, dict) else False,
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
next_action_type=intent_state.get("next_action_type", ""),
)
return payload
def stripe_confirm_direct_paypal(
stripe: Any,
cs_id: str,
stripe_pk: str,
billing: dict[str, str],
init_payload: dict[str, Any],
ctx: dict[str, Any],
checkout: dict[str, Any],
req: LongLinkRequest,
stripe_hosted_url: str,
) -> dict[str, Any]:
return_url = stripe_confirm_return_url(cs_id, checkout, stripe_hosted_url)
runtime_version = str(ctx.get("runtime_version") or DEFAULT_STRIPE_RUNTIME_VERSION)
log_info(
"stripe.confirm_direct.start",
route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
cs_id=cs_id,
billing_country=billing.get("country") or "",
expected_amount=str(ctx.get("checkout_amount") or expected_amount(init_payload)),
return_url=return_url,
)
body = {
"guid": uuid.uuid4().hex,
"muid": uuid.uuid4().hex,
"sid": uuid.uuid4().hex,
"payment_method_data[type]": "paypal",
"payment_method_data[billing_details][name]": billing.get("name") or "",
"payment_method_data[billing_details][email]": billing.get("email") or "",
"payment_method_data[billing_details][address][country]": billing.get("country") or "",
"payment_method_data[billing_details][address][line1]": billing.get("line1") or "",
"payment_method_data[billing_details][address][city]": billing.get("city") or "",
"payment_method_data[billing_details][address][postal_code]": billing.get("postal_code") or "",
"payment_method_data[billing_details][address][state]": billing.get("state") or "",
"init_checksum": str(init_payload.get("init_checksum") or ctx.get("init_checksum") or ""),
"version": runtime_version,
"expected_amount": str(ctx.get("checkout_amount") or expected_amount(init_payload)),
"expected_payment_method_type": "paypal",
"return_url": return_url,
"elements_session_client[session_id]": ctx["elements_session_id"],
"elements_session_client[locale]": str(ctx.get("locale") or "en"),
"elements_session_client[referrer_host]": "chatgpt.com",
"elements_session_client[is_aggregation_expected]": "false",
"elements_session_client[elements_init_source]": "custom_checkout",
"elements_session_client[stripe_js_id]": ctx["stripe_js_id"],
"elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
"elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
"elements_options_client[saved_payment_method][enable_save]": "never",
"elements_options_client[saved_payment_method][enable_redisplay]": "never",
"client_attribution_metadata[client_session_id]": ctx["stripe_js_id"],
"client_attribution_metadata[checkout_session_id]": cs_id,
"client_attribution_metadata[checkout_config_id]": ctx.get("config_id") or "",
"client_attribution_metadata[elements_session_id]": ctx["elements_session_id"],
"client_attribution_metadata[elements_session_config_id]": ctx["elements_session_config_id"],
"client_attribution_metadata[merchant_integration_source]": "checkout",
"client_attribution_metadata[merchant_integration_subtype]": "payment-element",
"client_attribution_metadata[merchant_integration_version]": "custom",
"client_attribution_metadata[payment_intent_creation_flow]": "deferred",
"client_attribution_metadata[payment_method_selection_flow]": "automatic",
"client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
"client_attribution_metadata[merchant_integration_additional_elements][1]": "address",
"consent[terms_of_service]": "accepted",
"key": stripe_pk,
"_stripe_version": str(ctx.get("stripe_version") or stripe_version_for("paypal")),
}
started = time.perf_counter()
response = stripe.post(f"https://api.stripe.com/v1/payment_pages/{cs_id}/confirm", data=body, timeout=DEFAULT_TIMEOUT)
log_info(
"stripe.confirm_direct.http",
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
url=f"https://api.stripe.com/v1/payment_pages/{cs_id}/confirm",
)
if response.status_code >= 400:
detail = http_error_detail("stripe direct paypal confirm failed", response)
log_warning("stripe.confirm_direct.error", status_code=response.status_code, detail=detail)
raise HTTPException(status_code=response.status_code, detail=detail)
payload = response.json() or {}
intent_state = stripe_intent_state(payload)
log_info(
"stripe.confirm_direct.done",
response_keys=response_keys(payload),
interesting_fields=interesting_payload_fields(payload),
has_redirect=bool(extract_redirect_to_url(payload)),
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
next_action_type=intent_state.get("next_action_type", ""),
)
return payload
NEXT_ACTION_URL_KEYS = (
"hosted_instructions_url",
"mobile_auth_url",
"url",
"hosted_voucher_url",
"hosted_verification_url",
"image_url_svg",
"image_url_png",
)
def next_action_from_payload(payload: Any) -> dict[str, Any]:
if not isinstance(payload, dict):
return {}
action = payload.get("next_action")
if isinstance(action, dict):
return action
for key in ("setup_intent", "payment_intent"):
nested = payload.get(key)
found = next_action_from_payload(nested)
if found:
return found
return {}
def next_action_type(payload: Any) -> str:
return str(next_action_from_payload(payload).get("type") or "").strip()
def extract_action_url(value: Any, depth: int = 0) -> str:
if depth > 5:
return ""
if isinstance(value, dict):
for key in NEXT_ACTION_URL_KEYS:
candidate = str(value.get(key) or "").strip()
if candidate.startswith(("https://", "http://")):
return candidate
for item in value.values():
candidate = extract_action_url(item, depth + 1)
if candidate:
return candidate
elif isinstance(value, list):
for item in value[:20]:
candidate = extract_action_url(item, depth + 1)
if candidate:
return candidate
return ""
def extract_redirect_to_url(payload: Any) -> str:
action = next_action_from_payload(payload)
if not action:
return ""
action_type = str(action.get("type") or "").strip()
action_payload = action.get(action_type)
if not isinstance(action_payload, dict) and action_type == "redirect_to_url":
action_payload = action.get("redirect_to_url")
if isinstance(action_payload, dict):
found = extract_action_url(action_payload)
if found:
return found
return extract_action_url(action)
def stripe_intent_state(payload: Any) -> dict[str, str]:
if not isinstance(payload, dict):
return {}
candidates: list[dict[str, Any]] = []
if payload.get("object") in {"setup_intent", "payment_intent"}:
candidates.append(payload)
for key in ("setup_intent", "payment_intent"):
nested = payload.get(key)
if isinstance(nested, dict):
candidates.append(nested)
for intent in candidates:
object_type = str(intent.get("object") or "")
error_key = "last_setup_error" if object_type == "setup_intent" else "last_payment_error"
error = intent.get(error_key)
error = error if isinstance(error, dict) else {}
next_action = intent.get("next_action")
next_action = next_action if isinstance(next_action, dict) else {}
return {
"object": object_type,
"status": str(intent.get("status") or ""),
"error_code": str(error.get("code") or ""),
"decline_code": str(error.get("decline_code") or ""),
"error_message": str(error.get("message") or ""),
"next_action_type": str(next_action.get("type") or ""),
}
return {}
def stripe_terminal_intent_error(payload: Any) -> str:
state = stripe_intent_state(payload)
status = state.get("status", "")
if status == "canceled":
return f"{state.get('object') or 'stripe intent'} canceled"
if status != "requires_payment_method":
return ""
code = state.get("error_code", "")
decline_code = state.get("decline_code", "")
message = state.get("error_message", "")
if not any((code, decline_code, message)):
return ""
parts = [f"{state.get('object') or 'stripe intent'} requires a new payment method"]
if code:
parts.append(f"code={code}")
if decline_code:
parts.append(f"decline_code={decline_code}")
if message:
parts.append(f"message={message}")
return "; ".join(parts)
def checkout_approval_reason(payload: Any) -> str:
if not isinstance(payload, dict):
return ""
submission = payload.get("submission_attempt")
if isinstance(submission, dict) and str(submission.get("state") or "").lower() == "requires_approval":
return "submission_requires_approval"
status = str(payload.get("status") or "").strip().lower()
state = str(payload.get("state") or "").strip().lower()
if status == "open" and state == "active":
return "checkout_open_active"
return ""
def stripe_payment_page_redirect_url(
stripe: Any,
cs_id: str,
stripe_pk: str,
req: LongLinkRequest,
ctx: dict[str, Any] | None = None,
timeout_seconds: float = 30,
max_attempts: int = STRIPE_REDIRECT_POLL_MAX_ATTEMPTS,
) -> str:
deadline = time.time() + max(1.0, float(timeout_seconds or 30))
# Provider actions can appear shortly after ChatGPT approval. Poll a small,
# bounded number of times; never fan out concurrent requests for one CS ID.
max_attempts = max(1, min(int(max_attempts or 1), STRIPE_REDIRECT_POLL_MAX_ATTEMPTS))
pool_workers = min(max(1, STRIPE_REDIRECT_POLL_WORKERS), max_attempts)
sequential = True
poll_proxies = redirect_poll_proxy_pool(req, stripe)
last_err = ""
log_info(
"stripe.redirect_poll.start",
route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
cs_id=cs_id,
timeout_seconds=timeout_seconds,
max_attempts=max_attempts,
pool_workers=1 if sequential else pool_workers,
reuse_context=bool(ctx),
poll_proxy_pool_count=len(poll_proxies),
poll_proxy_label=redact_proxy(poll_proxies[0]) if poll_proxies else "",
elements_session_id=str((ctx or {}).get("elements_session_id") or ""),
stripe_js_id=str((ctx or {}).get("stripe_js_id") or ""),
concurrent=not sequential,
)
request_id = REQUEST_ID.get()
task_callback = TASK_LOG_CALLBACK.get()
thread_state = local()
def poll_once(attempt: int) -> dict[str, Any]:
request_token = REQUEST_ID.set(request_id)
callback_token = TASK_LOG_CALLBACK.set(task_callback)
try:
session = clone_session(stripe)
poll_proxy = poll_proxies[(attempt - 1) % len(poll_proxies)] if poll_proxies else ""
if poll_proxy:
set_proxy_url(session, poll_proxy)
params = {
"elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
"elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
"elements_session_client[elements_init_source]": "custom_checkout",
"elements_session_client[referrer_host]": "chatgpt.com",
"elements_session_client[session_id]": str((ctx or {}).get("elements_session_id") or f"elements_session_{uuid.uuid4().hex[:11]}"),
"elements_session_client[stripe_js_id]": str((ctx or {}).get("stripe_js_id") or uuid.uuid4()),
"elements_session_client[locale]": str((ctx or {}).get("locale") or locale_parts(req.payment_locale)[1]),
"elements_session_client[is_aggregation_expected]": "false",
"elements_options_client[saved_payment_method][enable_save]": "never",
"elements_options_client[saved_payment_method][enable_redisplay]": "never",
"key": stripe_pk,
"_stripe_version": str((ctx or {}).get("stripe_version") or stripe_version_for(req.link_type)),
}
started = time.perf_counter()
try:
response = session.get(
f"https://api.stripe.com/v1/payment_pages/{cs_id}",
params=params,
timeout=DEFAULT_TIMEOUT,
)
except Exception as exc:
return {
"attempt": attempt,
"status_code": 0,
"elapsed_ms": elapsed_ms(started),
"redirect_url": "",
"terminal_error": "",
"detail": f"stripe redirect poll exception: {repr(exc)}",
"intent_state": {},
"response_keys": "",
"interesting_fields": "",
"poll_proxy_index": ((attempt - 1) % len(poll_proxies) + 1) if poll_proxies else 0,
"poll_proxy_count": len(poll_proxies),
"poll_proxy_label": redact_proxy(poll_proxy),
}
duration = elapsed_ms(started)
if response.status_code == 200:
payload = response.json() or {}
redirect_url = extract_redirect_to_url(payload)
intent_state = stripe_intent_state(payload)
terminal_error = stripe_terminal_intent_error(payload)
return {
"attempt": attempt,
"status_code": response.status_code,
"elapsed_ms": duration,
"redirect_url": redirect_url,
"terminal_error": terminal_error,
"detail": terminal_error or f"keys=[{','.join(sorted(payload.keys())[:8])}]",
"intent_state": intent_state,
"response_keys": response_keys(payload),
"interesting_fields": interesting_payload_fields(payload),
"poll_proxy_index": ((attempt - 1) % len(poll_proxies) + 1) if poll_proxies else 0,
"poll_proxy_count": len(poll_proxies),
"poll_proxy_label": redact_proxy(poll_proxy),
}
return {
"attempt": attempt,
"status_code": response.status_code,
"elapsed_ms": duration,
"redirect_url": "",
"terminal_error": "",
"detail": f"http {response.status_code}: {redact_text(response.text, max_len=120)}",
"intent_state": {},
"response_keys": "",
"interesting_fields": "",
"poll_proxy_index": ((attempt - 1) % len(poll_proxies) + 1) if poll_proxies else 0,
"poll_proxy_count": len(poll_proxies),
"poll_proxy_label": redact_proxy(poll_proxy),
}
finally:
TASK_LOG_CALLBACK.reset(callback_token)
REQUEST_ID.reset(request_token)
if sequential:
completed = 0
terminal_errors = 0
for attempt in range(1, max_attempts + 1):
if time.time() >= deadline:
break
item = poll_once(attempt)
completed += 1
status_code = int(item.get("status_code") or 0)
duration = int(item.get("elapsed_ms") or 0)
intent_state = item.get("intent_state") if isinstance(item.get("intent_state"), dict) else {}
candidate_url = str(item.get("redirect_url") or "")
terminal_error = str(item.get("terminal_error") or "")
if status_code == 200:
log_info(
"stripe.redirect_poll.http",
attempt=attempt,
completed=completed,
submitted=attempt,
pool_workers=1,
status_code=status_code,
elapsed_ms=duration,
has_redirect=bool(candidate_url),
poll_proxy_index=int(item.get("poll_proxy_index") or 0),
poll_proxy_count=int(item.get("poll_proxy_count") or 0),
poll_proxy_label=str(item.get("poll_proxy_label") or ""),
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
next_action_type=intent_state.get("next_action_type", ""),
response_keys=str(item.get("response_keys") or ""),
interesting_fields=str(item.get("interesting_fields") or ""),
)
else:
log_warning(
"stripe.redirect_poll.http_error",
attempt=attempt,
completed=completed,
submitted=attempt,
pool_workers=1,
status_code=status_code,
elapsed_ms=duration,
poll_proxy_index=int(item.get("poll_proxy_index") or 0),
poll_proxy_count=int(item.get("poll_proxy_count") or 0),
poll_proxy_label=str(item.get("poll_proxy_label") or ""),
detail=str(item.get("detail") or ""),
)
if candidate_url:
log_info(
"stripe.redirect_poll.done",
attempt=attempt,
completed=completed,
submitted=attempt,
pool_workers=1,
poll_proxy_index=int(item.get("poll_proxy_index") or 0),
poll_proxy_count=int(item.get("poll_proxy_count") or 0),
poll_proxy_label=str(item.get("poll_proxy_label") or ""),
redirect_url=candidate_url,
)
return candidate_url
if terminal_error:
terminal_errors += 1
last_err = terminal_error
log_warning(
"stripe.redirect_poll.intent_terminal",
attempt=attempt,
completed=completed,
submitted=attempt,
pool_workers=1,
poll_proxy_index=int(item.get("poll_proxy_index") or 0),
poll_proxy_count=int(item.get("poll_proxy_count") or 0),
poll_proxy_label=str(item.get("poll_proxy_label") or ""),
detail=terminal_error,
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
)
raise HTTPException(status_code=402, detail=terminal_error)
else:
last_err = str(item.get("detail") or last_err)
if attempt < max_attempts:
time.sleep(1)
if completed >= max_attempts:
detail = f"redirect url resolution stopped after {completed} sequential attempts: {last_err}"
log_warning(
"stripe.redirect_poll.max_attempts",
attempt=completed,
submitted=completed,
pool_workers=1,
terminal_errors=terminal_errors,
detail=detail,
)
if terminal_errors:
raise HTTPException(status_code=402, detail=last_err or detail)
raise HTTPException(status_code=504, detail=detail)
detail = f"redirect url resolution timeout after {completed} sequential attempts: {last_err}"
log_warning(
"stripe.redirect_poll.timeout",
attempt=completed,
submitted=completed,
pool_workers=1,
terminal_errors=terminal_errors,
detail=detail,
)
if terminal_errors:
raise HTTPException(status_code=402, detail=last_err or detail)
raise HTTPException(status_code=504, detail=detail)
executor = ThreadPoolExecutor(max_workers=pool_workers, thread_name_prefix="stripe-poll")
futures: dict[Any, int] = {}
next_attempt = 1
completed = 0
terminal_errors = 0
redirect_url = ""
def submit_until_full() -> None:
nonlocal next_attempt
while len(futures) < pool_workers and next_attempt <= max_attempts and time.time() < deadline:
future = executor.submit(poll_once, next_attempt)
futures[future] = next_attempt
next_attempt += 1
try:
submit_until_full()
while futures and not redirect_url and time.time() < deadline:
done, _ = wait(tuple(futures), return_when=FIRST_COMPLETED, timeout=max(0.2, min(1.0, deadline - time.time())))
if not done:
continue
for future in done:
futures.pop(future, None)
try:
item = future.result()
except Exception as exc:
item = {
"attempt": 0,
"status_code": 0,
"elapsed_ms": 0,
"redirect_url": "",
"terminal_error": "",
"detail": f"stripe redirect poll worker exception: {repr(exc)}",
"intent_state": {},
"response_keys": "",
"interesting_fields": "",
}
completed += 1
attempt = int(item.get("attempt") or 0)
status_code = int(item.get("status_code") or 0)
duration = int(item.get("elapsed_ms") or 0)
intent_state = item.get("intent_state") if isinstance(item.get("intent_state"), dict) else {}
candidate_url = str(item.get("redirect_url") or "")
terminal_error = str(item.get("terminal_error") or "")
if status_code == 200:
log_info(
"stripe.redirect_poll.http",
attempt=attempt,
completed=completed,
submitted=next_attempt - 1,
pool_workers=pool_workers,
status_code=status_code,
elapsed_ms=duration,
has_redirect=bool(candidate_url),
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
next_action_type=intent_state.get("next_action_type", ""),
response_keys=str(item.get("response_keys") or ""),
interesting_fields=str(item.get("interesting_fields") or ""),
)
else:
log_warning(
"stripe.redirect_poll.http_error",
attempt=attempt,
completed=completed,
submitted=next_attempt - 1,
pool_workers=pool_workers,
status_code=status_code,
elapsed_ms=duration,
detail=str(item.get("detail") or ""),
)
if candidate_url:
redirect_url = candidate_url
log_info(
"stripe.redirect_poll.done",
attempt=attempt,
completed=completed,
submitted=next_attempt - 1,
pool_workers=pool_workers,
redirect_url=redirect_url,
)
break
if terminal_error:
terminal_errors += 1
last_err = terminal_error
log_warning(
"stripe.redirect_poll.intent_terminal",
attempt=attempt,
completed=completed,
submitted=next_attempt - 1,
pool_workers=pool_workers,
detail=terminal_error,
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
)
else:
last_err = str(item.get("detail") or last_err)
if not redirect_url:
submit_until_full()
finally:
for future in futures:
future.cancel()
executor.shutdown(wait=not bool(redirect_url), cancel_futures=True)
if redirect_url:
return redirect_url
if completed >= max_attempts:
detail = f"redirect url resolution stopped after {completed} concurrent attempts: {last_err}"
log_warning(
"stripe.redirect_poll.max_attempts",
attempt=completed,
submitted=next_attempt - 1,
pool_workers=pool_workers,
terminal_errors=terminal_errors,
detail=detail,
)
if terminal_errors:
raise HTTPException(status_code=402, detail=last_err or detail)
raise HTTPException(status_code=504, detail=detail)
detail = f"redirect url resolution timeout after {completed} concurrent attempts: {last_err}"
log_warning(
"stripe.redirect_poll.timeout",
attempt=completed,
submitted=next_attempt - 1,
pool_workers=pool_workers,
terminal_errors=terminal_errors,
detail=detail,
)
if terminal_errors:
raise HTTPException(status_code=402, detail=last_err or detail)
raise HTTPException(status_code=504, detail=detail)
def approve_request(
session: Any,
cs_id: str,
processor_entity: str,
attempt: int,
) -> dict[str, Any]:
started = time.perf_counter()
try:
response = session.post(
"https://chatgpt.com/backend-api/payments/checkout/approve",
json={"checkout_session_id": cs_id, "processor_entity": processor_entity},
headers={
"Referer": f"https://chatgpt.com/checkout/{processor_entity}/{cs_id}",
"x-openai-target-path": "/backend-api/payments/checkout/approve",
"x-openai-target-route": "/backend-api/payments/checkout/approve",
},
timeout=DEFAULT_TIMEOUT,
)
except Exception as exc:
return {
"attempt": attempt,
"status_code": 0,
"elapsed_ms": elapsed_ms(started),
"result": "",
"response_keys": "",
"detail": f"chatgpt approve exception: {repr(exc)}",
}
try:
payload = response.json() or {}
except Exception:
payload = {}
result = approve_result_value(payload)
detail = ""
if response.status_code >= 400:
detail = http_error_detail("chatgpt approve failed", response)
elif not is_approved_result(result):
detail = f"chatgpt approve pending result: {result!r} keys={response_keys(payload)}"
return {
"attempt": attempt,
"status_code": response.status_code,
"elapsed_ms": elapsed_ms(started),
"result": result,
"response_keys": response_keys(payload),
"detail": detail,
}
def _legacy_chatgpt_approve_pool_disabled(
chatgpt: Any,
cs_id: str,
checkout: dict[str, Any],
approve_pool: list[str] | None = None,
) -> None:
country = checkout["billing_country"]
processor_entity = processor_entity_for_country(country, checkout.get("processor_entity", ""))
max_attempts = APPROVE_MAX_ATTEMPTS
approve_base_proxy = session_proxy_url(chatgpt)
sticky_requested = approve_pool is not None
approve_pool = ordered_proxy_pool("\n".join(approve_pool or []), approve_base_proxy)
if not approve_pool and approve_base_proxy:
approve_pool = [approve_base_proxy]
sticky_pool_mode = sticky_requested and bool(approve_pool)
if sticky_pool_mode:
pool_workers = min(
max_attempts,
APPROVE_STICKY_MAX_WORKERS,
max(1, len(approve_pool) * APPROVE_STICKY_PER_PROXY_CONCURRENCY),
)
initial_pool_workers = pool_workers
min_pool_workers = min(pool_workers, max(1, len(approve_pool)))
target_inflight = pool_workers
else:
initial_pool_workers = min(max(1, APPROVE_POOL_WORKERS), max_attempts)
pool_workers = min(max(initial_pool_workers, APPROVE_POOL_MAX_WORKERS), max_attempts)
min_pool_workers = min(max(1, APPROVE_POOL_MIN_WORKERS), pool_workers)
target_inflight = max(min_pool_workers, initial_pool_workers)
log_info(
"chatgpt.approve.start",
route="approve_proxy" if getattr(chatgpt, "proxies", {}) else "direct",
cs_id=cs_id,
processor_entity=processor_entity,
collision_mode="same_cs_id",
same_cs_id=True,
pool_workers=initial_pool_workers,
max_pool_workers=pool_workers,
min_pool_workers=min_pool_workers,
adaptive=APPROVE_POOL_ADAPTIVE and not sticky_pool_mode,
max_attempts=max_attempts,
sticky_pool=sticky_pool_mode,
sticky_pool_count=len(approve_pool),
sticky_per_proxy=APPROVE_STICKY_PER_PROXY_CONCURRENCY if sticky_pool_mode else 0,
)
if approve_base_proxy and not sticky_pool_mode:
initial_applied_proxy = proxy_for_attempt(approve_base_proxy, 1, "approve", force=True)
if initial_applied_proxy and initial_applied_proxy != approve_base_proxy:
set_proxy_url(chatgpt, initial_applied_proxy)
log_info(
"chatgpt.approve.dynamic_proxy.sessionized",
cs_id=cs_id,
same_cs_id=True,
session_key=PROXY_SESSION_KEY,
proxy_template=approve_base_proxy,
proxy_applied=initial_applied_proxy,
)
try:
started = time.perf_counter()
ping_response = chatgpt.post(
"https://chatgpt.com/backend-api/sentinel/ping",
json={},
headers={
"Referer": "https://chatgpt.com/",
"x-openai-target-path": "/backend-api/sentinel/ping",
"x-openai-target-route": "/backend-api/sentinel/ping",
},
timeout=DEFAULT_TIMEOUT,
)
log_info(
"chatgpt.sentinel_ping.done",
elapsed_ms=elapsed_ms(started),
status_code=getattr(ping_response, "status_code", ""),
)
except Exception as exc:
log_warning("chatgpt.sentinel_ping.error", error=repr(exc))
initial = approve_request(chatgpt, cs_id, processor_entity, 1)
initial["proxy_url"] = approve_base_proxy
initial["proxy_applied"] = session_proxy_url(chatgpt)
initial_outcome = approve_outcome(initial)
log_info(
"chatgpt.approve.http",
attempt=1,
max_attempts=max_attempts,
status_code=initial["status_code"],
elapsed_ms=initial["elapsed_ms"],
result=initial["result"],
outcome=initial_outcome,
response_keys=initial["response_keys"],
cs_id=cs_id,
same_cs_id=True,
url="https://chatgpt.com/backend-api/payments/checkout/approve",
)
if is_approved_result(initial["result"]):
if sticky_pool_mode and approve_base_proxy:
save_success_proxy("approve", approve_base_proxy)
log_info(
"chatgpt.approve.done",
attempt=1,
total_completed=1,
result=initial["result"],
cs_id=cs_id,
same_cs_id=True,
)
return
if max_attempts <= 1:
raise HTTPException(status_code=502, detail=initial["detail"] or "chatgpt approve failed")
stop_event = Event()
request_id = REQUEST_ID.get()
task_callback = TASK_LOG_CALLBACK.get()
task_cancel_check = TASK_CANCEL_CHECK.get()
active_sticky_proxies: list[str] = list(approve_pool)
sticky_proxy_stats: dict[str, Counter[str]] = {
proxy: Counter() for proxy in active_sticky_proxies
}
def pool_cancel_requested() -> bool:
return bool(task_cancel_check and task_cancel_check())
def pool_worker(attempt: int, selected_proxy: str = "") -> dict[str, Any]:
if stop_event.is_set() or pool_cancel_requested():
return {"attempt": attempt, "skipped": True}
request_token = REQUEST_ID.set(request_id)
callback_token = TASK_LOG_CALLBACK.set(task_callback)
session = None
try:
session = clone_session(chatgpt)
base_proxy = normalize_proxy_url(selected_proxy or approve_base_proxy)
applied_proxy = base_proxy
if base_proxy and not sticky_pool_mode:
applied_proxy = proxy_for_attempt(base_proxy, attempt, "approve")
if applied_proxy:
set_proxy_url(session, applied_proxy)
try:
session.headers.update({"Connection": "close"})
except Exception:
pass
item = approve_request(session, cs_id, processor_entity, attempt)
item["proxy_url"] = base_proxy
item["proxy_applied"] = session_proxy_url(session)
if (
not sticky_pool_mode
and APPROVE_IP_SAMPLE_ENABLED
and APPROVE_IP_SAMPLE_INTERVAL
and attempt % APPROVE_IP_SAMPLE_INTERVAL == 0
):
ip, ip_elapsed_or_error = sample_session_exit_ip(session)
log_info(
"chatgpt.approve.ip_sample",
attempt=attempt,
cs_id=cs_id,
same_cs_id=True,
exit_ip=ip,
elapsed_ms=ip_elapsed_or_error if ip else "",
error="" if ip else ip_elapsed_or_error,
proxy_label=redact_proxy(session_proxy_url(session)),
)
return item
finally:
if session is not None:
try:
session.close()
except Exception:
pass
TASK_LOG_CALLBACK.reset(callback_token)
REQUEST_ID.reset(request_token)
log_info(
"chatgpt.approve.pool.start",
cs_id=cs_id,
same_cs_id=True,
pool_workers=target_inflight,
max_pool_workers=pool_workers,
min_pool_workers=min_pool_workers,
adaptive=APPROVE_POOL_ADAPTIVE and not sticky_pool_mode,
adapt_interval=APPROVE_POOL_ADAPT_INTERVAL,
max_attempts=max_attempts,
initial_result=initial["result"],
initial_outcome=initial_outcome,
per_attempt_proxy=True,
sticky_pool=sticky_pool_mode,
sticky_pool_count=len(approve_pool),
sticky_per_proxy=APPROVE_STICKY_PER_PROXY_CONCURRENCY if sticky_pool_mode else 0,
approve_auto_session=proxy_supports_auto_sid(approve_base_proxy),
session_key=PROXY_SESSION_KEY if proxy_supports_auto_sid(approve_base_proxy) else "",
)
executor = ThreadPoolExecutor(max_workers=pool_workers, thread_name_prefix="approve")
futures: dict[Any, dict[str, Any]] = {}
next_attempt = 2
completed = 1
http_200 = 1 if initial["status_code"] == 200 else 0
min_elapsed = int(initial["elapsed_ms"] or 0)
max_elapsed = int(initial["elapsed_ms"] or 0)
last_detail = str(initial["detail"] or "")
last_result = str(initial["result"] or "")
next_progress = APPROVE_PROGRESS_INTERVAL
next_adapt = APPROVE_POOL_ADAPT_INTERVAL
recent: deque[dict[str, Any]] = deque(maxlen=max(20, APPROVE_POOL_ADAPT_INTERVAL))
recent.append(initial | {"outcome": initial_outcome})
outcomes: Counter[str] = Counter([initial_outcome])
approved: dict[str, Any] | None = None
terminal_failure: dict[str, Any] | None = None
def choose_submit_proxy() -> str:
if not sticky_pool_mode:
return approve_base_proxy
if not active_sticky_proxies:
return ""
inflight = Counter(
str(meta.get("proxy_url") or "")
for meta in futures.values()
if str(meta.get("proxy_url") or "")
)
available = [
proxy
for proxy in active_sticky_proxies
if inflight[proxy] < APPROVE_STICKY_PER_PROXY_CONCURRENCY
]
if not available:
return ""
return min(available, key=lambda proxy: inflight[proxy])
def submit_until_full() -> None:
nonlocal next_attempt
while (
len(futures) < target_inflight
and next_attempt <= max_attempts
and not stop_event.is_set()
and not pool_cancel_requested()
):
selected_proxy = choose_submit_proxy()
if sticky_pool_mode and not selected_proxy:
break
future = executor.submit(pool_worker, next_attempt, selected_proxy)
futures[future] = {"attempt": next_attempt, "proxy_url": selected_proxy}
next_attempt += 1
try:
submit_until_full()
while futures and not approved and not terminal_failure:
if pool_cancel_requested():
stop_event.set()
raise TaskCancelled("task cancelled")
done, _ = wait(tuple(futures), timeout=0.5, return_when=FIRST_COMPLETED)
if not done:
continue
for future in done:
meta = futures.pop(future, {}) or {}
try:
item = future.result()
except Exception as exc:
item = {
"attempt": int(meta.get("attempt") or 0),
"status_code": 0,
"elapsed_ms": 0,
"result": "",
"detail": f"approve worker exception: {repr(exc)}",
"proxy_url": str(meta.get("proxy_url") or ""),
}
if item.get("skipped"):
continue
if not item.get("proxy_url"):
item["proxy_url"] = str(meta.get("proxy_url") or "")
completed += 1
elapsed = int(item.get("elapsed_ms") or 0)
outcome = approve_outcome(item)
item["outcome"] = outcome
recent.append(dict(item))
outcomes[outcome] += 1
min_elapsed = min(min_elapsed, elapsed)
max_elapsed = max(max_elapsed, elapsed)
if int(item.get("status_code") or 0) == 200:
http_200 += 1
last_detail = str(item.get("detail") or last_detail)
last_result = str(item.get("result") or last_result)
item_proxy = normalize_proxy_url(str(item.get("proxy_url") or ""))
if sticky_pool_mode and item_proxy:
stats = sticky_proxy_stats.setdefault(item_proxy, Counter())
stats["total"] += 1
if is_approved_result(item.get("result")):
stats["success"] += 1
else:
stats["failure"] += 1
if (
APPROVE_STICKY_FAIL_DELETE
and stats["total"] >= APPROVE_STICKY_FAIL_WINDOW
and stats["success"] <= 0
and item_proxy in active_sticky_proxies
):
active_sticky_proxies.remove(item_proxy)
log_warning(
"chatgpt.approve.sticky_proxy.removed",
cs_id=cs_id,
same_cs_id=True,
proxy_label=redact_proxy(item_proxy),
attempts=stats["total"],
failures=stats["failure"],
active_count=len(active_sticky_proxies),
)
if is_approved_result(item.get("result")):
approved = item
if item_proxy:
save_success_proxy("approve", item_proxy)
log_info(
"chatgpt.approve.sticky_proxy.success",
cs_id=cs_id,
same_cs_id=True,
proxy_label=redact_proxy(item_proxy),
attempt=item.get("attempt"),
)
stop_event.set()
break
if sticky_pool_mode and not active_sticky_proxies and not approved and not terminal_failure:
terminal_failure = {
"attempt": completed,
"status_code": 0,
"result": "",
"outcome": "proxy_pool_exhausted",
"detail": "approve sticky proxy pool exhausted",
}
stop_event.set()
if (
not sticky_pool_mode
and not approved
and not terminal_failure
and APPROVE_BLOCKED_RESTART_AFTER > 0
and completed >= APPROVE_BLOCKED_RESTART_AFTER
):
blocked_count = int(outcomes.get("blocked", 0))
blocked_percent = int(round((blocked_count / max(1, completed)) * 100))
if blocked_count >= APPROVE_BLOCKED_RESTART_MIN_BLOCKED and blocked_percent >= APPROVE_BLOCKED_RESTART_RATIO:
terminal_failure = {
"attempt": completed,
"status_code": 200,
"result": "blocked",
"outcome": "blocked_restart",
"detail": (
f"approve blocked threshold reached: blocked={blocked_count}/{completed} "
f"({blocked_percent}%), restart checkout with fresh CS/IP"
),
}
stop_event.set()
log_warning(
"chatgpt.approve.blocked_restart",
cs_id=cs_id,
same_cs_id=True,
completed=completed,
blocked=blocked_count,
blocked_percent=blocked_percent,
restart_after=APPROVE_BLOCKED_RESTART_AFTER,
min_blocked=APPROVE_BLOCKED_RESTART_MIN_BLOCKED,
)
if APPROVE_POOL_ADAPTIVE and not sticky_pool_mode and completed >= next_adapt and not approved and not terminal_failure:
window_items = list(recent)
elapsed_window = [int(item.get("elapsed_ms") or 0) for item in window_items]
p95_elapsed = percentile_ms(elapsed_window, 95)
unstable_count = sum(
1
for item in window_items
if str(item.get("outcome") or "") in {"exception", "timeout", "rate_limited", "server_error"}
)
unstable_percent = int(round((unstable_count / max(1, len(window_items))) * 100))
old_target = target_inflight
if unstable_percent >= APPROVE_POOL_ERROR_RATE_HIGH_PERCENT or p95_elapsed >= APPROVE_POOL_LATENCY_HIGH_MS:
target_inflight = max(min_pool_workers, target_inflight - APPROVE_POOL_RAMP_STEP)
elif (
p95_elapsed <= APPROVE_POOL_LATENCY_LOW_MS
and unstable_percent == 0
and target_inflight < pool_workers
):
target_inflight = min(pool_workers, target_inflight + APPROVE_POOL_RAMP_STEP)
if target_inflight != old_target:
log_info(
"chatgpt.approve.pool.adjust",
cs_id=cs_id,
same_cs_id=True,
old_target_inflight=old_target,
target_inflight=target_inflight,
max_pool_workers=pool_workers,
min_pool_workers=min_pool_workers,
p95_elapsed_ms=p95_elapsed,
unstable_percent=unstable_percent,
window_size=len(window_items),
)
while next_adapt <= completed:
next_adapt += APPROVE_POOL_ADAPT_INTERVAL
if completed >= next_progress or approved or terminal_failure or (not futures and next_attempt > max_attempts):
window_elapsed = [int(item.get("elapsed_ms") or 0) for item in recent]
log_info(
"chatgpt.approve.pool.progress",
cs_id=cs_id,
same_cs_id=True,
completed=completed,
submitted=next_attempt - 1,
http_200=http_200,
pool_workers=target_inflight,
max_pool_workers=pool_workers,
max_attempts=max_attempts,
sticky_pool=sticky_pool_mode,
sticky_active_count=len(active_sticky_proxies) if sticky_pool_mode else 0,
min_elapsed_ms=min_elapsed,
max_elapsed_ms=max_elapsed,
p95_elapsed_ms=percentile_ms(window_elapsed, 95),
outcomes=compact_counts(outcomes),
last_result=last_result,
last_outcome=approve_outcome(approved or terminal_failure or item),
approved=bool(approved),
terminal_failure=bool(terminal_failure),
)
while next_progress <= completed:
next_progress += APPROVE_PROGRESS_INTERVAL
if not approved and not terminal_failure:
submit_until_full()
finally:
if approved or terminal_failure:
stop_event.set()
for future in futures:
future.cancel()
executor.shutdown(wait=not ((approved or terminal_failure) and APPROVE_POOL_EARLY_SHUTDOWN), cancel_futures=True)
if approved:
window_elapsed = [int(item.get("elapsed_ms") or 0) for item in recent]
log_info(
"chatgpt.approve.pool.done",
cs_id=cs_id,
same_cs_id=True,
approved_attempt=approved.get("attempt"),
completed=completed,
submitted=next_attempt - 1,
http_200=http_200,
pool_workers=target_inflight,
max_pool_workers=pool_workers,
sticky_pool=sticky_pool_mode,
sticky_active_count=len(active_sticky_proxies) if sticky_pool_mode else 0,
p95_elapsed_ms=percentile_ms(window_elapsed, 95),
outcomes=compact_counts(outcomes),
early_shutdown=APPROVE_POOL_EARLY_SHUTDOWN,
result=approved.get("result"),
)
log_info(
"chatgpt.approve.done",
attempt=approved.get("attempt"),
total_completed=completed,
result=approved.get("result"),
cs_id=cs_id,
same_cs_id=True,
)
return
if terminal_failure:
log_warning(
"chatgpt.approve.pool.terminal",
cs_id=cs_id,
same_cs_id=True,
attempt=terminal_failure.get("attempt"),
status_code=terminal_failure.get("status_code"),
result=terminal_failure.get("result"),
outcome=terminal_failure.get("outcome"),
detail=terminal_failure.get("detail"),
completed=completed,
submitted=next_attempt - 1,
outcomes=compact_counts(outcomes),
)
raise HTTPException(
status_code=502,
detail=str(terminal_failure.get("detail") or f"chatgpt approve terminal outcome: {terminal_failure.get('outcome')}"),
)
raise HTTPException(
status_code=502,
detail=last_detail or f"chatgpt approve exhausted {max_attempts} attempts",
)
def chatgpt_approve(
chatgpt: Any,
cs_id: str,
checkout: dict[str, Any],
approve_pool: list[str] | None = None,
) -> None:
"""Approve once per response state, without racing the same checkout ID."""
country = checkout["billing_country"]
processor_entity = processor_entity_for_country(country, checkout.get("processor_entity", ""))
max_attempts = max(1, min(APPROVE_MAX_ATTEMPTS, 5))
exact_proxy = session_proxy_url(chatgpt)
if approve_pool:
log_info(
"chatgpt.approve.pool.ignored",
reason="same checkout must keep one session/IP",
configured_count=len(approve_pool),
)
log_info(
"chatgpt.approve.start",
route="approve_proxy" if exact_proxy else "direct",
cs_id=cs_id,
processor_entity=processor_entity,
max_attempts=max_attempts,
pool_workers=1,
same_session=True,
approve_proxy=exact_proxy,
)
try:
started = time.perf_counter()
ping_response = chatgpt.post(
"https://chatgpt.com/backend-api/sentinel/ping",
json={},
headers={
"Referer": "https://chatgpt.com/",
"x-openai-target-path": "/backend-api/sentinel/ping",
"x-openai-target-route": "/backend-api/sentinel/ping",
},
timeout=DEFAULT_TIMEOUT,
)
log_info(
"chatgpt.sentinel_ping.done",
elapsed_ms=elapsed_ms(started),
status_code=getattr(ping_response, "status_code", ""),
)
except Exception as exc:
log_warning("chatgpt.sentinel_ping.error", error=repr(exc))
last_item: dict[str, Any] = {}
for attempt in range(1, max_attempts + 1):
cancel_check = TASK_CANCEL_CHECK.get()
if cancel_check and cancel_check():
raise TaskCancelled("task cancelled")
item = approve_request(chatgpt, cs_id, processor_entity, attempt)
last_item = item
outcome = approve_outcome(item)
log_info(
"chatgpt.approve.http",
attempt=attempt,
max_attempts=max_attempts,
status_code=item.get("status_code", 0),
elapsed_ms=item.get("elapsed_ms", 0),
result=item.get("result", ""),
outcome=outcome,
response_keys=item.get("response_keys", ""),
cs_id=cs_id,
same_session=True,
url="https://chatgpt.com/backend-api/payments/checkout/approve",
)
if is_approved_result(item.get("result")):
if exact_proxy:
save_success_proxy("approve", exact_proxy)
log_info(
"chatgpt.approve.done",
attempt=attempt,
total_completed=attempt,
result=item.get("result", ""),
cs_id=cs_id,
same_session=True,
)
return
# These responses describe the checkout itself. Repeating the same
# request hundreds of times cannot change them and only triggers abuse
# controls. A fresh outer checkout attempt is the only useful retry.
if outcome in {
"blocked",
"auth_error",
"missing",
"conflict",
"pending_expired",
"pending_canceled",
"pending_cancelled",
}:
detail = str(item.get("detail") or f"chatgpt approve terminal outcome: {outcome}")
status_code = 409 if outcome == "blocked" else 502
log_warning(
"chatgpt.approve.terminal",
attempt=attempt,
outcome=outcome,
detail=detail,
cs_id=cs_id,
)
raise HTTPException(status_code=status_code, detail=detail)
if attempt < max_attempts:
time.sleep((APPROVE_RETRY_DELAY_MS * attempt) / 1000)
detail = str(last_item.get("detail") or f"chatgpt approve exhausted {max_attempts} bounded attempts")
raise HTTPException(status_code=502, detail=detail)
def redirect_url_after_confirm(
chatgpt: Any,
stripe: Any,
confirm_payload: dict[str, Any],
cs_id: str,
pm_id: str,
stripe_pk: str,
init_payload: dict[str, Any],
ctx: dict[str, Any],
checkout: dict[str, Any],
req: LongLinkRequest,
stripe_hosted_url: str,
) -> str:
redirect_url = extract_redirect_to_url(confirm_payload)
if redirect_url:
log_info("provider.redirect.after_confirm", source="confirm_payload", redirect_url=redirect_url)
return redirect_url
terminal_error = stripe_terminal_intent_error(confirm_payload)
if terminal_error:
intent_state = stripe_intent_state(confirm_payload)
log_warning(
"provider.redirect.intent_terminal",
detail=terminal_error,
intent_status=intent_state.get("status", ""),
intent_error_code=intent_state.get("error_code", ""),
intent_decline_code=intent_state.get("decline_code", ""),
)
raise HTTPException(status_code=402, detail=terminal_error)
submission = confirm_payload.get("submission_attempt") if isinstance(confirm_payload, dict) else None
approval_reason = checkout_approval_reason(confirm_payload)
if approval_reason:
log_info(
"provider.redirect.requires_approval",
reason=approval_reason,
submission_state=submission.get("state") if isinstance(submission, dict) else "",
checkout_status=confirm_payload.get("status", "") if isinstance(confirm_payload, dict) else "",
checkout_state=confirm_payload.get("state", "") if isinstance(confirm_payload, dict) else "",
)
approve_proxy = approve_stage_proxy(req)
apply_approve_proxy(chatgpt, approve_proxy)
runtime_config = get_runtime_config()
approve_pool_mode = normalize_proxy_pool_mode(req.proxy_pool_mode or runtime_config.get("proxyPoolMode"))
approve_pool = approve_proxy_pool_for_request(req) if approve_pool_mode == "sticky" else None
if approve_pool_mode == "sticky":
log_info(
"chatgpt.approve.sticky_pool.enabled",
cs_id=cs_id,
pool_count=len(approve_pool or []),
per_proxy=APPROVE_STICKY_PER_PROXY_CONCURRENCY,
)
chatgpt_approve(chatgpt, cs_id, checkout, approve_pool=approve_pool)
log_info(
"provider.redirect.poll_after_approval",
stripe_route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
approve_route="approve_proxy" if approve_proxy else "direct",
)
return stripe_payment_page_redirect_url(stripe, cs_id, stripe_pk, req, ctx, timeout_seconds=45)
log_info(
"provider.redirect.poll_required",
submission_state=submission.get("state") if isinstance(submission, dict) else "",
response_keys=response_keys(confirm_payload),
)
return stripe_payment_page_redirect_url(stripe, cs_id, stripe_pk, req, ctx, timeout_seconds=30)
def resolve_external_redirect(
direct_session: Any,
redirect_url: str,
preferred_hosts: tuple[str, ...] = (),
proxied_session: Any | None = None,
proxied_hosts: tuple[str, ...] = (),
max_hops: int = 5,
) -> str:
current = str(redirect_url or "").strip()
preferred = tuple(host.lower().lstrip(".") for host in preferred_hosts if host)
proxied = tuple(host.lower().lstrip(".") for host in proxied_hosts if host)
provider_proxy_configured = bool(getattr(direct_session, "proxies", {})) or bool(
getattr(proxied_session, "proxies", {}) if proxied_session is not None else {}
)
log_info(
"provider.redirect_resolve.start",
redirect_url=current,
preferred_hosts=",".join(preferred),
proxied_hosts=",".join(proxied),
provider_proxy_configured=provider_proxy_configured,
max_hops=max_hops,
)
for hop in range(1, max(1, int(max_hops or 1)) + 1):
if not current:
log_warning("provider.redirect_resolve.empty", hop=hop)
return ""
host = (urlsplit(current).hostname or "").lower()
if preferred and host_matches_suffixes(host, preferred):
log_info("provider.redirect_resolve.preferred_host", hop=hop, host=host, final_url=current)
return current
try:
use_proxy = proxied_session is not None and host_matches_suffixes(host, proxied)
session = proxied_session if use_proxy else direct_session
route = "paypal_proxy" if use_proxy else ("provider_proxy" if getattr(session, "proxies", {}) else "direct")
started = time.perf_counter()
response = session.get(current, allow_redirects=False, timeout=DEFAULT_TIMEOUT)
log_info(
"provider.redirect_resolve.hop",
hop=hop,
host=host,
route=route,
status_code=response.status_code,
elapsed_ms=elapsed_ms(started),
url=current,
)
except Exception as exc:
log_warning("provider.redirect_resolve.exception", hop=hop, host=host, url=current, error=repr(exc))
return current
if response.status_code not in (301, 302, 303, 307, 308):
log_info(
"provider.redirect_resolve.final_non_redirect",
hop=hop,
host=host,
status_code=response.status_code,
final_url=current,
)
return current
location = str(response.headers.get("Location") or "").strip()
if not location:
log_warning("provider.redirect_resolve.missing_location", hop=hop, host=host, status_code=response.status_code)
return current
log_info(
"provider.redirect_resolve.location",
hop=hop,
status_code=response.status_code,
location=location,
)
current = urljoin(current, location)
log_info("provider.redirect_resolve.max_hops", final_url=current)
return current
def create_provider_link(
chatgpt: Any,
checkout: dict[str, Any],
init_payload: dict[str, Any],
stripe_hosted_url: str,
req: LongLinkRequest,
provider_proxy: str = "",
) -> dict[str, str]:
link_type = normalize_link_type(req.link_type)
require_payment_method_available(init_payload, link_type)
stripe_pk = str(checkout.get("stripe_publishable_key") or req.stripe_publishable_key).strip()
if not stripe_pk:
raise HTTPException(status_code=422, detail="provider stage missing resolved Stripe publishable key")
provider_proxy = normalize_proxy_url(provider_proxy)
log_info(
"provider.create.start",
link_type=link_type,
cs_id=checkout.get("cs_id", ""),
provider_proxy_configured=bool(provider_proxy),
provider_proxy=provider_proxy,
)
stripe = build_stripe_session(req, proxy_override=provider_proxy)
log_info("stripe.prepare.skip", reason="use_zip_provider_flow")
log_info("stripe.pre_confirm.skip", reason="use_zip_provider_flow")
ctx = stripe_context(checkout["cs_id"], init_payload, req)
log_info(
"provider.context.ready",
cs_id=checkout["cs_id"],
currency=ctx.get("currency", ""),
checkout_amount=ctx.get("checkout_amount", ""),
locale=ctx.get("locale", ""),
init_checksum_present=bool(ctx.get("init_checksum")),
)
billing = billing_for_link_type(link_type, effective_pm_country(req))
log_info("provider.direct_confirm.skip", reason="use_pm_create_confirm_flow")
pm_id = stripe_create_payment_method(
stripe,
checkout["cs_id"],
stripe_pk,
billing,
link_type,
ctx,
init_payload,
stripe_hosted_url,
)
confirm_payload = stripe_confirm(
stripe,
checkout["cs_id"],
pm_id,
stripe_pk,
link_type,
init_payload,
ctx,
checkout,
req,
stripe_hosted_url,
)
stripe_redirect_url = redirect_url_after_confirm(
chatgpt,
stripe,
confirm_payload,
checkout["cs_id"],
pm_id,
stripe_pk,
init_payload,
ctx,
checkout,
req,
stripe_hosted_url,
)
action_type = next_action_type(confirm_payload)
if link_type == "upi" and action_type == "upi_handle_redirect_or_display_qr_code":
# This is already Stripe's hosted QR/instructions page. Following it
# server-side can consume time, hide the QR action, or hit app-only URLs.
provider_url = stripe_redirect_url
else:
provider_url = resolve_external_redirect(
stripe,
stripe_redirect_url,
preferred_hosts=(
PAYPAL_HOST_SUFFIXES
if link_type == "paypal"
else IDEAL_HOST_SUFFIXES
if link_type == "ideal"
else UPI_HOST_SUFFIXES
),
)
log_info(
"provider.create.done",
payment_method_id=pm_id,
stripe_redirect_url=stripe_redirect_url,
provider_redirect_url=provider_url,
long_url=provider_url or stripe_redirect_url,
next_action_type=action_type,
)
return {
"payment_method_id": pm_id,
"stripe_redirect_url": stripe_redirect_url,
"provider_redirect_url": provider_url,
"long_url": provider_url or stripe_redirect_url,
}
app = FastAPI(title="OpenAI Pay Long Link")
app.mount("/public", StaticFiles(directory=PUBLIC_DIR), name="public")
TASK_LOCK = Lock()
TASKS: dict[str, dict[str, Any]] = {}
LATEST_RESULT: dict[str, Any] = {
"task_id": "",
"updated_at": 0.0,
"result": None,
"logs": [],
"probe_results": [],
"result_expires_at": 0,
}
TASK_RETENTION_SECONDS = 60 * 60
ACTIVE_TASK_STATUSES = {"queued", "running", "paused"}
TASK_LOG_LIMIT = 300
IDEAL_LINK_VALID_SECONDS = 30 * 60
AUTH_DB_PATH = Path(os.getenv("OPENAI_PAY_AUTH_DB", str(BASE_DIR / "auth.sqlite3")))
SESSION_COOKIE = "opay_session"
SESSION_TTL_SECONDS = env_int("OPENAI_PAY_SESSION_TTL_SECONDS", 60 * 60 * 24 * 7, minimum=3600, maximum=60 * 60 * 24 * 30)
SESSION_COOKIE_SECURE = env_bool("OPENAI_PAY_COOKIE_SECURE", False)
PASSWORD_ITERATIONS = 260_000
AUTH_LOCK = Lock()
def now_ts() -> int:
return int(time.time())
def auth_db() -> sqlite3.Connection:
conn = sqlite3.connect(AUTH_DB_PATH, timeout=30)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA busy_timeout = 30000")
return conn
def normalize_username(username: str) -> str:
return re.sub(r"\s+", "", str(username or "").strip().lower())
def success_proxy_for_stage(stage: str, base_proxy: Any) -> str:
base = normalize_proxy_url(str(base_proxy or ""))
if not base:
return ""
try:
with auth_db() as conn:
row = conn.execute(
"SELECT proxy_url FROM proxy_success WHERE stage = ?",
(str(stage or "").strip().lower(),),
).fetchone()
except Exception:
return ""
saved = str(row["proxy_url"] or "") if row else ""
return saved if proxies_compatible(saved, base) else ""
def success_proxy_for_pool(stage: str, candidates: Any) -> str:
proxies = proxy_pool(candidates)
if not proxies:
return ""
try:
with auth_db() as conn:
row = conn.execute(
"SELECT proxy_url FROM proxy_success WHERE stage = ?",
(str(stage or "").strip().lower(),),
).fetchone()
except Exception:
return ""
saved = str(row["proxy_url"] or "") if row else ""
if not saved:
return ""
return saved if any(proxies_compatible(saved, proxy) for proxy in proxies) else ""
def approve_proxy_pool_for_request(req: LongLinkRequest) -> list[str]:
try:
config = get_runtime_config()
except Exception:
config = default_runtime_config()
run_mode = normalize_run_mode(config.get("runMode", ""))
link_type = normalize_link_type(req.link_type)
if link_type in {"ideal", "upi"} or run_mode in {RUN_MODE_SPLIT, RUN_MODE_US_CHECKOUT_JP_PAYPAL}:
pool_value = runtime_proxy_pool(config, "jp") or req.approve_proxy
else:
pool_value = runtime_proxy_pool(config, "us") or req.approve_proxy
proxies = proxy_pool(pool_value)
explicit = first_proxy_from_pool(req.approve_proxy)
if explicit and explicit not in proxies:
proxies.insert(0, explicit)
saved = success_proxy_for_pool("approve", "\n".join(proxies))
if saved:
proxies = [saved] + [proxy for proxy in proxies if not proxies_compatible(saved, proxy)]
return proxies
def save_success_proxy(stage: str, proxy_url: Any, username: str = "") -> None:
proxy = normalize_proxy_url(str(proxy_url or ""))
stage = str(stage or "").strip().lower()
if not stage or not proxy:
return
with AUTH_LOCK, auth_db() as conn:
conn.execute(
"""
INSERT INTO proxy_success (stage, proxy_url, username, updated_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(stage) DO UPDATE SET
proxy_url = excluded.proxy_url,
username = excluded.username,
updated_at = excluded.updated_at
""",
(stage, proxy, normalize_username(username), now_ts()),
)
def update_success_proxy_ip(stage: str, info: dict[str, Any]) -> None:
stage = str(stage or "").strip().lower()
if not stage or not info.get("ok"):
return
with AUTH_LOCK, auth_db() as conn:
conn.execute(
"""
UPDATE proxy_success
SET ip = ?, country = ?, city = ?, updated_at = ?
WHERE stage = ?
""",
(
str(info.get("ip") or ""),
str(info.get("country") or ""),
str(info.get("city") or ""),
now_ts(),
stage,
),
)
def refresh_success_proxy_ip(stage: str, proxy_url: str) -> None:
try:
info = proxy_check_one(stage.upper(), proxy_url)
update_success_proxy_ip(stage, info)
log_info(
"proxy_success.ip_refreshed",
stage=stage,
proxy=proxy_url,
ip=info.get("ip", ""),
country=info.get("country", ""),
ok=bool(info.get("ok")),
)
except Exception as exc:
log_warning("proxy_success.ip_refresh_failed", stage=stage, proxy=proxy_url, error=repr(exc))
def record_proxy_success(username: str, req: LongLinkRequest) -> None:
stages = {
"checkout": checkout_stage_proxy(req),
"provider": provider_stage_proxy(req),
}
for stage, proxy in stages.items():
proxy = normalize_proxy_url(proxy)
if not proxy:
continue
save_success_proxy(stage, proxy, username)
Thread(target=refresh_success_proxy_ip, args=(stage, proxy), daemon=True).start()
log_info(
"proxy_success.record",
username=normalize_username(username),
checkout_proxy=stages.get("checkout", ""),
provider_proxy=stages.get("provider", ""),
)
def password_hash(password: str, salt: bytes | None = None) -> str:
salt = salt or secrets.token_bytes(16)
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, PASSWORD_ITERATIONS)
return f"pbkdf2_sha256${PASSWORD_ITERATIONS}${base64.b64encode(salt).decode()}${base64.b64encode(digest).decode()}"
def verify_password(password: str, stored: str) -> bool:
try:
scheme, iterations_raw, salt_raw, digest_raw = stored.split("$", 3)
if scheme != "pbkdf2_sha256":
return False
salt = base64.b64decode(salt_raw)
expected = base64.b64decode(digest_raw)
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, int(iterations_raw))
return secrets.compare_digest(digest, expected)
except Exception:
return False
def init_auth_db() -> None:
with AUTH_LOCK:
AUTH_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
with auth_db() as conn:
conn.executescript(
"""
PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
created_at INTEGER NOT NULL,
disabled_at INTEGER NOT NULL DEFAULT 0,
success_count INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS invites (
code TEXT PRIMARY KEY,
created_by TEXT NOT NULL,
created_at INTEGER NOT NULL,
used_by TEXT NOT NULL DEFAULT '',
used_at INTEGER NOT NULL DEFAULT 0,
revoked_at INTEGER NOT NULL DEFAULT 0,
max_uses INTEGER NOT NULL DEFAULT 10,
use_count INTEGER NOT NULL DEFAULT 0,
last_used_at INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
username TEXT NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS runtime_config (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_by TEXT NOT NULL DEFAULT '',
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS proxy_success (
stage TEXT PRIMARY KEY,
proxy_url TEXT NOT NULL DEFAULT '',
ip TEXT NOT NULL DEFAULT '',
country TEXT NOT NULL DEFAULT '',
city TEXT NOT NULL DEFAULT '',
username TEXT NOT NULL DEFAULT '',
updated_at INTEGER NOT NULL
);
"""
)
columns = {row["name"] for row in conn.execute("PRAGMA table_info(users)").fetchall()}
if "disabled_at" not in columns:
conn.execute("ALTER TABLE users ADD COLUMN disabled_at INTEGER NOT NULL DEFAULT 0")
if "success_count" not in columns:
conn.execute("ALTER TABLE users ADD COLUMN success_count INTEGER NOT NULL DEFAULT 0")
invite_columns = {row["name"] for row in conn.execute("PRAGMA table_info(invites)").fetchall()}
if "max_uses" not in invite_columns:
conn.execute("ALTER TABLE invites ADD COLUMN max_uses INTEGER NOT NULL DEFAULT 10")
if "use_count" not in invite_columns:
conn.execute("ALTER TABLE invites ADD COLUMN use_count INTEGER NOT NULL DEFAULT 0")
if "last_used_at" not in invite_columns:
conn.execute("ALTER TABLE invites ADD COLUMN last_used_at INTEGER NOT NULL DEFAULT 0")
admin_password = APP_PASSWORD or os.getenv("OPENAI_PAY_ADMIN_PASSWORD", "")
if admin_password:
existing = conn.execute("SELECT id FROM users WHERE username = ?", (normalize_username(APP_USERNAME),)).fetchone()
if not existing:
conn.execute(
"INSERT INTO users (username, password_hash, role, created_at) VALUES (?, ?, 'admin', ?)",
(normalize_username(APP_USERNAME), password_hash(admin_password), now_ts()),
)
def default_runtime_config() -> dict[str, str]:
return {
"runMode": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"proxyPoolMode": "dynamic",
"billingCountry": "US",
"pmCountry": "JP",
"paymentLocale": "en",
"jpProxy": "",
"usProxy": "",
"stickyJpProxy": "",
"stickyUsProxy": "",
"idealPromoProxy": "",
"stickyIdealPromoProxy": "",
}
def normalize_run_mode(value: str) -> str:
mode = str(value or "").strip()
aliases = {
"split": RUN_MODE_SPLIT,
"jp_us": RUN_MODE_SPLIT,
"jp-us": RUN_MODE_SPLIT,
"checkout-only-jp": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"checkout_jp_rest_provider": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"checkout-jp-rest-provider": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"uiai": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"uiai_style": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"uiai-style": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"us-au": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"us-jp": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"us_jp": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"us-checkout-jp": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"us_checkout_jp_paypal": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
"us-checkout-jp-paypal": RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
}
return aliases.get(mode, mode if mode in SUPPORTED_RUN_MODES else RUN_MODE_CHECKOUT_JP_REST_PROVIDER)
def normalize_proxy_pool_mode(value: Any) -> str:
mode = str(value or "").strip().lower()
return "sticky" if mode in {"sticky", "stick", "sticky_pool", "黏性", "粘性"} else "dynamic"
def normalize_runtime_config(payload: RuntimeConfigRequest | dict[str, Any] | None = None) -> dict[str, str]:
base = default_runtime_config()
if payload is None:
raw: dict[str, Any] = {}
elif isinstance(payload, RuntimeConfigRequest):
raw = payload.model_dump(by_alias=True)
else:
raw = dict(payload)
run_mode = normalize_run_mode(raw.get("runMode") or raw.get("run_mode") or base["runMode"])
proxy_pool_mode = normalize_proxy_pool_mode(raw.get("proxyPoolMode") or raw.get("proxy_pool_mode") or base["proxyPoolMode"])
billing_country = supported_country(str(raw.get("billingCountry") or raw.get("billing_country") or base["billingCountry"]).strip().upper(), "US")
pm_country = supported_country(
str(
raw.get("pmCountry")
or raw.get("pm_country")
or raw.get("billingCountry")
or raw.get("billing_country")
or base["pmCountry"]
or base["billingCountry"]
).strip().upper(),
"AU",
)
locale = str(raw.get("paymentLocale") or raw.get("payment_locale") or base["paymentLocale"]).strip() or base["paymentLocale"]
if locale not in LOCALE_MAP:
locale = "en"
us_proxy = normalize_proxy_pool_value(raw.get("usProxy") or raw.get("providerProxy") or raw.get("us_proxy") or "")
jp_proxy = normalize_proxy_pool_value(raw.get("jpProxy") or raw.get("checkoutProxy") or raw.get("jp_proxy") or "")
sticky_us_proxy = normalize_proxy_pool_value(raw.get("stickyUsProxy") or raw.get("stickyProviderProxy") or raw.get("sticky_us_proxy") or "")
sticky_jp_proxy = normalize_proxy_pool_value(raw.get("stickyJpProxy") or raw.get("stickyCheckoutProxy") or raw.get("sticky_jp_proxy") or "")
ideal_promo_proxy = normalize_proxy_pool_value(raw.get("idealPromoProxy") or raw.get("ideal_promo_proxy") or "")
sticky_ideal_promo_proxy = normalize_proxy_pool_value(raw.get("stickyIdealPromoProxy") or raw.get("sticky_ideal_promo_proxy") or "")
if not jp_proxy and not us_proxy:
jp_proxy = normalize_proxy_pool_value(raw.get("approveProxy") or "")
return {
"runMode": run_mode,
"proxyPoolMode": proxy_pool_mode,
"billingCountry": billing_country,
"pmCountry": pm_country,
"paymentLocale": locale,
"jpProxy": jp_proxy,
"usProxy": us_proxy,
"stickyJpProxy": sticky_jp_proxy,
"stickyUsProxy": sticky_us_proxy,
"idealPromoProxy": ideal_promo_proxy,
"stickyIdealPromoProxy": sticky_ideal_promo_proxy,
}
def runtime_proxy_pool(config: dict[str, str], lane: str) -> str:
mode = normalize_proxy_pool_mode(config.get("proxyPoolMode", "dynamic"))
lane = str(lane or "").strip().lower()
if lane in {"ideal-promo", "ideal_promo", "promo", "promotion"}:
return config.get("stickyIdealPromoProxy" if mode == "sticky" else "idealPromoProxy", "")
if mode == "sticky":
return config.get("stickyJpProxy" if lane == "jp" else "stickyUsProxy", "")
return config.get("jpProxy" if lane == "jp" else "usProxy", "")
def get_runtime_config() -> dict[str, str]:
config = default_runtime_config()
with auth_db() as conn:
rows = conn.execute("SELECT key, value FROM runtime_config").fetchall()
for row in rows:
key = str(row["key"])
if key in config:
config[key] = str(row["value"] or "")
return normalize_runtime_config(config)
def save_runtime_config(config: dict[str, str], username: str) -> dict[str, str]:
normalized = normalize_runtime_config(config)
with AUTH_LOCK, auth_db() as conn:
for key, value in normalized.items():
conn.execute(
"""
INSERT INTO runtime_config (key, value, updated_by, updated_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(key) DO UPDATE SET
value = excluded.value,
updated_by = excluded.updated_by,
updated_at = excluded.updated_at
""",
(key, value, username, now_ts()),
)
return normalized
def apply_runtime_defaults(req: LongLinkRequest) -> LongLinkRequest:
config = get_runtime_config()
data = req.model_dump(by_alias=True)
supplied = set(getattr(req, "model_fields_set", set()) or set())
data["payment_locale"] = config["paymentLocale"]
data["proxyPoolMode"] = config["proxyPoolMode"]
run_mode = normalize_run_mode(config["runMode"])
requested_checkout = first_proxy_from_pool(str(data.get("checkoutProxy") or data.get("proxy") or ""))
requested_approve = first_proxy_from_pool(str(data.get("approveProxy") or ""))
requested_provider = first_proxy_from_pool(str(data.get("providerProxy") or ""))
requested_promotion = first_proxy_from_pool(str(data.get("promotionProxy") or ""))
checkout_supplied = ("checkout_proxy" in supplied or "proxy" in supplied) and bool(requested_checkout)
approve_supplied = "approve_proxy" in supplied and bool(requested_approve)
provider_supplied = "provider_proxy" in supplied and bool(requested_provider)
promotion_supplied = "promotion_proxy" in supplied and bool(requested_promotion)
active_jp_pool = runtime_proxy_pool(config, "jp")
active_us_pool = runtime_proxy_pool(config, "us")
active_promotion_pool = runtime_proxy_pool(config, "ideal-promo")
jp_proxy = requested_checkout if checkout_supplied else first_proxy_from_pool(active_jp_pool)
provider_proxy = requested_provider if provider_supplied else select_proxy_from_pool(active_us_pool)
approve_proxy = requested_approve if approve_supplied else provider_proxy
promotion_proxy = requested_promotion if promotion_supplied else first_proxy_from_pool(active_promotion_pool)
data["promotionProxy"] = promotion_proxy
data["billing_country"] = supported_country(config["billingCountry"], "US")
data["pmCountry"] = supported_country(config["pmCountry"], "AU")
if run_mode == RUN_MODE_US_CHECKOUT_JP_PAYPAL:
data["checkout_ui_mode"] = "custom"
data["checkoutProxy"] = jp_proxy
data["approveProxy"] = jp_proxy
data["providerProxy"] = jp_proxy
return LongLinkRequest(**data)
if run_mode == RUN_MODE_UIAI_STYLE:
data["checkout_ui_mode"] = "custom"
data["checkoutProxy"] = jp_proxy
data["approveProxy"] = approve_proxy
data["providerProxy"] = provider_proxy
return LongLinkRequest(**data)
if run_mode == RUN_MODE_CHECKOUT_JP_REST_PROVIDER:
data["checkoutProxy"] = jp_proxy
data["approveProxy"] = approve_proxy
data["providerProxy"] = provider_proxy
return LongLinkRequest(**data)
if run_mode == RUN_MODE_SPLIT:
data["checkoutProxy"] = jp_proxy
data["approveProxy"] = jp_proxy
data["providerProxy"] = jp_proxy if jp_proxy and not provider_proxy else provider_proxy
return LongLinkRequest(**data)
if "checkout_proxy" not in supplied and "proxy" not in supplied:
data["checkoutProxy"] = jp_proxy
if "approve_proxy" not in supplied:
data["approveProxy"] = approve_proxy or jp_proxy
if "provider_proxy" not in supplied:
us_proxy = select_proxy_from_pool(active_us_pool)
data["providerProxy"] = jp_proxy if jp_proxy and not us_proxy else us_proxy
return LongLinkRequest(**data)
def user_from_session_token(token: str) -> dict[str, Any] | None:
if not token:
return None
with auth_db() as conn:
row = conn.execute(
"""
SELECT users.username, users.role
FROM sessions
JOIN users ON users.username = sessions.username
WHERE sessions.token = ? AND sessions.expires_at > ? AND COALESCE(users.disabled_at, 0) = 0
""",
(token, now_ts()),
).fetchone()
return dict(row) if row else None
def current_user(request: Request) -> dict[str, Any] | None:
return user_from_session_token(request.cookies.get(SESSION_COOKIE, ""))
def api_key_authenticated(request: Request) -> bool:
if not APP_API_KEY:
return False
supplied = (request.headers.get("X-API-Key") or "").strip()
auth_header = (request.headers.get("Authorization") or "").strip()
if not supplied and auth_header.lower().startswith("bearer "):
supplied = auth_header[7:].strip()
return bool(supplied) and secrets.compare_digest(supplied, APP_API_KEY)
def request_authenticated(request: Request) -> bool:
return bool(current_user(request) or api_key_authenticated(request))
def require_user(request: Request) -> dict[str, Any]:
user = current_user(request)
if not user and api_key_authenticated(request):
return {"username": "api", "role": "api"}
if not user:
raise HTTPException(status_code=401, detail="not authenticated")
return user
def require_admin(request: Request) -> dict[str, Any]:
user = require_user(request)
if user.get("role") != "admin":
raise HTTPException(status_code=403, detail="admin required")
return user
def normalize_cdk(code: Any) -> str:
return re.sub(r"\s+", "", str(code or "").strip()).upper()
def cdk_owner(code: str) -> str:
fingerprint = hashlib.sha256(normalize_cdk(code).encode("utf-8")).hexdigest()[:12]
return f"cdk_{fingerprint}"
def cdk_usage_from_row(row: sqlite3.Row) -> tuple[int, int, int]:
max_uses = max(1, int(row["max_uses"] or 10))
use_count = max(0, int(row["use_count"] or 0))
return max_uses, use_count, max(0, max_uses - use_count)
def cdk_status(code: Any) -> CdkCheckResponse:
cdk = normalize_cdk(code)
if not cdk:
raise HTTPException(status_code=403, detail="CDK required")
with auth_db() as conn:
row = conn.execute("SELECT * FROM invites WHERE code = ?", (cdk,)).fetchone()
if not row:
raise HTTPException(status_code=403, detail="invalid CDK")
max_uses, use_count, remaining = cdk_usage_from_row(row)
if int(row["revoked_at"] or 0):
raise HTTPException(status_code=403, detail="CDK revoked")
if remaining <= 0:
raise HTTPException(status_code=403, detail="CDK exhausted")
return CdkCheckResponse(ok=True, code=cdk, maxUses=max_uses, useCount=use_count, remainingUses=remaining)
def require_cdk_user(code: Any, consume: bool = False) -> dict[str, Any]:
cdk = normalize_cdk(code)
status = cdk_status(cdk)
max_uses = status.max_uses
use_count = status.use_count
if consume:
with AUTH_LOCK, auth_db() as conn:
row = conn.execute("SELECT * FROM invites WHERE code = ?", (cdk,)).fetchone()
if not row:
raise HTTPException(status_code=403, detail="invalid CDK")
max_uses, use_count, remaining = cdk_usage_from_row(row)
if int(row["revoked_at"] or 0):
raise HTTPException(status_code=403, detail="CDK revoked")
if remaining <= 0:
raise HTTPException(status_code=403, detail="CDK exhausted")
updated = conn.execute(
"""
UPDATE invites
SET use_count = use_count + 1,
last_used_at = ?
WHERE code = ?
AND revoked_at = 0
AND use_count < max_uses
""",
(now_ts(), cdk),
).rowcount
if not updated:
raise HTTPException(status_code=403, detail="CDK exhausted")
use_count += 1
log_info("cdk.verify", code=mask_identifier(cdk, keep_start=4, keep_end=4), consume=consume, remaining=max_uses - use_count)
return {"username": cdk_owner(cdk), "role": "cdk", "cdk": cdk}
def link_request_user(req: LongLinkRequest, request: Request, consume_cdk: bool = False) -> dict[str, Any]:
user = current_user(request)
if user:
return user
if api_key_authenticated(request):
return {"username": "api", "role": "api"}
return require_cdk_user(req.cdk, consume=consume_cdk)
def create_session(username: str) -> str:
token = secrets.token_urlsafe(32)
with AUTH_LOCK, auth_db() as conn:
conn.execute(
"INSERT INTO sessions (token, username, created_at, expires_at) VALUES (?, ?, ?, ?)",
(token, username, now_ts(), now_ts() + SESSION_TTL_SECONDS),
)
return token
def auth_response(user: dict[str, Any], token: str | None = None) -> JSONResponse:
response = JSONResponse({"ok": True, "authenticated": True, "username": user["username"], "role": user["role"]})
if token:
response.set_cookie(
SESSION_COOKIE,
token,
max_age=SESSION_TTL_SECONDS,
httponly=True,
samesite="lax",
secure=SESSION_COOKIE_SECURE,
)
return response
@app.on_event("startup")
def startup_auth() -> None:
init_auth_db()
@app.middleware("http")
async def require_session_for_private_api(request: Request, call_next: Any):
path = request.url.path
protected = path.startswith("/api/admin/")
if protected and not request_authenticated(request):
return JSONResponse({"detail": "not authenticated"}, status_code=401)
return await call_next(request)
def long_link_response_to_dict(response: LongLinkResponse) -> dict[str, Any]:
return response.model_dump()
def is_ideal_provider_url(value: Any) -> bool:
try:
parsed = urlsplit(str(value or "").strip())
except Exception:
return False
host = str(parsed.hostname or "").lower().rstrip(".")
return parsed.scheme == "https" and (host == "ideal.nl" or host.endswith(".ideal.nl"))
def extract_ideal_qr_url(provider_url: Any) -> str:
try:
outer = urlsplit(str(provider_url or "").strip())
except Exception:
return ""
outer_host = str(outer.hostname or "").lower().rstrip(".")
if outer.scheme != "https" or not (outer_host == "ideal.nl" or outer_host.endswith(".ideal.nl")):
return ""
marker = "/transactions/"
marker_at = outer.path.find(marker)
if marker_at < 0:
return ""
encoded = outer.path[marker_at + len(marker):]
if not encoded:
return ""
candidate = unquote(encoded)
try:
inner = urlsplit(candidate)
except Exception:
return ""
inner_host = str(inner.hostname or "").lower().rstrip(".")
if inner.scheme.lower() != "https" or inner_host != "tx.ideal.nl":
return ""
if not inner.query and outer.query:
candidate = f"{candidate}?{outer.query}"
return candidate
def cdk_ideal_response_succeeded(response: LongLinkResponse | None) -> bool:
return bool(
response
and not response.fallback
and response.provider_redirect_url
and is_ideal_provider_url(response.provider_redirect_url)
and (response.ideal_qr_url or extract_ideal_qr_url(response.provider_redirect_url))
)
def long_link_response_from_dict(data: dict[str, Any] | None) -> LongLinkResponse | None:
return LongLinkResponse(**data) if data else None
def access_token_fingerprint(req: LongLinkRequest) -> str:
token = normalize_access_token(req.access_token)
return hashlib.sha256(token.encode("utf-8")).hexdigest() if token else ""
def task_request_metadata(req: LongLinkRequest) -> dict[str, Any]:
"""Keep operational metadata only; never retain tokens, CDKs or proxy credentials."""
return {
"link_type": normalize_link_type(req.link_type),
"billing_country": effective_country(req),
"pm_country": effective_pm_country(req),
"checkout_ui_mode": str(req.checkout_ui_mode or ""),
"payment_locale": str(req.payment_locale or ""),
}
def cleanup_tasks_locked() -> None:
now = time.time()
stale = [
task_id
for task_id, task in TASKS.items()
if task.get("status") in {"done", "failed", "cancelled"}
and now - float(task.get("updated_at") or 0) > TASK_RETENTION_SECONDS
]
for task_id in stale:
TASKS.pop(task_id, None)
def active_task_for_token_locked(token_fingerprint: str) -> str:
if not token_fingerprint:
return ""
cleanup_tasks_locked()
for task_id, task in TASKS.items():
if str(task.get("token_fingerprint") or "") != token_fingerprint:
continue
if str(task.get("status") or "") in ACTIVE_TASK_STATUSES and not bool(task.get("cancel_requested")):
return task_id
return ""
def mark_task_cancelled_locked(task: dict[str, Any], message: str = "任务已停止,不会继续跑") -> None:
task["cancel_requested"] = True
task["paused"] = False
task["status"] = "cancelled"
task["progress"] = 0
task["stage"] = "已重置"
task["message"] = message
task["error"] = ""
task["updated_at"] = time.time()
def cancel_token_tasks_locked(token_fingerprint: str, message: str = "同一 token 已停止旧任务") -> list[str]:
cancelled: list[str] = []
if not token_fingerprint:
return cancelled
for task_id, task in TASKS.items():
if str(task.get("token_fingerprint") or "") != token_fingerprint:
continue
if str(task.get("status") or "") in ACTIVE_TASK_STATUSES:
mark_task_cancelled_locked(task, message)
cancelled.append(task_id)
return cancelled
def task_cancel_requested(task_id: str) -> bool:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
return True
return bool(task.get("cancel_requested")) or str(task.get("status") or "") == "cancelled"
def set_task_state(task_id: str, **updates: Any) -> None:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
return
if bool(task.get("cancel_requested")) or str(task.get("status") or "") == "cancelled":
allowed = {"elapsed_ms"}
updates = {key: value for key, value in updates.items() if key in allowed}
if not updates:
return
task.update(updates)
task["updated_at"] = time.time()
cleanup_tasks_locked()
def is_task_owner(task: dict[str, Any], user: dict[str, Any]) -> bool:
if not user:
return False
if user.get("role") == "admin":
return True
return str(task.get("owner") or "") == str(user.get("username") or "")
def task_user_from_request(request: Request) -> dict[str, Any] | None:
user = current_user(request)
if user:
return user
if api_key_authenticated(request):
return {"username": "api", "role": "api"}
return None
def require_task_access(task: dict[str, Any], request: Request) -> dict[str, Any] | None:
user = task_user_from_request(request)
if str(task.get("owner_role") or "") == "cdk":
if user and user.get("role") == "admin":
return user
supplied_cdk = normalize_cdk(request.headers.get("X-CDK") or "")
if supplied_cdk and cdk_owner(supplied_cdk) == str(task.get("owner") or ""):
return {"username": cdk_owner(supplied_cdk), "role": "cdk"}
raise HTTPException(status_code=403, detail="task CDK does not match")
if user and is_task_owner(task, user):
return user
if not user:
raise HTTPException(status_code=401, detail="not authenticated")
raise HTTPException(status_code=403, detail="not task owner")
def is_admin_request(request: Request) -> bool:
user = current_user(request)
return bool(user and user.get("role") == "admin")
def public_task_logs(logs: Any) -> list[dict[str, Any]]:
public_logs: list[dict[str, Any]] = []
for entry in list(logs or [])[-TASK_LOG_LIMIT:]:
if not isinstance(entry, dict):
continue
fields = entry.get("fields") if isinstance(entry.get("fields"), dict) else {}
safe_fields: dict[str, Any] = {}
for key, value in fields.items():
lowered = str(key).lower()
if "proxy" in lowered:
continue
if "token" in lowered or "authorization" in lowered or "secret" in lowered or "password" in lowered:
continue
safe_fields[key] = value
public_logs.append(
{
"time": entry.get("time", ""),
"level": entry.get("level", "info"),
"event": entry.get("event", ""),
"fields": safe_fields,
}
)
return public_logs
def wait_for_task_resume(task_id: str) -> str:
while True:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
return "missing"
status = str(task.get("status") or "")
if status in {"failed", "done", "cancelled"} or bool(task.get("cancel_requested")):
return status
if not bool(task.get("paused")):
return status
time.sleep(0.45)
def set_task_probe_results(task_id: str, results: list[dict[str, Any]]) -> None:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
return
task["probe_results"] = [dict(item) for item in results]
task["updated_at"] = time.time()
def append_task_log(task_id: str, entry: dict[str, Any]) -> None:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
return
logs = task.setdefault("logs", [])
entry = dict(entry)
entry["seq"] = int(task.get("log_seq") or 0) + 1
task["log_seq"] = entry["seq"]
logs.append(entry)
if len(logs) > TASK_LOG_LIMIT:
del logs[: len(logs) - TASK_LOG_LIMIT]
task["updated_at"] = time.time()
def task_log_callback(task_id: str):
def collect(entry: dict[str, Any]) -> None:
append_task_log(task_id, entry)
return collect
def set_latest_result(task_id: str, response: LongLinkResponse, success_attempt: int = 0) -> None:
with TASK_LOCK:
task = TASKS.get(task_id) or {}
response = response.model_copy(update={"success_attempt": success_attempt})
result_expires_at = result_expiry_timestamp(response)
LATEST_RESULT.update(
{
"task_id": task_id,
"updated_at": time.time(),
"result": long_link_response_to_dict(response),
"logs": list(task.get("logs") or []),
"probe_results": list(task.get("probe_results") or []),
"result_expires_at": result_expires_at,
}
)
def task_progress_callback(task_id: str):
def update(progress: int, stage: str, message: str) -> None:
if task_cancel_requested(task_id):
raise TaskCancelled("task cancelled")
resume_status = wait_for_task_resume(task_id)
if resume_status in {"cancelled", "missing"}:
raise TaskCancelled("task cancelled")
set_task_state(
task_id,
progress=max(0, min(99, int(progress))),
stage=stage,
message=message,
)
return update
def result_expiry_timestamp(response: LongLinkResponse | None) -> int:
if not response or normalize_link_type(response.link_type) != "ideal" or not str(response.long_url or "").strip():
return 0
return now_ts() + IDEAL_LINK_VALID_SECONDS
@app.get("/")
def index() -> FileResponse:
return FileResponse(PUBLIC_DIR / "index.html")
@app.get("/api/health")
def health() -> dict[str, bool]:
return {"ok": True}
@app.post("/api/cdk/check", response_model=CdkCheckResponse)
def check_cdk(payload: CdkCheckRequest) -> CdkCheckResponse:
return cdk_status(payload.cdk)
@app.get("/api/auth/me", response_model=UserResponse)
def auth_me(request: Request) -> UserResponse:
user = current_user(request)
if not user:
return UserResponse(ok=True, authenticated=False)
return UserResponse(ok=True, authenticated=True, username=user["username"], role=user["role"])
@app.post("/api/auth/login")
def auth_login(payload: AuthRequest) -> JSONResponse:
start = time.perf_counter()
username = normalize_username(payload.username)
log_info("auth.login.attempt", username=username, username_present=bool(username))
if not username or not payload.password:
raise HTTPException(status_code=400, detail="username and password required")
with auth_db() as conn:
row = conn.execute("SELECT username, password_hash, role, disabled_at FROM users WHERE username = ?", (username,)).fetchone()
if not row or not verify_password(payload.password, row["password_hash"]):
log_info("auth.login.failed", username=username, user_found=bool(row))
raise HTTPException(status_code=401, detail="invalid username or password")
if int(row["disabled_at"] or 0):
log_info("auth.login.disabled", username=username)
raise HTTPException(status_code=403, detail="user disabled")
token = create_session(row["username"])
log_info("auth.login.success", username=row["username"], role=row["role"], elapsed_ms=elapsed_ms(start))
return auth_response({"username": row["username"], "role": row["role"]}, token)
@app.post("/api/auth/logout")
def auth_logout(request: Request) -> JSONResponse:
token = request.cookies.get(SESSION_COOKIE, "")
if token:
with AUTH_LOCK, auth_db() as conn:
conn.execute("DELETE FROM sessions WHERE token = ?", (token,))
response = JSONResponse({"ok": True})
response.delete_cookie(SESSION_COOKIE)
return response
@app.post("/api/auth/register")
def auth_register(payload: RegisterRequest) -> JSONResponse:
raise HTTPException(status_code=410, detail="registration disabled; use CDK on the client")
def invite_from_row(row: sqlite3.Row) -> InviteResponse:
max_uses = max(1, int(row["max_uses"] or 10))
use_count = max(0, int(row["use_count"] or 0))
return InviteResponse(
code=row["code"],
created_by=row["created_by"],
created_at=int(row["created_at"] or 0),
used_by=row["used_by"] or "",
used_at=int(row["used_at"] or 0),
revoked_at=int(row["revoked_at"] or 0),
max_uses=max_uses,
use_count=use_count,
remaining_uses=max(0, max_uses - use_count),
last_used_at=int(row["last_used_at"] or 0),
)
def invite_create_cache_path(username: str, request_id: str) -> Path:
clean_user = re.sub(r"[^a-z0-9_.-]+", "_", normalize_username(username)) or "admin"
clean_request = re.sub(r"[^A-Za-z0-9_.-]+", "_", str(request_id or "").strip())[:80]
return BASE_DIR / ".invite-create-cache" / f"{clean_user}-{clean_request}.json"
def member_from_row(row: sqlite3.Row) -> MemberResponse:
return MemberResponse(
username=row["username"],
role=row["role"],
created_at=int(row["created_at"] or 0),
disabled_at=int(row["disabled_at"] or 0),
active_sessions=int(row["active_sessions"] or 0),
success_count=int(row["success_count"] or 0),
)
def record_user_success(username: str, response: LongLinkResponse) -> None:
user = normalize_username(username)
if not user or user == "api" or user.startswith("cdk_") or response.fallback:
return
with AUTH_LOCK, auth_db() as conn:
conn.execute(
"UPDATE users SET success_count = COALESCE(success_count, 0) + 1 WHERE username = ?",
(user,),
)
log_info("member.success_count.increment", username=user, cs_id=response.cs_id)
@app.post("/api/admin/invites", response_model=InviteCreateResponse)
def create_invite(request: Request, payload: InviteCreateRequest | None = None) -> InviteCreateResponse:
start = time.perf_counter()
admin = require_admin(request)
count = payload.count if payload else 1
max_uses = payload.max_uses if payload else 10
request_id = str(payload.request_id or "").strip() if payload else ""
cache_path = invite_create_cache_path(admin["username"], request_id) if request_id else None
if cache_path and cache_path.exists():
try:
cached = json.loads(cache_path.read_text(encoding="utf-8"))
codes = [str(code) for code in cached.get("codes", []) if code]
if codes:
with auth_db() as conn:
rows = [
conn.execute("SELECT * FROM invites WHERE code = ?", (code,)).fetchone()
for code in codes
]
invites = [invite_from_row(row) for row in rows if row]
if invites:
return InviteCreateResponse(ok=True, invite=invites[0], invites=invites)
except Exception:
try:
cache_path.unlink()
except OSError:
pass
created: list[InviteResponse] = []
with AUTH_LOCK, auth_db() as conn:
while len(created) < count:
code = f"CDK-{secrets.token_urlsafe(12).replace('-', '').replace('_', '').upper()[:16]}"
try:
conn.execute(
"INSERT INTO invites (code, created_by, created_at, max_uses, use_count, last_used_at) VALUES (?, ?, ?, ?, 0, 0)",
(code, admin["username"], now_ts(), max_uses),
)
except sqlite3.IntegrityError:
continue
row = conn.execute("SELECT * FROM invites WHERE code = ?", (code,)).fetchone()
created.append(invite_from_row(row))
if cache_path:
cache_path.parent.mkdir(parents=True, exist_ok=True)
cache_path.write_text(
json.dumps({"created_at": now_ts(), "codes": [invite.code for invite in created]}),
encoding="utf-8",
)
log_info(
"admin.invite.create",
username=admin["username"],
count=len(created),
max_uses=max_uses,
request_id_present=bool(request_id),
elapsed_ms=elapsed_ms(start),
)
return InviteCreateResponse(ok=True, invite=created[0], invites=created)
@app.get("/api/admin/invites", response_model=InviteListResponse)
def list_invites(request: Request) -> InviteListResponse:
require_admin(request)
with auth_db() as conn:
rows = conn.execute(
"""
SELECT * FROM invites
WHERE revoked_at = 0
AND COALESCE(use_count, 0) < COALESCE(max_uses, 10)
ORDER BY created_at DESC
LIMIT 100
"""
).fetchall()
return InviteListResponse(ok=True, invites=[invite_from_row(row) for row in rows])
@app.post("/api/admin/invites/{code}/revoke")
def revoke_invite(code: str, request: Request) -> dict[str, bool]:
require_admin(request)
invite_code = str(code or "").strip().upper()
with AUTH_LOCK, auth_db() as conn:
row = conn.execute("SELECT * FROM invites WHERE code = ?", (invite_code,)).fetchone()
if not row:
raise HTTPException(status_code=404, detail="invite not found")
if row["used_at"]:
raise HTTPException(status_code=400, detail="invite already used")
conn.execute("UPDATE invites SET revoked_at = ? WHERE code = ? AND revoked_at = 0", (now_ts(), invite_code))
return {"ok": True}
@app.post("/api/admin/invites/{code}/delete")
def delete_invite(code: str, request: Request) -> dict[str, bool]:
start = time.perf_counter()
require_admin(request)
invite_code = str(code or "").strip().upper()
with AUTH_LOCK, auth_db() as conn:
row = conn.execute("SELECT * FROM invites WHERE code = ?", (invite_code,)).fetchone()
if not row:
raise HTTPException(status_code=404, detail="invite not found")
if row["used_at"]:
raise HTTPException(status_code=400, detail="invite already used")
conn.execute("DELETE FROM invites WHERE code = ?", (invite_code,))
log_info("admin.invite.delete", code=invite_code, elapsed_ms=elapsed_ms(start))
return {"ok": True}
@app.get("/api/admin/members", response_model=MemberListResponse)
def list_members(request: Request) -> MemberListResponse:
require_admin(request)
with auth_db() as conn:
rows = conn.execute(
"""
SELECT
users.username,
users.role,
users.created_at,
COALESCE(users.disabled_at, 0) AS disabled_at,
COALESCE(users.success_count, 0) AS success_count,
COUNT(sessions.token) AS active_sessions
FROM users
LEFT JOIN sessions
ON sessions.username = users.username AND sessions.expires_at > ?
GROUP BY users.username, users.role, users.created_at, users.disabled_at, users.success_count
ORDER BY users.role = 'admin' DESC, users.created_at DESC
""",
(now_ts(),),
).fetchall()
return MemberListResponse(ok=True, members=[member_from_row(row) for row in rows])
@app.post("/api/admin/members", response_model=MemberResponse)
def create_member(payload: AuthRequest, request: Request) -> MemberResponse:
require_admin(request)
username = normalize_username(payload.username)
if not username or len(username) < 3:
raise HTTPException(status_code=400, detail="username must be at least 3 characters")
if not payload.password or len(payload.password) < 6:
raise HTTPException(status_code=400, detail="password must be at least 6 characters")
with AUTH_LOCK, auth_db() as conn:
exists = conn.execute("SELECT id FROM users WHERE username = ?", (username,)).fetchone()
if exists:
raise HTTPException(status_code=409, detail="username already exists")
conn.execute(
"INSERT INTO users (username, password_hash, role, created_at, disabled_at) VALUES (?, ?, 'user', ?, 0)",
(username, password_hash(payload.password), now_ts()),
)
row = conn.execute(
"""
SELECT username, role, created_at, disabled_at, 0 AS active_sessions, 0 AS success_count
FROM users
WHERE username = ?
""",
(username,),
).fetchone()
return member_from_row(row)
def proxy_check_payload(response: Any) -> dict[str, str]:
text = str(getattr(response, "text", "") or "").strip()
payload: Any = {}
if text:
try:
payload = json.loads(text)
except Exception:
payload = {}
if isinstance(payload, dict):
ip = str(payload.get("ip") or payload.get("query") or payload.get("origin") or "").split(",")[0].strip()
country = str(
payload.get("country_code")
or payload.get("countryCode")
or payload.get("country")
or ""
).strip()
city = str(payload.get("city") or "").strip()
else:
ip = ""
country = ""
city = ""
if not ip:
match = re.search(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", text)
if match:
ip = match.group(0)
return {"ip": ip, "country": country, "city": city}
def proxy_check_one(label: str, proxy: str) -> dict[str, Any]:
proxy = normalize_proxy_url(proxy)
session = new_session()
if proxy:
set_proxy_url(session, proxy)
checks = (
"http://ip-api.com/json/?fields=status,message,query,countryCode,city",
"https://ipinfo.io/json",
"https://api.ipify.org?format=json",
"https://ifconfig.me/ip",
)
last_error = ""
last_status = 0
total_started = time.perf_counter()
for url in checks:
started = time.perf_counter()
try:
response = session.get(url, timeout=12)
last_status = int(getattr(response, "status_code", 0) or 0)
parsed = proxy_check_payload(response)
if last_status == 200 and parsed["ip"]:
return {
"ok": True,
"label": label,
"status_code": last_status,
"ip": parsed["ip"],
"country": parsed["country"],
"city": parsed["city"],
"source": urlsplit(url).netloc,
"elapsed_ms": elapsed_ms(started),
}
last_error = f"status={last_status} body={redact_text(getattr(response, 'text', '') or '', max_len=120)}"
except Exception as exc:
last_error = redact_text(repr(exc), max_len=160)
return {
"ok": False,
"label": label,
"status_code": last_status,
"ip": "",
"country": "",
"city": "",
"source": "",
"elapsed_ms": elapsed_ms(total_started),
"error": last_error,
}
@app.post("/api/admin/proxy-check")
def admin_proxy_check(payload: ProxyCheckRequest | None, request: Request) -> dict[str, Any]:
require_admin(request)
payload = payload or ProxyCheckRequest()
checkout_proxy = select_proxy_from_pool(payload.checkout_proxy, 0)
provider_proxy = select_proxy_from_pool(payload.provider_proxy, 0)
return {
"ok": True,
"checkout": proxy_check_one("Checkout", checkout_proxy),
"provider": proxy_check_one("Provider", provider_proxy),
}
@app.get("/api/runtime-config")
def runtime_config(request: Request) -> dict[str, Any]:
config = get_runtime_config()
if not request_authenticated(request):
config = {
**config,
"jpProxy": "",
"usProxy": "",
"stickyJpProxy": "",
"stickyUsProxy": "",
"idealPromoProxy": "",
"stickyIdealPromoProxy": "",
}
return {"ok": True, "config": config}
@app.post("/api/admin/runtime-config")
def update_runtime_config(payload: RuntimeConfigRequest, request: Request) -> dict[str, Any]:
admin = require_admin(request)
config = save_runtime_config(payload.model_dump(by_alias=True), admin["username"])
log_info(
"admin.runtime_config.save",
username=admin["username"],
run_mode=config["runMode"],
proxy_pool_mode=config["proxyPoolMode"],
billing_country=config["billingCountry"],
pm_country=config["pmCountry"],
payment_locale=config["paymentLocale"],
jp_proxy=redact_proxy(config["jpProxy"]),
us_proxy=redact_proxy_pool(config["usProxy"]),
sticky_jp_proxy=redact_proxy_pool(config["stickyJpProxy"]),
sticky_us_proxy=redact_proxy_pool(config["stickyUsProxy"]),
ideal_promo_proxy=redact_proxy_pool(config["idealPromoProxy"]),
sticky_ideal_promo_proxy=redact_proxy_pool(config["stickyIdealPromoProxy"]),
)
return {"ok": True, "config": config}
def require_manageable_member(conn: sqlite3.Connection, username: str) -> sqlite3.Row:
row = conn.execute("SELECT username, role, disabled_at FROM users WHERE username = ?", (username,)).fetchone()
if not row:
raise HTTPException(status_code=404, detail="member not found")
if row["role"] == "admin":
raise HTTPException(status_code=400, detail="admin member cannot be changed here")
return row
@app.post("/api/admin/members/{username}/disable")
def disable_member(username: str, request: Request) -> dict[str, bool]:
require_admin(request)
member_username = normalize_username(username)
with AUTH_LOCK, auth_db() as conn:
require_manageable_member(conn, member_username)
conn.execute("UPDATE users SET disabled_at = ? WHERE username = ? AND role != 'admin'", (now_ts(), member_username))
conn.execute("DELETE FROM sessions WHERE username = ?", (member_username,))
return {"ok": True}
@app.post("/api/admin/members/{username}/enable")
def enable_member(username: str, request: Request) -> dict[str, bool]:
require_admin(request)
member_username = normalize_username(username)
with AUTH_LOCK, auth_db() as conn:
require_manageable_member(conn, member_username)
conn.execute("UPDATE users SET disabled_at = 0 WHERE username = ? AND role != 'admin'", (member_username,))
return {"ok": True}
@app.post("/api/admin/members/{username}/logout")
def logout_member(username: str, request: Request) -> dict[str, bool]:
require_admin(request)
member_username = normalize_username(username)
with AUTH_LOCK, auth_db() as conn:
require_manageable_member(conn, member_username)
conn.execute("DELETE FROM sessions WHERE username = ?", (member_username,))
return {"ok": True}
@app.post("/api/admin/members/{username}/delete")
def delete_member(username: str, request: Request) -> dict[str, bool]:
require_admin(request)
member_username = normalize_username(username)
with AUTH_LOCK, auth_db() as conn:
require_manageable_member(conn, member_username)
conn.execute("DELETE FROM sessions WHERE username = ?", (member_username,))
conn.execute("DELETE FROM users WHERE username = ? AND role != 'admin'", (member_username,))
return {"ok": True}
def build_long_link_response(
req: LongLinkRequest,
progress: Any | None = None,
request_id: str | None = None,
should_stop: Any | None = None,
) -> LongLinkResponse:
request_id = request_id or f"ll_{uuid.uuid4().hex[:10]}"
context_token = REQUEST_ID.set(request_id)
started = time.perf_counter()
def stop_if_requested() -> None:
if should_stop and should_stop():
raise TaskCancelled("task cancelled")
def advance(percent: int, stage: str, message: str) -> None:
stop_if_requested()
if progress:
try:
progress(percent, stage, message)
except TaskCancelled:
raise
except Exception as exc:
log_warning("api.progress_callback.error", error=repr(exc))
try:
link_type = normalize_link_type(req.link_type)
advance(8, "读取 Token", "已读取参数,准备创建 OpenAI Checkout")
log_info(
"api.long_link.start",
link_type=link_type,
submitted_link_type=req.link_type,
billing_country=effective_country(req),
pm_country=effective_pm_country(req),
payment_locale=req.payment_locale,
checkout_ui_mode=req.checkout_ui_mode,
checkout_proxy_configured=bool(checkout_stage_proxy(req)),
checkout_proxy=checkout_stage_proxy(req),
approve_proxy_configured=bool(approve_stage_proxy(req)),
approve_proxy=approve_stage_proxy(req),
provider_proxy_configured=bool(provider_stage_proxy(req)),
provider_proxy=provider_stage_proxy(req),
custom_stripe_pk=bool(req.stripe_publishable_key.strip()),
custom_device_id=bool(req.device_id.strip()),
custom_user_agent=bool(req.user_agent.strip()),
)
chatgpt = build_chatgpt_session(req)
advance(18, "OpenAI Checkout", "正在创建 Checkout")
checkout = create_checkout(req, chatgpt)
stop_if_requested()
post_checkout_proxy = provider_stage_proxy(req)
stripe_pk, stripe_key_source = resolve_stripe_publishable_key(req, checkout)
if not stripe_pk:
discovered_key = discover_stripe_key_from_hosted_page(checkout, req, post_checkout_proxy)
if discovered_key:
stripe_pk = discovered_key
stripe_key_source = "hosted_page"
if not stripe_pk:
processor_entity = processor_entity_for_country(
checkout["billing_country"],
checkout.get("processor_entity", ""),
)
env_name = stripe_key_env_name(processor_entity)
detail = (
f"no Stripe publishable key available for processor_entity={processor_entity}; "
f"set {env_name} or submit stripe_publishable_key"
)
log_warning(
"stripe.key_resolution.missing",
processor_entity=processor_entity,
expected_env=env_name,
checkout_key_present=bool(checkout.get("stripe_publishable_key")),
checkout_url_present=bool(checkout.get("checkout_url")),
detail=detail,
)
raise HTTPException(status_code=422, detail=detail)
checkout["stripe_publishable_key"] = stripe_pk
checkout["stripe_key_source"] = stripe_key_source
log_info(
"stripe.key_resolution.done",
processor_entity=checkout.get("processor_entity", ""),
stripe_key_source=stripe_key_source,
stripe_key_fingerprint=stripe_key_fingerprint(stripe_pk),
)
advance(40, "Stripe init", "正在初始化 Stripe 支付页")
init_payload = stripe_init(
checkout["cs_id"],
req,
proxy_override=post_checkout_proxy,
stripe_pk_override=stripe_pk,
stripe_key_source=stripe_key_source,
processor_entity=checkout.get("processor_entity", ""),
)
if link_type in {"ideal", "paypal"}:
# iDEAL must be present at NL bootstrap. PayPal can be absent on
# the initial country/currency combination; checkout/update may
# enable it on the same Checkout, so validate PayPal only after
# the VN promotion refresh.
if link_type == "ideal":
require_payment_method_available(init_payload, "ideal")
promotion_proxy = promotion_stage_proxy(req)
if not promotion_proxy:
promotion_proxy = proxy_for_required_country(checkout_stage_proxy(req) or post_checkout_proxy, "VN")
if (checkout_stage_proxy(req) or post_checkout_proxy) and not promotion_proxy:
raise HTTPException(status_code=422, detail=f"{link_type.upper()} 优惠阶段缺少可切换到 VN 的代理模板")
advance(43, "VN 优惠更新", f"保持同一 {link_type.upper()} Checkout,正在通过 VN 更新优惠")
update_checkout_promotion(chatgpt, checkout, promotion_proxy)
stop_if_requested()
advance(47, "主线路 Stripe init", "优惠已更新,正在切回主线路重新初始化 Stripe")
init_payload = stripe_init(
checkout["cs_id"],
req,
proxy_override=post_checkout_proxy,
stripe_pk_override=stripe_pk,
stripe_key_source=stripe_key_source,
processor_entity=checkout.get("processor_entity", ""),
)
require_payment_method_available(init_payload, link_type)
if link_type == "ideal":
advance(50, "NL 税务同步", "正在同步荷兰账单与 Stripe 税务地区")
update_ideal_tax_context(chatgpt, checkout, req, stripe_pk, post_checkout_proxy)
stop_if_requested()
init_payload = stripe_init(
checkout["cs_id"],
req,
proxy_override=post_checkout_proxy,
stripe_pk_override=stripe_pk,
stripe_key_source=stripe_key_source,
processor_entity=checkout.get("processor_entity", ""),
)
require_payment_method_available(init_payload, "ideal")
enforce_zero_checkout_amount(init_payload, req, checkout["cs_id"])
stop_if_requested()
checkout_amount = expected_amount(init_payload)
checkout_amount_currency = str(init_payload.get("currency") or checkout["currency"]).upper()
advance(45, "金额检测", f"付款金额 {checkout_amount} {checkout_amount_currency}")
stripe_hosted_url = str(init_payload.get("stripe_hosted_url") or "").strip()
if not stripe_hosted_url:
detail = f"stripe init response missing stripe_hosted_url, keys={response_keys(init_payload)}"
log_warning("stripe.init.missing_hosted_url", detail=detail)
raise HTTPException(status_code=502, detail=detail)
hosted_long_url = to_openai_pay_url(stripe_hosted_url)
log_info("api.hosted_url.ready", stripe_hosted_url=stripe_hosted_url, hosted_long_url=hosted_long_url)
advance(55, "重写长链", f"已获得 hosted 长链,正在提取 {link_type.upper()} 链")
provider = {
"payment_method_id": "",
"stripe_redirect_url": "",
"provider_redirect_url": "",
"long_url": hosted_long_url,
}
fallback = False
provider_error = ""
try:
advance(65, "Provider", f"正在创建 {link_type.upper()} 支付方式并确认")
provider = create_provider_link(
chatgpt,
checkout,
init_payload,
stripe_hosted_url,
req,
provider_proxy=post_checkout_proxy,
)
stop_if_requested()
advance(92, "Provider", f"已获得 {link_type.upper()} 跳转链接")
except HTTPException as exc:
fallback = True
provider_error = provider_error_diagnostic(exc.detail, link_type, checkout, req)
advance(92, "回退 hosted", "PP 提取失败,返回 hosted 长链")
log_warning(
"provider.create.fallback_http_exception",
status_code=exc.status_code,
detail=provider_error,
fallback_url=hosted_long_url,
)
except Exception as exc:
fallback = True
provider_error = provider_error_diagnostic(repr(exc), link_type, checkout, req)
advance(92, "回退 hosted", "PP 提取异常,返回 hosted 长链")
log_warning(
"provider.create.fallback_exception",
error=provider_error,
fallback_url=hosted_long_url,
)
response_payload = LongLinkResponse(
ok=True,
cs_id=checkout["cs_id"],
processor_entity=checkout["processor_entity"],
billing_country=checkout["billing_country"],
currency=checkout["currency"],
checkout_amount=checkout_amount,
payment_locale=locale_parts(req.payment_locale)[0],
link_type=link_type,
payment_method_type=link_type,
payment_method_id=provider["payment_method_id"],
stripe_redirect_url=provider["stripe_redirect_url"],
provider_redirect_url=provider["provider_redirect_url"],
fallback=fallback,
provider_error=provider_error,
stripe_hosted_url=stripe_hosted_url,
long_url=provider["long_url"] or hosted_long_url,
ideal_qr_url=(
extract_ideal_qr_url(provider["provider_redirect_url"])
if link_type == "ideal" and not fallback
else ""
),
)
log_info(
"api.long_link.done",
elapsed_ms=elapsed_ms(started),
fallback=fallback,
cs_id=response_payload.cs_id,
payment_method_id=response_payload.payment_method_id,
provider_redirect_url=response_payload.provider_redirect_url,
long_url=response_payload.long_url,
)
advance(100, "完成", "生成完成" if not fallback else "已回退 hosted 长链")
return response_payload
except HTTPException as exc:
advance(100, "失败", str(exc.detail))
log_warning(
"api.long_link.http_exception",
elapsed_ms=elapsed_ms(started),
status_code=exc.status_code,
detail=str(exc.detail),
)
raise
except TaskCancelled:
log_info("api.long_link.cancelled", elapsed_ms=elapsed_ms(started))
raise
except Exception as exc:
advance(100, "失败", repr(exc))
log_warning("api.long_link.exception", elapsed_ms=elapsed_ms(started), error=repr(exc))
raise
finally:
REQUEST_ID.reset(context_token)
def probe_base_proxy(req: LongLinkRequest) -> str:
return (
first_proxy_from_pool(provider_stage_proxy(req))
or first_proxy_from_pool(checkout_stage_proxy(req))
or first_proxy_from_pool(approve_stage_proxy(req))
)
def clone_request_for_country(base_req: LongLinkRequest, country: str, index: int = 0) -> LongLinkRequest:
target_country = supported_country(country, "")
if not target_country:
raise HTTPException(status_code=400, detail=f"unsupported probe country: {country}")
base_proxy = probe_base_proxy(base_req)
sid = f"gp{target_country.lower()}{max(0, int(index)):02d}{secrets.token_hex(3)}"
country_proxy = proxy_for_probe_country(base_proxy, target_country, sid)
if not country_proxy:
raise HTTPException(
status_code=422,
detail="proxy username must contain region-XX/res-XX/country-XX/cc-XX for global probe",
)
data = base_req.model_dump(by_alias=True)
data.update(
{
"link_type": "paypal",
"billing_country": target_country,
"pmCountry": target_country,
"checkout_ui_mode": "custom",
"checkoutProxy": country_proxy,
"approveProxy": country_proxy,
"providerProxy": country_proxy,
"autoProbe": False,
}
)
return LongLinkRequest(**data)
def parse_probe_countries(req: LongLinkRequest) -> list[str]:
raw = str(req.probe_countries or "").strip() or DEFAULT_PROBE_COUNTRIES_RAW
values: list[str] = []
for item in re.split(r"[\s,;|/]+", raw):
country = supported_country(item, "")
if country and country not in values:
values.append(country)
current = effective_country(req)
if current and current not in values:
values.append(current)
return (values or [current or "DE"])[:80]
def probe_one_country(base_req: LongLinkRequest, country: str, index: int, total: int) -> dict[str, Any]:
req = clone_request_for_country(base_req, country, index)
started = time.perf_counter()
result: dict[str, Any] = {
"country": effective_country(req),
"currency": currency_for_country(effective_country(req)),
"result": "FAIL",
"amount": "",
"zero_offer": False,
"paypal": False,
"ideal": False,
"upi": False,
"payment_methods": [],
"provider": "",
"proxy_country": proxy_country_hint(checkout_stage_proxy(req)),
"elapsed_ms": 0,
"error": "",
}
log_info("probe.country.start", index=index, total=total, country=result["country"], currency=result["currency"])
try:
chatgpt = build_chatgpt_session(req)
checkout = create_checkout(req, chatgpt)
provider_proxy = provider_stage_proxy(req)
stripe_pk, stripe_key_source = resolve_stripe_publishable_key(req, checkout)
if not stripe_pk:
discovered_key = discover_stripe_key_from_hosted_page(checkout, req, provider_proxy)
if discovered_key:
stripe_pk = discovered_key
stripe_key_source = "hosted_page"
if not stripe_pk:
raise HTTPException(status_code=422, detail="missing stripe publishable key")
init_payload = stripe_init(
checkout["cs_id"],
req,
proxy_override=provider_proxy,
stripe_pk_override=stripe_pk,
stripe_key_source=stripe_key_source,
processor_entity=checkout.get("processor_entity", ""),
)
amount = expected_amount(init_payload)
methods = sorted(available_payment_method_types(init_payload))
has_paypal = "paypal" in methods
provider = processor_entity_for_country(checkout["billing_country"], checkout.get("processor_entity", ""))
result.update(
{
"result": "OK",
"amount": amount,
"zero_offer": amount_is_zero(amount),
"paypal": has_paypal,
"ideal": "ideal" in methods,
"upi": "upi" in methods,
"payment_methods": methods,
"provider": provider,
"elapsed_ms": elapsed_ms(started),
"checkout_session_id": checkout["cs_id"],
}
)
log_info(
"probe.country.done",
index=index,
total=total,
country=result["country"],
currency=result["currency"],
amount=amount,
zero_offer=result["zero_offer"],
paypal=has_paypal,
ideal="ideal" in methods,
upi="upi" in methods,
payment_methods=",".join(methods),
provider=provider,
elapsed_ms=result["elapsed_ms"],
)
except Exception as exc:
detail = str(exc.detail) if isinstance(exc, HTTPException) else repr(exc)
result.update({"result": "FAIL", "error": redact_text(detail, max_len=180), "elapsed_ms": elapsed_ms(started)})
log_warning(
"probe.country.failed",
index=index,
total=total,
country=result["country"],
currency=result["currency"],
error=result["error"],
elapsed_ms=result["elapsed_ms"],
)
return result
def run_country_probe(task_id: str, req: LongLinkRequest) -> tuple[LongLinkRequest, list[dict[str, Any]]]:
countries = parse_probe_countries(req)
results: list[dict[str, Any]] = []
selected_country = ""
total = len(countries)
set_task_state(task_id, progress=4, stage="国家探针", message=f"正在探测 {total} 个账单地区")
for index, country in enumerate(countries, start=1):
set_task_state(
task_id,
progress=max(4, min(20, int((index - 1) / max(1, total) * 16) + 4)),
stage="国家探针",
message=f"正在探测 {country}/{currency_for_country(country)}",
)
result = probe_one_country(req, country, index, total)
results.append(result)
set_task_probe_results(task_id, results)
if result.get("result") == "OK" and amount_is_zero(result.get("amount")) and result.get("paypal"):
selected_country = str(result.get("country") or country)
break
if selected_country:
set_task_state(task_id, progress=22, stage="国家探针", message=f"探针命中 {selected_country},继续生成 PP 链")
log_info("probe.country.selected", country=selected_country, tested=len(results), total=total)
return clone_request_for_country(req, selected_country), results
fallback_country = effective_country(req)
set_task_state(task_id, progress=22, stage="国家探针", message=f"未命中 0 元 PayPal 地区,使用当前地区 {fallback_country}")
log_warning("probe.country.no_match", fallback_country=fallback_country, tested=len(results), total=total)
return clone_request_for_country(req, fallback_country), results
def run_global_promo_probe_task(task_id: str, req: LongLinkRequest, owner: str) -> None:
request_id = f"probe_{task_id[-10:]}"
started = time.perf_counter()
log_callback_token = TASK_LOG_CALLBACK.set(task_log_callback(task_id))
cancel_check_token = TASK_CANCEL_CHECK.set(lambda: task_cancel_requested(task_id))
countries = parse_probe_countries(req)
results: list[dict[str, Any]] = []
set_task_state(
task_id,
status="running",
progress=1,
stage="全球优惠探针",
message=f"准备依次探测 {len(countries)} 个国家",
)
request_context = REQUEST_ID.set(request_id)
try:
total = len(countries)
for index, country in enumerate(countries, start=1):
if task_cancel_requested(task_id):
raise TaskCancelled("task cancelled")
resume_status = wait_for_task_resume(task_id)
if resume_status in {"cancelled", "missing"}:
raise TaskCancelled("task cancelled")
set_task_state(
task_id,
status="running",
progress=max(1, min(98, int(((index - 1) / max(1, total)) * 98) + 1)),
stage=f"探测 {index}/{total}",
message=f"正在切换 {country} 代理并检查 0 元优惠",
attempt=index,
)
result = probe_one_country(req, country, index, total)
results.append(result)
set_task_probe_results(task_id, results)
if index < total:
time.sleep(0.25)
successful = [item for item in results if str(item.get("result") or "").upper() == "OK"]
zero_countries = [str(item.get("country") or "") for item in successful if bool(item.get("zero_offer"))]
failed_count = len(results) - len(successful)
if not successful:
set_task_state(
task_id,
status="failed",
progress=100,
stage="探针失败",
message=f"{len(results)} 个国家全部探测失败",
elapsed_ms=elapsed_ms(started),
error="所有国家探测失败,请检查 Token 或动态代理模板",
probe_results=results,
)
return
summary = (
f"探针完成,发现 {len(zero_countries)} 个 0 元优惠国家:{', '.join(zero_countries)}"
if zero_countries
else "探针完成,未发现 0 元优惠国家"
)
if failed_count:
summary += f";{failed_count} 个国家失败"
set_task_state(
task_id,
status="done",
progress=100,
stage="探针完成",
message=summary,
elapsed_ms=elapsed_ms(started),
error="",
probe_results=results,
)
log_info(
"probe.global.done",
owner=owner,
tested=len(results),
successful=len(successful),
zero_offer_countries=zero_countries,
failed=failed_count,
elapsed_ms=elapsed_ms(started),
)
except TaskCancelled:
set_task_state(
task_id,
status="cancelled",
progress=0,
stage="已停止",
message="全球优惠探针已停止",
elapsed_ms=elapsed_ms(started),
error="",
probe_results=results,
)
except Exception as exc:
detail = str(exc.detail) if isinstance(exc, HTTPException) else repr(exc)
set_task_state(
task_id,
status="failed",
progress=100,
stage="探针失败",
message=detail,
elapsed_ms=elapsed_ms(started),
error=detail,
probe_results=results,
)
finally:
REQUEST_ID.reset(request_context)
TASK_LOG_CALLBACK.reset(log_callback_token)
TASK_CANCEL_CHECK.reset(cancel_check_token)
def launch_global_promo_probe_worker(task_id: str, req: LongLinkRequest, owner: str) -> None:
Thread(target=run_global_promo_probe_task, args=(task_id, req, owner), daemon=True).start()
@app.post("/api/global-promo-probe-task", response_model=LongLinkTaskStartResponse)
def start_global_promo_probe_task(req: LongLinkRequest, request: Request) -> LongLinkTaskStartResponse:
admin = require_admin(request)
req = apply_runtime_defaults(req)
req = req.model_copy(update={"link_type": "paypal", "auto_probe": True, "checkout_ui_mode": "custom"})
countries = parse_probe_countries(req)
base_proxy = probe_base_proxy(req)
if not base_proxy:
raise HTTPException(status_code=422, detail="全球探针需要动态代理模板")
if not proxy_supports_country_rewrite(base_proxy):
raise HTTPException(
status_code=422,
detail="代理用户名需要包含 region-XX、res-XX、country-XX 或 cc-XX 才能自动切换国家",
)
if not countries:
raise HTTPException(status_code=400, detail="至少需要一个探针国家")
task_id = f"prb_{uuid.uuid4().hex[:12]}"
token_fingerprint = access_token_fingerprint(req)
with TASK_LOCK:
active_task_id = active_task_for_token_locked(token_fingerprint)
if active_task_id:
raise HTTPException(status_code=409, detail=f"当前 token 已有任务运行:{active_task_id},请先停止或等待结束")
TASKS[task_id] = {
"task_id": task_id,
"task_kind": "global_promo_probe",
"status": "queued",
"progress": 1,
"stage": "全球优惠探针",
"message": f"探针已创建,共 {len(countries)} 个国家",
"attempt": 0,
"created_at": time.time(),
"updated_at": time.time(),
"elapsed_ms": 0,
"result": None,
"result_expires_at": 0,
"error": "",
"logs": [],
"probe_results": [],
"log_seq": 0,
"paused": False,
"owner": admin["username"],
"owner_role": admin["role"],
"request_payload": task_request_metadata(req),
"token_fingerprint": token_fingerprint,
"cancel_requested": False,
}
cleanup_tasks_locked()
launch_global_promo_probe_worker(task_id, req, admin["username"])
return LongLinkTaskStartResponse(ok=True, task_id=task_id)
@app.post("/api/long-link", response_model=LongLinkResponse)
def generate_long_link(req: LongLinkRequest, request: Request) -> LongLinkResponse:
user = link_request_user(req, request, consume_cdk=False)
if user.get("role") == "cdk" and normalize_link_type(req.link_type) != "ideal":
raise HTTPException(status_code=403, detail="CDK only supports iDEAL extraction")
req = apply_runtime_defaults(req)
response = build_long_link_response(req)
if user.get("role") == "cdk" and not response.fallback and response.provider_redirect_url:
user = require_cdk_user(req.cdk, consume=True)
record_user_success(user["username"], response)
if not response.fallback and response.provider_redirect_url:
record_proxy_success(user["username"], req)
return response
def token_from_any(value: Any) -> str:
if not value:
return ""
if isinstance(value, str):
text = value.strip()
if text.startswith("{") or text.startswith("["):
try:
return token_from_any(json.loads(text)) or text
except Exception:
return text
return text
if isinstance(value, list):
for item in value:
token = token_from_any(item)
if token:
return token
if isinstance(value, dict):
for key in ("accessToken", "access_token", "token"):
token = token_from_any(value.get(key))
if token:
return token
for item in value.values():
token = token_from_any(item)
if token:
return token
return ""
def long_link_request_from_access_token(access_token: str) -> LongLinkRequest:
return apply_runtime_defaults(
LongLinkRequest(
accessToken=access_token,
link_type="paypal",
checkout_ui_mode="custom",
)
)
@app.post("/api/extract-pp", response_model=LongLinkResponse)
def api_extract_pp(payload: ApiExtractRequest, request: Request) -> LongLinkResponse:
access_token = token_from_any(payload.access_token) or token_from_any(payload.token) or token_from_any(payload.session_json)
if not access_token:
raise HTTPException(status_code=400, detail="accessToken required")
req = long_link_request_from_access_token(access_token)
req = req.model_copy(update={"cdk": payload.cdk})
user = link_request_user(req, request, consume_cdk=False)
if user.get("role") == "cdk":
raise HTTPException(status_code=403, detail="CDK only supports iDEAL extraction")
response = build_long_link_response(req)
record_user_success(user["username"], response)
if not response.fallback and response.provider_redirect_url:
record_proxy_success(user["username"], req)
return response
@app.post("/api/business-checkout", response_model=BusinessCheckoutResponse)
def create_business_checkout(payload: BusinessCheckoutRequest) -> BusinessCheckoutResponse:
"""Create or inspect an independent ChatGPT Business checkout.
This endpoint intentionally does not enter the PP/iDEAL provider flow. A
pasted Business checkout is returned as-is; Token mode creates a new
Business checkout while preserving the supplied campaign id.
"""
pasted = str(payload.checkout_url or "").strip()
if pasted:
parsed = urlsplit(pasted)
if parsed.scheme != "https" or parsed.netloc.lower() != "chatgpt.com":
raise HTTPException(status_code=400, detail="Business Checkout URL 必须是 https://chatgpt.com/checkout/... 链接")
match = re.search(r"/checkout/([^/]+)/((?:cs|oaics)_[A-Za-z0-9_-]+)", parsed.path)
if not match:
raise HTTPException(status_code=400, detail="Business Checkout URL 缺少有效的 cs_id")
return BusinessCheckoutResponse(
ok=True,
checkoutUrl=pasted,
externalUrl="",
processorEntity=match.group(1),
csId=match.group(2),
planName=payload.plan_name,
promoCode=payload.promo_code or payload.promo_campaign_id,
seatQuantity=payload.seat_quantity,
message="已识别 Business Checkout;粘贴链接本身已是支付长链。",
)
access_token = token_from_any(payload.access_token) or token_from_any(payload.token) or token_from_any(payload.session_json)
if not access_token:
raise HTTPException(status_code=400, detail="请粘贴 Business Checkout 链接,或提供对应 Token/session JSON")
plan_name = re.sub(r"[^a-zA-Z0-9_.-]", "", payload.plan_name.strip()) or "chatgptteamplan"
billing_country = supported_country(payload.billing_country, "US")
currency = currency_for_country(billing_country)
req = LongLinkRequest(
accessToken=access_token,
checkoutProxy=payload.proxy,
billing_country=billing_country,
pmCountry=billing_country,
checkout_ui_mode="custom",
)
session = build_chatgpt_session(req)
# Business/Team uses the legacy team plan enum. Do not send checkout_ui_mode
# (the endpoint rejects that mode field for this order type).
body: dict[str, Any] = {
"entry_point": "all_plans_pricing_modal",
"plan_name": plan_name,
"billing_details": {"country": billing_country, "currency": currency},
"team_plan_data": {
"price_interval": payload.price_interval if payload.price_interval in {"month", "year"} else "month",
"seat_quantity": payload.seat_quantity,
"workspace_name": "ChatGPT Business",
},
}
campaign = (payload.promo_campaign_id or payload.promo_code).strip()
promo_match = re.search(r"(?:[?&]promoCode=|^)([A-Za-z0-9_.:-]+)$", campaign)
if promo_match:
campaign = promo_match.group(1)
if campaign:
# Business promo links use the short promo code at order creation;
# promo_campaign_id alone is accepted but does not apply the discount.
body["promo_code"] = campaign
body["promo_campaign"] = {"promo_campaign_id": campaign, "is_coupon_from_query_param": False}
response = session.post(
"https://chatgpt.com/backend-api/payments/checkout",
json=body,
headers={
"Referer": "https://chatgpt.com/",
"x-openai-target-path": "/backend-api/payments/checkout",
"x-openai-target-route": "/backend-api/payments/checkout",
},
timeout=DEFAULT_TIMEOUT,
)
if response.status_code >= 400:
raise HTTPException(status_code=response.status_code, detail=http_error_detail("Business Checkout 创建失败", response))
data = response.json() or {}
cs_id = extract_checkout_session_id(data)
if not cs_id:
raise HTTPException(status_code=502, detail=f"Business Checkout 未返回 cs_id: keys={response_keys(data)}")
processor = extract_processor_entity(data) or "openai_llc"
checkout_url = extract_checkout_url(data) or f"https://chatgpt.com/checkout/{processor}/{cs_id}"
stripe_pk = extract_stripe_publishable_key(data)
external_url = ""
if stripe_pk:
req = req.model_copy(update={"stripe_publishable_key": stripe_pk})
init_payload = stripe_init(
cs_id,
req,
proxy_override=payload.proxy,
stripe_pk_override=stripe_pk,
stripe_key_source="business_checkout_response",
processor_entity=processor,
)
external_url = str(init_payload.get("stripe_hosted_url") or "").strip()
return BusinessCheckoutResponse(
ok=True,
checkoutUrl=checkout_url,
externalUrl=external_url,
processorEntity=processor,
csId=cs_id,
planName=plan_name,
promoCode=campaign,
seatQuantity=payload.seat_quantity,
message="Business Checkout 已创建,并已生成站外 Stripe 支付长链。" if external_url else "Business Checkout 已创建,但未返回站外 Stripe 长链。",
)
def run_long_link_task(task_id: str, req: LongLinkRequest, owner: str) -> None:
request_id = f"ll_{task_id[-10:]}"
started = time.perf_counter()
log_callback_token = TASK_LOG_CALLBACK.set(task_log_callback(task_id))
cancel_check_token = TASK_CANCEL_CHECK.set(lambda: task_cancel_requested(task_id))
set_task_state(task_id, status="running", progress=3, stage="排队", message="任务已开始")
try:
response = build_long_link_response(
req,
progress=task_progress_callback(task_id),
request_id=request_id,
should_stop=lambda: task_cancel_requested(task_id),
)
if task_cancel_requested(task_id):
return
record_user_success(owner, response)
if not response.fallback and response.provider_redirect_url:
record_proxy_success(owner, req)
set_latest_result(task_id, response)
result_expires_at = result_expiry_timestamp(response)
set_task_state(
task_id,
status="done",
progress=100,
stage="完成",
message="生成完成" if not response.fallback else "PP 提取失败,已回退 hosted 长链",
elapsed_ms=elapsed_ms(started),
result=long_link_response_to_dict(response),
result_expires_at=result_expires_at,
error="",
)
except HTTPException as exc:
set_task_state(
task_id,
status="failed",
progress=100,
stage="失败",
message=str(exc.detail),
elapsed_ms=elapsed_ms(started),
error=str(exc.detail),
)
except TaskCancelled:
set_task_state(task_id, status="cancelled", progress=0, stage="已重置", message="任务已停止", elapsed_ms=elapsed_ms(started), error="")
except Exception as exc:
set_task_state(
task_id,
status="failed",
progress=100,
stage="失败",
message=repr(exc),
elapsed_ms=elapsed_ms(started),
error=repr(exc),
)
finally:
TASK_LOG_CALLBACK.reset(log_callback_token)
TASK_CANCEL_CHECK.reset(cancel_check_token)
def request_for_retry_attempt(req: LongLinkRequest, attempt: int) -> LongLinkRequest:
config = get_runtime_config()
run_mode = normalize_run_mode(config["runMode"])
if run_mode not in {RUN_MODE_SPLIT, RUN_MODE_UIAI_STYLE, RUN_MODE_CHECKOUT_JP_REST_PROVIDER, RUN_MODE_US_CHECKOUT_JP_PAYPAL}:
return req
link_type = normalize_link_type(req.link_type)
ideal_mode = link_type == "ideal"
upi_mode = link_type == "upi"
dynamic_pool = normalize_proxy_pool_mode(req.proxy_pool_mode or config.get("proxyPoolMode")) == "dynamic"
attempt_index = max(0, attempt - 1)
fingerprint = access_token_fingerprint(req)
pool_index = attempt_index + (int(fingerprint[:8], 16) if fingerprint else 0)
active_jp_pool = runtime_proxy_pool(config, "jp")
active_us_pool = runtime_proxy_pool(config, "us")
checkout_candidates = active_jp_pool if active_jp_pool else req.checkout_proxy
if ideal_mode:
provider_candidates = active_us_pool if active_us_pool else req.provider_proxy
base_nl_proxy = (
select_proxy_from_pool(checkout_candidates, pool_index)
or select_proxy_from_pool(provider_candidates, pool_index)
or first_proxy_from_pool(req.checkout_proxy)
or first_proxy_from_pool(req.provider_proxy)
)
promo_candidates = runtime_proxy_pool(config, "ideal-promo") or req.promotion_proxy or base_nl_proxy
base_promo_proxy = select_proxy_from_pool(promo_candidates, pool_index) or base_nl_proxy
nl_seed = proxy_for_attempt(base_nl_proxy, attempt, "idealnl", force=dynamic_pool)
promo_seed = proxy_for_attempt(base_promo_proxy, attempt, "idealvn", force=dynamic_pool)
nl_proxy = proxy_for_required_country(nl_seed, "NL")
promotion_proxy = proxy_for_required_country(promo_seed, "VN")
if base_nl_proxy and not nl_proxy:
raise HTTPException(status_code=422, detail="iDEAL 主代理无法切换到 NL")
if base_promo_proxy and not promotion_proxy:
raise HTTPException(status_code=422, detail="iDEAL 优惠代理无法切换到 VN")
data = req.model_dump(by_alias=True)
data["checkoutProxy"] = nl_proxy
data["approveProxy"] = nl_proxy
data["providerProxy"] = nl_proxy
data["promotionProxy"] = promotion_proxy
data["billing_country"] = "NL"
data["pmCountry"] = "NL"
data["checkout_ui_mode"] = "custom"
log_info(
"api.long_link.retry_attempt.ideal_proxy_selected",
attempt=attempt,
pool_index=pool_index,
dynamic_pool=dynamic_pool,
checkout_proxy=nl_proxy,
promotion_proxy=promotion_proxy,
provider_proxy=nl_proxy,
approve_proxy=nl_proxy,
checkout_country=proxy_country_hint(nl_proxy),
promotion_country=proxy_country_hint(promotion_proxy),
)
return LongLinkRequest(**data)
if run_mode == RUN_MODE_US_CHECKOUT_JP_PAYPAL:
base_proxy = select_proxy_from_pool(checkout_candidates, pool_index) or first_proxy_from_pool(req.checkout_proxy)
shared_proxy = proxy_for_attempt(base_proxy, attempt, "shared", force=dynamic_pool)
data = req.model_dump(by_alias=True)
data["checkoutProxy"] = shared_proxy
data["approveProxy"] = shared_proxy
data["providerProxy"] = shared_proxy
log_info(
"api.long_link.retry_attempt.proxy_selected",
attempt=attempt,
pool_index=pool_index,
run_mode=run_mode,
checkout_proxy=data["checkoutProxy"],
provider_proxy=data["providerProxy"],
checkout_country=proxy_country_hint(data["checkoutProxy"]),
provider_country=proxy_country_hint(data["providerProxy"]),
checkout_auto_sid=proxy_supports_auto_sid(data["checkoutProxy"]),
provider_auto_sid=proxy_supports_auto_sid(data["providerProxy"]),
shared_proxy=True,
)
return LongLinkRequest(**data)
provider_candidates = active_us_pool if active_us_pool else req.provider_proxy
base_checkout_proxy = select_proxy_from_pool(checkout_candidates, pool_index) or first_proxy_from_pool(req.checkout_proxy)
base_provider_proxy = select_proxy_from_pool(provider_candidates, pool_index) or first_proxy_from_pool(req.provider_proxy)
# UPI is country-bound and PayPal should follow its billing profile. iDEAL
# itself is selected by the NL billing data; forcing the proxy to NL broke
# routes that had already succeeded through the configured provider lane.
provider_country = "IN" if upi_mode else (effective_pm_country(req) if not ideal_mode else "")
provider_source = base_provider_proxy or base_checkout_proxy
if provider_source and provider_country:
aligned_provider = proxy_for_required_country(provider_source, provider_country)
if not aligned_provider:
raise HTTPException(
status_code=422,
detail=f"provider proxy cannot switch to required {provider_country} country",
)
base_provider_proxy = aligned_provider
checkout_proxy = proxy_for_attempt(base_checkout_proxy, attempt, "checkout", force=dynamic_pool)
provider_proxy = proxy_for_attempt(base_provider_proxy, attempt, "provider", force=dynamic_pool)
if link_type == "paypal":
checkout_country = effective_country(req)
aligned_checkout = proxy_for_required_country(checkout_proxy, checkout_country)
if checkout_proxy and not aligned_checkout:
raise HTTPException(status_code=422, detail=f"PayPal Checkout 代理无法切换到账单国家 {checkout_country}")
checkout_proxy = aligned_checkout
if provider_proxy and provider_country:
verified_provider = proxy_for_required_country(provider_proxy, provider_country)
if not verified_provider:
raise HTTPException(
status_code=422,
detail=f"provider proxy country mismatch; required={provider_country}",
)
provider_proxy = verified_provider
data = req.model_dump(by_alias=True)
data["checkoutProxy"] = checkout_proxy
# Approval is part of the ChatGPT checkout. It must reuse the exact checkout
# proxy/SID instead of moving to the Stripe provider lane.
data["approveProxy"] = checkout_proxy
data["providerProxy"] = provider_proxy
if link_type == "paypal":
promo_base = first_proxy_from_pool(req.promotion_proxy) or base_checkout_proxy
promo_seed = proxy_for_attempt(promo_base, attempt, "paypalvn", force=dynamic_pool)
promotion_proxy = proxy_for_required_country(promo_seed, "VN")
if promo_base and not promotion_proxy:
raise HTTPException(status_code=422, detail="PayPal 优惠代理无法切换到 VN")
data["promotionProxy"] = promotion_proxy
log_info(
"api.long_link.retry_attempt.proxy_selected",
attempt=attempt,
pool_index=pool_index,
link_type=link_type,
provider_required_country=provider_country or "configured",
dynamic_pool=dynamic_pool,
checkout_proxy=data["checkoutProxy"],
approve_proxy=data["approveProxy"],
provider_proxy=data["providerProxy"],
checkout_country=proxy_country_hint(data["checkoutProxy"]),
approve_country=proxy_country_hint(data["approveProxy"]),
provider_country=proxy_country_hint(data["providerProxy"]),
checkout_auto_sid=proxy_supports_auto_sid(data["checkoutProxy"]),
approve_auto_sid=proxy_supports_auto_sid(data["approveProxy"]),
provider_auto_sid=proxy_supports_auto_sid(data["providerProxy"]),
)
return LongLinkRequest(**data)
def launch_long_link_task_worker(task_id: str, req: LongLinkRequest, owner: str, owner_role: str = "user") -> None:
Thread(target=run_long_link_task_retrying, args=(task_id, req, owner, owner_role), daemon=True).start()
def run_long_link_task_retrying(task_id: str, req: LongLinkRequest, owner: str, owner_role: str = "user") -> None:
request_id = f"ll_{task_id[-10:]}"
started = time.perf_counter()
max_attempts = 3 if owner_role == "cdk" else (ADMIN_LONG_LINK_MAX_ATTEMPTS if owner_role == "admin" else LONG_LINK_MAX_ATTEMPTS)
log_callback_token = TASK_LOG_CALLBACK.set(task_log_callback(task_id))
cancel_check_token = TASK_CANCEL_CHECK.set(lambda: task_cancel_requested(task_id))
set_task_state(
task_id,
status="running",
progress=3,
stage="排队",
message=f"任务已开始,最多连续尝试 {max_attempts} 次",
)
try:
last_response: LongLinkResponse | None = None
last_error = ""
last_attempt = 0
stopped_early = False
for attempt in range(1, max_attempts + 1):
if task_cancel_requested(task_id):
raise TaskCancelled("task cancelled")
resume_status = wait_for_task_resume(task_id)
if resume_status in {"done", "failed", "cancelled", "missing"}:
return
last_attempt = attempt
attempt_request_id = f"{request_id}_{attempt:02d}"
attempt_req = request_for_retry_attempt(req, attempt)
attempt_country = effective_country(attempt_req)
set_task_state(
task_id,
status="running",
progress=max(3, min(95, int(((attempt - 1) / max_attempts) * 100))),
stage=f"第 {attempt}/{max_attempts} 次",
message=f"正在第 {attempt} 次尝试,账单地区 {attempt_country}/{currency_for_country(attempt_country)}",
attempt=attempt,
)
log_info(
"api.long_link.retry_attempt.start",
attempt=attempt,
max_attempts=max_attempts,
owner=owner,
owner_role=owner_role,
billing_country=attempt_country,
pm_country=effective_pm_country(attempt_req),
currency=currency_for_country(attempt_country),
checkout_ui_mode=attempt_req.checkout_ui_mode,
provider_proxy=provider_stage_proxy(attempt_req),
)
try:
response = build_long_link_response(
attempt_req,
progress=task_progress_callback(task_id),
request_id=attempt_request_id,
should_stop=lambda: task_cancel_requested(task_id),
)
if task_cancel_requested(task_id):
return
last_response = response
provider_success = bool(not response.fallback and response.provider_redirect_url)
if owner_role == "cdk" and normalize_link_type(req.link_type) == "ideal":
provider_success = cdk_ideal_response_succeeded(response)
if provider_success:
if owner_role == "cdk":
require_cdk_user(req.cdk, consume=True)
record_user_success(owner, response)
record_proxy_success(owner, attempt_req)
response = response.model_copy(update={"success_attempt": attempt})
set_latest_result(task_id, response, success_attempt=attempt)
result_expires_at = result_expiry_timestamp(response)
set_task_state(
task_id,
status="done",
progress=100,
stage="完成",
message=f"第 {attempt} 次成功",
attempt=attempt,
elapsed_ms=elapsed_ms(started),
result=long_link_response_to_dict(response),
result_expires_at=result_expires_at,
error="",
)
log_info("api.long_link.retry_attempt.success", attempt=attempt, max_attempts=max_attempts)
return
last_error = response.provider_error or "PP 提取失败,已回退 hosted 长链"
log_warning(
"api.long_link.retry_attempt.fallback",
attempt=attempt,
max_attempts=max_attempts,
provider_error=last_error,
)
if not retryable_failure(last_error, fresh_checkout=True):
stopped_early = True
log_warning(
"api.long_link.retry_attempt.non_retryable",
attempt=attempt,
detail=last_error,
)
break
except HTTPException as exc:
if is_amount_guard_error(exc):
raise
last_error = str(exc.detail)
log_warning(
"api.long_link.retry_attempt.http_exception",
attempt=attempt,
max_attempts=max_attempts,
status_code=exc.status_code,
detail=last_error,
)
if not retryable_failure(last_error, exc.status_code, fresh_checkout=True):
raise
except Exception as exc:
last_error = repr(exc)
log_warning(
"api.long_link.retry_attempt.exception",
attempt=attempt,
max_attempts=max_attempts,
error=last_error,
)
if not retryable_failure(last_error, fresh_checkout=True):
raise HTTPException(status_code=500, detail=last_error)
if attempt < max_attempts:
resume_status = wait_for_task_resume(task_id)
if resume_status in {"done", "failed", "cancelled", "missing"}:
return
time.sleep(0.4)
if last_response is not None:
if owner_role == "cdk":
link_type = normalize_link_type(req.link_type)
if link_type == "ideal" and not cdk_ideal_response_succeeded(last_response):
detail = last_error or "iDEAL 提炼未成功,未获得 ideal.nl 支付链接"
else:
detail = last_error or "PayPal 提链未成功,未获得支付链接"
raise HTTPException(status_code=502, detail=detail)
if normalize_link_type(req.link_type) == "paypal":
raise HTTPException(
status_code=502,
detail=last_error or "PayPal 提链未成功,回退链接不作为成功结果",
)
if last_attempt:
last_response = last_response.model_copy(update={"success_attempt": last_attempt})
set_latest_result(task_id, last_response, success_attempt=last_attempt)
result_expires_at = result_expiry_timestamp(last_response)
set_task_state(
task_id,
status="done",
progress=100,
stage="完成",
message=(
f"第 {last_attempt} 次遇到不可重试的支付结果,已返回 hosted 回退链接"
if stopped_early
else f"连续 {last_attempt} 次未成功,已返回最后一次 hosted 回退结果"
),
attempt=last_attempt,
elapsed_ms=elapsed_ms(started),
result=long_link_response_to_dict(last_response),
result_expires_at=result_expires_at,
error=last_error,
)
return
raise HTTPException(status_code=502, detail=last_error or f"连续 {max_attempts} 次尝试均失败")
except HTTPException as exc:
set_task_state(
task_id,
status="failed",
progress=100,
stage="失败",
message=str(exc.detail),
elapsed_ms=elapsed_ms(started),
error=str(exc.detail),
)
except TaskCancelled:
set_task_state(task_id, status="cancelled", progress=0, stage="已重置", message="任务已停止", elapsed_ms=elapsed_ms(started), error="")
except Exception as exc:
set_task_state(
task_id,
status="failed",
progress=100,
stage="失败",
message=repr(exc),
elapsed_ms=elapsed_ms(started),
error=repr(exc),
)
finally:
TASK_LOG_CALLBACK.reset(log_callback_token)
TASK_CANCEL_CHECK.reset(cancel_check_token)
@app.post("/api/long-link-task", response_model=LongLinkTaskStartResponse)
def start_long_link_task(req: LongLinkRequest, request: Request) -> LongLinkTaskStartResponse:
user = link_request_user(req, request, consume_cdk=False)
req = apply_runtime_defaults(req)
task_id = f"llt_{uuid.uuid4().hex[:12]}"
token_fingerprint = access_token_fingerprint(req)
with TASK_LOCK:
active_task_id = active_task_for_token_locked(token_fingerprint)
if active_task_id:
raise HTTPException(status_code=409, detail=f"当前 token 已有任务运行:{active_task_id},请先停止或等待结束")
TASKS[task_id] = {
"task_id": task_id,
"status": "queued",
"progress": 1,
"stage": "排队",
"message": "任务已创建",
"attempt": 0,
"created_at": time.time(),
"updated_at": time.time(),
"elapsed_ms": 0,
"result": None,
"result_expires_at": 0,
"error": "",
"logs": [],
"probe_results": [],
"log_seq": 0,
"paused": False,
"owner": user["username"],
"owner_role": user["role"],
"request_payload": task_request_metadata(req),
"token_fingerprint": token_fingerprint,
"cancel_requested": False,
}
cleanup_tasks_locked()
launch_long_link_task_worker(task_id, req, user["username"], user["role"])
return LongLinkTaskStartResponse(ok=True, task_id=task_id)
@app.post("/api/ideal-long-link-task", response_model=LongLinkTaskStartResponse)
def start_ideal_long_link_task(req: LongLinkRequest, request: Request) -> LongLinkTaskStartResponse:
user = link_request_user(req, request, consume_cdk=False)
req = apply_runtime_defaults(req)
checkout_proxy = checkout_stage_proxy(req)
provider_proxy = normalize_proxy_url(provider_stage_proxy(req) or checkout_proxy)
req = req.model_copy(
update={
"link_type": "ideal",
"billing_country": "NL",
"pm_country": "NL",
"checkout_ui_mode": "custom",
"checkout_proxy": checkout_proxy,
"approve_proxy": checkout_proxy,
"provider_proxy": provider_proxy,
}
)
task_id = f"ilt_{uuid.uuid4().hex[:12]}"
token_fingerprint = access_token_fingerprint(req)
with TASK_LOCK:
active_task_id = active_task_for_token_locked(token_fingerprint)
if active_task_id:
raise HTTPException(status_code=409, detail=f"当前 token 已有任务运行:{active_task_id},请先停止或等待结束")
TASKS[task_id] = {
"task_id": task_id,
"status": "queued",
"progress": 1,
"stage": "queued",
"message": "iDEAL task created",
"created_at": time.time(),
"updated_at": time.time(),
"elapsed_ms": 0,
"result": None,
"result_expires_at": 0,
"error": "",
"logs": [],
"probe_results": [],
"log_seq": 0,
"paused": False,
"owner": user["username"],
"owner_role": user["role"],
"request_payload": task_request_metadata(req),
"token_fingerprint": token_fingerprint,
"cancel_requested": False,
}
cleanup_tasks_locked()
launch_long_link_task_worker(task_id, req, user["username"], user["role"])
return LongLinkTaskStartResponse(ok=True, task_id=task_id)
@app.post("/api/upi-long-link-task", response_model=LongLinkTaskStartResponse)
def start_upi_long_link_task(req: LongLinkRequest, request: Request) -> LongLinkTaskStartResponse:
user = link_request_user(req, request, consume_cdk=False)
if user.get("role") == "cdk":
raise HTTPException(status_code=403, detail="CDK only supports iDEAL extraction")
req = apply_runtime_defaults(req)
checkout_proxy = checkout_stage_proxy(req)
provider_proxy = proxy_with_region(provider_stage_proxy(req) or checkout_proxy, "IN")
req = req.model_copy(
update={
"link_type": "upi",
"billing_country": "IN",
"pm_country": "IN",
"checkout_ui_mode": "hosted",
"checkout_proxy": checkout_proxy,
"approve_proxy": checkout_proxy,
"provider_proxy": provider_proxy,
}
)
task_id = f"upi_{uuid.uuid4().hex[:12]}"
token_fingerprint = access_token_fingerprint(req)
with TASK_LOCK:
active_task_id = active_task_for_token_locked(token_fingerprint)
if active_task_id:
raise HTTPException(status_code=409, detail=f"当前 token 已有任务运行:{active_task_id},请先停止或等待结束")
TASKS[task_id] = {
"task_id": task_id,
"status": "queued",
"progress": 1,
"stage": "queued",
"message": "UPI task created",
"created_at": time.time(),
"updated_at": time.time(),
"elapsed_ms": 0,
"result": None,
"result_expires_at": 0,
"error": "",
"logs": [],
"probe_results": [],
"log_seq": 0,
"paused": False,
"owner": user["username"],
"owner_role": user["role"],
"request_payload": task_request_metadata(req),
"token_fingerprint": token_fingerprint,
"cancel_requested": False,
}
cleanup_tasks_locked()
launch_long_link_task_worker(task_id, req, user["username"], user["role"])
return LongLinkTaskStartResponse(ok=True, task_id=task_id)
@app.get("/api/long-link-task/{task_id}", response_model=LongLinkTaskStatusResponse)
def get_long_link_task(task_id: str, request: Request) -> LongLinkTaskStatusResponse:
with TASK_LOCK:
task = dict(TASKS.get(task_id) or {})
task["logs"] = list(task.get("logs") or [])
if not task:
raise HTTPException(status_code=404, detail="task not found")
require_task_access(task, request)
response_logs = task.get("logs") or []
response_probe_results = task.get("probe_results") or []
if not is_admin_request(request):
response_logs = []
response_probe_results = []
created_at = float(task.get("created_at") or time.time())
elapsed = int((time.time() - created_at) * 1000)
if task.get("elapsed_ms"):
elapsed = int(task["elapsed_ms"])
return LongLinkTaskStatusResponse(
ok=task.get("status") != "failed",
task_id=task_id,
status=str(task.get("status") or "unknown"),
progress=int(task.get("progress") or 0),
stage=str(task.get("stage") or ""),
message=str(task.get("message") or ""),
attempt=int(task.get("attempt") or 0),
paused=bool(task.get("paused") or False),
elapsed_ms=elapsed,
result=long_link_response_from_dict(task.get("result")),
error=str(task.get("error") or ""),
logs=response_logs,
probe_results=response_probe_results,
created_at=int(float(task.get("created_at") or 0)),
updated_at=int(float(task.get("updated_at") or 0)),
result_expires_at=int(task.get("result_expires_at") or 0),
)
@app.post("/api/long-link-task/{task_id}/pause")
def set_long_link_task_paused(task_id: str, payload: TaskPauseRequest, request: Request) -> dict[str, Any]:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
raise HTTPException(status_code=404, detail="task not found")
require_task_access(task, request)
status = str(task.get("status") or "")
if status in {"done", "failed", "cancelled"}:
return {"ok": True, "task_id": task_id, "paused": bool(task.get("paused") or False)}
task["paused"] = bool(payload.paused)
task["updated_at"] = time.time()
if task["paused"]:
task["status"] = "paused"
task["stage"] = "暂停"
task["message"] = "任务已暂停"
else:
task["status"] = "running"
if task.get("progress", 0) <= 0:
task["progress"] = 3
task["stage"] = str(task.get("stage") or "处理中")
task["message"] = "任务已恢复"
return {"ok": True, "task_id": task_id, "paused": bool(task.get("paused") or False)}
@app.post("/api/long-link-task/{task_id}/reset")
def reset_long_link_task(task_id: str, request: Request) -> dict[str, Any]:
with TASK_LOCK:
task = TASKS.get(task_id)
if not task:
raise HTTPException(status_code=404, detail="task not found")
require_task_access(task, request)
token_fingerprint = str(task.get("token_fingerprint") or "")
cancelled = cancel_token_tasks_locked(token_fingerprint, "任务已停止,不会继续跑")
if task_id not in cancelled:
mark_task_cancelled_locked(task, "任务状态已重置")
preserve_probe_results = str(task.get("task_kind") or "") == "global_promo_probe"
if not preserve_probe_results:
task["elapsed_ms"] = 0
task["result"] = None
task["result_expires_at"] = 0
task["error"] = ""
if not preserve_probe_results:
task["logs"] = []
task["probe_results"] = []
task["log_seq"] = 0
task["paused"] = False
return {"ok": True, "task_id": task_id, "status": "cancelled", "cancelled": cancelled}
@app.post("/api/long-link-task/stop-token")
def stop_long_link_tasks_for_token(req: LongLinkRequest, request: Request) -> dict[str, Any]:
link_request_user(req, request, consume_cdk=False)
req = apply_runtime_defaults(req)
token_fingerprint = access_token_fingerprint(req)
with TASK_LOCK:
cancelled = cancel_token_tasks_locked(token_fingerprint, "当前 token 的任务已停止")
return {"ok": True, "status": "cancelled", "cancelled": cancelled}
@app.get("/api/long-link-latest", response_model=LongLinkTaskStatusResponse)
def get_latest_long_link(request: Request) -> LongLinkTaskStatusResponse:
require_admin(request)
with TASK_LOCK:
latest = dict(LATEST_RESULT)
latest["logs"] = list(latest.get("logs") or [])
result = long_link_response_from_dict(latest.get("result"))
if not result:
raise HTTPException(status_code=404, detail="latest result not found")
return LongLinkTaskStatusResponse(
ok=True,
task_id=str(latest.get("task_id") or "latest"),
status="done",
progress=100,
stage="最近结果",
message="已取回最近一次生成结果",
attempt=int((latest.get("result") or {}).get("success_attempt") or 0),
elapsed_ms=0,
result=result,
paused=bool(latest.get("paused") or False),
error="",
logs=latest.get("logs") or [],
probe_results=latest.get("probe_results") or [],
created_at=int(float(latest.get("updated_at") or 0)),
updated_at=int(float(latest.get("updated_at") or 0)),
result_expires_at=int(latest.get("result_expires_at") or 0),
)
|