axm0121 commited on
Commit
e2fb2d6
·
verified ·
1 Parent(s): d1eb2d9

Add GoPay extraction flow

Browse files
Files changed (3) hide show
  1. app.py +210 -48
  2. public/index.html +35 -4
  3. tests/test_app.py +121 -0
app.py CHANGED
@@ -129,8 +129,8 @@ STRIPE_INIT_RESOURCE_MISSING_DELAY_MS = env_int(
129
  )
130
  BASE_DIR = Path(__file__).resolve().parent
131
  PUBLIC_DIR = BASE_DIR / "public"
132
- PAYPAL_HOST_SUFFIXES = ("paypal.com", "paypalobjects.com")
133
- IDEAL_HOST_SUFFIXES = ("ideal.nl",)
134
  UPI_HOST_SUFFIXES = ("stripe.com", "stripe.network")
135
  LOG_LEVEL = os.getenv("OPENAI_PAY_LOG_LEVEL", "INFO").strip().upper() or "INFO"
136
  logging.basicConfig(
@@ -370,15 +370,23 @@ BILLING_PROFILES = {
370
  "state": "IST",
371
  "postal_code": "34000",
372
  },
373
- "IN": {
374
- "first_name": "Ravi",
375
- "last_name": "Sharma",
376
- "line1": "221B Nehru Marg",
377
- "city": "New Delhi",
378
- "state": "DL",
379
- "postal_code": "110001",
380
- },
381
- }
 
 
 
 
 
 
 
 
382
  COUNTRY_NAME_SEEDS = [
383
  ("Alex", "Morgan"),
384
  ("Daniel", "Evans"),
@@ -426,6 +434,7 @@ COUNTRY_TIMEZONE = {
426
  "DE": "Europe/Berlin",
427
  "IE": "Europe/Dublin",
428
  "IN": "Asia/Kolkata",
 
429
  "JP": "Asia/Tokyo",
430
  "ZA": "Africa/Johannesburg",
431
  "US": "America/New_York",
@@ -1429,7 +1438,9 @@ def normalize_link_type(link_type: str) -> str:
1429
  "ideal": "ideal",
1430
  "idealpay": "ideal",
1431
  "i-deal": "ideal",
1432
- "upi": "upi",
 
 
1433
  "payment": "paypal",
1434
  "pay": "paypal",
1435
  "long": "paypal",
@@ -1444,11 +1455,15 @@ def stripe_version_for(link_type: str) -> str:
1444
 
1445
 
1446
  def effective_country(req: LongLinkRequest) -> str:
1447
- return supported_country(req.billing_country, "DE")
 
 
1448
 
1449
 
1450
- def effective_pm_country(req: LongLinkRequest) -> str:
1451
- return supported_country(req.pm_country, effective_country(req))
 
 
1452
 
1453
 
1454
  def locale_parts(locale: str) -> tuple[str, str]:
@@ -1813,9 +1828,14 @@ def create_checkout(
1813
  elapsed_ms=elapsed_ms(started),
1814
  url="https://chatgpt.com/backend-api/payments/checkout",
1815
  )
1816
- if response.status_code >= 400:
1817
- detail = http_error_detail("checkout create failed", response)
1818
- log_warning("chatgpt.checkout.error", status_code=response.status_code, detail=detail)
 
 
 
 
 
1819
  raise HTTPException(
1820
  status_code=response.status_code,
1821
  detail=detail,
@@ -2604,6 +2624,9 @@ NON_RETRYABLE_ERROR_MARKERS = (
2604
  "does not offer paypal",
2605
  "does not offer ideal",
2606
  "does not offer upi",
 
 
 
2607
  "payment method is not available",
2608
  "payment_method_not_available",
2609
  "payment_method_unsupported_type",
@@ -2683,6 +2706,7 @@ KNOWN_PAYMENT_METHOD_TYPES = {
2683
  "paypal",
2684
  "ideal",
2685
  "upi",
 
2686
  "google_pay",
2687
  "apple_pay",
2688
  }
@@ -2822,7 +2846,7 @@ def build_stripe_session(req: LongLinkRequest, proxy_override: str = "") -> Any:
2822
  return stripe
2823
 
2824
 
2825
- def stripe_create_payment_method(
2826
  stripe: Any,
2827
  cs_id: str,
2828
  stripe_pk: str,
@@ -2846,9 +2870,22 @@ def stripe_create_payment_method(
2846
  billing_postal_code=billing.get("postal_code") or "",
2847
  currency=ctx.get("currency", ""),
2848
  checkout_amount=ctx.get("checkout_amount", ""),
2849
- )
2850
  hosted_mode = str(ctx.get("checkout_ui_mode") or "").lower() == "hosted"
2851
- if hosted_mode:
 
 
 
 
 
 
 
 
 
 
 
 
 
2852
  body = {
2853
  "billing_details[name]": billing.get("name") or "John Doe",
2854
  "billing_details[email]": billing.get("email") or "buyer@example.com",
@@ -2922,10 +2959,54 @@ def stripe_create_payment_method(
2922
  log_warning("stripe.payment_method.bad_response", detail=detail)
2923
  raise HTTPException(status_code=502, detail=detail)
2924
  log_info("stripe.payment_method.done", payment_method_id=pm_id, response_keys=response_keys(payload))
2925
- return pm_id
2926
-
2927
-
2928
- def stripe_confirm(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2929
  stripe: Any,
2930
  cs_id: str,
2931
  pm_id: str,
@@ -2951,7 +3032,30 @@ def stripe_confirm(
2951
  return_url=return_url,
2952
  mode="hosted" if hosted_mode else "custom",
2953
  )
2954
- if hosted_mode:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2955
  amounts = display_amounts(init_payload)
2956
  body = {
2957
  "eid": "NA",
@@ -3023,7 +3127,7 @@ def stripe_confirm(
3023
  }
3024
  started = time.perf_counter()
3025
  headers = None
3026
- if hosted_mode:
3027
  headers = {
3028
  "Origin": "https://pay.openai.com",
3029
  "Referer": hosted_checkout_referrer(cs_id, init_payload, stripe_hosted_url),
@@ -4530,16 +4634,19 @@ def create_provider_link(
4530
  # server-side can consume time, hide the QR action, or hit app-only URLs.
4531
  provider_url = stripe_redirect_url
4532
  else:
 
 
 
 
 
 
 
 
 
4533
  provider_url = resolve_external_redirect(
4534
  stripe,
4535
  stripe_redirect_url,
4536
- preferred_hosts=(
4537
- PAYPAL_HOST_SUFFIXES
4538
- if link_type == "paypal"
4539
- else IDEAL_HOST_SUFFIXES
4540
- if link_type == "ideal"
4541
- else UPI_HOST_SUFFIXES
4542
- ),
4543
  )
4544
  log_info(
4545
  "provider.create.done",
@@ -5983,7 +6090,7 @@ def build_long_link_response(
5983
  stripe_key_source=stripe_key_source,
5984
  processor_entity=checkout.get("processor_entity", ""),
5985
  )
5986
- if link_type in {"ideal", "paypal", "upi"}:
5987
  # iDEAL must be present at NL bootstrap. PayPal/UPI can be absent
5988
  # before the promotion refresh, so validate them afterwards.
5989
  if link_type == "ideal":
@@ -6055,7 +6162,7 @@ def build_long_link_response(
6055
  except HTTPException as exc:
6056
  fallback = True
6057
  provider_error = provider_error_diagnostic(exc.detail, link_type, checkout, req)
6058
- advance(92, "回退 hosted", "PP 提取失败,返回 hosted 长链")
6059
  log_warning(
6060
  "provider.create.fallback_http_exception",
6061
  status_code=exc.status_code,
@@ -6065,7 +6172,7 @@ def build_long_link_response(
6065
  except Exception as exc:
6066
  fallback = True
6067
  provider_error = provider_error_diagnostic(repr(exc), link_type, checkout, req)
6068
- advance(92, "回退 hosted", "PP 提取异常,返回 hosted 长链")
6069
  log_warning(
6070
  "provider.create.fallback_exception",
6071
  error=provider_error,
@@ -6688,7 +6795,7 @@ def run_long_link_task(task_id: str, req: LongLinkRequest, owner: str) -> None:
6688
  TASK_CANCEL_CHECK.reset(cancel_check_token)
6689
 
6690
 
6691
- def request_for_retry_attempt(req: LongLinkRequest, attempt: int) -> LongLinkRequest:
6692
  config = get_runtime_config()
6693
  run_mode = normalize_run_mode(config["runMode"])
6694
  if run_mode not in {RUN_MODE_SPLIT, RUN_MODE_UIAI_STYLE, RUN_MODE_CHECKOUT_JP_REST_PROVIDER, RUN_MODE_US_CHECKOUT_JP_PAYPAL}:
@@ -6696,6 +6803,7 @@ def request_for_retry_attempt(req: LongLinkRequest, attempt: int) -> LongLinkReq
6696
  link_type = normalize_link_type(req.link_type)
6697
  ideal_mode = link_type == "ideal"
6698
  upi_mode = link_type == "upi"
 
6699
  dynamic_pool = normalize_proxy_pool_mode(req.proxy_pool_mode or config.get("proxyPoolMode")) == "dynamic"
6700
  attempt_index = max(0, attempt - 1)
6701
  fingerprint = access_token_fingerprint(req)
@@ -6742,7 +6850,7 @@ def request_for_retry_attempt(req: LongLinkRequest, attempt: int) -> LongLinkReq
6742
  promotion_country=proxy_country_hint(promotion_proxy),
6743
  )
6744
  return LongLinkRequest(**data)
6745
- if run_mode == RUN_MODE_US_CHECKOUT_JP_PAYPAL:
6746
  base_proxy = select_proxy_from_pool(checkout_candidates, pool_index) or first_proxy_from_pool(req.checkout_proxy)
6747
  shared_proxy = proxy_for_attempt(base_proxy, attempt, "shared", force=dynamic_pool)
6748
  data = req.model_dump(by_alias=True)
@@ -6769,7 +6877,7 @@ def request_for_retry_attempt(req: LongLinkRequest, attempt: int) -> LongLinkReq
6769
  # UPI is country-bound and PayPal should follow its billing profile. iDEAL
6770
  # itself is selected by the NL billing data; forcing the proxy to NL broke
6771
  # routes that had already succeeded through the configured provider lane.
6772
- provider_country = "IN" if upi_mode else (effective_pm_country(req) if not ideal_mode else "")
6773
  provider_source = base_provider_proxy or base_checkout_proxy
6774
  if provider_source and provider_country:
6775
  aligned_provider = proxy_for_required_country(provider_source, provider_country)
@@ -6806,7 +6914,7 @@ def request_for_retry_attempt(req: LongLinkRequest, attempt: int) -> LongLinkReq
6806
  # proxy/SID instead of moving to the Stripe provider lane.
6807
  data["approveProxy"] = checkout_proxy
6808
  data["providerProxy"] = provider_proxy
6809
- if link_type in {"paypal", "upi"}:
6810
  promo_base = first_proxy_from_pool(req.promotion_proxy) or base_checkout_proxy
6811
  promo_seed = proxy_for_attempt(promo_base, attempt, f"{link_type}vn", force=dynamic_pool)
6812
  promotion_proxy = proxy_for_required_country(promo_seed, "VN")
@@ -6920,7 +7028,8 @@ def run_long_link_task_retrying(task_id: str, req: LongLinkRequest, owner: str,
6920
  )
6921
  log_info("api.long_link.retry_attempt.success", attempt=attempt, max_attempts=max_attempts)
6922
  return
6923
- last_error = response.provider_error or "PP 提取失败,已回退 hosted 长链"
 
6924
  log_warning(
6925
  "api.long_link.retry_attempt.fallback",
6926
  attempt=attempt,
@@ -6972,10 +7081,11 @@ def run_long_link_task_retrying(task_id: str, req: LongLinkRequest, owner: str,
6972
  else:
6973
  detail = last_error or "PayPal 提链未成功,未获得支付链接"
6974
  raise HTTPException(status_code=502, detail=detail)
6975
- if normalize_link_type(req.link_type) == "paypal":
 
6976
  raise HTTPException(
6977
  status_code=502,
6978
- detail=last_error or "PayPal 提链未成功,回退链接不作为成功结果",
6979
  )
6980
  if last_attempt:
6981
  last_response = last_response.model_copy(update={"success_attempt": last_attempt})
@@ -7162,10 +7272,62 @@ def start_upi_long_link_task(req: LongLinkRequest, request: Request) -> LongLink
7162
  "cancel_requested": False,
7163
  }
7164
  cleanup_tasks_locked()
7165
- launch_long_link_task_worker(task_id, req, user["username"], user["role"])
7166
- return LongLinkTaskStartResponse(ok=True, task_id=task_id)
7167
-
7168
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7169
  @app.get("/api/long-link-task/{task_id}", response_model=LongLinkTaskStatusResponse)
7170
  def get_long_link_task(task_id: str, request: Request) -> LongLinkTaskStatusResponse:
7171
  with TASK_LOCK:
 
129
  )
130
  BASE_DIR = Path(__file__).resolve().parent
131
  PUBLIC_DIR = BASE_DIR / "public"
132
+ PAYPAL_HOST_SUFFIXES = ("paypal.com", "paypalobjects.com")
133
+ IDEAL_HOST_SUFFIXES = ("ideal.nl",)
134
  UPI_HOST_SUFFIXES = ("stripe.com", "stripe.network")
135
  LOG_LEVEL = os.getenv("OPENAI_PAY_LOG_LEVEL", "INFO").strip().upper() or "INFO"
136
  logging.basicConfig(
 
370
  "state": "IST",
371
  "postal_code": "34000",
372
  },
373
+ "IN": {
374
+ "first_name": "Ravi",
375
+ "last_name": "Sharma",
376
+ "line1": "221B Nehru Marg",
377
+ "city": "New Delhi",
378
+ "state": "DL",
379
+ "postal_code": "110001",
380
+ },
381
+ "ID": {
382
+ "first_name": "Budi",
383
+ "last_name": "Santoso",
384
+ "line1": "Jl. Jend. Sudirman No. 1",
385
+ "city": "Jakarta",
386
+ "state": "DKI Jakarta",
387
+ "postal_code": "10210",
388
+ },
389
+ }
390
  COUNTRY_NAME_SEEDS = [
391
  ("Alex", "Morgan"),
392
  ("Daniel", "Evans"),
 
434
  "DE": "Europe/Berlin",
435
  "IE": "Europe/Dublin",
436
  "IN": "Asia/Kolkata",
437
+ "ID": "Asia/Jakarta",
438
  "JP": "Asia/Tokyo",
439
  "ZA": "Africa/Johannesburg",
440
  "US": "America/New_York",
 
1438
  "ideal": "ideal",
1439
  "idealpay": "ideal",
1440
  "i-deal": "ideal",
1441
+ "upi": "upi",
1442
+ "gopy": "gopay",
1443
+ "gopay": "gopay",
1444
  "payment": "paypal",
1445
  "pay": "paypal",
1446
  "long": "paypal",
 
1455
 
1456
 
1457
  def effective_country(req: LongLinkRequest) -> str:
1458
+ if normalize_link_type(req.link_type) == "gopay":
1459
+ return "ID"
1460
+ return supported_country(req.billing_country, "DE")
1461
 
1462
 
1463
+ def effective_pm_country(req: LongLinkRequest) -> str:
1464
+ if normalize_link_type(req.link_type) == "gopay":
1465
+ return "ID"
1466
+ return supported_country(req.pm_country, effective_country(req))
1467
 
1468
 
1469
  def locale_parts(locale: str) -> tuple[str, str]:
 
1828
  elapsed_ms=elapsed_ms(started),
1829
  url="https://chatgpt.com/backend-api/payments/checkout",
1830
  )
1831
+ if response.status_code >= 400:
1832
+ detail = http_error_detail("checkout create failed", response)
1833
+ if normalize_link_type(req.link_type) == "gopay" and "cannot combine currencies" in str(detail).lower():
1834
+ detail = (
1835
+ "GoPay 需要 IDR Checkout,但当前 Stripe customer 已存在 USD Checkout/订阅状态;"
1836
+ "请更换新账号,或等待原 USD Checkout 状态失效。"
1837
+ )
1838
+ log_warning("chatgpt.checkout.error", status_code=response.status_code, detail=detail)
1839
  raise HTTPException(
1840
  status_code=response.status_code,
1841
  detail=detail,
 
2624
  "does not offer paypal",
2625
  "does not offer ideal",
2626
  "does not offer upi",
2627
+ "does not offer gopay",
2628
+ "cannot combine currencies",
2629
+ "gopay 需要 idr checkout",
2630
  "payment method is not available",
2631
  "payment_method_not_available",
2632
  "payment_method_unsupported_type",
 
2706
  "paypal",
2707
  "ideal",
2708
  "upi",
2709
+ "gopay",
2710
  "google_pay",
2711
  "apple_pay",
2712
  }
 
2846
  return stripe
2847
 
2848
 
2849
+ def stripe_create_payment_method(
2850
  stripe: Any,
2851
  cs_id: str,
2852
  stripe_pk: str,
 
2870
  billing_postal_code=billing.get("postal_code") or "",
2871
  currency=ctx.get("currency", ""),
2872
  checkout_amount=ctx.get("checkout_amount", ""),
2873
+ )
2874
  hosted_mode = str(ctx.get("checkout_ui_mode") or "").lower() == "hosted"
2875
+ if payment_method_type == "gopay":
2876
+ body = {
2877
+ "billing_details[name]": billing.get("name") or "Budi Santoso",
2878
+ "billing_details[email]": billing.get("email") or "buyer@example.com",
2879
+ "billing_details[address][country]": billing.get("country") or "ID",
2880
+ "billing_details[address][line1]": billing.get("line1") or "Jl. Jend. Sudirman No. 1",
2881
+ "billing_details[address][city]": billing.get("city") or "Jakarta",
2882
+ "billing_details[address][postal_code]": billing.get("postal_code") or "10210",
2883
+ "billing_details[address][state]": billing.get("state") or "DKI Jakarta",
2884
+ "type": "gopay",
2885
+ "client_attribution_metadata[checkout_session_id]": cs_id,
2886
+ "key": stripe_pk,
2887
+ }
2888
+ elif hosted_mode:
2889
  body = {
2890
  "billing_details[name]": billing.get("name") or "John Doe",
2891
  "billing_details[email]": billing.get("email") or "buyer@example.com",
 
2959
  log_warning("stripe.payment_method.bad_response", detail=detail)
2960
  raise HTTPException(status_code=502, detail=detail)
2961
  log_info("stripe.payment_method.done", payment_method_id=pm_id, response_keys=response_keys(payload))
2962
+ return pm_id
2963
+
2964
+
2965
+ def stripe_init_gopay_checksum(
2966
+ stripe: Any,
2967
+ cs_id: str,
2968
+ stripe_pk: str,
2969
+ req: LongLinkRequest,
2970
+ ) -> str:
2971
+ browser_locale, elements_locale = locale_parts(req.payment_locale)
2972
+ body = {
2973
+ "browser_locale": browser_locale,
2974
+ "browser_timezone": "Asia/Shanghai",
2975
+ "elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
2976
+ "elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
2977
+ "elements_session_client[elements_init_source]": "custom_checkout",
2978
+ "elements_session_client[referrer_host]": "chatgpt.com",
2979
+ "elements_session_client[stripe_js_id]": str(uuid.uuid4()),
2980
+ "elements_session_client[locale]": elements_locale,
2981
+ "elements_session_client[is_aggregation_expected]": "false",
2982
+ "key": stripe_pk,
2983
+ }
2984
+ started = time.perf_counter()
2985
+ response = stripe.post(
2986
+ f"https://api.stripe.com/v1/payment_pages/{cs_id}/init",
2987
+ data=body,
2988
+ timeout=DEFAULT_TIMEOUT,
2989
+ )
2990
+ log_info(
2991
+ "stripe.gopay_init.http",
2992
+ status_code=response.status_code,
2993
+ elapsed_ms=elapsed_ms(started),
2994
+ url=f"https://api.stripe.com/v1/payment_pages/{cs_id}/init",
2995
+ )
2996
+ if response.status_code >= 400:
2997
+ detail = http_error_detail("stripe gopay init failed", response)
2998
+ log_warning("stripe.gopay_init.error", status_code=response.status_code, detail=detail)
2999
+ raise HTTPException(status_code=response.status_code, detail=detail)
3000
+ payload = response.json() or {}
3001
+ checksum = str(payload.get("init_checksum") or "").strip()
3002
+ if not checksum:
3003
+ detail = f"stripe gopay init missing init_checksum: keys={response_keys(payload)}"
3004
+ log_warning("stripe.gopay_init.missing_checksum", detail=detail)
3005
+ raise HTTPException(status_code=502, detail=detail)
3006
+ return checksum
3007
+
3008
+
3009
+ def stripe_confirm(
3010
  stripe: Any,
3011
  cs_id: str,
3012
  pm_id: str,
 
3032
  return_url=return_url,
3033
  mode="hosted" if hosted_mode else "custom",
3034
  )
3035
+ if payment_method_type == "gopay":
3036
+ init_checksum = stripe_init_gopay_checksum(stripe, cs_id, stripe_pk, req)
3037
+ body = {
3038
+ "guid": uuid.uuid4().hex,
3039
+ "muid": uuid.uuid4().hex,
3040
+ "sid": uuid.uuid4().hex,
3041
+ "payment_method": pm_id,
3042
+ "init_checksum": init_checksum,
3043
+ "version": "fed52f3bc6",
3044
+ "expected_amount": "0",
3045
+ "expected_payment_method_type": "gopay",
3046
+ "return_url": return_url,
3047
+ "elements_session_client[session_id]": f"elements_session_{uuid.uuid4().hex[:11]}",
3048
+ "elements_session_client[locale]": locale_parts(req.payment_locale)[1],
3049
+ "elements_session_client[referrer_host]": "chatgpt.com",
3050
+ "elements_session_client[is_aggregation_expected]": "false",
3051
+ "client_attribution_metadata[client_session_id]": str(uuid.uuid4()),
3052
+ "client_attribution_metadata[merchant_integration_source]": "elements",
3053
+ "client_attribution_metadata[merchant_integration_subtype]": "payment-element",
3054
+ "client_attribution_metadata[payment_intent_creation_flow]": "deferred",
3055
+ "consent[terms_of_service]": "accepted",
3056
+ "key": stripe_pk,
3057
+ }
3058
+ elif hosted_mode:
3059
  amounts = display_amounts(init_payload)
3060
  body = {
3061
  "eid": "NA",
 
3127
  }
3128
  started = time.perf_counter()
3129
  headers = None
3130
+ if hosted_mode and payment_method_type != "gopay":
3131
  headers = {
3132
  "Origin": "https://pay.openai.com",
3133
  "Referer": hosted_checkout_referrer(cs_id, init_payload, stripe_hosted_url),
 
4634
  # server-side can consume time, hide the QR action, or hit app-only URLs.
4635
  provider_url = stripe_redirect_url
4636
  else:
4637
+ preferred_hosts = (
4638
+ PAYPAL_HOST_SUFFIXES
4639
+ if link_type == "paypal"
4640
+ else IDEAL_HOST_SUFFIXES
4641
+ if link_type == "ideal"
4642
+ else UPI_HOST_SUFFIXES
4643
+ if link_type == "upi"
4644
+ else ()
4645
+ )
4646
  provider_url = resolve_external_redirect(
4647
  stripe,
4648
  stripe_redirect_url,
4649
+ preferred_hosts=preferred_hosts,
 
 
 
 
 
 
4650
  )
4651
  log_info(
4652
  "provider.create.done",
 
6090
  stripe_key_source=stripe_key_source,
6091
  processor_entity=checkout.get("processor_entity", ""),
6092
  )
6093
+ if link_type in {"ideal", "paypal", "upi", "gopay"}:
6094
  # iDEAL must be present at NL bootstrap. PayPal/UPI can be absent
6095
  # before the promotion refresh, so validate them afterwards.
6096
  if link_type == "ideal":
 
6162
  except HTTPException as exc:
6163
  fallback = True
6164
  provider_error = provider_error_diagnostic(exc.detail, link_type, checkout, req)
6165
+ advance(92, "回退 hosted", f"{link_type.upper()} 提取失败,返回 hosted 长链")
6166
  log_warning(
6167
  "provider.create.fallback_http_exception",
6168
  status_code=exc.status_code,
 
6172
  except Exception as exc:
6173
  fallback = True
6174
  provider_error = provider_error_diagnostic(repr(exc), link_type, checkout, req)
6175
+ advance(92, "回退 hosted", f"{link_type.upper()} 提取异常,返回 hosted 长链")
6176
  log_warning(
6177
  "provider.create.fallback_exception",
6178
  error=provider_error,
 
6795
  TASK_CANCEL_CHECK.reset(cancel_check_token)
6796
 
6797
 
6798
+ def request_for_retry_attempt(req: LongLinkRequest, attempt: int) -> LongLinkRequest:
6799
  config = get_runtime_config()
6800
  run_mode = normalize_run_mode(config["runMode"])
6801
  if run_mode not in {RUN_MODE_SPLIT, RUN_MODE_UIAI_STYLE, RUN_MODE_CHECKOUT_JP_REST_PROVIDER, RUN_MODE_US_CHECKOUT_JP_PAYPAL}:
 
6803
  link_type = normalize_link_type(req.link_type)
6804
  ideal_mode = link_type == "ideal"
6805
  upi_mode = link_type == "upi"
6806
+ gopay_mode = link_type == "gopay"
6807
  dynamic_pool = normalize_proxy_pool_mode(req.proxy_pool_mode or config.get("proxyPoolMode")) == "dynamic"
6808
  attempt_index = max(0, attempt - 1)
6809
  fingerprint = access_token_fingerprint(req)
 
6850
  promotion_country=proxy_country_hint(promotion_proxy),
6851
  )
6852
  return LongLinkRequest(**data)
6853
+ if run_mode == RUN_MODE_US_CHECKOUT_JP_PAYPAL and link_type == "paypal":
6854
  base_proxy = select_proxy_from_pool(checkout_candidates, pool_index) or first_proxy_from_pool(req.checkout_proxy)
6855
  shared_proxy = proxy_for_attempt(base_proxy, attempt, "shared", force=dynamic_pool)
6856
  data = req.model_dump(by_alias=True)
 
6877
  # UPI is country-bound and PayPal should follow its billing profile. iDEAL
6878
  # itself is selected by the NL billing data; forcing the proxy to NL broke
6879
  # routes that had already succeeded through the configured provider lane.
6880
+ provider_country = "IN" if upi_mode else "ID" if gopay_mode else (effective_pm_country(req) if not ideal_mode else "")
6881
  provider_source = base_provider_proxy or base_checkout_proxy
6882
  if provider_source and provider_country:
6883
  aligned_provider = proxy_for_required_country(provider_source, provider_country)
 
6914
  # proxy/SID instead of moving to the Stripe provider lane.
6915
  data["approveProxy"] = checkout_proxy
6916
  data["providerProxy"] = provider_proxy
6917
+ if link_type in {"paypal", "upi", "gopay"}:
6918
  promo_base = first_proxy_from_pool(req.promotion_proxy) or base_checkout_proxy
6919
  promo_seed = proxy_for_attempt(promo_base, attempt, f"{link_type}vn", force=dynamic_pool)
6920
  promotion_proxy = proxy_for_required_country(promo_seed, "VN")
 
7028
  )
7029
  log_info("api.long_link.retry_attempt.success", attempt=attempt, max_attempts=max_attempts)
7030
  return
7031
+ link_label = normalize_link_type(req.link_type).upper()
7032
+ last_error = response.provider_error or f"{link_label} 提取失败,已回退 hosted 长链"
7033
  log_warning(
7034
  "api.long_link.retry_attempt.fallback",
7035
  attempt=attempt,
 
7081
  else:
7082
  detail = last_error or "PayPal 提链未成功,未获得支付链接"
7083
  raise HTTPException(status_code=502, detail=detail)
7084
+ failed_link_type = normalize_link_type(req.link_type)
7085
+ if failed_link_type in {"paypal", "gopay"}:
7086
  raise HTTPException(
7087
  status_code=502,
7088
+ detail=last_error or f"{failed_link_type.upper()} 提链未成功,回退链接不作为成功结果",
7089
  )
7090
  if last_attempt:
7091
  last_response = last_response.model_copy(update={"success_attempt": last_attempt})
 
7272
  "cancel_requested": False,
7273
  }
7274
  cleanup_tasks_locked()
7275
+ launch_long_link_task_worker(task_id, req, user["username"], user["role"])
7276
+ return LongLinkTaskStartResponse(ok=True, task_id=task_id)
7277
+
7278
+
7279
+ @app.post("/api/gopay-long-link-task", response_model=LongLinkTaskStartResponse)
7280
+ def start_gopay_long_link_task(req: LongLinkRequest, request: Request) -> LongLinkTaskStartResponse:
7281
+ user = link_request_user(req, request, consume_cdk=False)
7282
+ if user.get("role") == "cdk":
7283
+ raise HTTPException(status_code=403, detail="CDK only supports iDEAL extraction")
7284
+ req = apply_runtime_defaults(req)
7285
+ checkout_proxy = checkout_stage_proxy(req)
7286
+ provider_proxy = proxy_with_region(provider_stage_proxy(req) or checkout_proxy, "ID")
7287
+ req = req.model_copy(
7288
+ update={
7289
+ "link_type": "gopay",
7290
+ "billing_country": "ID",
7291
+ "pm_country": "ID",
7292
+ "checkout_ui_mode": "custom",
7293
+ "checkout_proxy": checkout_proxy,
7294
+ "approve_proxy": checkout_proxy,
7295
+ "provider_proxy": provider_proxy,
7296
+ }
7297
+ )
7298
+ task_id = f"gpy_{uuid.uuid4().hex[:12]}"
7299
+ token_fingerprint = access_token_fingerprint(req)
7300
+ with TASK_LOCK:
7301
+ active_task_id = active_task_for_token_locked(token_fingerprint)
7302
+ if active_task_id:
7303
+ raise HTTPException(status_code=409, detail=f"当前 token 已有任务运行:{active_task_id},请先停止或等待结束")
7304
+ TASKS[task_id] = {
7305
+ "task_id": task_id,
7306
+ "status": "queued",
7307
+ "progress": 1,
7308
+ "stage": "queued",
7309
+ "message": "GoPay task created",
7310
+ "created_at": time.time(),
7311
+ "updated_at": time.time(),
7312
+ "elapsed_ms": 0,
7313
+ "result": None,
7314
+ "result_expires_at": 0,
7315
+ "error": "",
7316
+ "logs": [],
7317
+ "probe_results": [],
7318
+ "log_seq": 0,
7319
+ "paused": False,
7320
+ "owner": user["username"],
7321
+ "owner_role": user["role"],
7322
+ "request_payload": task_request_metadata(req),
7323
+ "token_fingerprint": token_fingerprint,
7324
+ "cancel_requested": False,
7325
+ }
7326
+ cleanup_tasks_locked()
7327
+ launch_long_link_task_worker(task_id, req, user["username"], user["role"])
7328
+ return LongLinkTaskStartResponse(ok=True, task_id=task_id)
7329
+
7330
+
7331
  @app.get("/api/long-link-task/{task_id}", response_model=LongLinkTaskStatusResponse)
7332
  def get_long_link_task(task_id: str, request: Request) -> LongLinkTaskStatusResponse:
7333
  with TASK_LOCK:
public/index.html CHANGED
@@ -3870,6 +3870,7 @@
3870
  <option value="ideal">iDEAL 荷兰链接</option>
3871
  <option value="paypal">PayPal 链</option>
3872
  <option value="upi" data-admin-option>UPI 印度链接</option>
 
3873
  </select>
3874
  </div>
3875
  <div class="wb-submit-row">
@@ -4448,8 +4449,8 @@
4448
  const zero = Boolean(item.zero_offer ?? item.zeroOffer);
4449
  const methods = Array.isArray(item.payment_methods) ? item.payment_methods : [];
4450
  const methodText = methods.length
4451
- ? methods.filter((method) => ["paypal", "ideal", "upi"].includes(String(method))).map((method) => String(method).toUpperCase()).join("/") || "无目标支付方式"
4452
- : `${item.paypal ? "PayPal 可用" : "无 PayPal"}${item.upi ? " / UPI" : ""}${item.ideal ? " / iDEAL" : ""}`;
4453
  const detail = ok
4454
  ? `${methodText} · ${item.provider || "-"}`
4455
  : (item.error || "探测失败");
@@ -4880,7 +4881,7 @@
4880
  return String(error.detail.active_task_id);
4881
  }
4882
  const text = error instanceof Error ? error.message : String(error || "");
4883
- const match = text.match(/\b(?:llt|ilt|upi|prb)_[a-f0-9]{12}\b/i);
4884
  return match ? match[0] : "";
4885
  }
4886
 
@@ -4987,6 +4988,33 @@
4987
  };
4988
  }
4989
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4990
  function normalizedGlobalProbeCountries() {
4991
  const values = [];
4992
  const seen = new Set();
@@ -5213,7 +5241,7 @@
5213
  }
5214
 
5215
  function workbenchTypeLabel(type) {
5216
- return { ideal: "iDEAL · NL", paypal: "PayPal", upi: "UPI · IN" }[type] || type || "iDEAL · NL";
5217
  }
5218
 
5219
  function workbenchIdealProviderUrl(result) {
@@ -5383,6 +5411,8 @@
5383
  ? buildPayload(accessToken)
5384
  : normalizedType === "upi"
5385
  ? buildUpiPayload(accessToken)
 
 
5386
  : buildIdealPayload(accessToken);
5387
  payload.cdk = isAdmin() ? "" : workbenchReadCdk();
5388
  return payload;
@@ -5391,6 +5421,7 @@
5391
  function workbenchEndpoint(type) {
5392
  if (type === "paypal") return "/api/long-link-task";
5393
  if (type === "upi") return "/api/upi-long-link-task";
 
5394
  return "/api/ideal-long-link-task";
5395
  }
5396
 
 
3870
  <option value="ideal">iDEAL 荷兰链接</option>
3871
  <option value="paypal">PayPal 链</option>
3872
  <option value="upi" data-admin-option>UPI 印度链接</option>
3873
+ <option value="gopay" data-admin-option>GoPay 印尼链接</option>
3874
  </select>
3875
  </div>
3876
  <div class="wb-submit-row">
 
4449
  const zero = Boolean(item.zero_offer ?? item.zeroOffer);
4450
  const methods = Array.isArray(item.payment_methods) ? item.payment_methods : [];
4451
  const methodText = methods.length
4452
+ ? methods.filter((method) => ["paypal", "ideal", "upi", "gopay"].includes(String(method))).map((method) => String(method).toUpperCase()).join("/") || "无目标支付方式"
4453
+ : `${item.paypal ? "PayPal 可用" : "无 PayPal"}${item.upi ? " / UPI" : ""}${item.ideal ? " / iDEAL" : ""}${item.gopay ? " / GoPay" : ""}`;
4454
  const detail = ok
4455
  ? `${methodText} · ${item.provider || "-"}`
4456
  : (item.error || "探测失败");
 
4881
  return String(error.detail.active_task_id);
4882
  }
4883
  const text = error instanceof Error ? error.message : String(error || "");
4884
+ const match = text.match(/\b(?:llt|ilt|upi|gpy|prb)_[a-f0-9]{12}\b/i);
4885
  return match ? match[0] : "";
4886
  }
4887
 
 
4988
  };
4989
  }
4990
 
4991
+ function buildGopayPayload(accessToken) {
4992
+ const config = isAdmin() ? readAdminRuntimeConfig() : runtimeConfig;
4993
+ const pools = activeProxyPools(config);
4994
+ const jp = pools.jp;
4995
+ const us = pools.us;
4996
+ const plan = proxyPlanForMode(config.runMode || "uiai-style", jp, us);
4997
+ return {
4998
+ accessToken,
4999
+ cdk: isAdmin() ? "" : readCdkInput(),
5000
+ link_type: "gopay",
5001
+ proxyPoolMode: config.proxyPoolMode || "dynamic",
5002
+ proxy: "",
5003
+ checkoutProxy: config.checkoutProxy || plan.checkout,
5004
+ approveProxy: config.approveProxy || plan.approve,
5005
+ providerProxy: config.providerProxy || plan.provider,
5006
+ promotionProxy: config.idealPromoProxy || "",
5007
+ billing_country: "ID",
5008
+ pmCountry: "ID",
5009
+ checkout_ui_mode: "custom",
5010
+ payment_locale: config.paymentLocale || "en",
5011
+ autoProbe: false,
5012
+ stripe_publishable_key: "",
5013
+ device_id: "",
5014
+ user_agent: "",
5015
+ };
5016
+ }
5017
+
5018
  function normalizedGlobalProbeCountries() {
5019
  const values = [];
5020
  const seen = new Set();
 
5241
  }
5242
 
5243
  function workbenchTypeLabel(type) {
5244
+ return { ideal: "iDEAL · NL", paypal: "PayPal", upi: "UPI · IN", gopay: "GoPay · ID" }[type] || type || "iDEAL · NL";
5245
  }
5246
 
5247
  function workbenchIdealProviderUrl(result) {
 
5411
  ? buildPayload(accessToken)
5412
  : normalizedType === "upi"
5413
  ? buildUpiPayload(accessToken)
5414
+ : normalizedType === "gopay"
5415
+ ? buildGopayPayload(accessToken)
5416
  : buildIdealPayload(accessToken);
5417
  payload.cdk = isAdmin() ? "" : workbenchReadCdk();
5418
  return payload;
 
5421
  function workbenchEndpoint(type) {
5422
  if (type === "paypal") return "/api/long-link-task";
5423
  if (type === "upi") return "/api/upi-long-link-task";
5424
+ if (type === "gopay") return "/api/gopay-long-link-task";
5425
  return "/api/ideal-long-link-task";
5426
  }
5427
 
tests/test_app.py CHANGED
@@ -226,6 +226,127 @@ class PaymentFlowTests(unittest.TestCase):
226
  with self.assertRaises(HTTPException):
227
  app.require_payment_method_available({"payment_method_types": ["card"]}, "ideal")
228
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  def test_approval_blocked_is_terminal_and_bounded(self):
230
  session = FakeApproveSession(["blocked", "approved", "approved"])
231
  with self.assertRaises(HTTPException) as caught:
 
226
  with self.assertRaises(HTTPException):
227
  app.require_payment_method_available({"payment_method_types": ["card"]}, "ideal")
228
 
229
+ def test_gopay_normalization_and_explicit_availability(self):
230
+ payload = {
231
+ "payment_method_types": ["card"],
232
+ "payment_method_specs": [{"type": "gopay"}],
233
+ }
234
+
235
+ self.assertEqual(app.normalize_link_type("gopy"), "gopay")
236
+ self.assertEqual(app.normalize_link_type(" GoPay "), "gopay")
237
+ self.assertIn("gopay", app.available_payment_method_types(payload))
238
+ self.assertTrue(app.payment_method_is_available(payload, "gopy"))
239
+ app.require_payment_method_available(payload, "gopay")
240
+
241
+ def test_gopay_forces_effective_billing_and_payment_method_country_to_id(self):
242
+ req = app.LongLinkRequest(
243
+ accessToken="token-value",
244
+ link_type="gopy",
245
+ billing_country="US",
246
+ pmCountry="NL",
247
+ )
248
+
249
+ self.assertEqual(app.effective_country(req), "ID")
250
+ self.assertEqual(app.effective_pm_country(req), "ID")
251
+
252
+ def test_gopay_payment_method_uses_minimal_payload(self):
253
+ stripe = FakeStripeSession([{"id": "pm_gopay_test"}])
254
+ billing = {
255
+ "name": "Budi Santoso",
256
+ "email": "budi@example.com",
257
+ "country": "ID",
258
+ "line1": "Jl. Jend. Sudirman No. 1",
259
+ "city": "Jakarta",
260
+ "postal_code": "10210",
261
+ "state": "DKI Jakarta",
262
+ }
263
+
264
+ pm_id = app.stripe_create_payment_method(
265
+ stripe,
266
+ "cs_gopay_test",
267
+ "pk_test_value",
268
+ billing,
269
+ "gopay",
270
+ {"checkout_ui_mode": "custom", "currency": "idr", "checkout_amount": "0"},
271
+ )
272
+
273
+ self.assertEqual(pm_id, "pm_gopay_test")
274
+ url, kwargs = stripe.calls[0]
275
+ self.assertEqual(url, "https://api.stripe.com/v1/payment_methods")
276
+ self.assertEqual(
277
+ kwargs["data"],
278
+ {
279
+ "billing_details[name]": "Budi Santoso",
280
+ "billing_details[email]": "budi@example.com",
281
+ "billing_details[address][country]": "ID",
282
+ "billing_details[address][line1]": "Jl. Jend. Sudirman No. 1",
283
+ "billing_details[address][city]": "Jakarta",
284
+ "billing_details[address][postal_code]": "10210",
285
+ "billing_details[address][state]": "DKI Jakarta",
286
+ "type": "gopay",
287
+ "client_attribution_metadata[checkout_session_id]": "cs_gopay_test",
288
+ "key": "pk_test_value",
289
+ },
290
+ )
291
+ self.assertIsNone(kwargs["headers"])
292
+
293
+ def test_gopay_confirm_fetches_fresh_checksum_and_uses_special_payload(self):
294
+ stripe = FakeStripeSession(
295
+ [
296
+ {"init_checksum": "fresh-gopay-checksum"},
297
+ {"setup_intent": {"status": "requires_action"}},
298
+ ]
299
+ )
300
+ req = app.LongLinkRequest(
301
+ accessToken="token-value",
302
+ link_type="gopay",
303
+ billing_country="US",
304
+ pmCountry="NL",
305
+ checkout_ui_mode="custom",
306
+ paymentLocale="en",
307
+ )
308
+ ctx = {
309
+ "init_checksum": "stale-context-checksum",
310
+ "checkout_amount": "999",
311
+ "checkout_ui_mode": "custom",
312
+ }
313
+
314
+ app.stripe_confirm(
315
+ stripe,
316
+ "cs_gopay_test",
317
+ "pm_gopay_test",
318
+ "pk_test_value",
319
+ "gopay",
320
+ {"init_checksum": "stale-payload-checksum", "total_summary": {"due": 999}},
321
+ ctx,
322
+ {"billing_country": "ID", "processor_entity": "openai_ie"},
323
+ req,
324
+ "https://checkout.stripe.com/c/pay/cs_gopay_test",
325
+ )
326
+
327
+ init_url, init_kwargs = stripe.calls[0]
328
+ self.assertEqual(init_url, "https://api.stripe.com/v1/payment_pages/cs_gopay_test/init")
329
+ self.assertEqual(init_kwargs["data"]["browser_timezone"], "Asia/Shanghai")
330
+ self.assertEqual(init_kwargs["data"]["elements_session_client[elements_init_source]"], "custom_checkout")
331
+ self.assertEqual(init_kwargs["data"]["key"], "pk_test_value")
332
+
333
+ confirm_url, confirm_kwargs = stripe.calls[1]
334
+ confirm_body = confirm_kwargs["data"]
335
+ self.assertEqual(confirm_url, "https://api.stripe.com/v1/payment_pages/cs_gopay_test/confirm")
336
+ self.assertEqual(confirm_body["payment_method"], "pm_gopay_test")
337
+ self.assertEqual(confirm_body["init_checksum"], "fresh-gopay-checksum")
338
+ self.assertEqual(confirm_body["version"], "fed52f3bc6")
339
+ self.assertEqual(confirm_body["expected_amount"], "0")
340
+ self.assertEqual(confirm_body["expected_payment_method_type"], "gopay")
341
+ self.assertEqual(confirm_body["client_attribution_metadata[merchant_integration_source]"], "elements")
342
+ self.assertEqual(confirm_body["client_attribution_metadata[payment_intent_creation_flow]"], "deferred")
343
+ self.assertEqual(confirm_body["consent[terms_of_service]"], "accepted")
344
+ self.assertEqual(confirm_body["key"], "pk_test_value")
345
+ self.assertNotIn("_stripe_version", confirm_body)
346
+ self.assertNotIn("stale-context-checksum", confirm_body.values())
347
+ self.assertNotIn("stale-payload-checksum", confirm_body.values())
348
+ self.assertIsNone(confirm_kwargs["headers"])
349
+
350
  def test_approval_blocked_is_terminal_and_bounded(self):
351
  session = FakeApproveSession(["blocked", "approved", "approved"])
352
  with self.assertRaises(HTTPException) as caught: