-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathpay.py
More file actions
1569 lines (1342 loc) · 63.4 KB
/
Copy pathpay.py
File metadata and controls
1569 lines (1342 loc) · 63.4 KB
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
"""
Stripe Checkout 自动化支付脚本
用法:
python pay.py <session_id> [--card N] [--config path] [--token TOKEN]
示例:
python pay.py cs_live_a12H3g13P9TH6udPmljRCpWsmHiKRFH7VUiZBbcA1U60eMzFFI2wp3rtXL
"""
import argparse
import base64
import hashlib
import json
import os
import random
import re
import string
import sys
import time
import urllib.parse
import uuid
from datetime import datetime
import requests
LOG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "log.txt")
def _init_log():
"""清空并初始化 log.txt"""
with open(LOG_FILE, "w", encoding="utf-8") as f:
f.write(f"{'='*80}\n")
f.write(f" Stripe 自动化支付 日志 — {datetime.now().isoformat()}\n")
f.write(f"{'='*80}\n\n")
def _log(msg: str):
"""追加一行到 log.txt 并同时 print"""
ts = datetime.now().strftime("%H:%M:%S.%f")[:-3]
line = f"[{ts}] {msg}"
print(line)
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(line + "\n")
def _log_raw(text: str):
"""追加原始文本到 log.txt(不 print)"""
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(text + "\n")
def _log_request(method: str, url: str, data=None, params=None, tag: str = ""):
"""记录 HTTP 请求详情"""
_log_raw(f"\n{'─'*70}")
_log_raw(f">>> REQUEST {tag}")
_log_raw(f" {method} {url}")
if params:
_log_raw(f" PARAMS: {json.dumps(params, ensure_ascii=False, indent=6)}")
if data:
# 脱敏卡号
safe = dict(data) if isinstance(data, dict) else {}
if "card[number]" in safe:
safe["card[number]"] = "****" + str(safe["card[number]"])[-4:]
if "card[cvc]" in safe:
safe["card[cvc]"] = "***"
_log_raw(f" BODY: {json.dumps(safe, ensure_ascii=False, indent=6)}")
def _log_response(resp: requests.Response, tag: str = ""):
"""记录 HTTP 响应详情"""
_log_raw(f"<<< RESPONSE {tag} status={resp.status_code}")
try:
body = resp.json()
_log_raw(f" BODY: {json.dumps(body, ensure_ascii=False, indent=6)}")
except Exception:
_log_raw(f" BODY(raw): {resp.text[:2000]}")
_log_raw(f"{'─'*70}\n")
# ---------------------------------------------------------------------------
# 常量
# ---------------------------------------------------------------------------
STRIPE_API = "https://api.stripe.com"
STRIPE_VERSION_FULL = "2025-03-31.basil; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1"
STRIPE_VERSION_BASE = "2025-03-31.basil"
USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/146.0.0.0 Safari/537.36"
)
HCAPTCHA_SITE_KEY_FALLBACK = "c7faac4c-1cd7-4b1b-b2d4-42ba98d09c7a"
KNOWN_PUBLISHABLE_KEYS = {
"1HOrSwC6h1nxGoI3": "pk_live_51HOrSwC6h1nxGoI3lTAgRjYVrz4dU3fVOabyCcKR3pbEJguCVAlqCxdxCUvoRh1XWwRacViovU3kLKvpkjh7IqkW00iXQsjo3n",
}
# ---------------------------------------------------------------------------
# 地域 / 浏览器配置 — 必须和代理 IP 出口一致
# ---------------------------------------------------------------------------
LOCALE_PROFILES = {
"US": {
"browser_locale": "en-US",
"browser_timezone": "America/Chicago",
"browser_tz_offset": 360, # CST = UTC-6 → 360
"browser_language": "en-US",
"color_depth": 24,
"screen_w": 1920, "screen_h": 1080, "dpr": 1,
},
"KR": {
"browser_locale": "ko-KR",
"browser_timezone": "Asia/Seoul",
"browser_tz_offset": -540, # KST = UTC+9 → -540
"browser_language": "ko-KR",
"color_depth": 24,
"screen_w": 1920, "screen_h": 1080, "dpr": 1,
},
}
APATA_RBA_ORG_ID = "8t63q4n4"
def _build_browser_fingerprint(locale_profile: dict) -> dict:
"""构建 RecordBrowserInfo 的完整设备指纹 payload"""
sw = locale_profile["screen_w"]
sh = locale_profile["screen_h"]
dpr = locale_profile["dpr"]
cd = locale_profile["color_depth"]
lang = locale_profile["browser_language"]
tz_name = locale_profile["browser_timezone"]
tz_offset = locale_profile["browser_tz_offset"]
# 可用高度 = 屏幕高度 - 任务栏 (48-60px)
avail_h = sh - random.randint(40, 60)
return {
"navigator": {
"mediaDevices": {"audioinput": random.randint(1, 3), "videoinput": random.randint(0, 2),
"audiooutput": random.randint(1, 3)},
"battery": {"charging": True, "chargingTime": 0, "dischargingTime": None,
"level": round(random.uniform(0.5, 1.0), 2)},
"appCodeName": "Mozilla", "appName": "Netscape",
"appVersion": USER_AGENT.replace("Mozilla/", ""),
"cookieEnabled": True, "doNotTrack": None,
"hardwareConcurrency": random.choice([8, 12, 16, 32]),
"language": lang,
"languages": [lang, lang.split("-")[0]],
"maxTouchPoints": 0, "onLine": True,
"platform": "Win32", "product": "Gecko", "productSub": "20030107",
"userAgent": USER_AGENT,
"vendor": "Google Inc.", "vendorSub": "",
"webdriver": False,
"deviceMemory": random.choice([4, 8, 16]),
"pdfViewerEnabled": True, "javaEnabled": False,
"plugins": "PDF Viewer,Chrome PDF Viewer,Chromium PDF Viewer,Microsoft Edge PDF Viewer,WebKit built-in PDF",
"connections": {
"effectiveType": "4g",
"downlink": round(random.uniform(1.0, 10.0), 2),
"rtt": random.choice([50, 100, 150, 200, 250, 300, 350, 400]),
"saveData": False,
},
},
"screen": {
"availHeight": avail_h, "availWidth": sw,
"availLeft": 0, "availTop": 0,
"colorDepth": cd, "height": sh, "width": sw,
"pixelDepth": cd,
"orientation": "landscape-primary",
"devicePixelRatio": dpr,
},
"timezone": {"offset": tz_offset, "timezone": tz_name},
"canvas": hashlib.sha256(os.urandom(32)).hexdigest(),
"permissions": {
"geolocation": "denied", "notifications": "denied",
"midi": "denied", "camera": "denied", "microphone": "denied",
"background-fetch": "prompt", "background-sync": "granted",
"persistent-storage": "granted", "accelerometer": "granted",
"gyroscope": "granted", "magnetometer": "granted",
"clipboard-read": "denied", "clipboard-write": "denied",
"screen-wake-lock": "denied", "display-capture": "denied",
"idle-detection": "denied",
},
"audio": {"sum": 124.04347527516074},
"browserBars": {
"locationbar": True, "menubar": True, "personalbar": True,
"statusbar": True, "toolbar": True, "scrollbars": True,
},
"sensors": {
"accelerometer": True, "gyroscope": True, "linearAcceleration": True,
"absoluteOrientation": True, "relativeOrientation": True,
"magnetometer": False, "ambientLight": False, "proximity": False,
},
"storage": {
"localStorage": True, "sessionStorage": True,
"indexedDB": True, "openDatabase": False,
},
"webGl": {
"dataHash": hashlib.sha256(os.urandom(32)).hexdigest(),
"vendor": "Google Inc. (NVIDIA)",
"renderer": "ANGLE (NVIDIA, NVIDIA GeForce RTX 4060 (0x00002882) Direct3D11 vs_5_0 ps_5_0, D3D11)",
},
"adblock": False,
"clientRects": {
"x": round(-10004 + random.uniform(-1, 1), 10),
"y": round(2.35 + random.uniform(-0.01, 0.01), 10),
"width": round(111.29 + random.uniform(-0.01, 0.01), 10),
"height": round(111.29 + random.uniform(-0.01, 0.01), 10),
"top": round(2.35 + random.uniform(-0.01, 0.01), 10),
"bottom": round(113.64 + random.uniform(-0.01, 0.01), 10),
"left": round(-10004 + random.uniform(-1, 1), 10),
"right": round(-9893 + random.uniform(-1, 1), 10),
},
"fonts": {"installed_count": random.randint(40, 60), "not_installed_count": 0},
}
def _gen_fingerprint():
def _id():
return str(uuid.uuid4()).replace("-", "") + uuid.uuid4().hex[:6]
return _id(), _id(), _id()
_PLUGINS_STR = (
"PDF Viewer,internal-pdf-viewer,application/pdf,pdf++text/pdf,pdf, "
"Chrome PDF Viewer,internal-pdf-viewer,application/pdf,pdf++text/pdf,pdf, "
"Chromium PDF Viewer,internal-pdf-viewer,application/pdf,pdf++text/pdf,pdf, "
"Microsoft Edge PDF Viewer,internal-pdf-viewer,application/pdf,pdf++text/pdf,pdf, "
"WebKit built-in PDF,internal-pdf-viewer,application/pdf,pdf++text/pdf,pdf"
)
_CANVAS_FPS = [
"0100100101111111101111101111111001110010110111110111111",
"0100100101111111101111101111111001110010110111110111110",
"0100100101111111101111101111111001110010110111110111101",
]
_AUDIO_FPS = [
"d331ca493eb692cfcd19ae5db713ad4b",
"a7c5f72e1b3d4e8f9c0d2a6b7e8f1c3d",
"e4b8d6f2a0c3d5e7f9b1c3d5e7f9a0b2",
]
def _encode_m6(payload: dict) -> str:
"""JSON → urlencode → base64 (m.stripe.com/6 编码格式)"""
raw = json.dumps(payload, separators=(",", ":"))
return base64.b64encode(urllib.parse.quote(raw, safe="").encode()).decode()
def _b64url_seg(n: int = 32) -> str:
return base64.urlsafe_b64encode(os.urandom(n)).rstrip(b"=").decode()
def register_fingerprint(http: "requests.Session") -> tuple[str, str, str]:
"""向 m.stripe.com/6 发送 4 次指纹上报, 返回服务端分配的 (guid, muid, sid)。
如果请求失败, 返回本地随机生成的值。
"""
# 本地备用值
guid, muid, sid = _gen_fingerprint()
fp_id = uuid.uuid4().hex
# 屏幕参数 (US 常见配置)
screens = [(1920, 1080, 1), (1536, 864, 1.25), (2560, 1440, 1), (1440, 900, 1)]
sw, sh, dpr = random.choice(screens)
vh = sh - random.randint(40, 70) # viewport = screen - chrome
cpu = random.choice([4, 8, 12, 16])
canvas_fp = random.choice(_CANVAS_FPS)
audio_fp = random.choice(_AUDIO_FPS)
def _build_full(v2: int, inc_ids: bool) -> dict:
s1, s2, s3, s4, s5 = (_b64url_seg() for _ in range(5))
ts_now = int(time.time() * 1000)
return {
"v2": v2, "id": fp_id,
"t": round(random.uniform(3, 120), 1),
"tag": "$npm_package_version", "src": "js",
"a": {
"a": {"v": "true", "t": 0},
"b": {"v": "true", "t": 0},
"c": {"v": "en-US", "t": 0},
"d": {"v": "Win32", "t": 0},
"e": {"v": _PLUGINS_STR, "t": round(random.uniform(0, 0.5), 1)},
"f": {"v": f"{sw}w_{vh}h_24d_{dpr}r", "t": 0},
"g": {"v": str(cpu), "t": 0},
"h": {"v": "false", "t": 0},
"i": {"v": "sessionStorage-enabled, localStorage-enabled", "t": round(random.uniform(0.5, 2), 1)},
"j": {"v": canvas_fp, "t": round(random.uniform(5, 120), 1)},
"k": {"v": "", "t": 0},
"l": {"v": USER_AGENT, "t": 0},
"m": {"v": "", "t": 0},
"n": {"v": "false", "t": round(random.uniform(3, 50), 1)},
"o": {"v": audio_fp, "t": round(random.uniform(20, 30), 1)},
},
"b": {
"a": f"https://{s1}.{s2}.{s3}/",
"b": f"https://{s1}.{s3}/{s4}/{s5}/{_b64url_seg()}",
"c": _b64url_seg(),
"d": muid if inc_ids else "NA",
"e": sid if inc_ids else "NA",
"f": False, "g": True, "h": True,
"i": ["location"], "j": [],
"n": round(random.uniform(800, 2000), 1),
"u": "chatgpt.com", "v": "auth.openai.com",
"w": f"{ts_now}:{hashlib.sha256(os.urandom(32)).hexdigest()}",
},
"h": os.urandom(10).hex(),
}
def _build_mouse(source: str) -> dict:
return {
"muid": muid, "sid": sid,
"url": f"https://{_b64url_seg()}.{_b64url_seg()}/{_b64url_seg()}/{_b64url_seg()}/{_b64url_seg()}",
"source": source,
"data": [random.randint(1, 8) for _ in range(10)],
}
m6_headers = {
"User-Agent": USER_AGENT,
"Content-Type": "text/plain;charset=UTF-8",
"Accept": "*/*",
"Origin": "https://m.stripe.network",
"Referer": "https://m.stripe.network/",
}
m6_url = "https://m.stripe.com/6"
_log("[1/6] 注册浏览器指纹 ...")
# #1 完整指纹 (v2=1, 无 ID)
try:
r1 = http.post(m6_url, data=_encode_m6(_build_full(1, False)), headers=m6_headers, timeout=10)
if r1.status_code == 200:
j = r1.json()
muid = j.get("muid", muid)
guid = j.get("guid", guid)
sid = j.get("sid", sid)
_log(f" 指纹上报 1/4 完成")
except Exception as e:
_log(f" 指纹上报 1/4 失败: {e}")
# #2 完整指纹 (v2=2, 带 ID)
try:
r2 = http.post(m6_url, data=_encode_m6(_build_full(2, True)), headers=m6_headers, timeout=10)
if r2.status_code == 200:
j = r2.json()
guid = j.get("guid", guid)
_log(f" 指纹上报 2/4 完成")
except Exception as e:
_log(f" 指纹上报 2/4 失败: {e}")
# #3 鼠标行为 (mouse-timings-10-v2)
try:
http.post(m6_url, data=_encode_m6(_build_mouse("mouse-timings-10-v2")), headers=m6_headers, timeout=10)
_log(" 指纹上报 3/4 完成 (鼠标行为)")
except Exception:
pass
# #4 鼠标行为 (mouse-timings-10)
try:
http.post(m6_url, data=_encode_m6(_build_mouse("mouse-timings-10")), headers=m6_headers, timeout=10)
_log(" 指纹上报 4/4 完成 (鼠标轨迹)")
except Exception:
pass
_log(f" 浏览器指纹注册完成")
return guid, muid, sid
def _gen_elements_session_id():
"""生成类似 elements_session_15hfldlRpSm 的 session id"""
import random, string
chars = string.ascii_letters + string.digits
return "elements_session_" + "".join(random.choices(chars, k=11))
def _stripe_headers():
return {
"User-Agent": USER_AGENT,
"Accept": "application/json",
"Origin": "https://js.stripe.com",
"Referer": "https://js.stripe.com/",
}
def parse_checkout_url(raw: str) -> tuple[str, str]:
"""解析输入,返回 (session_id, stripe_checkout_url)
支持以下格式:
- 裸 session_id: cs_live_xxx / cs_test_xxx
- Stripe URL: https://checkout.stripe.com/c/pay/cs_live_xxx
- ChatGPT URL: https://chatgpt.com/checkout/openai_llc/cs_live_xxx
"""
raw = raw.strip()
m = re.search(r"(cs_(?:live|test)_[A-Za-z0-9]+)", raw)
if not m:
raise ValueError(f"无法从输入中提取 checkout_session_id: {raw[:120]}...")
session_id = m.group(1)
# 构建用于 Playwright 等回退方案的 Stripe checkout URL
# 如果输入是 checkout.stripe.com 的链接则直接使用,否则用标准格式构建
if "checkout.stripe.com" in raw:
stripe_url = raw
else:
stripe_url = f"https://checkout.stripe.com/c/pay/{session_id}"
return session_id, stripe_url
def fetch_publishable_key(session: requests.Session, session_id: str, stripe_checkout_url: str) -> str:
checkout_url = stripe_checkout_url
_log("[2/6] 获取商户密钥 ...")
for acct_id_part, known_pk in KNOWN_PUBLISHABLE_KEYS.items():
try:
url = f"{STRIPE_API}/v1/payment_pages/{session_id}/init"
post_data = {"key": known_pk, "_stripe_version": STRIPE_VERSION_BASE,
"browser_locale": "en-US"}
_log_request("POST", url, data=post_data, tag="[2/6] pk探测")
test_resp = session.post(url, data=post_data, headers=_stripe_headers(), timeout=15)
_log_response(test_resp, tag="[2/6] pk探测")
if test_resp.status_code == 200:
_log(f" 商户密钥已匹配 (缓存命中)")
return known_pk
except Exception as e:
_log(f" 密钥探测异常: {e}")
pk = _fetch_pk_playwright(checkout_url)
if pk:
_log(f" 商户密钥已获取 (浏览器解析)")
return pk
raise RuntimeError("无法提取商户密钥, 请检查支付链接是否有效")
def _fetch_pk_playwright(checkout_url: str) -> str | None:
try:
from playwright.sync_api import sync_playwright
except ImportError:
return None
pk = None
def on_request(request):
nonlocal pk
if pk:
return
if "api.stripe.com" in request.url and "init" in request.url:
post = request.post_data or ""
m = re.search(r"key=(pk_(?:live|test)_[A-Za-z0-9]+)", post)
if m:
pk = m.group(1)
try:
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.on("request", on_request)
try:
page.goto(checkout_url, wait_until="domcontentloaded", timeout=20000)
for _ in range(10):
if pk:
break
page.wait_for_timeout(1000)
except Exception:
pass
browser.close()
except Exception:
return None
return pk
def init_checkout(session: requests.Session, session_id: str, pk: str, locale_profile: dict = None) -> tuple[dict, str, dict]:
"""返回 (init_resp, stripe_ver, ctx) — ctx 包含后续步骤需要的上下文"""
locale_profile = locale_profile or LOCALE_PROFILES["US"]
url = f"{STRIPE_API}/v1/payment_pages/{session_id}/init"
stripe_js_id = str(uuid.uuid4())
elements_session_id = _gen_elements_session_id()
for version in [STRIPE_VERSION_BASE, STRIPE_VERSION_FULL]:
data = {
"browser_locale": locale_profile["browser_locale"],
"browser_timezone": locale_profile["browser_timezone"],
"elements_session_client[elements_init_source]": "custom_checkout",
"elements_session_client[referrer_host]": "chatgpt.com",
"elements_session_client[stripe_js_id]": stripe_js_id,
"elements_session_client[locale]": locale_profile["browser_locale"],
"elements_session_client[is_aggregation_expected]": "false",
"key": pk,
"_stripe_version": version,
}
if version == STRIPE_VERSION_FULL:
data["elements_session_client[client_betas][0]"] = "custom_checkout_server_updates_1"
data["elements_session_client[client_betas][1]"] = "custom_checkout_manual_approval_1"
_log(f" 初始化结账会话 ...")
_log_request("POST", url, data=data, tag="[2b/6] init")
resp = session.post(url, data=data, headers=_stripe_headers())
_log_response(resp, tag="[2b/6] init")
if resp.status_code == 200:
ctx = {
"stripe_js_id": stripe_js_id,
"elements_session_id": elements_session_id,
}
return resp.json(), version, ctx
if resp.status_code == 400 and "beta" in resp.text.lower():
_log(f" 当前API版本不匹配, 切换备用版本 ...")
continue
raise RuntimeError(f"init 失败 [{resp.status_code}]: {resp.text[:500]}")
raise RuntimeError("init 失败: 所有 Stripe API 版本均不可用")
def extract_hcaptcha_config(init_resp: dict) -> dict:
raw = json.dumps(init_resp)
result = {"site_key": HCAPTCHA_SITE_KEY_FALLBACK, "rqdata": ""}
if init_resp.get("site_key"):
result["site_key"] = init_resp["site_key"]
m = re.search(r'"hcaptcha_site_key"\s*:\s*"([^"]+)"', raw)
if m and not init_resp.get("site_key"):
result["site_key"] = m.group(1)
m = re.search(r'"hcaptcha_rqdata"\s*:\s*"([^"]+)"', raw)
if m:
result["rqdata"] = m.group(1)
return result
def fetch_elements_session(
session: requests.Session,
pk: str,
session_id: str,
ctx: dict,
stripe_ver: str = STRIPE_VERSION_FULL,
locale_profile: dict = None,
) -> dict:
"""调用 elements/sessions, 返回响应 dict 并更新 ctx 中的 elements_session_id"""
locale_profile = locale_profile or LOCALE_PROFILES["US"]
locale_short = locale_profile["browser_locale"].split("-")[0] # HAR: "zh" 而非 "zh-CN"
stripe_js_id = ctx.get("stripe_js_id", str(uuid.uuid4()))
url = f"{STRIPE_API}/v1/elements/sessions"
params = {
"client_betas[0]": "custom_checkout_server_updates_1",
"client_betas[1]": "custom_checkout_manual_approval_1",
"deferred_intent[mode]": "subscription",
"deferred_intent[amount]": "0",
"deferred_intent[currency]": "usd",
"deferred_intent[setup_future_usage]": "off_session",
"deferred_intent[payment_method_types][0]": "card",
"currency": "usd",
"key": pk,
"_stripe_version": stripe_ver,
"elements_init_source": "custom_checkout",
"referrer_host": "chatgpt.com",
"stripe_js_id": stripe_js_id,
"locale": locale_short,
"type": "deferred_intent",
"checkout_session_id": session_id,
}
_log(" 获取支付元素会话 ...")
_log_request("GET", url, params=params, tag="[2c] elements/sessions")
resp = session.get(url, params=params, headers=_stripe_headers())
_log_response(resp, tag="[2c] elements/sessions")
if resp.status_code == 200:
data = resp.json()
# 提取真实的 elements_session_id (如果有)
real_es_id = data.get("session_id") or data.get("id")
if real_es_id:
ctx["elements_session_id"] = real_es_id
_log(f" 支付元素会话已建立")
# 提取 config_id
config_id = data.get("config_id")
if config_id:
ctx["config_id"] = config_id
_log(f" 配置标识已获取")
return data
else:
_log(f" 支付元素获取失败 ({resp.status_code}), 使用本地会话继续")
return {}
def lookup_consumer(
session: requests.Session,
pk: str,
email: str,
stripe_ver: str = STRIPE_VERSION_FULL,
):
"""查询 Stripe Link 消费者会话,模拟真实浏览器的两次 lookup"""
url = f"{STRIPE_API}/v1/consumers/sessions/lookup"
surfaces = [
("web_link_authentication_in_payment_element", "default_value"),
("web_elements_controller", "default_value"),
]
for surface, source in surfaces:
data = {
"request_surface": surface,
"email_address": email,
"email_source": source,
"session_id": str(uuid.uuid4()),
"key": pk,
"_stripe_version": stripe_ver,
}
if surface == "web_elements_controller":
data["do_not_log_consumer_funnel_event"] = "true"
try:
_log(f" 查询 Link 消费者信息 ...")
_log_request("POST", url, data=data, tag="[2d] consumer/lookup")
resp = session.post(url, data=data, headers=_stripe_headers(), timeout=10)
_log_response(resp, tag="[2d] consumer/lookup")
except Exception as e:
_log(f" Link 查询异常 (不影响流程): {e}")
time.sleep(random.uniform(0.3, 0.8))
def update_payment_page_address(
session: requests.Session,
pk: str,
session_id: str,
card: dict,
ctx: dict,
stripe_ver: str = STRIPE_VERSION_FULL,
):
"""模拟浏览器逐字段提交地址/税区信息, 共 6 次 POST"""
url = f"{STRIPE_API}/v1/payment_pages/{session_id}"
addr = card.get("address", {})
elements_session_id = ctx.get("elements_session_id", _gen_elements_session_id())
stripe_js_id = ctx.get("stripe_js_id", str(uuid.uuid4()))
# 基础字段 — 每次 update 都要带
base = {
"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]": elements_session_id,
"elements_session_client[stripe_js_id]": stripe_js_id,
"elements_session_client[locale]": "en-US",
"elements_session_client[is_aggregation_expected]": "false",
"client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
"client_attribution_metadata[merchant_integration_additional_elements][1]": "address",
"key": pk,
"_stripe_version": stripe_ver,
}
# HAR 中的逐字段提交顺序: country → (重复一次) → line1 → city → state → postal_code
address_steps = [
{"tax_region[country]": addr.get("country", "US")},
{}, # 重复提交 (无新字段, 模拟用户切换焦点)
{"tax_region[line1]": addr.get("line1", "")},
{"tax_region[city]": addr.get("city", "")},
{"tax_region[state]": addr.get("state", "")},
{"tax_region[postal_code]": addr.get("postal_code", "")},
]
_log(" 开始提交账单地址 ...")
accumulated = {}
for step_idx, new_fields in enumerate(address_steps):
accumulated.update(new_fields)
data = dict(base)
data.update(accumulated)
step_name = list(new_fields.keys())[0].split("]")[-1] if new_fields else "焦点变更"
_log(f" 提交地址字段 {step_idx + 1}/6: {step_name}")
_log_request("POST", url, data=data, tag=f"[2e] update_address({step_idx + 1}/6)")
resp = session.post(url, data=data, headers=_stripe_headers())
_log_response(resp, tag=f"[2e] update_address({step_idx + 1}/6)")
if resp.status_code != 200:
_log(f" 地址字段 {step_idx + 1} 返回 {resp.status_code}, 继续 ...")
# 模拟人类输入间隔 (2-5 秒)
time.sleep(random.uniform(2.0, 4.5))
def send_telemetry(
session: requests.Session,
event_type: str,
session_id: str,
ctx: dict,
):
"""向 r.stripe.com/b 发送遥测事件, 模拟 stripe.js 行为上报"""
url = "https://r.stripe.com/b"
muid = ctx.get("muid", "")
sid = ctx.get("sid", "")
guid = ctx.get("guid", "")
payload = {
"v2": 1,
"tag": event_type,
"src": "js",
"pid": "checkout_" + session_id[:20],
"muid": muid,
"sid": sid,
"guid": guid,
}
headers = {
"User-Agent": USER_AGENT,
"Content-Type": "text/plain;charset=UTF-8",
"Accept": "*/*",
"Origin": "https://js.stripe.com",
"Referer": "https://js.stripe.com/",
}
try:
body = base64.b64encode(json.dumps(payload, separators=(",", ":")).encode()).decode()
session.post(url, data=body, headers=headers, timeout=5)
except Exception:
pass
def send_telemetry_batch(
session: requests.Session,
session_id: str,
ctx: dict,
phase: str = "init",
):
"""按阶段批量发送遥测事件"""
events_map = {
"init": ["checkout.init", "elements.create", "payment_element.mount"],
"address": ["address.update", "address.focus", "address.blur"],
"card_input": ["card.focus", "card.input", "card.blur", "cvc.input"],
"confirm": ["checkout.confirm.start", "payment_method.create", "checkout.confirm.intent"],
"3ds": ["three_ds2.start", "three_ds2.fingerprint", "three_ds2.authenticate"],
"poll": ["checkout.poll", "checkout.complete"],
}
events = events_map.get(phase, [])
for evt in events:
send_telemetry(session, evt, session_id, ctx)
time.sleep(random.uniform(0.05, 0.2))
def submit_apata_fingerprint(
session: requests.Session,
three_ds_server_trans_id: str,
three_ds_method_url: str,
notification_url: str,
locale_profile: dict,
ctx: dict,
):
# 1) POST acs-method.apata.io/v1/houston/method — 提交 threeDSMethodData
_log(" 3DS 设备指纹: 提交认证数据 ...")
method_data = base64.b64encode(json.dumps({
"threeDSServerTransID": three_ds_server_trans_id,
"threeDSMethodNotificationURL": notification_url,
}, separators=(",", ":")).encode()).decode()
try:
method_url = three_ds_method_url or "https://acs-method.apata.io/v1/houston/method"
resp = session.post(
method_url,
data={"threeDSMethodData": method_data},
headers={
"User-Agent": USER_AGENT,
"Content-Type": "application/x-www-form-urlencoded",
"Origin": "https://js.stripe.com",
"Referer": "https://js.stripe.com/",
},
timeout=15,
)
_log(f" 3DS 认证数据已提交 ({resp.status_code})")
except Exception as e:
_log(f" 3DS 认证数据提交异常: {e}")
time.sleep(random.uniform(0.5, 1.0))
# 2) POST acs-method.apata.io/v1/RecordBrowserInfo — 设备指纹上报
_log(" 3DS 设备指纹: 上报浏览器信息 ...")
# 生成 possessionDeviceId (localStorage acsRbaDeviceId 模拟)
possession_device_id = ctx.get("apata_device_id") or str(uuid.uuid4())
ctx["apata_device_id"] = possession_device_id
fp_data = _build_browser_fingerprint(locale_profile)
record_payload = {
"threeDSServerTransID": three_ds_server_trans_id,
"computedValue": hashlib.sha256(os.urandom(32)).hexdigest()[:20],
"possessionDeviceId": possession_device_id,
}
record_payload.update(fp_data)
try:
record_url = "https://acs-method.apata.io/v1/RecordBrowserInfo"
resp = session.post(
record_url,
json=record_payload,
headers={
"User-Agent": USER_AGENT,
"Content-Type": "application/json",
"Origin": "https://acs-method.apata.io",
"Referer": "https://acs-method.apata.io/",
},
timeout=15,
)
_log(f" 浏览器信息已上报 ({resp.status_code})")
except Exception as e:
_log(f" 浏览器信息上报异常: {e}")
time.sleep(random.uniform(0.5, 1.0))
# 3) GET rba.apata.io/xxx.js — 模拟 RBA profile 脚本加载
_log(" 3DS 设备指纹: 加载风控脚本 ...")
rba_session_id = ctx.get("rba_session_id") or str(uuid.uuid4())
ctx["rba_session_id"] = rba_session_id
try:
# HAR 中的 URL 格式: rba.apata.io/<random>.js?<random_param>=<org_id>&<random_param>=<session_id>
rba_script_name = ''.join(random.choices(string.ascii_lowercase + string.digits, k=16)) + ".js"
rba_param1 = ''.join(random.choices(string.ascii_lowercase + string.digits, k=16))
rba_param2 = ''.join(random.choices(string.ascii_lowercase + string.digits, k=16))
rba_url = f"https://rba.apata.io/{rba_script_name}?{rba_param1}={APATA_RBA_ORG_ID}&{rba_param2}={rba_session_id}"
resp = session.get(rba_url, headers={"User-Agent": USER_AGENT}, timeout=10)
_log(f" 风控脚本已加载 ({resp.status_code})")
except Exception as e:
_log(f" 风控脚本加载异常: {e}")
# 4) 模拟 aa.online-metrix.net CONNECT (WebRTC beacon 不可模拟, 仅日志标记)
_log(" WebRTC 信标已跳过 (协议模式不支持)")
# 总等待: 让 Apata 有时间处理指纹结果 (HAR 中这个窗口约 8-12 秒)
wait = random.uniform(5.0, 8.0)
_log(f" 等待指纹处理 ({wait:.1f}s) ...")
time.sleep(wait)
def solve_hcaptcha(captcha_cfg: dict, hcaptcha_config: dict, max_retries: int = 3) -> tuple[str, str]:
"""返回 (token, ekey) 元组"""
api_url = captcha_cfg.get("api_url", "https://api.yescaptcha.com")
client_key = captcha_cfg["api_key"]
site_key = hcaptcha_config["site_key"]
rqdata = hcaptcha_config.get("rqdata", "")
for retry in range(max_retries):
if retry > 0:
_log(f" [重试 {retry + 1}/{max_retries}] 重新发起验证码请求")
_log(f" 正在请求人机验证解题 ...")
# 创建 1 个任务
task_body = {
"type": "HCaptchaTaskProxyless",
"websiteURL": "https://b.stripecdn.com/stripethirdparty-srv/assets/v32.1/HCaptchaInvisible.html",
"websiteKey": site_key,
"isEnterprise": True,
"userAgent": USER_AGENT,
}
create_payload = {"clientKey": client_key, "task": task_body}
try:
create_url = f"{api_url}/createTask"
_log_request("POST", create_url, data=create_payload, tag="[captcha] createTask")
create_resp = requests.post(create_url, json=create_payload, timeout=15)
_log_response(create_resp, tag="[captcha] createTask")
data = create_resp.json()
if data.get("errorId", 1) != 0:
_log(f" 验证码任务创建失败: {data.get('errorDescription', '?')}")
time.sleep(3)
continue
task_id = data["taskId"]
except Exception as e:
_log(f" 验证码任务创建异常: {e}")
time.sleep(3)
continue
_log(f" 验证码任务已创建, 等待平台解题 ...")
for attempt in range(60):
time.sleep(3)
try:
result_url = f"{api_url}/getTaskResult"
result_payload = {"clientKey": client_key, "taskId": task_id}
result_resp = requests.post(result_url, json=result_payload, timeout=10)
result_data = result_resp.json()
except Exception:
continue
if result_data.get("errorId", 0) != 0:
error_code = result_data.get("errorCode", "")
if error_code == "ERROR_TASK_TIMEOUT":
_log(" 验证码解题超时, 重新发起 ...")
break
continue
if result_data.get("status") == "ready":
solution = result_data["solution"]
_log_raw(f" solution keys: {list(solution.keys())}")
_log_raw(f" solution full: {json.dumps(solution, ensure_ascii=False)[:500]}")
token = solution["gRecaptchaResponse"]
# eKey 可能在不同字段名下
ekey = solution.get("eKey", "") or solution.get("respKey", "") or solution.get("ekey", "")
_log(f" 验证码已解决 (token长度: {len(token)})")
_log_raw(f" captcha_token(前100): {token[:100]}...")
if ekey:
_log_raw(f" captcha_ekey(前100): {ekey[:100]}...")
return token, ekey
if attempt % 5 == 4:
_log(f" 解题中, 请耐心等待 ... ({attempt + 1}/60)")
raise RuntimeError(f"人机验证解题失败 (已重试 {max_retries} 轮, 请检查打码平台余额)")
def create_payment_method(
session: requests.Session,
pk: str,
card: dict,
captcha_token: str,
session_id: str,
stripe_ver: str = STRIPE_VERSION_BASE,
ctx: dict = None,
) -> str:
ctx = ctx or {}
guid = ctx.get("guid") or _gen_fingerprint()[0]
muid = ctx.get("muid") or _gen_fingerprint()[0]
sid = ctx.get("sid") or _gen_fingerprint()[0]
addr = card.get("address", {})
data = {
"billing_details[name]": card["name"],
"billing_details[email]": card["email"],
"billing_details[address][country]": addr.get("country", "US"),
"billing_details[address][line1]": addr.get("line1", ""),
"billing_details[address][city]": addr.get("city", ""),
"billing_details[address][postal_code]": addr.get("postal_code", ""),
"billing_details[address][state]": addr.get("state", ""),
"type": "card",
"card[number]": card["number"],
"card[cvc]": card["cvc"],
"card[exp_year]": card["exp_year"],
"card[exp_month]": card["exp_month"],
"allow_redisplay": "unspecified",
"payment_user_agent": "stripe.js/5412f474d5; stripe-js-v3/5412f474d5; payment-element; deferred-intent",
"referrer": "https://chatgpt.com",
# time_on_page: 模拟从页面加载到提交的真实耗时 (HAR: 31368ms / 249421ms)
"time_on_page": str(ctx.get("time_on_page", random.randint(25000, 55000))),
"client_attribution_metadata[client_session_id]": str(uuid.uuid4()),
"client_attribution_metadata[checkout_session_id]": session_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",
"guid": guid,
"muid": muid,
"sid": sid,
"key": pk,
"_stripe_version": stripe_ver,
}
if captcha_token:
data["radar_options[hcaptcha_token]"] = captcha_token
url = f"{STRIPE_API}/v1/payment_methods"
_log("[4/6] 创建支付方式 ...")
_log_request("POST", url, data=data, tag="[4/6] create_payment_method")
resp = session.post(url, data=data, headers=_stripe_headers())
_log_response(resp, tag="[4/6] create_payment_method")
if resp.status_code != 200:
raise RuntimeError(f"创建 payment_method 失败 [{resp.status_code}]: {resp.text[:500]}")
pm = resp.json()
pm_id = pm["id"]
brand = pm.get("card", {}).get("display_brand", "unknown")
last4 = pm.get("card", {}).get("last4", "????")
_log(f" 支付方式创建成功: {brand} ****{last4}")
return pm_id
def confirm_payment(
session: requests.Session,
pk: str,
session_id: str,
pm_id: str,
captcha_token: str,
init_resp: dict,
stripe_ver: str = STRIPE_VERSION_BASE,
captcha_cfg: dict = None,
captcha_ekey: str = "",
ctx: dict = None,
locale_profile: dict = None,
) -> dict:
ctx = ctx or {}
locale_profile = locale_profile or LOCALE_PROFILES["US"]
guid = ctx.get("guid") or _gen_fingerprint()[0]
muid = ctx.get("muid") or _gen_fingerprint()[0]
sid = ctx.get("sid") or _gen_fingerprint()[0]
expected_amount = "0"
line_items = init_resp.get("line_items", [])
if line_items:
total = sum(item.get("amount", 0) for item in line_items)
expected_amount = str(total)
init_checksum = init_resp.get("init_checksum", "")
config_id = init_resp.get("config_id", "")
stripe_js_id = ctx.get("stripe_js_id", str(uuid.uuid4()))
elements_session_id = ctx.get("elements_session_id", _gen_elements_session_id())
checkout_url = init_resp.get("url") or init_resp.get("stripe_hosted_url") or ""
ver = STRIPE_VERSION_FULL
data = {
"guid": guid,
"muid": muid,
"sid": sid,
"payment_method": pm_id,
"expected_amount": expected_amount,
"expected_payment_method_type": "card",