File size: 7,878 Bytes
3ec0f02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from __future__ import annotations
import base64
import importlib.util
import json
import sys
import uuid
from typing import Any


def protocol_runtime_missing() -> list[str]:
 missing=[]
 for name in ("stripe_checkout","provider_checkout","ph_short_extractor"):
  if importlib.util.find_spec(name) is None:missing.append(name)
 try:
  import app as runtime_app
  if not callable(getattr(runtime_app,"sentinel_headers",None)):missing.append("app.sentinel_headers")
 except Exception:missing.append("app.sentinel_headers")
 return missing

RUNTIME_MISSING=protocol_runtime_missing()
protocol=None
if not RUNTIME_MISSING:
 import ph_checkout_protocol as protocol

UA="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:144.0) Gecko/20100101 Firefox/144.0"
def emit(message:str,level:str="info",phase:str="")->None:print(json.dumps({"type":"log","level":level,"message":message,"phase":phase},ensure_ascii=True),flush=True)
def saved_methods(snapshot:dict[str,Any])->list[str]:
 proxy=protocol.normalize_proxy(str(snapshot.get("proxy") or snapshot.get("checkout_proxy") or ""));http=protocol.build_identity_http(proxy,str(snapshot.get("user_agent") or UA));did=str(snapshot.get("checkout_device_id") or uuid.uuid4());protocol.install_cookies(http,dict(snapshot.get("session_cookies") or {}),did);aid=str(snapshot.get("chatgpt_account_id") or "")
 headers={"Authorization":f"Bearer {str(snapshot.get('access_token') or '')}","ChatGPT-Account-Id":aid,"OAI-Device-Id":did,"User-Agent":str(snapshot.get("user_agent") or UA),"Accept":"application/json","Origin":"https://chatgpt.com","Referer":"https://chatgpt.com/"}
 r=http.get("https://chatgpt.com/backend-api/payments/payment_methods",params={"account_id":aid},headers=headers,timeout=45)
 if r.status_code in {401,403}:raise RuntimeError(f"AT_INVALID_OR_EXPIRED: HTTP {r.status_code}")
 if r.status_code!=200:raise RuntimeError(f"PAYMENT_METHOD_QUERY_FAILED: HTTP {r.status_code}")
 try:b=r.json()
 except Exception as exc:raise RuntimeError("PAYMENT_METHOD_QUERY_NON_JSON") from exc
 items=b if isinstance(b,list) else ((b.get("data") or b.get("payment_methods") or []) if isinstance(b,dict) else [])
 return [str(x.get("id") or "") for x in items if isinstance(x,dict) and str(x.get("id") or "").startswith("pm_")]
def prepare(snapshot:dict[str,Any],proxies:list[str])->dict[str,Any]:
 last="";snapshot.setdefault("user_agent",UA)
 requested_method=str(snapshot.get("saved_payment_method_id") or "").strip()
 if requested_method and not requested_method.startswith("pm_"):raise ValueError("INVALID_PAYMENT_METHOD")
 for index,candidate in enumerate(proxies[:3],1):
  a=dict(snapshot);a["proxy"]=candidate;a["checkout_proxy"]=candidate
  if not (bool(snapshot.get("preserve_checkout_identity")) and index==1):a["checkout_device_id"]=str(uuid.uuid4());a["checkout_chatgpt_session_id"]=""
  else:emit(f"Reusing original Checkout identity: {str(snapshot.get('context_source') or 'context_store')}",phase="validate")
  try:
   emit(f"Preparing saved card route {index}/{min(3,len(proxies))}",phase="validate");methods=saved_methods(a)
   if not methods:raise RuntimeError("NO_SAVED_PAYMENT_METHOD: bind a card first")
   selected_method=requested_method or methods[0]
   if selected_method not in methods:raise RuntimeError("SAVED_PAYMENT_METHOD_ACCOUNT_MISMATCH: selected card is not attached to this account")
   proxy=protocol.normalize_proxy(candidate);http=protocol.build_identity_http(proxy,str(a.get("user_agent") or UA));did=str(a.get("checkout_device_id") or uuid.uuid4());protocol.install_cookies(http,dict(a.get("session_cookies") or {}),did)
   processor=str(a.get("processor_entity") or "openai_llc");session_id=str(a.get("checkout_session_id") or "")
   state=protocol.resolve_oaics_checkout(http,a,processor,session_id,did);pk=str(state.get("publishable_key") or "");amount,currency=protocol.oaics_total(state)
   stripe=protocol.build_stripe_http(proxy,str(a.get("user_agent") or UA));ctx=protocol.fetch_deferred_elements(stripe,state,session_id,str(a.get("user_agent") or UA))
   checkout_methods=list(ctx.get("customer_payment_method_ids") or [])
   if selected_method not in checkout_methods:raise RuntimeError("SAVED_PAYMENT_METHOD_CONTEXT_MISMATCH: selected card is not attached to this Checkout customer")
   billing=protocol.default_billing("PH",str(a.get("email") or ""),real_random=True)
   tax_state=protocol.submit_checkout_taxes(http,a,processor,session_id,did,billing,currency)
   if tax_state:state={**state,**tax_state};pk=str(state.get("publishable_key") or pk);amount,currency=protocol.oaics_total(state)
   protocol.update_saved_payment_method_billing(stripe,pk,selected_method,billing,ctx,str(a.get("user_agent") or UA))
   ctx=protocol.fetch_deferred_elements(stripe,state,session_id,str(a.get("user_agent") or UA))
   if selected_method not in list(ctx.get("customer_payment_method_ids") or []):raise RuntimeError("SAVED_PAYMENT_METHOD_CONTEXT_CHANGED: selected card disappeared after billing refresh")
   emit(f"Checkout customer/card context matched: customer={str(ctx.get('customer_id') or '')[-6:]} pm={selected_method[-6:]}",phase="validate")
   ctoken=protocol.create_confirmation_token(stripe,pk,selected_method,str(state.get("confirm_return_url") or ""),setup_only=(amount==0),elements_context=ctx,user_agent=str(a.get("user_agent") or UA))
   emit("Saved PaymentMethod, taxes, billing and ConfirmationToken are prepared",phase="prepared")
   pp={"short_url":a.get("short_url"),"processor_entity":processor,"checkout_session_id":session_id,"access_token":a.get("access_token"),"chatgpt_account_id":a.get("chatgpt_account_id"),"session_cookies":a.get("session_cookies") or {},"user_agent":a.get("user_agent") or UA,"checkout_device_id":a.get("checkout_device_id"),"checkout_chatgpt_session_id":a.get("checkout_chatgpt_session_id"),"email":a.get("email"),"proxy":candidate,"proxies":[candidate],"saved_payment_method_id":selected_method,"confirmation_token":ctoken,"card_retry_count":0,"card_retry_delay":1,"prepared_checkout_state":state,"prepared_elements_context":ctx,"prepared_amount":amount,"prepared_currency":currency,"preserve_checkout_identity":True}
   return {"status":"prepared","prepared":{"protocol_payload":pp},"safe":{"amount":amount,"currency":currency.upper(),"saved_payment_method_count":len(methods),"selected_payment_method":True,"route_attempt":index}}
  except Exception as exc:last=f"{type(exc).__name__}: {exc}";emit(f"Preparation route {index} failed: {last}","warn","validate")
 raise RuntimeError(last or "PREPARE_FAILED")
def confirm(prepared:dict[str,Any])->dict[str,Any]:
 pp=dict(prepared.get("protocol_payload") or {})
 if not pp or not str(pp.get("confirmation_token") or "").startswith("ctoken_"):raise ValueError("PREPARED_CONTEXT_INVALID")
 emit("Barrier released; submitting subscription now",phase="protocol");result=dict(protocol.run(pp) or {});result.update({"flow":"batch_saved_card_protocol","account_email":str(pp.get("email") or ""),"checkout_url":str(pp.get("short_url") or "")});return result
def main()->int:
 if RUNTIME_MISSING:raise RuntimeError("PROTOCOL_RUNTIME_DEPENDENCY_MISSING: "+", ".join(RUNTIME_MISSING))
 payload=json.loads(sys.stdin.read() or "{}");mode=str(payload.get("mode") or "run").lower()
 if mode=="prepare":result=prepare(dict(payload.get("snapshot") or {}),list(payload.get("proxies") or []))
 elif mode=="confirm":result=confirm(dict(payload.get("prepared") or {}))
 else:
  pre=prepare(dict(payload.get("snapshot") or {}),list(payload.get("proxies") or []));result=confirm(dict(pre.get("prepared") or {}))
 print(json.dumps({"type":"result","result":result},ensure_ascii=True),flush=True);return 0
if __name__=="__main__":
 try:raise SystemExit(main())
 except Exception as exc:print(json.dumps({"type":"error","error":f"{type(exc).__name__}: {exc}"},ensure_ascii=True),flush=True);raise SystemExit(1)