axm0121 commited on
Commit
702fa4e
·
verified ·
1 Parent(s): 3c47eb3

Deploy migrated UPI GoPay and iDEAL provider flows

Browse files
Files changed (7) hide show
  1. .hfignore +20 -0
  2. README.md +17 -40
  3. app.py +760 -159
  4. deploy/openai-pay-pp.service +0 -22
  5. deploy/zz-safe-runtime.conf +0 -7
  6. requirements.txt +1 -0
  7. tests/test_app.py +0 -1069
.hfignore ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .git/
2
+ .agents/
3
+ .env
4
+ .venv/
5
+ .pytest_cache/
6
+ __pycache__/
7
+ *.py[cod]
8
+ *.sqlite3
9
+ *.sqlite3-*
10
+ .invite-create-cache/
11
+ *.log
12
+ *.bak*
13
+ *.zip
14
+ .coverage
15
+ tests/
16
+ deploy/
17
+ artifacts/
18
+ task_plan.md
19
+ findings.md
20
+ progress.md
README.md CHANGED
@@ -8,37 +8,33 @@ app_port: 7860
8
  suggested_hardware: cpu-basic
9
  ---
10
 
11
- # OpenAI Pay Link Panel?????
12
 
13
- ????????CDK ????iDEAL?PayPal?UPI??????????????????? PP/UPI ?????????????
14
 
15
- ## ????
16
 
17
- - ?? Checkout ? approve ???????????? 3 ??`blocked` ???????????? 100 ???3000 ??????
18
- - Checkout ? approve ????????? URL/SID??????????? Checkout ??? SID?
19
- - Provider ????????PayPal ?? PM ???UPI ?? IN?iDEAL ???????????? Provider ?????????? NL?
20
- - Stripe ?????PayPal/iDEAL ?????? `2025-03-31.basil`?UPI ???? `2026-06-24.dahlia`?
21
- - ?? UPI `upi_handle_redirect_or_display_qr_code`?hosted instructions ? QR PNG/SVG URL?
22
- - Stripe redirect ?????? 3 ??UPI confirm ??? 60 ??
23
- - ?? Checkout ? `generic_decline/setup_attempt_failed` ????????? CS ????????? CS/? SID ??????
24
- - ???? Stripe ?????????????????????? `payment_method_types_mismatch`?
25
- - ????????????????? PayPal/iDEAL/UPI ????
26
- - CDK ???? `X-CDK` ?????????????????????????? Token/CDK/?????
27
 
28
- ????? [`docs/AUDIT.md`](docs/AUDIT.md)?
29
 
30
- ## ????
 
 
 
 
 
 
31
 
32
  ```bash
33
  python -m venv .venv
34
  . .venv/bin/activate
35
  pip install -r requirements.txt
36
- cp .env.example .env
37
- set -a; . ./.env; set +a
38
  uvicorn app:app --host 127.0.0.1 --port 8796
39
  ```
40
 
41
- Windows PowerShell?
42
 
43
  ```powershell
44
  python -m venv .venv
@@ -48,28 +44,9 @@ $env:APP_PASSWORD = "change-me"
48
  uvicorn app:app --host 127.0.0.1 --port 8796
49
  ```
50
 
51
- ## ??
52
 
53
  ```bash
54
- python -m py_compile app.py
55
- python -m unittest discover -s tests -v
56
  ```
57
-
58
- ## ??
59
-
60
- 1. ? `.env.example` ??? root ????????
61
- 2. ?? `deploy/openai-pay-pp.service`?
62
- 3. ????????? `deploy/zz-safe-runtime.conf`????? approve ???
63
- 4. ?? Nginx/Caddy ?? HTTPS?Uvicorn ????????
64
-
65
- ```bash
66
- sudo systemctl daemon-reload
67
- sudo systemctl enable --now openai-pay-pp
68
- ```
69
-
70
- ## PP / UPI ????
71
-
72
- - Checkout ????? 0??? Stripe init ???????????
73
- - PayPal ????? Processor/???? SetupIntent???????? `generic_decline` ??????
74
- - UPI ?? INR/IN PM?IN Provider ??? Stripe schema?????? hosted QR/instructions ??
75
- - `0 ?`?`??????`?`OpenAI approve ??`?`Stripe/Provider ????`?????????
 
8
  suggested_hardware: cpu-basic
9
  ---
10
 
11
+ # OpenAI Pay Link Panel
12
 
13
+ 基于 FastAPI 的支付提链面板,支持 PayPal、UPI、GoPay 与 iDEAL,并提供同步接口、异步任务、重试和管理后台。
14
 
15
+ ## Hugging Face Spaces
16
 
17
+ 项目使用 Docker SDK,容器监听 `0.0.0.0:7860`,健康检查地址为 `/api/health`。
 
 
 
 
 
 
 
 
 
18
 
19
+ 建议在 Space Settings 中配置:
20
 
21
+ - Secret:`APP_PASSWORD`
22
+ - 可选 Secret:`APP_API_KEY`、各阶段带凭据的代理配置
23
+ - Variable:`APP_USERNAME`(默认 `admin`)、`OPENAI_PAY_LOG_LEVEL`
24
+
25
+ 数据库路径为 `/data/auth.sqlite3`。需要跨重建保留用户、CDK、Session 和运行配置时,请为 Space 启用 `/data` Persistent Storage。
26
+
27
+ ## 本地运行
28
 
29
  ```bash
30
  python -m venv .venv
31
  . .venv/bin/activate
32
  pip install -r requirements.txt
33
+ export APP_PASSWORD="change-me"
 
34
  uvicorn app:app --host 127.0.0.1 --port 8796
35
  ```
36
 
37
+ Windows PowerShell:
38
 
39
  ```powershell
40
  python -m venv .venv
 
44
  uvicorn app:app --host 127.0.0.1 --port 8796
45
  ```
46
 
47
+ ## 验证
48
 
49
  ```bash
50
+ python -m compileall -q app.py tests
51
+ python -m pytest -q
52
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -3,8 +3,9 @@
3
  import contextvars
4
  import base64
5
  import binascii
6
- import hashlib
7
- import json
 
8
  import logging
9
  import os
10
  import random
@@ -20,7 +21,8 @@ from threading import Event, Lock, Thread, local
20
  from typing import Any
21
  from urllib.parse import parse_qsl, quote, unquote, urlencode, urljoin, urlsplit, urlunsplit
22
 
23
- import requests
 
24
  from fastapi import FastAPI, HTTPException, Request
25
  from fastapi.responses import FileResponse, JSONResponse, Response
26
  from fastapi.staticfiles import StaticFiles
@@ -705,7 +707,9 @@ class LongLinkRequest(BaseModel):
705
  device_id: str = ""
706
  user_agent: str = ""
707
  auto_probe: bool = Field(True, alias="autoProbe")
708
- probe_countries: str = Field("", alias="probeCountries")
 
 
709
 
710
 
711
  class LongLinkResponse(BaseModel):
@@ -726,6 +730,16 @@ class LongLinkResponse(BaseModel):
726
  stripe_hosted_url: str
727
  long_url: str
728
  ideal_qr_url: str = ""
 
 
 
 
 
 
 
 
 
 
729
  success_attempt: int = 0
730
 
731
 
@@ -1151,6 +1165,16 @@ def proxy_for_required_country(proxy: Any, country: str) -> str:
1151
  the proxy used for that stage.
1152
  """
1153
  return normalize_proxy_url(str(proxy or ""))
 
 
 
 
 
 
 
 
 
 
1154
 
1155
 
1156
  def proxy_without_sid(proxy: Any) -> str:
@@ -1643,15 +1667,35 @@ def stripe_version_for(link_type: str) -> str:
1643
  return STRIPE_VERSION_FULL
1644
 
1645
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1646
  def effective_country(req: LongLinkRequest) -> str:
1647
- if normalize_link_type(req.link_type) == "gopay":
1648
- return "ID"
 
1649
  return supported_checkout_country(req.billing_country, "DE")
1650
 
1651
 
1652
  def effective_pm_country(req: LongLinkRequest) -> str:
1653
- if normalize_link_type(req.link_type) == "gopay":
1654
- return "ID"
 
1655
  return supported_checkout_country(req.pm_country, effective_country(req))
1656
 
1657
 
@@ -2278,8 +2322,8 @@ def stripe_init(
2278
  "supply stripe_publishable_key or configure the matching processor environment variable"
2279
  ),
2280
  )
2281
- browser_locale, elements_locale = locale_parts(req.payment_locale)
2282
- browser_timezone = timezone_for_country(effective_country(req))
2283
  proxy_override = normalize_proxy_url(proxy_override)
2284
  log_info(
2285
  "stripe.init.start",
@@ -2464,12 +2508,17 @@ def stripe_confirm_return_url(cs_id: str, checkout: dict[str, Any], stripe_hoste
2464
  checkout["billing_country"],
2465
  checkout.get("processor_entity", ""),
2466
  )
2467
- if "pay.openai.com/" in hosted_url or "checkout.stripe.com/" in hosted_url:
2468
- parsed = urlsplit(hosted_url)
2469
- query = dict(parse_qsl(parsed.query, keep_blank_values=True))
2470
- query.setdefault("redirect_pm_type", payment_method_type)
2471
- query.setdefault("lid", "".join(random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") for _ in range(24)))
2472
- query.setdefault("ui_mode", "hosted")
 
 
 
 
 
2473
  query.setdefault(
2474
  "success_return_url",
2475
  chatgpt_success_return_url(
@@ -3060,7 +3109,7 @@ def require_payment_method_available(payload: Any, link_type: str) -> None:
3060
 
3061
 
3062
  def stripe_context(cs_id: str, init_payload: dict[str, Any], req: LongLinkRequest) -> dict[str, Any]:
3063
- _, elements_locale = locale_parts(req.payment_locale)
3064
  checkout_ui_mode = (req.checkout_ui_mode or "custom").strip() or "custom"
3065
  return {
3066
  "stripe_js_id": str(uuid.uuid4()),
@@ -3163,9 +3212,13 @@ def stripe_create_payment_method(
3163
  ctx: dict[str, Any],
3164
  init_payload: dict[str, Any] | None = None,
3165
  stripe_hosted_url: str = "",
3166
- ) -> str:
3167
- payment_method_type = normalize_link_type(payment_method_type)
3168
- runtime_version = str(ctx.get("runtime_version") or DEFAULT_STRIPE_RUNTIME_VERSION)
 
 
 
 
3169
  log_info(
3170
  "stripe.payment_method.start",
3171
  route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
@@ -3179,35 +3232,9 @@ def stripe_create_payment_method(
3179
  currency=ctx.get("currency", ""),
3180
  checkout_amount=ctx.get("checkout_amount", ""),
3181
  )
3182
- hosted_mode = str(ctx.get("checkout_ui_mode") or "").lower() == "hosted"
3183
- if payment_method_type == "upi":
3184
- body = {
3185
- "billing_details[name]": billing.get("name") or "Aisha Sharma",
3186
- "billing_details[email]": billing.get("email") or "buyer@example.com",
3187
- "billing_details[address][country]": billing.get("country") or "IN",
3188
- "billing_details[address][line1]": billing.get("line1") or "24 Park Street",
3189
- "billing_details[address][city]": billing.get("city") or "Kolkata",
3190
- "billing_details[address][postal_code]": billing.get("postal_code") or "700016",
3191
- "type": "upi",
3192
- "client_attribution_metadata[checkout_session_id]": cs_id,
3193
- "key": stripe_pk,
3194
- }
3195
- if billing.get("state"):
3196
- body["billing_details[address][state]"] = billing["state"]
3197
- elif payment_method_type == "gopay":
3198
- body = {
3199
- "billing_details[name]": billing.get("name") or "Budi Santoso",
3200
- "billing_details[email]": billing.get("email") or "buyer@example.com",
3201
- "billing_details[address][country]": billing.get("country") or "ID",
3202
- "billing_details[address][line1]": billing.get("line1") or "Jl. Jend. Sudirman No. 1",
3203
- "billing_details[address][city]": billing.get("city") or "Jakarta",
3204
- "billing_details[address][postal_code]": billing.get("postal_code") or "10210",
3205
- "billing_details[address][state]": billing.get("state") or "DKI Jakarta",
3206
- "type": "gopay",
3207
- "client_attribution_metadata[checkout_session_id]": cs_id,
3208
- "key": stripe_pk,
3209
- }
3210
- elif hosted_mode:
3211
  body = {
3212
  "billing_details[name]": billing.get("name") or "John Doe",
3213
  "billing_details[email]": billing.get("email") or "buyer@example.com",
@@ -3253,11 +3280,21 @@ def stripe_create_payment_method(
3253
  "client_attribution_metadata[payment_method_selection_flow]": "automatic",
3254
  "client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
3255
  "client_attribution_metadata[merchant_integration_additional_elements][1]": "address",
3256
- "key": stripe_pk,
3257
  "_stripe_version": str(ctx.get("stripe_version") or stripe_version_for(payment_method_type)),
3258
- }
3259
- started = time.perf_counter()
3260
- headers = None
 
 
 
 
 
 
 
 
 
 
3261
  if hosted_mode:
3262
  headers = {
3263
  "Origin": "https://pay.openai.com",
@@ -3290,10 +3327,10 @@ def stripe_init_gopay_checksum(
3290
  stripe_pk: str,
3291
  req: LongLinkRequest,
3292
  ) -> str:
3293
- browser_locale, elements_locale = locale_parts(req.payment_locale)
3294
  body = {
3295
  "browser_locale": browser_locale,
3296
- "browser_timezone": "Asia/Shanghai",
3297
  "elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
3298
  "elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
3299
  "elements_session_client[elements_init_source]": "custom_checkout",
@@ -3339,11 +3376,16 @@ def stripe_confirm(
3339
  checkout: dict[str, Any],
3340
  req: LongLinkRequest,
3341
  stripe_hosted_url: str,
3342
- ) -> dict[str, Any]:
3343
- payment_method_type = normalize_link_type(payment_method_type)
3344
- return_url = stripe_confirm_return_url(cs_id, checkout, stripe_hosted_url, payment_method_type)
 
 
 
 
3345
  runtime_version = str(ctx.get("runtime_version") or DEFAULT_STRIPE_RUNTIME_VERSION)
3346
- hosted_mode = str(ctx.get("checkout_ui_mode") or "").lower() == "hosted"
 
3347
  log_info(
3348
  "stripe.confirm.start",
3349
  route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
@@ -3362,20 +3404,35 @@ def stripe_confirm(
3362
  "sid": uuid.uuid4().hex,
3363
  "payment_method": pm_id,
3364
  "init_checksum": init_checksum,
3365
- "version": "fed52f3bc6",
3366
- "expected_amount": "0",
3367
  "expected_payment_method_type": "gopay",
3368
  "return_url": return_url,
3369
- "elements_session_client[session_id]": f"elements_session_{uuid.uuid4().hex[:11]}",
3370
- "elements_session_client[locale]": locale_parts(req.payment_locale)[1],
3371
  "elements_session_client[referrer_host]": "chatgpt.com",
3372
  "elements_session_client[is_aggregation_expected]": "false",
3373
- "client_attribution_metadata[client_session_id]": str(uuid.uuid4()),
3374
- "client_attribution_metadata[merchant_integration_source]": "elements",
 
 
 
 
 
 
 
 
 
 
3375
  "client_attribution_metadata[merchant_integration_subtype]": "payment-element",
 
3376
  "client_attribution_metadata[payment_intent_creation_flow]": "deferred",
 
 
 
3377
  "consent[terms_of_service]": "accepted",
3378
  "key": stripe_pk,
 
3379
  }
3380
  elif hosted_mode:
3381
  amounts = display_amounts(init_payload)
@@ -3439,9 +3496,7 @@ def stripe_confirm(
3439
  "client_attribution_metadata[elements_session_config_id]": ctx["elements_session_config_id"],
3440
  "client_attribution_metadata[merchant_integration_source]": "checkout",
3441
  "client_attribution_metadata[merchant_integration_subtype]": "payment-element",
3442
- "client_attribution_metadata[merchant_integration_version]": (
3443
- "custom_checkout" if payment_method_type == "upi" else "custom"
3444
- ),
3445
  "client_attribution_metadata[payment_intent_creation_flow]": "deferred",
3446
  "client_attribution_metadata[payment_method_selection_flow]": "automatic",
3447
  "client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
@@ -3450,8 +3505,6 @@ def stripe_confirm(
3450
  "key": stripe_pk,
3451
  "_stripe_version": str(ctx.get("stripe_version") or stripe_version_for(payment_method_type)),
3452
  }
3453
- if payment_method_type == "upi":
3454
- body["link_brand"] = "link"
3455
  started = time.perf_counter()
3456
  headers = None
3457
  if hosted_mode and payment_method_type != "gopay":
@@ -3485,7 +3538,11 @@ def stripe_confirm(
3485
  "stripe.confirm.done",
3486
  response_keys=response_keys(payload),
3487
  interesting_fields=interesting_payload_fields(payload),
3488
- has_redirect=bool(extract_redirect_to_url(payload)),
 
 
 
 
3489
  submission_state=submission_state,
3490
  checkout_status=payload.get("status", "") if isinstance(payload, dict) else "",
3491
  checkout_state=payload.get("state", "") if isinstance(payload, dict) else "",
@@ -3608,7 +3665,7 @@ def next_action_from_payload(payload: Any) -> dict[str, Any]:
3608
  action = payload.get("next_action")
3609
  if isinstance(action, dict):
3610
  return action
3611
- for key in ("setup_intent", "payment_intent"):
3612
  nested = payload.get(key)
3613
  found = next_action_from_payload(nested)
3614
  if found:
@@ -3653,6 +3710,26 @@ def extract_redirect_to_url(payload: Any) -> str:
3653
  if found:
3654
  return found
3655
  return extract_action_url(action)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3656
 
3657
 
3658
  def stripe_intent_state(payload: Any) -> dict[str, str]:
@@ -3729,10 +3806,18 @@ def stripe_payment_page_redirect_url(
3729
  ctx: dict[str, Any] | None = None,
3730
  timeout_seconds: float = 30,
3731
  max_attempts: int = STRIPE_REDIRECT_POLL_MAX_ATTEMPTS,
3732
- ) -> str:
3733
- deadline = time.time() + max(1.0, float(timeout_seconds or 30))
 
 
 
 
 
 
 
3734
  # Provider actions can appear shortly after ChatGPT approval. Poll a small,
3735
- # bounded number of times; never fan out concurrent requests for one CS ID.
 
3736
  max_attempts = max(1, min(int(max_attempts or 1), STRIPE_REDIRECT_POLL_MAX_ATTEMPTS))
3737
  pool_workers = min(max(1, STRIPE_REDIRECT_POLL_WORKERS), max_attempts)
3738
  sequential = True
@@ -3742,8 +3827,9 @@ def stripe_payment_page_redirect_url(
3742
  "stripe.redirect_poll.start",
3743
  route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
3744
  cs_id=cs_id,
3745
- timeout_seconds=timeout_seconds,
3746
- max_attempts=max_attempts,
 
3747
  pool_workers=1 if sequential else pool_workers,
3748
  reuse_context=bool(ctx),
3749
  poll_proxy_pool_count=len(poll_proxies),
@@ -3801,10 +3887,10 @@ def stripe_payment_page_redirect_url(
3801
  "poll_proxy_count": len(poll_proxies),
3802
  "poll_proxy_label": redact_proxy(poll_proxy),
3803
  }
3804
- duration = elapsed_ms(started)
3805
- if response.status_code == 200:
3806
- payload = response.json() or {}
3807
- redirect_url = extract_redirect_to_url(payload)
3808
  intent_state = stripe_intent_state(payload)
3809
  terminal_error = stripe_terminal_intent_error(payload)
3810
  return {
@@ -3839,12 +3925,19 @@ def stripe_payment_page_redirect_url(
3839
  TASK_LOG_CALLBACK.reset(callback_token)
3840
  REQUEST_ID.reset(request_token)
3841
 
3842
- if sequential:
3843
- completed = 0
3844
- terminal_errors = 0
3845
- for attempt in range(1, max_attempts + 1):
3846
- if time.time() >= deadline:
3847
- break
 
 
 
 
 
 
 
3848
  item = poll_once(attempt)
3849
  completed += 1
3850
  status_code = int(item.get("status_code") or 0)
@@ -3919,9 +4012,11 @@ def stripe_payment_page_redirect_url(
3919
  raise HTTPException(status_code=402, detail=terminal_error)
3920
  else:
3921
  last_err = str(item.get("detail") or last_err)
3922
- if attempt < max_attempts:
3923
- time.sleep(1)
3924
- if completed >= max_attempts:
 
 
3925
  detail = f"redirect url resolution stopped after {completed} sequential attempts: {last_err}"
3926
  log_warning(
3927
  "stripe.redirect_poll.max_attempts",
@@ -4081,7 +4176,216 @@ def stripe_payment_page_redirect_url(
4081
  raise HTTPException(status_code=504, detail=detail)
4082
 
4083
 
4084
- def approve_request(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4085
  session: Any,
4086
  cs_id: str,
4087
  processor_entity: str,
@@ -4717,6 +5021,86 @@ def chatgpt_approve(
4717
  raise HTTPException(status_code=502, detail=detail)
4718
 
4719
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4720
  def redirect_url_after_confirm(
4721
  chatgpt: Any,
4722
  stripe: Any,
@@ -4727,10 +5111,16 @@ def redirect_url_after_confirm(
4727
  init_payload: dict[str, Any],
4728
  ctx: dict[str, Any],
4729
  checkout: dict[str, Any],
4730
- req: LongLinkRequest,
4731
- stripe_hosted_url: str,
4732
- ) -> str:
4733
- redirect_url = extract_redirect_to_url(confirm_payload)
 
 
 
 
 
 
4734
  if redirect_url:
4735
  log_info("provider.redirect.after_confirm", source="confirm_payload", redirect_url=redirect_url)
4736
  return redirect_url
@@ -4745,8 +5135,11 @@ def redirect_url_after_confirm(
4745
  intent_decline_code=intent_state.get("decline_code", ""),
4746
  )
4747
  raise HTTPException(status_code=402, detail=terminal_error)
4748
- submission = confirm_payload.get("submission_attempt") if isinstance(confirm_payload, dict) else None
4749
- approval_reason = checkout_approval_reason(confirm_payload)
 
 
 
4750
  if approval_reason:
4751
  log_info(
4752
  "provider.redirect.requires_approval",
@@ -4755,9 +5148,17 @@ def redirect_url_after_confirm(
4755
  checkout_status=confirm_payload.get("status", "") if isinstance(confirm_payload, dict) else "",
4756
  checkout_state=confirm_payload.get("state", "") if isinstance(confirm_payload, dict) else "",
4757
  )
4758
- upi_mode = normalize_link_type(req.link_type) == "upi"
4759
- approve_proxy = provider_stage_proxy(req) if upi_mode else approve_stage_proxy(req)
4760
- apply_approve_proxy(chatgpt, approve_proxy)
 
 
 
 
 
 
 
 
4761
  runtime_config = get_runtime_config()
4762
  approve_pool_mode = normalize_proxy_pool_mode(req.proxy_pool_mode or runtime_config.get("proxyPoolMode"))
4763
  approve_pool = approve_proxy_pool_for_request(req) if approve_pool_mode == "sticky" else None
@@ -4768,14 +5169,24 @@ def redirect_url_after_confirm(
4768
  pool_count=len(approve_pool or []),
4769
  per_proxy=APPROVE_STICKY_PER_PROXY_CONCURRENCY,
4770
  )
4771
- chatgpt_approve(chatgpt, cs_id, checkout, approve_pool=approve_pool)
 
 
4772
  log_info(
4773
  "provider.redirect.poll_after_approval",
4774
  stripe_route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
4775
  approve_route="approve_proxy" if approve_proxy else "direct",
4776
- )
4777
  try:
4778
- return stripe_payment_page_redirect_url(stripe, cs_id, stripe_pk, req, ctx, timeout_seconds=45)
 
 
 
 
 
 
 
 
4779
  except HTTPException as exc:
4780
  if not upi_mode or exc.status_code not in {502, 504}:
4781
  raise
@@ -4829,7 +5240,15 @@ def redirect_url_after_confirm(
4829
  submission_state=submission.get("state") if isinstance(submission, dict) else "",
4830
  response_keys=response_keys(confirm_payload),
4831
  )
4832
- return stripe_payment_page_redirect_url(stripe, cs_id, stripe_pk, req, ctx, timeout_seconds=30)
 
 
 
 
 
 
 
 
4833
 
4834
 
4835
  def resolve_external_redirect(
@@ -4904,6 +5323,107 @@ def resolve_external_redirect(
4904
  return current
4905
 
4906
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4907
  def create_provider_link(
4908
  chatgpt: Any,
4909
  checkout: dict[str, Any],
@@ -4911,9 +5431,10 @@ def create_provider_link(
4911
  stripe_hosted_url: str,
4912
  req: LongLinkRequest,
4913
  provider_proxy: str = "",
4914
- ) -> dict[str, str]:
4915
  link_type = normalize_link_type(req.link_type)
4916
- require_payment_method_available(init_payload, link_type)
 
4917
  stripe_pk = str(checkout.get("stripe_publishable_key") or req.stripe_publishable_key).strip()
4918
  if not stripe_pk:
4919
  raise HTTPException(status_code=422, detail="provider stage missing resolved Stripe publishable key")
@@ -4924,9 +5445,11 @@ def create_provider_link(
4924
  cs_id=checkout.get("cs_id", ""),
4925
  provider_proxy_configured=bool(provider_proxy),
4926
  provider_proxy=provider_proxy,
4927
- )
4928
- stripe = build_stripe_session(req, proxy_override=provider_proxy)
4929
- log_info("stripe.prepare.skip", reason="use_zip_provider_flow")
 
 
4930
  log_info("stripe.pre_confirm.skip", reason="use_zip_provider_flow")
4931
  ctx = stripe_context(checkout["cs_id"], init_payload, req)
4932
  log_info(
@@ -4993,6 +5516,29 @@ def create_provider_link(
4993
  req,
4994
  stripe_hosted_url,
4995
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4996
  stripe_redirect_url = redirect_url_after_confirm(
4997
  chatgpt,
4998
  stripe,
@@ -5007,18 +5553,14 @@ def create_provider_link(
5007
  stripe_hosted_url,
5008
  )
5009
  action_type = next_action_type(confirm_payload)
5010
- if link_type == "upi" and action_type == "upi_handle_redirect_or_display_qr_code":
5011
- # This is already Stripe's hosted QR/instructions page. Following it
5012
- # server-side can consume time, hide the QR action, or hit app-only URLs.
5013
  provider_url = stripe_redirect_url
5014
  else:
5015
  preferred_hosts = (
5016
  PAYPAL_HOST_SUFFIXES
5017
  if link_type == "paypal"
5018
- else IDEAL_HOST_SUFFIXES
5019
- if link_type == "ideal"
5020
- else UPI_HOST_SUFFIXES
5021
- if link_type == "upi"
5022
  else ()
5023
  )
5024
  provider_url = resolve_external_redirect(
@@ -5026,6 +5568,18 @@ def create_provider_link(
5026
  stripe_redirect_url,
5027
  preferred_hosts=preferred_hosts,
5028
  )
 
 
 
 
 
 
 
 
 
 
 
 
5029
  log_info(
5030
  "provider.create.done",
5031
  payment_method_id=pm_id,
@@ -5034,12 +5588,24 @@ def create_provider_link(
5034
  long_url=provider_url or stripe_redirect_url,
5035
  next_action_type=action_type,
5036
  )
5037
- return {
5038
- "payment_method_id": pm_id,
5039
- "stripe_redirect_url": stripe_redirect_url,
5040
- "provider_redirect_url": provider_url,
5041
- "long_url": provider_url or stripe_redirect_url,
5042
- }
 
 
 
 
 
 
 
 
 
 
 
 
5043
 
5044
 
5045
  app = FastAPI(title="OpenAI Pay Long Link")
@@ -5707,13 +6273,22 @@ def extract_ideal_qr_url(provider_url: Any) -> str:
5707
 
5708
 
5709
  def cdk_ideal_response_succeeded(response: LongLinkResponse | None) -> bool:
5710
- return bool(
5711
- response
5712
- and not response.fallback
5713
- and response.provider_redirect_url
5714
- and is_ideal_provider_url(response.provider_redirect_url)
5715
- and (response.ideal_qr_url or extract_ideal_qr_url(response.provider_redirect_url))
5716
- )
 
 
 
 
 
 
 
 
 
5717
 
5718
 
5719
  def long_link_response_from_dict(data: dict[str, Any] | None) -> LongLinkResponse | None:
@@ -5950,9 +6525,14 @@ def task_progress_callback(task_id: str):
5950
 
5951
 
5952
  def result_expiry_timestamp(response: LongLinkResponse | None) -> int:
5953
- if not response or normalize_link_type(response.link_type) != "ideal" or not str(response.long_url or "").strip():
5954
  return 0
5955
- return now_ts() + IDEAL_LINK_VALID_SECONDS
 
 
 
 
 
5956
 
5957
 
5958
  @app.get("/")
@@ -6486,7 +7066,7 @@ def build_long_link_response(
6486
  stripe_key_source=stripe_key_source,
6487
  processor_entity=checkout.get("processor_entity", ""),
6488
  )
6489
- if link_type in {"ideal", "paypal", "upi", "gopay"}:
6490
  # iDEAL must be present at NL bootstrap. PayPal/UPI can be absent
6491
  # before the promotion refresh, so validate them afterwards.
6492
  if link_type == "ideal":
@@ -6558,17 +7138,18 @@ def build_long_link_response(
6558
  processor_entity=checkout.get("processor_entity", ""),
6559
  )
6560
  require_payment_method_available(init_payload, "upi")
6561
- enforce_zero_checkout_amount(init_payload, req, checkout["cs_id"])
 
6562
  stop_if_requested()
6563
  checkout_amount = expected_amount(init_payload)
6564
  checkout_amount_currency = str(init_payload.get("currency") or checkout["currency"]).upper()
6565
  advance(45, "金额检测", f"付款金额 {checkout_amount} {checkout_amount_currency}")
6566
  stripe_hosted_url = str(init_payload.get("stripe_hosted_url") or "").strip()
6567
- if not stripe_hosted_url:
6568
  detail = f"stripe init response missing stripe_hosted_url, keys={response_keys(init_payload)}"
6569
  log_warning("stripe.init.missing_hosted_url", detail=detail)
6570
  raise HTTPException(status_code=502, detail=detail)
6571
- hosted_long_url = to_openai_pay_url(stripe_hosted_url)
6572
  log_info("api.hosted_url.ready", stripe_hosted_url=stripe_hosted_url, hosted_long_url=hosted_long_url)
6573
  advance(55, "重写长链", f"已获得 hosted 长链,正在提取 {link_type.upper()} 链")
6574
  provider = {
@@ -6592,6 +7173,8 @@ def build_long_link_response(
6592
  stop_if_requested()
6593
  advance(92, "Provider", f"已获得 {link_type.upper()} 跳转链接")
6594
  except HTTPException as exc:
 
 
6595
  fallback = True
6596
  provider_error = provider_error_diagnostic(exc.detail, link_type, checkout, req)
6597
  advance(92, "回退 hosted", f"{link_type.upper()} 提取失败,返回 hosted 长链")
@@ -6602,6 +7185,8 @@ def build_long_link_response(
6602
  fallback_url=hosted_long_url,
6603
  )
6604
  except Exception as exc:
 
 
6605
  fallback = True
6606
  provider_error = provider_error_diagnostic(repr(exc), link_type, checkout, req)
6607
  advance(92, "回退 hosted", f"{link_type.upper()} 提取异常,返回 hosted 长链")
@@ -6618,21 +7203,31 @@ def build_long_link_response(
6618
  billing_country=checkout["billing_country"],
6619
  currency=checkout["currency"],
6620
  checkout_amount=checkout_amount,
6621
- payment_locale=locale_parts(req.payment_locale)[0],
6622
  link_type=link_type,
6623
  payment_method_type=link_type,
6624
- payment_method_id=provider["payment_method_id"],
6625
- stripe_redirect_url=provider["stripe_redirect_url"],
6626
- provider_redirect_url=provider["provider_redirect_url"],
6627
  fallback=fallback,
6628
  provider_error=provider_error,
6629
  stripe_hosted_url=stripe_hosted_url,
6630
- long_url=provider["long_url"] or hosted_long_url,
6631
  ideal_qr_url=(
6632
- extract_ideal_qr_url(provider["provider_redirect_url"])
6633
  if link_type == "ideal" and not fallback
6634
  else ""
6635
  ),
 
 
 
 
 
 
 
 
 
 
6636
  )
6637
  log_info(
6638
  "api.long_link.done",
@@ -7002,8 +7597,8 @@ def generate_long_link(req: LongLinkRequest, request: Request) -> LongLinkRespon
7002
  if user.get("role") == "cdk" and not response.fallback and response.provider_redirect_url:
7003
  user = require_cdk_user(req.cdk, consume=True)
7004
  record_user_success(user["username"], response)
7005
- if not response.fallback and response.provider_redirect_url:
7006
- record_proxy_success(user["username"], req)
7007
  return response
7008
 
7009
 
@@ -7057,8 +7652,8 @@ def api_extract_pp(payload: ApiExtractRequest, request: Request) -> LongLinkResp
7057
  raise HTTPException(status_code=403, detail="CDK only supports iDEAL extraction")
7058
  response = build_long_link_response(req)
7059
  record_user_success(user["username"], response)
7060
- if not response.fallback and response.provider_redirect_url:
7061
- record_proxy_success(user["username"], req)
7062
  return response
7063
 
7064
 
@@ -7185,8 +7780,8 @@ def run_long_link_task(task_id: str, req: LongLinkRequest, owner: str) -> None:
7185
  if task_cancel_requested(task_id):
7186
  return
7187
  record_user_success(owner, response)
7188
- if not response.fallback and response.provider_redirect_url:
7189
- record_proxy_success(owner, req)
7190
  set_latest_result(task_id, response)
7191
  result_expires_at = result_expiry_timestamp(response)
7192
  set_task_state(
@@ -7254,7 +7849,7 @@ def request_for_retry_attempt(req: LongLinkRequest, attempt: int) -> LongLinkReq
7254
  base_promo_proxy = select_proxy_from_pool(promo_candidates, pool_index) or base_nl_proxy
7255
  nl_seed = proxy_for_attempt(base_nl_proxy, attempt, "idealnl", force=dynamic_pool)
7256
  promo_seed = proxy_for_attempt(base_promo_proxy, attempt, "idealvn", force=dynamic_pool)
7257
- nl_proxy = proxy_for_required_country(nl_seed, "NL")
7258
  promotion_proxy = proxy_for_required_country(promo_seed, "VN")
7259
  if base_nl_proxy and not nl_proxy:
7260
  raise HTTPException(status_code=422, detail="iDEAL 主代理无法切换到 NL")
@@ -7311,12 +7906,12 @@ def request_for_retry_attempt(req: LongLinkRequest, attempt: int) -> LongLinkReq
7311
  # UPI keeps the IN -> VN -> IN country chain while proxy_for_attempt keeps
7312
  # the dynamic SID/session for this provider attempt. Confirm and poll then
7313
  # reuse that same provider proxy unchanged.
7314
- provider_country = "IN" if link_type == "upi" else "ID" if gopay_mode else (effective_pm_country(req) if link_type == "paypal" else "")
7315
  provider_source = base_provider_proxy or base_checkout_proxy
7316
  if provider_source and provider_country:
7317
  aligned_provider = (
7318
- proxy_with_region(provider_source, "IN")
7319
- if link_type == "upi"
7320
  else proxy_for_required_country(provider_source, provider_country)
7321
  )
7322
  if not aligned_provider:
@@ -7327,6 +7922,8 @@ def request_for_retry_attempt(req: LongLinkRequest, attempt: int) -> LongLinkReq
7327
  base_provider_proxy = aligned_provider
7328
  checkout_proxy = proxy_for_attempt(base_checkout_proxy, attempt, "checkout", force=dynamic_pool)
7329
  provider_proxy = proxy_for_attempt(base_provider_proxy, attempt, "provider", force=dynamic_pool)
 
 
7330
  if link_type == "paypal":
7331
  checkout_country = effective_country(req)
7332
  aligned_checkout = proxy_for_required_country(checkout_proxy, checkout_country)
@@ -7334,7 +7931,11 @@ def request_for_retry_attempt(req: LongLinkRequest, attempt: int) -> LongLinkReq
7334
  raise HTTPException(status_code=422, detail=f"PayPal Checkout 代理无法切换到账单国家 {checkout_country}")
7335
  checkout_proxy = aligned_checkout
7336
  if provider_proxy and provider_country:
7337
- verified_provider = proxy_for_required_country(provider_proxy, provider_country)
 
 
 
 
7338
  if not verified_provider:
7339
  raise HTTPException(
7340
  status_code=422,
@@ -7441,7 +8042,7 @@ def run_long_link_task_retrying(task_id: str, req: LongLinkRequest, owner: str,
7441
  if task_cancel_requested(task_id):
7442
  return
7443
  last_response = response
7444
- provider_success = bool(not response.fallback and response.provider_redirect_url)
7445
  if owner_role == "cdk" and normalize_link_type(req.link_type) == "ideal":
7446
  provider_success = cdk_ideal_response_succeeded(response)
7447
  if provider_success:
@@ -7616,8 +8217,8 @@ def start_long_link_task(req: LongLinkRequest, request: Request) -> LongLinkTask
7616
  def start_ideal_long_link_task(req: LongLinkRequest, request: Request) -> LongLinkTaskStartResponse:
7617
  user = link_request_user(req, request, consume_cdk=False)
7618
  req = apply_runtime_defaults(req)
7619
- checkout_proxy = checkout_stage_proxy(req)
7620
- provider_proxy = normalize_proxy_url(provider_stage_proxy(req) or checkout_proxy)
7621
  req = req.model_copy(
7622
  update={
7623
  "link_type": "ideal",
@@ -7668,8 +8269,8 @@ def start_upi_long_link_task(req: LongLinkRequest, request: Request) -> LongLink
7668
  if user.get("role") == "cdk":
7669
  raise HTTPException(status_code=403, detail="CDK only supports iDEAL extraction")
7670
  req = apply_runtime_defaults(req)
7671
- checkout_proxy = checkout_stage_proxy(req)
7672
- provider_proxy = proxy_with_region(provider_stage_proxy(req) or checkout_proxy, "IN")
7673
  req = req.model_copy(
7674
  update={
7675
  "link_type": "upi",
@@ -7720,8 +8321,8 @@ def start_gopay_long_link_task(req: LongLinkRequest, request: Request) -> LongLi
7720
  if user.get("role") == "cdk":
7721
  raise HTTPException(status_code=403, detail="CDK only supports iDEAL extraction")
7722
  req = apply_runtime_defaults(req)
7723
- checkout_proxy = checkout_stage_proxy(req)
7724
- provider_proxy = proxy_with_region(provider_stage_proxy(req) or checkout_proxy, "ID")
7725
  req = req.model_copy(
7726
  update={
7727
  "link_type": "gopay",
 
3
  import contextvars
4
  import base64
5
  import binascii
6
+ import hashlib
7
+ import io
8
+ import json
9
  import logging
10
  import os
11
  import random
 
21
  from typing import Any
22
  from urllib.parse import parse_qsl, quote, unquote, urlencode, urljoin, urlsplit, urlunsplit
23
 
24
+ import requests
25
+ import segno
26
  from fastapi import FastAPI, HTTPException, Request
27
  from fastapi.responses import FileResponse, JSONResponse, Response
28
  from fastapi.staticfiles import StaticFiles
 
707
  device_id: str = ""
708
  user_agent: str = ""
709
  auto_probe: bool = Field(True, alias="autoProbe")
710
+ probe_countries: str = Field("", alias="probeCountries")
711
+ pool_keep: int = Field(10, alias="poolKeep")
712
+ pool_max: int = Field(200, alias="poolMax")
713
 
714
 
715
  class LongLinkResponse(BaseModel):
 
730
  stripe_hosted_url: str
731
  long_url: str
732
  ideal_qr_url: str = ""
733
+ provider_qr_url: str = ""
734
+ provider_qr_svg: str = ""
735
+ provider_expires_at: int = 0
736
+ next_action_type: str = ""
737
+ upi_qr_data: str = ""
738
+ upi_qr_image_url: str = ""
739
+ upi_hosted_url: str = ""
740
+ approval_result: str = ""
741
+ submission_state: str = ""
742
+ completion_stage: str = ""
743
  success_attempt: int = 0
744
 
745
 
 
1165
  the proxy used for that stage.
1166
  """
1167
  return normalize_proxy_url(str(proxy or ""))
1168
+
1169
+
1170
+ def proxy_for_provider_region(proxy: Any, country: str) -> str:
1171
+ """Apply the opll2 provider-region rewrite without rejecting fixed proxies."""
1172
+ proxy_url = normalize_proxy_url(str(proxy or ""))
1173
+ if not proxy_url:
1174
+ return ""
1175
+ if proxy_supports_country_rewrite(proxy_url):
1176
+ return proxy_for_probe_country(proxy_url, country) or proxy_url
1177
+ return proxy_url
1178
 
1179
 
1180
  def proxy_without_sid(proxy: Any) -> str:
 
1667
  return STRIPE_VERSION_FULL
1668
 
1669
 
1670
+ def effective_payment_locale(link_type: str, requested: str = "") -> str:
1671
+ normalized = normalize_link_type(link_type)
1672
+ forced = {"ideal": "nl", "upi": "en", "gopay": "id"}.get(normalized)
1673
+ if forced:
1674
+ return forced
1675
+ value = str(requested or "en").strip()
1676
+ return value or "en"
1677
+
1678
+
1679
+ def browser_timezone_for_link_type(link_type: str) -> str:
1680
+ normalized = normalize_link_type(link_type)
1681
+ return {
1682
+ "ideal": "Europe/Amsterdam",
1683
+ "upi": "Asia/Kolkata",
1684
+ "gopay": "Asia/Jakarta",
1685
+ }.get(normalized, "")
1686
+
1687
+
1688
  def effective_country(req: LongLinkRequest) -> str:
1689
+ forced = {"ideal": "NL", "upi": "IN", "gopay": "ID"}.get(normalize_link_type(req.link_type))
1690
+ if forced:
1691
+ return forced
1692
  return supported_checkout_country(req.billing_country, "DE")
1693
 
1694
 
1695
  def effective_pm_country(req: LongLinkRequest) -> str:
1696
+ forced = {"ideal": "NL", "upi": "IN", "gopay": "ID"}.get(normalize_link_type(req.link_type))
1697
+ if forced:
1698
+ return forced
1699
  return supported_checkout_country(req.pm_country, effective_country(req))
1700
 
1701
 
 
2322
  "supply stripe_publishable_key or configure the matching processor environment variable"
2323
  ),
2324
  )
2325
+ browser_locale, elements_locale = locale_parts(effective_payment_locale(req.link_type, req.payment_locale))
2326
+ browser_timezone = browser_timezone_for_link_type(req.link_type) or timezone_for_country(effective_country(req))
2327
  proxy_override = normalize_proxy_url(proxy_override)
2328
  log_info(
2329
  "stripe.init.start",
 
2508
  checkout["billing_country"],
2509
  checkout.get("processor_entity", ""),
2510
  )
2511
+ if "pay.openai.com/" in hosted_url or "checkout.stripe.com/" in hosted_url:
2512
+ parsed = urlsplit(hosted_url)
2513
+ query = dict(parse_qsl(parsed.query, keep_blank_values=True))
2514
+ # opll2's UPI/GoPay/iDEAL provider confirms preserve the Checkout URL and
2515
+ # only add ChatGPT's success destination. The extra hosted-flow
2516
+ # markers belong to the existing PayPal path and can change how a
2517
+ # custom wallet return is interpreted.
2518
+ if payment_method_type not in {"upi", "gopay", "ideal"}:
2519
+ query.setdefault("redirect_pm_type", payment_method_type)
2520
+ query.setdefault("lid", "".join(random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") for _ in range(24)))
2521
+ query.setdefault("ui_mode", "hosted")
2522
  query.setdefault(
2523
  "success_return_url",
2524
  chatgpt_success_return_url(
 
3109
 
3110
 
3111
  def stripe_context(cs_id: str, init_payload: dict[str, Any], req: LongLinkRequest) -> dict[str, Any]:
3112
+ _, elements_locale = locale_parts(effective_payment_locale(req.link_type, req.payment_locale))
3113
  checkout_ui_mode = (req.checkout_ui_mode or "custom").strip() or "custom"
3114
  return {
3115
  "stripe_js_id": str(uuid.uuid4()),
 
3212
  ctx: dict[str, Any],
3213
  init_payload: dict[str, Any] | None = None,
3214
  stripe_hosted_url: str = "",
3215
+ ) -> str:
3216
+ payment_method_type = normalize_link_type(payment_method_type)
3217
+ ctx = dict(ctx)
3218
+ ctx.setdefault("stripe_js_id", str(uuid.uuid4()))
3219
+ ctx.setdefault("elements_session_id", f"elements_session_{uuid.uuid4().hex[:11]}")
3220
+ ctx.setdefault("elements_session_config_id", str(ctx.get("config_id") or uuid.uuid4()))
3221
+ runtime_version = str(ctx.get("runtime_version") or DEFAULT_STRIPE_RUNTIME_VERSION)
3222
  log_info(
3223
  "stripe.payment_method.start",
3224
  route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
 
3232
  currency=ctx.get("currency", ""),
3233
  checkout_amount=ctx.get("checkout_amount", ""),
3234
  )
3235
+ opll2_provider_mode = payment_method_type in {"upi", "gopay", "ideal"}
3236
+ hosted_mode = str(ctx.get("checkout_ui_mode") or "").lower() == "hosted" and not opll2_provider_mode
3237
+ if hosted_mode:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3238
  body = {
3239
  "billing_details[name]": billing.get("name") or "John Doe",
3240
  "billing_details[email]": billing.get("email") or "buyer@example.com",
 
3280
  "client_attribution_metadata[payment_method_selection_flow]": "automatic",
3281
  "client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
3282
  "client_attribution_metadata[merchant_integration_additional_elements][1]": "address",
3283
+ "key": stripe_pk,
3284
  "_stripe_version": str(ctx.get("stripe_version") or stripe_version_for(payment_method_type)),
3285
+ }
3286
+ if payment_method_type == "gopay":
3287
+ body.update(
3288
+ {
3289
+ "guid": uuid.uuid4().hex,
3290
+ "muid": uuid.uuid4().hex,
3291
+ "sid": uuid.uuid4().hex,
3292
+ }
3293
+ )
3294
+ if payment_method_type == "ideal":
3295
+ body["ideal[bank]"] = "bunq"
3296
+ started = time.perf_counter()
3297
+ headers = None
3298
  if hosted_mode:
3299
  headers = {
3300
  "Origin": "https://pay.openai.com",
 
3327
  stripe_pk: str,
3328
  req: LongLinkRequest,
3329
  ) -> str:
3330
+ browser_locale, elements_locale = locale_parts(effective_payment_locale(req.link_type, req.payment_locale))
3331
  body = {
3332
  "browser_locale": browser_locale,
3333
+ "browser_timezone": browser_timezone_for_link_type(req.link_type) or "Asia/Shanghai",
3334
  "elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
3335
  "elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
3336
  "elements_session_client[elements_init_source]": "custom_checkout",
 
3376
  checkout: dict[str, Any],
3377
  req: LongLinkRequest,
3378
  stripe_hosted_url: str,
3379
+ ) -> dict[str, Any]:
3380
+ payment_method_type = normalize_link_type(payment_method_type)
3381
+ ctx = dict(ctx)
3382
+ ctx.setdefault("stripe_js_id", str(uuid.uuid4()))
3383
+ ctx.setdefault("elements_session_id", f"elements_session_{uuid.uuid4().hex[:11]}")
3384
+ ctx.setdefault("elements_session_config_id", str(ctx.get("config_id") or uuid.uuid4()))
3385
+ return_url = stripe_confirm_return_url(cs_id, checkout, stripe_hosted_url, payment_method_type)
3386
  runtime_version = str(ctx.get("runtime_version") or DEFAULT_STRIPE_RUNTIME_VERSION)
3387
+ opll2_provider_mode = payment_method_type in {"upi", "gopay", "ideal"}
3388
+ hosted_mode = str(ctx.get("checkout_ui_mode") or "").lower() == "hosted" and not opll2_provider_mode
3389
  log_info(
3390
  "stripe.confirm.start",
3391
  route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
 
3404
  "sid": uuid.uuid4().hex,
3405
  "payment_method": pm_id,
3406
  "init_checksum": init_checksum,
3407
+ "version": runtime_version,
3408
+ "expected_amount": str(ctx.get("checkout_amount") or expected_amount(init_payload)),
3409
  "expected_payment_method_type": "gopay",
3410
  "return_url": return_url,
3411
+ "elements_session_client[session_id]": ctx["elements_session_id"],
3412
+ "elements_session_client[locale]": str(ctx.get("locale") or "id"),
3413
  "elements_session_client[referrer_host]": "chatgpt.com",
3414
  "elements_session_client[is_aggregation_expected]": "false",
3415
+ "elements_session_client[elements_init_source]": "custom_checkout",
3416
+ "elements_session_client[stripe_js_id]": ctx["stripe_js_id"],
3417
+ "elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
3418
+ "elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
3419
+ "elements_options_client[saved_payment_method][enable_save]": "never",
3420
+ "elements_options_client[saved_payment_method][enable_redisplay]": "never",
3421
+ "client_attribution_metadata[client_session_id]": ctx["stripe_js_id"],
3422
+ "client_attribution_metadata[checkout_session_id]": cs_id,
3423
+ "client_attribution_metadata[checkout_config_id]": ctx.get("config_id") or "",
3424
+ "client_attribution_metadata[elements_session_id]": ctx["elements_session_id"],
3425
+ "client_attribution_metadata[elements_session_config_id]": ctx["elements_session_config_id"],
3426
+ "client_attribution_metadata[merchant_integration_source]": "checkout",
3427
  "client_attribution_metadata[merchant_integration_subtype]": "payment-element",
3428
+ "client_attribution_metadata[merchant_integration_version]": "custom",
3429
  "client_attribution_metadata[payment_intent_creation_flow]": "deferred",
3430
+ "client_attribution_metadata[payment_method_selection_flow]": "automatic",
3431
+ "client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
3432
+ "client_attribution_metadata[merchant_integration_additional_elements][1]": "address",
3433
  "consent[terms_of_service]": "accepted",
3434
  "key": stripe_pk,
3435
+ "_stripe_version": str(ctx.get("stripe_version") or stripe_version_for(payment_method_type)),
3436
  }
3437
  elif hosted_mode:
3438
  amounts = display_amounts(init_payload)
 
3496
  "client_attribution_metadata[elements_session_config_id]": ctx["elements_session_config_id"],
3497
  "client_attribution_metadata[merchant_integration_source]": "checkout",
3498
  "client_attribution_metadata[merchant_integration_subtype]": "payment-element",
3499
+ "client_attribution_metadata[merchant_integration_version]": "custom",
 
 
3500
  "client_attribution_metadata[payment_intent_creation_flow]": "deferred",
3501
  "client_attribution_metadata[payment_method_selection_flow]": "automatic",
3502
  "client_attribution_metadata[merchant_integration_additional_elements][0]": "payment",
 
3505
  "key": stripe_pk,
3506
  "_stripe_version": str(ctx.get("stripe_version") or stripe_version_for(payment_method_type)),
3507
  }
 
 
3508
  started = time.perf_counter()
3509
  headers = None
3510
  if hosted_mode and payment_method_type != "gopay":
 
3538
  "stripe.confirm.done",
3539
  response_keys=response_keys(payload),
3540
  interesting_fields=interesting_payload_fields(payload),
3541
+ has_redirect=bool(
3542
+ extract_redirect_to_url_strict(payload)
3543
+ if payment_method_type in {"gopay", "ideal"}
3544
+ else extract_redirect_to_url(payload)
3545
+ ),
3546
  submission_state=submission_state,
3547
  checkout_status=payload.get("status", "") if isinstance(payload, dict) else "",
3548
  checkout_state=payload.get("state", "") if isinstance(payload, dict) else "",
 
3665
  action = payload.get("next_action")
3666
  if isinstance(action, dict):
3667
  return action
3668
+ for key in ("setup_intent", "payment_intent", "payment_method_object"):
3669
  nested = payload.get(key)
3670
  found = next_action_from_payload(nested)
3671
  if found:
 
3710
  if found:
3711
  return found
3712
  return extract_action_url(action)
3713
+
3714
+
3715
+ def extract_redirect_to_url_strict(payload: Any) -> str:
3716
+ """Extract only Stripe's redirect_to_url action, matching opll2 provider flows."""
3717
+ if not isinstance(payload, dict):
3718
+ return ""
3719
+ next_action = payload.get("next_action")
3720
+ if isinstance(next_action, dict) and str(next_action.get("type") or "") == "redirect_to_url":
3721
+ redirect_payload = next_action.get("redirect_to_url")
3722
+ if isinstance(redirect_payload, dict):
3723
+ url = str(redirect_payload.get("url") or "").strip()
3724
+ if url:
3725
+ return url
3726
+ for key in ("setup_intent", "payment_intent", "payment_method_object"):
3727
+ nested = payload.get(key)
3728
+ if isinstance(nested, dict):
3729
+ url = extract_redirect_to_url_strict(nested)
3730
+ if url:
3731
+ return url
3732
+ return ""
3733
 
3734
 
3735
  def stripe_intent_state(payload: Any) -> dict[str, str]:
 
3806
  ctx: dict[str, Any] | None = None,
3807
  timeout_seconds: float = 30,
3808
  max_attempts: int = STRIPE_REDIRECT_POLL_MAX_ATTEMPTS,
3809
+ ) -> str:
3810
+ deadline = time.time() + max(1.0, float(timeout_seconds or 30))
3811
+ link_type = normalize_link_type(req.link_type)
3812
+ deadline_poll = link_type in {"gopay", "ideal"}
3813
+ redirect_extractor = (
3814
+ extract_redirect_to_url_strict
3815
+ if deadline_poll
3816
+ else extract_redirect_to_url
3817
+ )
3818
  # Provider actions can appear shortly after ChatGPT approval. Poll a small,
3819
+ # bounded number of times for legacy paths; opll2's GoPay/iDEAL flow polls
3820
+ # once per second until its deadline. Never fan out requests for one CS ID.
3821
  max_attempts = max(1, min(int(max_attempts or 1), STRIPE_REDIRECT_POLL_MAX_ATTEMPTS))
3822
  pool_workers = min(max(1, STRIPE_REDIRECT_POLL_WORKERS), max_attempts)
3823
  sequential = True
 
3827
  "stripe.redirect_poll.start",
3828
  route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
3829
  cs_id=cs_id,
3830
+ timeout_seconds=timeout_seconds,
3831
+ max_attempts=max_attempts,
3832
+ deadline_poll=deadline_poll,
3833
  pool_workers=1 if sequential else pool_workers,
3834
  reuse_context=bool(ctx),
3835
  poll_proxy_pool_count=len(poll_proxies),
 
3887
  "poll_proxy_count": len(poll_proxies),
3888
  "poll_proxy_label": redact_proxy(poll_proxy),
3889
  }
3890
+ duration = elapsed_ms(started)
3891
+ if response.status_code == 200:
3892
+ payload = response.json() or {}
3893
+ redirect_url = redirect_extractor(payload)
3894
  intent_state = stripe_intent_state(payload)
3895
  terminal_error = stripe_terminal_intent_error(payload)
3896
  return {
 
3925
  TASK_LOG_CALLBACK.reset(callback_token)
3926
  REQUEST_ID.reset(request_token)
3927
 
3928
+ if sequential:
3929
+ completed = 0
3930
+ terminal_errors = 0
3931
+
3932
+ def sequential_attempts():
3933
+ attempt = 1
3934
+ while deadline_poll or attempt <= max_attempts:
3935
+ yield attempt
3936
+ attempt += 1
3937
+
3938
+ for attempt in sequential_attempts():
3939
+ if time.time() >= deadline:
3940
+ break
3941
  item = poll_once(attempt)
3942
  completed += 1
3943
  status_code = int(item.get("status_code") or 0)
 
4012
  raise HTTPException(status_code=402, detail=terminal_error)
4013
  else:
4014
  last_err = str(item.get("detail") or last_err)
4015
+ has_more_attempts = deadline_poll or attempt < max_attempts
4016
+ remaining = deadline - time.time()
4017
+ if has_more_attempts and remaining > 0:
4018
+ time.sleep(min(1.0, remaining))
4019
+ if not deadline_poll and completed >= max_attempts:
4020
  detail = f"redirect url resolution stopped after {completed} sequential attempts: {last_err}"
4021
  log_warning(
4022
  "stripe.redirect_poll.max_attempts",
 
4176
  raise HTTPException(status_code=504, detail=detail)
4177
 
4178
 
4179
+ def render_qr_svg(qr_value: str) -> str:
4180
+ buffer = io.BytesIO()
4181
+ segno.make(str(qr_value or ""), error="m").save(buffer, kind="svg", scale=6, border=2)
4182
+ return buffer.getvalue().decode("utf-8")
4183
+
4184
+
4185
+ def parse_expires_at(value: Any) -> int:
4186
+ try:
4187
+ return int(value or 0)
4188
+ except (TypeError, ValueError):
4189
+ return 0
4190
+
4191
+
4192
+ def normalize_upi_qr_display(display: dict[str, Any]) -> dict[str, Any]:
4193
+ qr_value = str(display.get("data") or display.get("qr_code") or display.get("url") or "").strip()
4194
+ hosted_url = str(display.get("hosted_instructions_url") or "").strip()
4195
+ image_url = str(
4196
+ display.get("image_url_png")
4197
+ or display.get("image_url")
4198
+ or display.get("image_url_utf8")
4199
+ or display.get("image_url_uri")
4200
+ or display.get("image_url_svg")
4201
+ or ""
4202
+ ).strip()
4203
+ if not qr_value and not image_url and not hosted_url:
4204
+ return {}
4205
+ return {
4206
+ "provider_qr_url": qr_value or image_url,
4207
+ "provider_qr_svg": render_qr_svg(qr_value) if qr_value else "",
4208
+ "provider_qr_image_url": image_url,
4209
+ "provider_expires_at": parse_expires_at(display.get("expires_at")),
4210
+ "upi_hosted_url": hosted_url,
4211
+ }
4212
+
4213
+
4214
+ def extract_upi_qr_next_action(next_action: dict[str, Any]) -> dict[str, Any]:
4215
+ action_type = str(next_action.get("type") or "").strip()
4216
+ supported = {
4217
+ "upi_display_qr_code",
4218
+ "display_upi_qr_code",
4219
+ "display_qr_code",
4220
+ "upi_handle_redirect_or_display_qr_code",
4221
+ }
4222
+ if action_type and action_type not in supported:
4223
+ return {}
4224
+ if action_type == "upi_handle_redirect_or_display_qr_code":
4225
+ handle_payload = next_action.get(action_type)
4226
+ if isinstance(handle_payload, dict):
4227
+ qr_code = handle_payload.get("qr_code")
4228
+ if isinstance(qr_code, dict):
4229
+ details = normalize_upi_qr_display(qr_code)
4230
+ if details:
4231
+ hosted_url = str(handle_payload.get("hosted_instructions_url") or "").strip()
4232
+ if hosted_url:
4233
+ details["upi_hosted_url"] = hosted_url
4234
+ return details
4235
+ details = normalize_upi_qr_display(handle_payload)
4236
+ if details:
4237
+ return details
4238
+ for key in ("upi_display_qr_code", "display_upi_qr_code", "display_qr_code", "qr_code"):
4239
+ display = next_action.get(key)
4240
+ if isinstance(display, dict):
4241
+ details = normalize_upi_qr_display(display)
4242
+ if details:
4243
+ return details
4244
+ return normalize_upi_qr_display(next_action)
4245
+
4246
+
4247
+ def extract_upi_qr_details(payload: Any) -> dict[str, Any]:
4248
+ if not isinstance(payload, dict):
4249
+ return {}
4250
+ next_action = payload.get("next_action")
4251
+ if isinstance(next_action, dict):
4252
+ details = extract_upi_qr_next_action(next_action)
4253
+ if details:
4254
+ return details
4255
+ for key in ("setup_intent", "payment_intent", "payment_method_object"):
4256
+ nested = payload.get(key)
4257
+ if isinstance(nested, dict):
4258
+ details = extract_upi_qr_details(nested)
4259
+ if details:
4260
+ return details
4261
+ return {}
4262
+
4263
+
4264
+ def extract_upi_redirect_url(payload: Any) -> str:
4265
+ """Extract the app/browser route without confusing hosted or QR image URLs for it."""
4266
+ if not isinstance(payload, dict):
4267
+ return ""
4268
+ next_action = payload.get("next_action")
4269
+ if isinstance(next_action, dict):
4270
+ action_type = str(next_action.get("type") or "").strip()
4271
+ action_payload = next_action.get(action_type) if action_type else None
4272
+ if action_type == "redirect_to_url" and not isinstance(action_payload, dict):
4273
+ action_payload = next_action.get("redirect_to_url")
4274
+ if action_type in {"redirect_to_url", "upi_handle_redirect_or_display_qr_code"}:
4275
+ candidates = [action_payload, next_action]
4276
+ for candidate in candidates:
4277
+ if not isinstance(candidate, dict):
4278
+ continue
4279
+ for key in ("mobile_auth_url", "redirect_url", "url"):
4280
+ value = candidate.get(key)
4281
+ if isinstance(value, dict):
4282
+ value = value.get("url")
4283
+ url = str(value or "").strip()
4284
+ if url.startswith(("https://", "http://")):
4285
+ return url
4286
+ redirect_to_url = candidate.get("redirect_to_url")
4287
+ if isinstance(redirect_to_url, dict):
4288
+ url = str(redirect_to_url.get("url") or "").strip()
4289
+ if url.startswith(("https://", "http://")):
4290
+ return url
4291
+ for key in ("setup_intent", "payment_intent", "payment_method_object"):
4292
+ nested = payload.get(key)
4293
+ if isinstance(nested, dict):
4294
+ url = extract_upi_redirect_url(nested)
4295
+ if url:
4296
+ return url
4297
+ return ""
4298
+
4299
+
4300
+ def extract_upi_success_result(payload: Any) -> dict[str, Any]:
4301
+ if not isinstance(payload, dict):
4302
+ return {}
4303
+ qr_details = extract_upi_qr_details(payload)
4304
+ redirect_url = extract_upi_redirect_url(payload)
4305
+ if qr_details:
4306
+ qr_value = str(qr_details.get("provider_qr_url") or "").strip()
4307
+ image_url = str(qr_details.get("provider_qr_image_url") or "").strip()
4308
+ hosted_url = str(qr_details.get("upi_hosted_url") or image_url or "").strip()
4309
+ return {
4310
+ "next_action_type": next_action_type(payload),
4311
+ "upi_redirect_url": redirect_url,
4312
+ "upi_qr_data": qr_value if qr_value and not qr_value.startswith(("http://", "https://")) else "",
4313
+ "upi_qr_image_url": image_url or (qr_value if qr_value.startswith(("http://", "https://")) else ""),
4314
+ "upi_hosted_url": hosted_url,
4315
+ "provider_redirect_url": redirect_url,
4316
+ "provider_qr_url": qr_value,
4317
+ "provider_qr_svg": str(qr_details.get("provider_qr_svg") or ""),
4318
+ "provider_qr_image_url": image_url,
4319
+ "provider_expires_at": int(qr_details.get("provider_expires_at") or 0),
4320
+ }
4321
+ redirect_url = redirect_url or extract_redirect_to_url_strict(payload)
4322
+ if redirect_url:
4323
+ return {
4324
+ "next_action_type": "redirect_to_url",
4325
+ "upi_redirect_url": redirect_url,
4326
+ "upi_qr_data": "",
4327
+ "upi_qr_image_url": "",
4328
+ "upi_hosted_url": redirect_url,
4329
+ "provider_redirect_url": redirect_url,
4330
+ }
4331
+ return {}
4332
+
4333
+
4334
+ def result_provider_display_ready(result: dict[str, Any]) -> bool:
4335
+ return bool(
4336
+ str(result.get("provider_redirect_url") or "").strip()
4337
+ or str(result.get("long_url") or "").strip()
4338
+ or str(result.get("upi_hosted_url") or "").strip()
4339
+ or str(result.get("provider_qr_url") or "").strip()
4340
+ or str(result.get("provider_qr_svg") or "").strip()
4341
+ or str(result.get("upi_qr_data") or "").strip()
4342
+ or str(result.get("upi_qr_image_url") or "").strip()
4343
+ )
4344
+
4345
+
4346
+ def stripe_payment_page_upi_details(
4347
+ stripe: Any,
4348
+ cs_id: str,
4349
+ stripe_pk: str,
4350
+ req: LongLinkRequest,
4351
+ job_id: str = "",
4352
+ timeout_seconds: float = 30,
4353
+ ) -> dict[str, Any]:
4354
+ deadline = time.time() + max(1.0, float(timeout_seconds or 30))
4355
+ last_err = ""
4356
+ params = {
4357
+ "key": stripe_pk,
4358
+ "_stripe_version": stripe_version_for("upi"),
4359
+ "elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
4360
+ "elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
4361
+ "elements_session_client[elements_init_source]": "custom_checkout",
4362
+ "elements_session_client[referrer_host]": "chatgpt.com",
4363
+ }
4364
+ log_info("provider.upi_qr_poll.start", cs_id=cs_id, job_id=job_id, timeout_seconds=timeout_seconds)
4365
+ while time.time() < deadline:
4366
+ response = stripe.get(
4367
+ f"https://api.stripe.com/v1/payment_pages/{cs_id}",
4368
+ params=params,
4369
+ timeout=DEFAULT_TIMEOUT,
4370
+ )
4371
+ if response.status_code == 200:
4372
+ try:
4373
+ payload = response.json() or {}
4374
+ except Exception:
4375
+ payload = {}
4376
+ result = extract_upi_success_result(payload)
4377
+ if result:
4378
+ log_info("provider.upi_qr_poll.done", cs_id=cs_id, job_id=job_id)
4379
+ return result
4380
+ submission = payload.get("submission_attempt") if isinstance(payload, dict) else None
4381
+ last_err = f"state={str((submission or {}).get('state') or '-')} keys={response_keys(payload)}"
4382
+ else:
4383
+ last_err = f"http {response.status_code}: {str(response.text or '')[:120]}"
4384
+ time.sleep(1)
4385
+ raise HTTPException(status_code=504, detail=f"upi qr resolution timeout: {last_err}")
4386
+
4387
+
4388
+ def approve_request(
4389
  session: Any,
4390
  cs_id: str,
4391
  processor_entity: str,
 
5021
  raise HTTPException(status_code=502, detail=detail)
5022
 
5023
 
5024
+ def chatgpt_approve_result(
5025
+ chatgpt: Any,
5026
+ cs_id: str,
5027
+ checkout: dict[str, Any],
5028
+ job_id: str = "",
5029
+ ) -> str:
5030
+ processor_entity = processor_entity_for_country(
5031
+ checkout["billing_country"],
5032
+ checkout.get("processor_entity", ""),
5033
+ )
5034
+ try:
5035
+ chatgpt.post(
5036
+ "https://chatgpt.com/backend-api/sentinel/ping",
5037
+ json={},
5038
+ headers={
5039
+ "Referer": "https://chatgpt.com/",
5040
+ "x-openai-target-path": "/backend-api/sentinel/ping",
5041
+ "x-openai-target-route": "/backend-api/sentinel/ping",
5042
+ },
5043
+ timeout=DEFAULT_TIMEOUT,
5044
+ )
5045
+ except Exception:
5046
+ pass
5047
+ item = approve_request(chatgpt, cs_id, processor_entity, 1)
5048
+ result = str(item.get("result") or "").strip()
5049
+ if not result:
5050
+ detail = str(item.get("detail") or "chatgpt approve missing result")
5051
+ status_code = int(item.get("status_code") or 0)
5052
+ raise HTTPException(status_code=status_code if status_code >= 400 else 502, detail=detail)
5053
+ log_info("chatgpt.approve_result", cs_id=cs_id, job_id=job_id, result=result)
5054
+ return result
5055
+
5056
+
5057
+ def chatgpt_approve_pool(
5058
+ chatgpt: Any,
5059
+ cs_id: str,
5060
+ checkout: dict[str, Any],
5061
+ *,
5062
+ pool_keep: int,
5063
+ pool_max: int,
5064
+ job_id: str = "",
5065
+ ) -> str:
5066
+ keep = max(1, min(50, int(pool_keep or 1)))
5067
+ max_attempts = max(1, min(2000, int(pool_max or keep)))
5068
+ blocked = 0
5069
+ other = 0
5070
+ for attempt in range(1, max_attempts + 1):
5071
+ cancel_check = TASK_CANCEL_CHECK.get()
5072
+ if cancel_check and cancel_check():
5073
+ raise TaskCancelled("task cancelled")
5074
+ try:
5075
+ result = chatgpt_approve_result(chatgpt, cs_id, checkout, job_id=job_id)
5076
+ except HTTPException as exc:
5077
+ if "blocked" in str(exc.detail).lower():
5078
+ blocked += 1
5079
+ else:
5080
+ other += 1
5081
+ result = ""
5082
+ if result == "approved":
5083
+ log_info(
5084
+ "chatgpt.approve_pool.hit",
5085
+ cs_id=cs_id,
5086
+ job_id=job_id,
5087
+ attempt=attempt,
5088
+ pool_keep=keep,
5089
+ pool_max=max_attempts,
5090
+ )
5091
+ return result
5092
+ if attempt % 50 == 0 or attempt == max_attempts:
5093
+ log_info(
5094
+ "chatgpt.approve_pool.tick",
5095
+ cs_id=cs_id,
5096
+ job_id=job_id,
5097
+ attempt=attempt,
5098
+ blocked=blocked,
5099
+ other=other,
5100
+ )
5101
+ raise HTTPException(status_code=502, detail="approve blocked")
5102
+
5103
+
5104
  def redirect_url_after_confirm(
5105
  chatgpt: Any,
5106
  stripe: Any,
 
5111
  init_payload: dict[str, Any],
5112
  ctx: dict[str, Any],
5113
  checkout: dict[str, Any],
5114
+ req: LongLinkRequest,
5115
+ stripe_hosted_url: str,
5116
+ ) -> str:
5117
+ link_type = normalize_link_type(req.link_type)
5118
+ redirect_extractor = (
5119
+ extract_redirect_to_url_strict
5120
+ if link_type in {"gopay", "ideal"}
5121
+ else extract_redirect_to_url
5122
+ )
5123
+ redirect_url = redirect_extractor(confirm_payload)
5124
  if redirect_url:
5125
  log_info("provider.redirect.after_confirm", source="confirm_payload", redirect_url=redirect_url)
5126
  return redirect_url
 
5135
  intent_decline_code=intent_state.get("decline_code", ""),
5136
  )
5137
  raise HTTPException(status_code=402, detail=terminal_error)
5138
+ submission = confirm_payload.get("submission_attempt") if isinstance(confirm_payload, dict) else None
5139
+ approval_reason = checkout_approval_reason(confirm_payload)
5140
+ submission_state = str((submission or {}).get("state") or "").strip()
5141
+ if link_type in {"gopay", "ideal"} and submission_state != "requires_approval":
5142
+ approval_reason = ""
5143
  if approval_reason:
5144
  log_info(
5145
  "provider.redirect.requires_approval",
 
5148
  checkout_status=confirm_payload.get("status", "") if isinstance(confirm_payload, dict) else "",
5149
  checkout_state=confirm_payload.get("state", "") if isinstance(confirm_payload, dict) else "",
5150
  )
5151
+ upi_mode = link_type == "upi"
5152
+ provider_session_approval = link_type in {"gopay", "ideal"}
5153
+ if provider_session_approval:
5154
+ # create_provider_link already moves this same ChatGPT session to
5155
+ # the provider lane. opll2 keeps that session/IP through approval;
5156
+ # switching back to approveProxy here can split one CS across two
5157
+ # SIDs and prevent the provider redirect from materializing.
5158
+ approve_proxy = session_proxy_url(chatgpt) or provider_stage_proxy(req)
5159
+ else:
5160
+ approve_proxy = provider_stage_proxy(req) if upi_mode else approve_stage_proxy(req)
5161
+ apply_approve_proxy(chatgpt, approve_proxy)
5162
  runtime_config = get_runtime_config()
5163
  approve_pool_mode = normalize_proxy_pool_mode(req.proxy_pool_mode or runtime_config.get("proxyPoolMode"))
5164
  approve_pool = approve_proxy_pool_for_request(req) if approve_pool_mode == "sticky" else None
 
5169
  pool_count=len(approve_pool or []),
5170
  per_proxy=APPROVE_STICKY_PER_PROXY_CONCURRENCY,
5171
  )
5172
+ chatgpt_approve(chatgpt, cs_id, checkout, approve_pool=approve_pool)
5173
+ if link_type == "ideal":
5174
+ time.sleep(2)
5175
  log_info(
5176
  "provider.redirect.poll_after_approval",
5177
  stripe_route="provider_proxy" if getattr(stripe, "proxies", {}) else "direct",
5178
  approve_route="approve_proxy" if approve_proxy else "direct",
5179
+ )
5180
  try:
5181
+ approval_timeout = 90 if link_type in {"gopay", "ideal"} else 45
5182
+ return stripe_payment_page_redirect_url(
5183
+ stripe,
5184
+ cs_id,
5185
+ stripe_pk,
5186
+ req,
5187
+ ctx,
5188
+ timeout_seconds=approval_timeout,
5189
+ )
5190
  except HTTPException as exc:
5191
  if not upi_mode or exc.status_code not in {502, 504}:
5192
  raise
 
5240
  submission_state=submission.get("state") if isinstance(submission, dict) else "",
5241
  response_keys=response_keys(confirm_payload),
5242
  )
5243
+ fallback_timeout = 60 if normalize_link_type(req.link_type) == "gopay" else 30
5244
+ return stripe_payment_page_redirect_url(
5245
+ stripe,
5246
+ cs_id,
5247
+ stripe_pk,
5248
+ req,
5249
+ ctx,
5250
+ timeout_seconds=fallback_timeout,
5251
+ )
5252
 
5253
 
5254
  def resolve_external_redirect(
 
5323
  return current
5324
 
5325
 
5326
+ def upi_details_after_confirm(
5327
+ chatgpt: Any,
5328
+ stripe: Any,
5329
+ confirm_payload: dict[str, Any],
5330
+ cs_id: str,
5331
+ stripe_pk: str,
5332
+ checkout: dict[str, Any],
5333
+ req: LongLinkRequest,
5334
+ job_id: str = "",
5335
+ pool_keep: int = 1,
5336
+ pool_max: int = 1,
5337
+ ) -> dict[str, Any]:
5338
+ submission = confirm_payload.get("submission_attempt") if isinstance(confirm_payload, dict) else None
5339
+ submission_state = str((submission or {}).get("state") or "").strip()
5340
+ details = extract_upi_success_result(confirm_payload)
5341
+ # Match opll2: once Stripe has already returned a usable UPI artifact, do
5342
+ # not let a redundant approval/poll overwrite that success with a timeout.
5343
+ if details:
5344
+ return {**details, "submission_state": submission_state}
5345
+ if submission_state == "requires_approval":
5346
+ approval_result = chatgpt_approve_pool(
5347
+ chatgpt,
5348
+ cs_id,
5349
+ checkout,
5350
+ pool_keep=pool_keep,
5351
+ pool_max=pool_max,
5352
+ job_id=job_id,
5353
+ )
5354
+ if approval_result != "approved":
5355
+ raise HTTPException(status_code=502, detail=f"provider approval did not succeed: {approval_result!r}")
5356
+ resolved = stripe_payment_page_upi_details(
5357
+ stripe,
5358
+ cs_id,
5359
+ stripe_pk,
5360
+ req,
5361
+ job_id=job_id,
5362
+ timeout_seconds=45,
5363
+ )
5364
+ return {
5365
+ **resolved,
5366
+ "approval_result": approval_result,
5367
+ "submission_state": submission_state,
5368
+ }
5369
+ resolved = stripe_payment_page_upi_details(
5370
+ stripe,
5371
+ cs_id,
5372
+ stripe_pk,
5373
+ req,
5374
+ job_id=job_id,
5375
+ timeout_seconds=30,
5376
+ )
5377
+ return {**resolved, "submission_state": submission_state}
5378
+
5379
+
5380
+ def build_upi_provider_fields(
5381
+ pm_id: str,
5382
+ checkout: dict[str, Any],
5383
+ upi_details: dict[str, Any],
5384
+ ) -> dict[str, Any]:
5385
+ qr_url = str(upi_details.get("provider_qr_url") or "").strip()
5386
+ qr_image_url = str(upi_details.get("provider_qr_image_url") or upi_details.get("upi_qr_image_url") or "").strip()
5387
+ display_url = qr_url or qr_image_url
5388
+ redirect_url = str(
5389
+ upi_details.get("provider_redirect_url")
5390
+ or upi_details.get("upi_redirect_url")
5391
+ or ""
5392
+ ).strip()
5393
+ explicit_hosted_url = str(upi_details.get("upi_hosted_url") or "").strip()
5394
+ hosted_url = explicit_hosted_url or redirect_url
5395
+ checkout_url = str(checkout.get("checkout_url") or "").strip()
5396
+ qr_data = str(upi_details.get("upi_qr_data") or "").strip()
5397
+ if not qr_data and qr_url and not qr_url.startswith(("http://", "https://")):
5398
+ qr_data = qr_url
5399
+ submission_state = str(upi_details.get("submission_state") or "").strip()
5400
+ approval_result = str(upi_details.get("approval_result") or "").strip()
5401
+ if display_url:
5402
+ completion_stage = "provider_qr_ready"
5403
+ elif redirect_url:
5404
+ completion_stage = "provider_redirect_ready"
5405
+ elif explicit_hosted_url:
5406
+ completion_stage = "provider_hosted_ready"
5407
+ else:
5408
+ completion_stage = ""
5409
+ return {
5410
+ "payment_method_id": pm_id,
5411
+ "stripe_redirect_url": "",
5412
+ "provider_redirect_url": redirect_url,
5413
+ "long_url": hosted_url or checkout_url,
5414
+ "provider_qr_url": display_url,
5415
+ "provider_qr_svg": str(upi_details.get("provider_qr_svg") or ""),
5416
+ "provider_expires_at": int(upi_details.get("provider_expires_at") or 0),
5417
+ "next_action_type": str(upi_details.get("next_action_type") or "").strip(),
5418
+ "upi_qr_data": qr_data,
5419
+ "upi_qr_image_url": qr_image_url,
5420
+ "upi_hosted_url": hosted_url,
5421
+ "approval_result": approval_result,
5422
+ "submission_state": submission_state,
5423
+ "completion_stage": completion_stage,
5424
+ }
5425
+
5426
+
5427
  def create_provider_link(
5428
  chatgpt: Any,
5429
  checkout: dict[str, Any],
 
5431
  stripe_hosted_url: str,
5432
  req: LongLinkRequest,
5433
  provider_proxy: str = "",
5434
+ ) -> dict[str, Any]:
5435
  link_type = normalize_link_type(req.link_type)
5436
+ if link_type not in {"upi", "gopay", "ideal"}:
5437
+ require_payment_method_available(init_payload, link_type)
5438
  stripe_pk = str(checkout.get("stripe_publishable_key") or req.stripe_publishable_key).strip()
5439
  if not stripe_pk:
5440
  raise HTTPException(status_code=422, detail="provider stage missing resolved Stripe publishable key")
 
5445
  cs_id=checkout.get("cs_id", ""),
5446
  provider_proxy_configured=bool(provider_proxy),
5447
  provider_proxy=provider_proxy,
5448
+ )
5449
+ stripe = build_stripe_session(req, proxy_override=provider_proxy)
5450
+ if link_type in {"upi", "gopay", "ideal"} and provider_proxy:
5451
+ set_proxy_url(chatgpt, provider_proxy)
5452
+ log_info("stripe.prepare.skip", reason="use_zip_provider_flow")
5453
  log_info("stripe.pre_confirm.skip", reason="use_zip_provider_flow")
5454
  ctx = stripe_context(checkout["cs_id"], init_payload, req)
5455
  log_info(
 
5516
  req,
5517
  stripe_hosted_url,
5518
  )
5519
+ if link_type == "upi":
5520
+ upi_details = upi_details_after_confirm(
5521
+ chatgpt,
5522
+ stripe,
5523
+ confirm_payload,
5524
+ checkout["cs_id"],
5525
+ stripe_pk,
5526
+ checkout,
5527
+ req,
5528
+ job_id=str(REQUEST_ID.get() or ""),
5529
+ pool_keep=max(1, min(50, int(req.pool_keep or 1))),
5530
+ pool_max=max(1, min(2000, int(req.pool_max or 1))),
5531
+ )
5532
+ fields = build_upi_provider_fields(pm_id, checkout, upi_details)
5533
+ log_info(
5534
+ "provider.create.done",
5535
+ payment_method_id=pm_id,
5536
+ provider_redirect_url=fields.get("provider_redirect_url", ""),
5537
+ long_url=fields.get("long_url", ""),
5538
+ next_action_type=fields.get("next_action_type", ""),
5539
+ provider_qr_ready=bool(fields.get("provider_qr_url") or fields.get("provider_qr_svg")),
5540
+ )
5541
+ return fields
5542
  stripe_redirect_url = redirect_url_after_confirm(
5543
  chatgpt,
5544
  stripe,
 
5553
  stripe_hosted_url,
5554
  )
5555
  action_type = next_action_type(confirm_payload)
5556
+ if link_type == "ideal":
 
 
5557
  provider_url = stripe_redirect_url
5558
  else:
5559
  preferred_hosts = (
5560
  PAYPAL_HOST_SUFFIXES
5561
  if link_type == "paypal"
5562
+ else ("gopay.co.id", "gojek.com", "midtrans.com")
5563
+ if link_type == "gopay"
 
 
5564
  else ()
5565
  )
5566
  provider_url = resolve_external_redirect(
 
5568
  stripe_redirect_url,
5569
  preferred_hosts=preferred_hosts,
5570
  )
5571
+ if link_type == "gopay":
5572
+ if not provider_url:
5573
+ raise HTTPException(status_code=502, detail="provider redirect missing after approval")
5574
+ provider_host = (urlsplit(provider_url).hostname or "").lower()
5575
+ if not any(
5576
+ provider_host == host or provider_host.endswith(f".{host}")
5577
+ for host in preferred_hosts
5578
+ ):
5579
+ raise HTTPException(
5580
+ status_code=502,
5581
+ detail=f"provider redirect host mismatch: {provider_url[:200]}",
5582
+ )
5583
  log_info(
5584
  "provider.create.done",
5585
  payment_method_id=pm_id,
 
5588
  long_url=provider_url or stripe_redirect_url,
5589
  next_action_type=action_type,
5590
  )
5591
+ fields: dict[str, Any] = {
5592
+ "payment_method_id": pm_id,
5593
+ "stripe_redirect_url": stripe_redirect_url,
5594
+ "provider_redirect_url": provider_url,
5595
+ "long_url": provider_url or stripe_redirect_url,
5596
+ "next_action_type": action_type,
5597
+ }
5598
+ submission = confirm_payload.get("submission_attempt") if isinstance(confirm_payload, dict) else None
5599
+ submission_state = str((submission or {}).get("state") or "").strip()
5600
+ if link_type in {"gopay", "ideal"} and submission_state == "requires_approval":
5601
+ fields.update(
5602
+ {
5603
+ "approval_result": "approved",
5604
+ "submission_state": submission_state,
5605
+ "completion_stage": "provider_redirect_ready",
5606
+ }
5607
+ )
5608
+ return fields
5609
 
5610
 
5611
  app = FastAPI(title="OpenAI Pay Long Link")
 
6273
 
6274
 
6275
  def cdk_ideal_response_succeeded(response: LongLinkResponse | None) -> bool:
6276
+ return bool(response and not response.fallback and response.provider_redirect_url)
6277
+
6278
+
6279
+ def long_link_provider_succeeded(response: LongLinkResponse | None) -> bool:
6280
+ if not response or response.fallback:
6281
+ return False
6282
+ if normalize_link_type(response.link_type) == "upi":
6283
+ return bool(
6284
+ response.provider_redirect_url
6285
+ or response.upi_hosted_url
6286
+ or response.provider_qr_url
6287
+ or response.provider_qr_svg
6288
+ or response.upi_qr_data
6289
+ or response.upi_qr_image_url
6290
+ )
6291
+ return bool(response.provider_redirect_url)
6292
 
6293
 
6294
  def long_link_response_from_dict(data: dict[str, Any] | None) -> LongLinkResponse | None:
 
6525
 
6526
 
6527
  def result_expiry_timestamp(response: LongLinkResponse | None) -> int:
6528
+ if not response:
6529
  return 0
6530
+ link_type = normalize_link_type(response.link_type)
6531
+ if link_type == "upi":
6532
+ return max(0, int(response.provider_expires_at or 0))
6533
+ if link_type == "ideal" and str(response.long_url or "").strip():
6534
+ return now_ts() + IDEAL_LINK_VALID_SECONDS
6535
+ return 0
6536
 
6537
 
6538
  @app.get("/")
 
7066
  stripe_key_source=stripe_key_source,
7067
  processor_entity=checkout.get("processor_entity", ""),
7068
  )
7069
+ if link_type == "paypal":
7070
  # iDEAL must be present at NL bootstrap. PayPal/UPI can be absent
7071
  # before the promotion refresh, so validate them afterwards.
7072
  if link_type == "ideal":
 
7138
  processor_entity=checkout.get("processor_entity", ""),
7139
  )
7140
  require_payment_method_available(init_payload, "upi")
7141
+ if link_type not in {"upi", "gopay", "ideal"}:
7142
+ enforce_zero_checkout_amount(init_payload, req, checkout["cs_id"])
7143
  stop_if_requested()
7144
  checkout_amount = expected_amount(init_payload)
7145
  checkout_amount_currency = str(init_payload.get("currency") or checkout["currency"]).upper()
7146
  advance(45, "金额检测", f"付款金额 {checkout_amount} {checkout_amount_currency}")
7147
  stripe_hosted_url = str(init_payload.get("stripe_hosted_url") or "").strip()
7148
+ if not stripe_hosted_url and link_type not in {"upi", "gopay", "ideal"}:
7149
  detail = f"stripe init response missing stripe_hosted_url, keys={response_keys(init_payload)}"
7150
  log_warning("stripe.init.missing_hosted_url", detail=detail)
7151
  raise HTTPException(status_code=502, detail=detail)
7152
+ hosted_long_url = to_openai_pay_url(stripe_hosted_url) or str(checkout.get("checkout_url") or "").strip()
7153
  log_info("api.hosted_url.ready", stripe_hosted_url=stripe_hosted_url, hosted_long_url=hosted_long_url)
7154
  advance(55, "重写长链", f"已获得 hosted 长链,正在提取 {link_type.upper()} 链")
7155
  provider = {
 
7173
  stop_if_requested()
7174
  advance(92, "Provider", f"已获得 {link_type.upper()} 跳转链接")
7175
  except HTTPException as exc:
7176
+ if link_type in {"upi", "gopay", "ideal"}:
7177
+ raise
7178
  fallback = True
7179
  provider_error = provider_error_diagnostic(exc.detail, link_type, checkout, req)
7180
  advance(92, "回退 hosted", f"{link_type.upper()} 提取失败,返回 hosted 长链")
 
7185
  fallback_url=hosted_long_url,
7186
  )
7187
  except Exception as exc:
7188
+ if link_type in {"upi", "gopay", "ideal"}:
7189
+ raise
7190
  fallback = True
7191
  provider_error = provider_error_diagnostic(repr(exc), link_type, checkout, req)
7192
  advance(92, "回退 hosted", f"{link_type.upper()} 提取异常,返回 hosted 长链")
 
7203
  billing_country=checkout["billing_country"],
7204
  currency=checkout["currency"],
7205
  checkout_amount=checkout_amount,
7206
+ payment_locale=locale_parts(effective_payment_locale(link_type, req.payment_locale))[0],
7207
  link_type=link_type,
7208
  payment_method_type=link_type,
7209
+ payment_method_id=str(provider.get("payment_method_id") or ""),
7210
+ stripe_redirect_url=str(provider.get("stripe_redirect_url") or ""),
7211
+ provider_redirect_url=str(provider.get("provider_redirect_url") or ""),
7212
  fallback=fallback,
7213
  provider_error=provider_error,
7214
  stripe_hosted_url=stripe_hosted_url,
7215
+ long_url=str(provider.get("long_url") or "") or hosted_long_url,
7216
  ideal_qr_url=(
7217
+ extract_ideal_qr_url(provider.get("provider_redirect_url"))
7218
  if link_type == "ideal" and not fallback
7219
  else ""
7220
  ),
7221
+ provider_qr_url=str(provider.get("provider_qr_url") or ""),
7222
+ provider_qr_svg=str(provider.get("provider_qr_svg") or ""),
7223
+ provider_expires_at=int(provider.get("provider_expires_at") or 0),
7224
+ next_action_type=str(provider.get("next_action_type") or ""),
7225
+ upi_qr_data=str(provider.get("upi_qr_data") or ""),
7226
+ upi_qr_image_url=str(provider.get("upi_qr_image_url") or ""),
7227
+ upi_hosted_url=str(provider.get("upi_hosted_url") or ""),
7228
+ approval_result=str(provider.get("approval_result") or ""),
7229
+ submission_state=str(provider.get("submission_state") or ""),
7230
+ completion_stage=str(provider.get("completion_stage") or ""),
7231
  )
7232
  log_info(
7233
  "api.long_link.done",
 
7597
  if user.get("role") == "cdk" and not response.fallback and response.provider_redirect_url:
7598
  user = require_cdk_user(req.cdk, consume=True)
7599
  record_user_success(user["username"], response)
7600
+ if long_link_provider_succeeded(response):
7601
+ record_proxy_success(user["username"], req)
7602
  return response
7603
 
7604
 
 
7652
  raise HTTPException(status_code=403, detail="CDK only supports iDEAL extraction")
7653
  response = build_long_link_response(req)
7654
  record_user_success(user["username"], response)
7655
+ if long_link_provider_succeeded(response):
7656
+ record_proxy_success(user["username"], req)
7657
  return response
7658
 
7659
 
 
7780
  if task_cancel_requested(task_id):
7781
  return
7782
  record_user_success(owner, response)
7783
+ if long_link_provider_succeeded(response):
7784
+ record_proxy_success(owner, req)
7785
  set_latest_result(task_id, response)
7786
  result_expires_at = result_expiry_timestamp(response)
7787
  set_task_state(
 
7849
  base_promo_proxy = select_proxy_from_pool(promo_candidates, pool_index) or base_nl_proxy
7850
  nl_seed = proxy_for_attempt(base_nl_proxy, attempt, "idealnl", force=dynamic_pool)
7851
  promo_seed = proxy_for_attempt(base_promo_proxy, attempt, "idealvn", force=dynamic_pool)
7852
+ nl_proxy = proxy_for_provider_region(nl_seed, "NL")
7853
  promotion_proxy = proxy_for_required_country(promo_seed, "VN")
7854
  if base_nl_proxy and not nl_proxy:
7855
  raise HTTPException(status_code=422, detail="iDEAL 主代理无法切换到 NL")
 
7906
  # UPI keeps the IN -> VN -> IN country chain while proxy_for_attempt keeps
7907
  # the dynamic SID/session for this provider attempt. Confirm and poll then
7908
  # reuse that same provider proxy unchanged.
7909
+ provider_country = "IN" if link_type == "upi" else "JP" if gopay_mode else (effective_pm_country(req) if link_type == "paypal" else "")
7910
  provider_source = base_provider_proxy or base_checkout_proxy
7911
  if provider_source and provider_country:
7912
  aligned_provider = (
7913
+ proxy_for_provider_region(provider_source, provider_country)
7914
+ if link_type in {"upi", "gopay"}
7915
  else proxy_for_required_country(provider_source, provider_country)
7916
  )
7917
  if not aligned_provider:
 
7922
  base_provider_proxy = aligned_provider
7923
  checkout_proxy = proxy_for_attempt(base_checkout_proxy, attempt, "checkout", force=dynamic_pool)
7924
  provider_proxy = proxy_for_attempt(base_provider_proxy, attempt, "provider", force=dynamic_pool)
7925
+ if link_type in {"upi", "gopay"}:
7926
+ checkout_proxy = proxy_for_provider_region(checkout_proxy, "JP")
7927
  if link_type == "paypal":
7928
  checkout_country = effective_country(req)
7929
  aligned_checkout = proxy_for_required_country(checkout_proxy, checkout_country)
 
7931
  raise HTTPException(status_code=422, detail=f"PayPal Checkout 代理无法切换到账单国家 {checkout_country}")
7932
  checkout_proxy = aligned_checkout
7933
  if provider_proxy and provider_country:
7934
+ verified_provider = (
7935
+ proxy_for_provider_region(provider_proxy, provider_country)
7936
+ if link_type in {"upi", "gopay"}
7937
+ else proxy_for_required_country(provider_proxy, provider_country)
7938
+ )
7939
  if not verified_provider:
7940
  raise HTTPException(
7941
  status_code=422,
 
8042
  if task_cancel_requested(task_id):
8043
  return
8044
  last_response = response
8045
+ provider_success = long_link_provider_succeeded(response)
8046
  if owner_role == "cdk" and normalize_link_type(req.link_type) == "ideal":
8047
  provider_success = cdk_ideal_response_succeeded(response)
8048
  if provider_success:
 
8217
  def start_ideal_long_link_task(req: LongLinkRequest, request: Request) -> LongLinkTaskStartResponse:
8218
  user = link_request_user(req, request, consume_cdk=False)
8219
  req = apply_runtime_defaults(req)
8220
+ checkout_proxy = proxy_for_provider_region(checkout_stage_proxy(req), "NL")
8221
+ provider_proxy = proxy_for_provider_region(provider_stage_proxy(req) or checkout_proxy, "NL")
8222
  req = req.model_copy(
8223
  update={
8224
  "link_type": "ideal",
 
8269
  if user.get("role") == "cdk":
8270
  raise HTTPException(status_code=403, detail="CDK only supports iDEAL extraction")
8271
  req = apply_runtime_defaults(req)
8272
+ checkout_proxy = proxy_for_provider_region(checkout_stage_proxy(req), "JP")
8273
+ provider_proxy = proxy_for_provider_region(provider_stage_proxy(req) or checkout_proxy, "IN")
8274
  req = req.model_copy(
8275
  update={
8276
  "link_type": "upi",
 
8321
  if user.get("role") == "cdk":
8322
  raise HTTPException(status_code=403, detail="CDK only supports iDEAL extraction")
8323
  req = apply_runtime_defaults(req)
8324
+ checkout_proxy = proxy_for_provider_region(checkout_stage_proxy(req), "JP")
8325
+ provider_proxy = proxy_for_provider_region(provider_stage_proxy(req) or checkout_proxy, "JP")
8326
  req = req.model_copy(
8327
  update={
8328
  "link_type": "gopay",
deploy/openai-pay-pp.service DELETED
@@ -1,22 +0,0 @@
1
- [Unit]
2
- Description=OpenAI Pay Link Panel
3
- After=network-online.target
4
- Wants=network-online.target
5
-
6
- [Service]
7
- Type=simple
8
- User=openai-pay
9
- Group=openai-pay
10
- WorkingDirectory=/opt/openai-pay-pp
11
- EnvironmentFile=/etc/openai-pay-pp.env
12
- ExecStart=/opt/openai-pay-pp/.venv/bin/python -m uvicorn app:app --host 127.0.0.1 --port 8796 --no-access-log
13
- Restart=on-failure
14
- RestartSec=3
15
- NoNewPrivileges=true
16
- PrivateTmp=true
17
- ProtectSystem=strict
18
- ProtectHome=true
19
- ReadWritePaths=/opt/openai-pay-pp
20
-
21
- [Install]
22
- WantedBy=multi-user.target
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deploy/zz-safe-runtime.conf DELETED
@@ -1,7 +0,0 @@
1
- [Service]
2
- Environment="OPENAI_PAY_APPROVE_MAX_ATTEMPTS=3"
3
- Environment="OPENAI_PAY_APPROVE_POOL_WORKERS=1"
4
- Environment="OPENAI_PAY_APPROVE_POOL_MAX_WORKERS=1"
5
- Environment="OPENAI_PAY_APPROVE_POOL_MIN_WORKERS=1"
6
- Environment="OPENAI_PAY_STRIPE_REDIRECT_POLL_MAX_ATTEMPTS=3"
7
- Environment="OPENAI_PAY_STRIPE_VERSION=2025-03-31.basil; checkout_server_update_beta=v1; checkout_manual_approval_preview=v1"
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -3,3 +3,4 @@ uvicorn==0.49.0
3
  pydantic==2.13.4
4
  requests==2.34.2
5
  curl-cffi==0.15.0
 
 
3
  pydantic==2.13.4
4
  requests==2.34.2
5
  curl-cffi==0.15.0
6
+ segno==1.6.6
tests/test_app.py DELETED
@@ -1,1069 +0,0 @@
1
- import importlib
2
- import json
3
- import os
4
- import sys
5
- import tempfile
6
- import unittest
7
- from pathlib import Path
8
- from unittest.mock import patch
9
-
10
- from fastapi import HTTPException, Request
11
-
12
-
13
- ROOT = Path(__file__).resolve().parents[1]
14
- sys.path.insert(0, str(ROOT))
15
- os.environ.setdefault("OPENAI_PAY_AUTH_DB", str(Path(tempfile.gettempdir()) / "openai-pay-pp-tests.sqlite3"))
16
- app = importlib.import_module("app")
17
-
18
- UPSTREAM_CHECKOUT_CURRENCIES = frozenset(
19
- "USD AUD CAD GBP EUR CLP JPY INR IDR PKR THB MYR TWD VND PHP NGN ZAR KZT "
20
- "TZS EGP BRL SEK CZK PLN DKK NOK KRW COP MXN PEN HUF QAR RON ILS AED SGD "
21
- "NZD CHF SAR".split()
22
- )
23
- EXPECTED_ADMIN_COUNTRY_CODES = tuple(
24
- "AD AT AU BE BQ BR CA CH CK CY CZ DE DK EC EE ES FI FR GB GF GP GR GU HR HU "
25
- "IE IL IN IT JP LI LR LT LU LV MC ME MF MT NL NO NZ PL PR PS PT RO SE SI SK "
26
- "US ZA".split()
27
- )
28
-
29
-
30
- def fake_runtime_config():
31
- return {
32
- "runMode": app.RUN_MODE_CHECKOUT_JP_REST_PROVIDER,
33
- "proxyPoolMode": "dynamic",
34
- "billingCountry": "US",
35
- "pmCountry": "US",
36
- "paymentLocale": "en",
37
- "jpProxy": "http://buyer-region-MX:secret@proxy.example:8080",
38
- "usProxy": "http://buyer-region-TR:secret@proxy.example:8080",
39
- "stickyJpProxy": "",
40
- "stickyUsProxy": "",
41
- }
42
-
43
-
44
- class FakeResponse:
45
- def __init__(self, payload, status_code=200):
46
- self._payload = payload
47
- self.status_code = status_code
48
- self.text = json.dumps(payload)
49
- self.headers = {}
50
-
51
- def json(self):
52
- return self._payload
53
-
54
-
55
- class FakeApproveSession:
56
- def __init__(self, results):
57
- self.results = list(results)
58
- self.calls = []
59
- self.proxies = {}
60
- self.headers = {}
61
-
62
- def post(self, url, **kwargs):
63
- self.calls.append(url)
64
- if url.endswith("/sentinel/ping"):
65
- return FakeResponse({"ok": True})
66
- result = self.results.pop(0)
67
- return FakeResponse({"result": result})
68
-
69
-
70
- class FakeStripeSession:
71
- def __init__(self, payloads):
72
- self.payloads = list(payloads)
73
- self.calls = []
74
- self.proxies = {}
75
- self.headers = {}
76
-
77
- def post(self, url, **kwargs):
78
- self.calls.append((url, kwargs))
79
- return FakeResponse(self.payloads.pop(0))
80
-
81
-
82
- class PaymentFlowTests(unittest.TestCase):
83
- @staticmethod
84
- def long_link_response(**updates):
85
- data = {
86
- "ok": True,
87
- "cs_id": "cs_test",
88
- "processor_entity": "openai_llc",
89
- "billing_country": "NL",
90
- "currency": "EUR",
91
- "payment_locale": "nl-NL",
92
- "link_type": "ideal",
93
- "payment_method_type": "ideal",
94
- "payment_method_id": "pm_test",
95
- "stripe_redirect_url": "",
96
- "provider_redirect_url": "",
97
- "fallback": False,
98
- "provider_error": "",
99
- "stripe_hosted_url": "https://pay.openai.com/c/pay/cs_test",
100
- "long_url": "https://pay.openai.com/c/pay/cs_test",
101
- }
102
- data.update(updates)
103
- return app.LongLinkResponse(**data)
104
-
105
- def test_admin_country_catalog_only_contains_upstream_supported_currencies(self):
106
- self.assertEqual(app.CHECKOUT_SUPPORTED_CURRENCIES, UPSTREAM_CHECKOUT_CURRENCIES)
107
- self.assertEqual(len(EXPECTED_ADMIN_COUNTRY_CODES), 52)
108
- self.assertEqual(tuple(app.ADMIN_COUNTRY_CODES), EXPECTED_ADMIN_COUNTRY_CODES)
109
- self.assertEqual(len(app.ADMIN_COUNTRY_CODES), len(set(app.ADMIN_COUNTRY_CODES)))
110
- self.assertNotIn("AR", app.ADMIN_COUNTRY_CODES)
111
- self.assertIn("IL", app.ADMIN_COUNTRY_CODES)
112
- self.assertIn("PS", app.ADMIN_COUNTRY_CODES)
113
-
114
- option_codes = [item["code"] for item in app.admin_country_options()]
115
- self.assertEqual(option_codes, list(app.ADMIN_COUNTRY_CODES))
116
- self.assertEqual(option_codes, sorted(option_codes))
117
- for item in app.admin_country_options():
118
- self.assertIn(item["currency"], UPSTREAM_CHECKOUT_CURRENCIES)
119
-
120
- def test_admin_country_catalog_has_currency_timezone_and_local_billing_address(self):
121
- for country in app.ADMIN_COUNTRY_CODES:
122
- with self.subTest(country=country):
123
- self.assertEqual(app.supported_country(country, ""), country)
124
- self.assertEqual(app.supported_checkout_country(country, ""), country)
125
- self.assertIn(country, app.COUNTRY_CURRENCY)
126
- self.assertIn(country, app.COUNTRY_TIMEZONE)
127
- self.assertTrue(country in app.BILLING_PROFILES or country in app.COUNTRY_CITY_SEEDS)
128
-
129
- normalized = app.normalize_runtime_config(
130
- {"billingCountry": country, "pmCountry": country}
131
- )
132
- self.assertEqual(normalized["billingCountry"], country)
133
- self.assertEqual(normalized["pmCountry"], country)
134
-
135
- billing = app.billing_for_link_type("paypal", country)
136
- self.assertEqual(billing["country"], country)
137
- self.assertTrue(billing["line1"])
138
- self.assertTrue(billing["city"])
139
- self.assertTrue(billing["postal_code"])
140
- self.assertNotEqual(billing["line1"], "Central Avenue 10")
141
- self.assertNotEqual(billing["city"], "Capital City")
142
-
143
- def test_unsupported_currency_country_is_removed_from_config_and_checkout_payload(self):
144
- normalized = app.normalize_runtime_config({"billingCountry": "AR", "pmCountry": "AR"})
145
- self.assertEqual(normalized["billingCountry"], "US")
146
- self.assertEqual(normalized["pmCountry"], "US")
147
- self.assertEqual(app.supported_checkout_country("AR", "DE"), "DE")
148
-
149
- stripe = FakeStripeSession([
150
- {
151
- "checkout_session_id": "cs_test_ar",
152
- "processor_entity": "openai_ie",
153
- "stripe_publishable_key": "pk_test_value",
154
- }
155
- ])
156
- checkout = app.create_checkout(
157
- app.LongLinkRequest(
158
- accessToken="token-value",
159
- billing_country="AR",
160
- pmCountry="AR",
161
- ),
162
- chatgpt_session=stripe,
163
- include_promo=False,
164
- )
165
- body = stripe.calls[0][1]["json"]
166
- self.assertEqual(body["billing_details"], {"country": "DE", "currency": "EUR"})
167
- self.assertNotEqual(body["billing_details"]["currency"], "ARS")
168
- self.assertEqual(checkout["billing_profile"]["country"], "DE")
169
-
170
- def test_supported_ils_country_reaches_checkout_unchanged(self):
171
- stripe = FakeStripeSession([
172
- {
173
- "checkout_session_id": "cs_test_il",
174
- "processor_entity": "openai_ie",
175
- "stripe_publishable_key": "pk_test_value",
176
- }
177
- ])
178
- checkout = app.create_checkout(
179
- app.LongLinkRequest(
180
- accessToken="token-value",
181
- billing_country="IL",
182
- pmCountry="IL",
183
- ),
184
- chatgpt_session=stripe,
185
- include_promo=False,
186
- )
187
- body = stripe.calls[0][1]["json"]
188
- self.assertEqual(body["billing_details"], {"country": "IL", "currency": "ILS"})
189
- self.assertEqual(checkout["billing_profile"]["country"], "IL")
190
-
191
- def test_new_country_currency_mappings(self):
192
- expected = {
193
- "AG": "XCD", "AO": "AOA", "AR": "ARS", "BD": "BDT", "BF": "XOF",
194
- "BH": "BHD", "CD": "CDF", "CF": "XAF", "CK": "NZD", "CW": "ANG",
195
- "EC": "USD", "GF": "EUR", "IL": "ILS", "IQ": "IQD", "KW": "KWD",
196
- "MF": "EUR", "MR": "MRU", "PS": "ILS", "WS": "WST", "YE": "YER",
197
- }
198
- for country, currency in expected.items():
199
- with self.subTest(country=country):
200
- self.assertEqual(app.currency_for_country(country), currency)
201
-
202
- def test_frontend_populates_billing_and_pm_selects_from_backend_catalog(self):
203
- source = (ROOT / "public" / "index.html").read_text(encoding="utf-8")
204
- self.assertIn('["adminBillingCountry", "adminPmCountry"]', source)
205
- self.assertIn("populateAdminCountrySelects(data.countries || [])", source)
206
- self.assertIn("checkoutSupportedCurrencies.has(item.currency)", source)
207
- for select_id in ("adminBillingCountry", "adminPmCountry"):
208
- markup = source.split(f'<select id="{select_id}">', 1)[1].split("</select>", 1)[0]
209
- for unsupported in ("BG", "IS", "TR"):
210
- self.assertNotIn(f'value="{unsupported}"', markup)
211
-
212
- def test_proxy_country_rewrite_and_session_pin(self):
213
- source = "http://buyer-region-TR:secret@proxy.example:8080"
214
- rewritten = app.proxy_for_payment_country(source, "IN", "session123")
215
- self.assertEqual(app.proxy_country_hint(rewritten), "IN")
216
- self.assertIn("session123", rewritten)
217
- self.assertNotIn("region-TR", rewritten)
218
-
219
- def test_runtime_defaults_use_stage_proxy_environment(self):
220
- checkout = "http://buyer-region-IN:secret@proxy.example:8080"
221
- promotion = "http://buyer-region-TR:secret@proxy.example:8080"
222
- with patch.dict(
223
- os.environ,
224
- {
225
- "OPENAI_PAY_CHECKOUT_PROXY": checkout,
226
- "OPENAI_PAY_PROVIDER_PROXY": checkout,
227
- "OPENAI_PAY_PROMOTION_PROXY": promotion,
228
- },
229
- ):
230
- config = app.default_runtime_config()
231
-
232
- self.assertEqual(config["jpProxy"], checkout)
233
- self.assertEqual(config["usProxy"], checkout)
234
- self.assertEqual(config["idealPromoProxy"], promotion)
235
-
236
- def test_success_proxy_persistence_failure_does_not_break_provider_flow(self):
237
- with patch.object(app, "auth_db", side_effect=RuntimeError("database unavailable")):
238
- app.save_success_proxy(
239
- "approve",
240
- "http://buyer-region-IN:secret@proxy.example:8080",
241
- )
242
-
243
- def test_upi_reuses_stripe_customer_billing(self):
244
- billing = app.billing_from_stripe_init(
245
- {
246
- "customer": {
247
- "name": "Neha Sharma",
248
- "email": "neha@example.com",
249
- "address": {
250
- "country": "IN",
251
- "line1": "12 MG Road",
252
- "city": "Kohima",
253
- "state": "Nagaland",
254
- "postal_code": "797001",
255
- },
256
- }
257
- },
258
- "upi",
259
- "IN",
260
- )
261
- self.assertEqual(billing["name"], "Neha Sharma")
262
- self.assertEqual(billing["city"], "Kohima")
263
- self.assertEqual(billing["state"], "Nagaland")
264
- self.assertEqual(billing["postal_code"], "797001")
265
-
266
- def test_checkout_carries_one_billing_profile_for_later_upi_stages(self):
267
- session = FakeStripeSession([])
268
- session.post = lambda *args, **kwargs: FakeResponse(
269
- {
270
- "checkout_session_id": "cs_test_billing_profile",
271
- "checkout_provider": "stripe",
272
- "processor_entity": "openai_llc",
273
- "stripe_publishable_key": "pk_test",
274
- }
275
- )
276
- req = app.LongLinkRequest(accessToken="token-value", link_type="upi", billing_country="IN", pmCountry="IN")
277
- checkout = app.create_checkout(req, session)
278
- self.assertEqual(checkout["billing_profile"]["country"], "IN")
279
- self.assertTrue(checkout["billing_profile"]["name"])
280
-
281
- def test_promotion_retries_transient_403_on_same_checkout(self):
282
- checkout = {"cs_id": "cs_same", "processor_entity": "openai_llc"}
283
- with (
284
- patch.object(
285
- app,
286
- "update_checkout_promotion",
287
- side_effect=[HTTPException(status_code=403, detail="blocked node"), {"success": True}],
288
- ) as update,
289
- patch.object(app.time, "sleep"),
290
- ):
291
- result = app.update_checkout_promotion_retrying(
292
- object(), checkout, "http://buyer-region-TR:secret@proxy.example:8080", 3
293
- )
294
- self.assertEqual(result, {"success": True})
295
- self.assertEqual(update.call_count, 2)
296
- self.assertEqual(update.call_args_list[0].args[1], checkout)
297
- self.assertEqual(update.call_args_list[1].args[1], checkout)
298
-
299
- def test_retry_plan_keeps_approve_on_checkout_and_routes_provider(self):
300
- cases = (("paypal", "US"), ("ideal", "TR"), ("upi", "IN"))
301
- with patch.object(app, "get_runtime_config", side_effect=fake_runtime_config):
302
- for link_type, expected_provider_country in cases:
303
- req = app.LongLinkRequest(
304
- accessToken="token-value",
305
- link_type=link_type,
306
- billing_country="US" if link_type == "paypal" else expected_provider_country,
307
- pmCountry=expected_provider_country,
308
- proxyPoolMode="dynamic",
309
- )
310
- planned = app.request_for_retry_attempt(req, 1)
311
- self.assertEqual(planned.approve_proxy, planned.checkout_proxy)
312
- self.assertEqual(app.proxy_country_hint(planned.checkout_proxy), "MX")
313
- expected_provider = {"ideal": "MX", "upi": "IN"}.get(link_type, "TR")
314
- self.assertEqual(app.proxy_country_hint(planned.provider_proxy), expected_provider)
315
- if link_type == "paypal":
316
- self.assertEqual(app.proxy_country_hint(planned.promotion_proxy), "MX")
317
-
318
- def test_upi_keeps_in_dynamic_provider_for_confirm_and_poll(self):
319
- provider_proxy = "http://buyer-region-TR-session-dynamic:secret@proxy.example:8080"
320
- req = app.LongLinkRequest(
321
- accessToken="token-value",
322
- link_type="upi",
323
- billing_country="IN",
324
- pmCountry="IN",
325
- providerProxy=provider_proxy,
326
- proxyPoolMode="dynamic",
327
- )
328
- config = fake_runtime_config()
329
- config["usProxy"] = ""
330
-
331
- with patch.object(app, "get_runtime_config", return_value=config):
332
- planned = app.request_for_retry_attempt(req, 1)
333
-
334
- self.assertEqual(app.proxy_country_hint(planned.provider_proxy), "IN")
335
- self.assertIn("buyer-region-IN-session-", planned.provider_proxy)
336
- stripe = FakeStripeSession([])
337
- app.set_proxy_url(stripe, planned.provider_proxy)
338
- self.assertEqual(app.redirect_poll_proxy_pool(planned, stripe), [planned.provider_proxy])
339
-
340
- def test_upi_keeps_explicit_tr_promotion_template_unchanged(self):
341
- checkout_proxy = "http://buyer-region-IN:secret@proxy.example:8080"
342
- promotion_proxy = "http://buyer-region-TR:secret@proxy.example:8080"
343
- req = app.LongLinkRequest(
344
- accessToken="token-value",
345
- link_type="upi",
346
- billing_country="IN",
347
- pmCountry="IN",
348
- checkoutProxy=checkout_proxy,
349
- providerProxy=checkout_proxy,
350
- promotionProxy=promotion_proxy,
351
- proxyPoolMode="dynamic",
352
- )
353
- config = fake_runtime_config()
354
- config["jpProxy"] = ""
355
- config["usProxy"] = ""
356
- with patch.object(app, "get_runtime_config", return_value=config):
357
- planned = app.request_for_retry_attempt(req, 1)
358
-
359
- self.assertEqual(app.proxy_country_hint(planned.checkout_proxy), "IN")
360
- self.assertEqual(app.proxy_country_hint(planned.provider_proxy), "IN")
361
- self.assertEqual(app.proxy_country_hint(planned.promotion_proxy), "TR")
362
-
363
- def test_paypal_retry_rebuild_switches_to_inline_confirm(self):
364
- req = app.LongLinkRequest(
365
- accessToken="token-value",
366
- link_type="paypal",
367
- billing_country="US",
368
- pmCountry="US",
369
- proxyPoolMode="dynamic",
370
- )
371
- with patch.object(app, "get_runtime_config", side_effect=fake_runtime_config):
372
- first = app.request_for_retry_attempt(req, 1)
373
- second = app.request_for_retry_attempt(req, 2)
374
- self.assertEqual(first.paypal_confirm_strategy, "baseline")
375
- self.assertEqual(second.paypal_confirm_strategy, "inline")
376
- self.assertEqual(second.billing_country, "US")
377
- self.assertEqual(app.proxy_country_hint(second.provider_proxy), "TR")
378
- self.assertEqual(second.approve_proxy, second.checkout_proxy)
379
-
380
- def test_paypal_tax_region_uses_billing_address(self):
381
- stripe = FakeStripeSession([{"init_checksum": "updated"}])
382
- init_payload = {"stripe_hosted_url": "https://checkout.stripe.com/c/pay/cs_test"}
383
- billing = {
384
- "country": "US",
385
- "state": "CA",
386
- "postal_code": "94105",
387
- "line1": "123 Market St",
388
- "city": "San Francisco",
389
- }
390
- app.stripe_update_paypal_tax_region(
391
- stripe,
392
- "cs_test",
393
- "pk_test",
394
- billing,
395
- init_payload,
396
- init_payload["stripe_hosted_url"],
397
- )
398
- url, kwargs = stripe.calls[0]
399
- self.assertEqual(url, "https://api.stripe.com/v1/payment_pages/cs_test")
400
- self.assertEqual(kwargs["data"]["tax_region[country]"], "US")
401
- self.assertEqual(kwargs["data"]["tax_region[state]"], "CA")
402
- self.assertEqual(init_payload["init_checksum"], "updated")
403
-
404
- def test_inline_paypal_confirm_submits_payment_method_data(self):
405
- stripe = FakeStripeSession([{"setup_intent": {"status": "requires_action"}}])
406
- req = app.LongLinkRequest(
407
- accessToken="token-value",
408
- link_type="paypal",
409
- billing_country="US",
410
- checkout_ui_mode="custom",
411
- paypalConfirmStrategy="inline",
412
- )
413
- ctx = app.stripe_context("cs_test", {"init_checksum": "sum", "amount": 0}, req)
414
- app.stripe_confirm_direct_paypal(
415
- stripe,
416
- "cs_test",
417
- "pk_test",
418
- {
419
- "name": "Jane Doe",
420
- "email": "jane@example.com",
421
- "country": "US",
422
- "line1": "123 Market St",
423
- "city": "San Francisco",
424
- "postal_code": "94105",
425
- "state": "CA",
426
- },
427
- {"init_checksum": "sum", "amount": 0},
428
- ctx,
429
- {"billing_country": "US", "currency": "USD"},
430
- req,
431
- "https://checkout.stripe.com/c/pay/cs_test",
432
- )
433
- url, kwargs = stripe.calls[0]
434
- self.assertEqual(url, "https://api.stripe.com/v1/payment_pages/cs_test/confirm")
435
- self.assertEqual(kwargs["data"]["payment_method_data[type]"], "paypal")
436
- self.assertEqual(kwargs["data"]["payment_method_data[billing_details][address][country]"], "US")
437
- self.assertNotIn("payment_method", kwargs["data"])
438
-
439
- def test_upi_next_action_returns_hosted_instructions(self):
440
- payload = {
441
- "setup_intent": {
442
- "object": "setup_intent",
443
- "status": "requires_action",
444
- "next_action": {
445
- "type": "upi_handle_redirect_or_display_qr_code",
446
- "upi_handle_redirect_or_display_qr_code": {
447
- "hosted_instructions_url": "https://hooks.stripe.com/upi/instructions",
448
- "qr_code": {
449
- "image_url_png": "https://hooks.stripe.com/upi/code.png",
450
- "image_url_svg": "https://hooks.stripe.com/upi/code.svg",
451
- },
452
- },
453
- },
454
- }
455
- }
456
- self.assertEqual(app.next_action_type(payload), "upi_handle_redirect_or_display_qr_code")
457
- self.assertEqual(app.extract_redirect_to_url(payload), "https://hooks.stripe.com/upi/instructions")
458
-
459
- def test_explicit_payment_method_detection(self):
460
- payload = {
461
- "payment_method_types": ["card", "upi"],
462
- "payment_method_specs": [{"type": "paypal"}],
463
- "paypal_unrelated_copy": True,
464
- }
465
- self.assertEqual(app.available_payment_method_types(payload), {"card", "upi", "paypal"})
466
- self.assertTrue(app.payment_method_is_available(payload, "upi"))
467
- with self.assertRaises(HTTPException):
468
- app.require_payment_method_available({"payment_method_types": ["card"]}, "ideal")
469
-
470
- def test_gopay_normalization_and_explicit_availability(self):
471
- payload = {
472
- "payment_method_types": ["card"],
473
- "payment_method_specs": [{"type": "gopay"}],
474
- }
475
-
476
- self.assertEqual(app.normalize_link_type("gopy"), "gopay")
477
- self.assertEqual(app.normalize_link_type(" GoPay "), "gopay")
478
- self.assertIn("gopay", app.available_payment_method_types(payload))
479
- self.assertTrue(app.payment_method_is_available(payload, "gopy"))
480
- app.require_payment_method_available(payload, "gopay")
481
-
482
- def test_gopay_forces_effective_billing_and_payment_method_country_to_id(self):
483
- req = app.LongLinkRequest(
484
- accessToken="token-value",
485
- link_type="gopy",
486
- billing_country="US",
487
- pmCountry="NL",
488
- )
489
-
490
- self.assertEqual(app.effective_country(req), "ID")
491
- self.assertEqual(app.effective_pm_country(req), "ID")
492
-
493
- def test_gopay_payment_method_uses_minimal_payload(self):
494
- stripe = FakeStripeSession([{"id": "pm_gopay_test"}])
495
- billing = {
496
- "name": "Budi Santoso",
497
- "email": "budi@example.com",
498
- "country": "ID",
499
- "line1": "Jl. Jend. Sudirman No. 1",
500
- "city": "Jakarta",
501
- "postal_code": "10210",
502
- "state": "DKI Jakarta",
503
- }
504
-
505
- pm_id = app.stripe_create_payment_method(
506
- stripe,
507
- "cs_gopay_test",
508
- "pk_test_value",
509
- billing,
510
- "gopay",
511
- {"checkout_ui_mode": "custom", "currency": "idr", "checkout_amount": "0"},
512
- )
513
-
514
- self.assertEqual(pm_id, "pm_gopay_test")
515
- url, kwargs = stripe.calls[0]
516
- self.assertEqual(url, "https://api.stripe.com/v1/payment_methods")
517
- self.assertEqual(
518
- kwargs["data"],
519
- {
520
- "billing_details[name]": "Budi Santoso",
521
- "billing_details[email]": "budi@example.com",
522
- "billing_details[address][country]": "ID",
523
- "billing_details[address][line1]": "Jl. Jend. Sudirman No. 1",
524
- "billing_details[address][city]": "Jakarta",
525
- "billing_details[address][postal_code]": "10210",
526
- "billing_details[address][state]": "DKI Jakarta",
527
- "type": "gopay",
528
- "client_attribution_metadata[checkout_session_id]": "cs_gopay_test",
529
- "key": "pk_test_value",
530
- },
531
- )
532
- self.assertIsNone(kwargs["headers"])
533
-
534
- def test_gopay_confirm_fetches_fresh_checksum_and_uses_special_payload(self):
535
- stripe = FakeStripeSession(
536
- [
537
- {"init_checksum": "fresh-gopay-checksum"},
538
- {"setup_intent": {"status": "requires_action"}},
539
- ]
540
- )
541
- req = app.LongLinkRequest(
542
- accessToken="token-value",
543
- link_type="gopay",
544
- billing_country="US",
545
- pmCountry="NL",
546
- checkout_ui_mode="custom",
547
- paymentLocale="en",
548
- )
549
- ctx = {
550
- "init_checksum": "stale-context-checksum",
551
- "checkout_amount": "999",
552
- "checkout_ui_mode": "custom",
553
- }
554
-
555
- app.stripe_confirm(
556
- stripe,
557
- "cs_gopay_test",
558
- "pm_gopay_test",
559
- "pk_test_value",
560
- "gopay",
561
- {"init_checksum": "stale-payload-checksum", "total_summary": {"due": 999}},
562
- ctx,
563
- {"billing_country": "ID", "processor_entity": "openai_ie"},
564
- req,
565
- "https://checkout.stripe.com/c/pay/cs_gopay_test",
566
- )
567
-
568
- init_url, init_kwargs = stripe.calls[0]
569
- self.assertEqual(init_url, "https://api.stripe.com/v1/payment_pages/cs_gopay_test/init")
570
- self.assertEqual(init_kwargs["data"]["browser_timezone"], "Asia/Shanghai")
571
- self.assertEqual(init_kwargs["data"]["elements_session_client[elements_init_source]"], "custom_checkout")
572
- self.assertEqual(init_kwargs["data"]["key"], "pk_test_value")
573
-
574
- confirm_url, confirm_kwargs = stripe.calls[1]
575
- confirm_body = confirm_kwargs["data"]
576
- self.assertEqual(confirm_url, "https://api.stripe.com/v1/payment_pages/cs_gopay_test/confirm")
577
- self.assertEqual(confirm_body["payment_method"], "pm_gopay_test")
578
- self.assertEqual(confirm_body["init_checksum"], "fresh-gopay-checksum")
579
- self.assertEqual(confirm_body["version"], "fed52f3bc6")
580
- self.assertEqual(confirm_body["expected_amount"], "0")
581
- self.assertEqual(confirm_body["expected_payment_method_type"], "gopay")
582
- self.assertEqual(confirm_body["client_attribution_metadata[merchant_integration_source]"], "elements")
583
- self.assertEqual(confirm_body["client_attribution_metadata[payment_intent_creation_flow]"], "deferred")
584
- self.assertEqual(confirm_body["consent[terms_of_service]"], "accepted")
585
- self.assertEqual(confirm_body["key"], "pk_test_value")
586
- self.assertNotIn("_stripe_version", confirm_body)
587
- self.assertNotIn("stale-context-checksum", confirm_body.values())
588
- self.assertNotIn("stale-payload-checksum", confirm_body.values())
589
- self.assertIsNone(confirm_kwargs["headers"])
590
-
591
- def test_approval_blocked_is_terminal_and_bounded(self):
592
- session = FakeApproveSession(["blocked", "approved", "approved"])
593
- with self.assertRaises(HTTPException) as caught:
594
- app.chatgpt_approve(
595
- session,
596
- "cs_test_blocked",
597
- {"billing_country": "US", "processor_entity": "openai_llc"},
598
- )
599
- self.assertEqual(caught.exception.status_code, 409)
600
- approve_calls = [url for url in session.calls if url.endswith("/checkout/approve")]
601
- self.assertEqual(len(approve_calls), 1)
602
-
603
- def test_approval_pending_is_not_retried(self):
604
- session = FakeApproveSession(["processing", "approved"])
605
- with self.assertRaises(HTTPException):
606
- app.chatgpt_approve(
607
- session,
608
- "cs_test_pending",
609
- {"billing_country": "US", "processor_entity": "openai_llc"},
610
- )
611
- approve_calls = [url for url in session.calls if url.endswith("/checkout/approve")]
612
- self.assertEqual(len(approve_calls), 1)
613
-
614
- def test_retry_classifier_stops_provider_declines(self):
615
- self.assertFalse(app.retryable_failure("setup_attempt_failed; generic_decline", 402))
616
- self.assertTrue(app.retryable_failure("setup_attempt_failed; generic_decline", 402, fresh_checkout=True))
617
- self.assertFalse(app.retryable_failure("Could not parse your authentication token", 401))
618
- self.assertTrue(app.retryable_failure("proxy TLS connect error", 502))
619
- self.assertTrue(app.retryable_failure("chatgpt approve pending result: 'blocked'", 409))
620
-
621
- def test_upi_uses_existing_stripe_schema_without_changing_paypal_and_ideal(self):
622
- self.assertEqual(app.stripe_version_for("paypal"), app.STRIPE_VERSION_FULL)
623
- self.assertEqual(app.stripe_version_for("ideal"), app.STRIPE_VERSION_FULL)
624
- self.assertEqual(app.stripe_version_for("upi"), app.STRIPE_VERSION_FULL)
625
- self.assertIn("2025-03-31.basil", app.stripe_version_for("ideal"))
626
- self.assertIn("2025-03-31.basil", app.stripe_version_for("upi"))
627
-
628
- def test_upi_stripe_init_uses_country_timezone_and_existing_version(self):
629
- stripe = FakeStripeSession([{"stripe_hosted_url": "https://checkout.stripe.com/c/pay/cs_upi_test"}])
630
- req = app.LongLinkRequest(
631
- accessToken="token-value",
632
- link_type="upi",
633
- billing_country="IN",
634
- pmCountry="IN",
635
- checkout_ui_mode="custom",
636
- )
637
- with patch.object(app, "new_session", return_value=stripe):
638
- app.stripe_init(
639
- "cs_upi_test",
640
- req,
641
- stripe_pk_override="pk_test_value",
642
- stripe_key_source="test",
643
- processor_entity="openai_ie",
644
- )
645
- body = stripe.calls[0][1]["data"]
646
- self.assertEqual(body["browser_timezone"], "Asia/Kolkata")
647
- self.assertEqual(body["elements_session_client[elements_init_source]"], "custom_checkout")
648
- self.assertEqual(body["_stripe_version"], app.STRIPE_VERSION_FULL)
649
-
650
- def test_upi_honors_explicit_checkout_ui_mode_like_other_providers(self):
651
- for ui_mode in ("hosted", "custom"):
652
- req = app.LongLinkRequest(
653
- accessToken="token-value",
654
- link_type="upi",
655
- billing_country="IN",
656
- pmCountry="IN",
657
- checkout_ui_mode=ui_mode,
658
- )
659
- ctx = app.stripe_context("cs_upi_test", {"currency": "inr"}, req)
660
-
661
- self.assertEqual(ctx["checkout_ui_mode"], ui_mode)
662
-
663
- def test_upi_uses_existing_custom_chain_with_upi_parameters(self):
664
- stripe = FakeStripeSession(
665
- [
666
- {"id": "pm_upi_test"},
667
- {
668
- "setup_intent": {
669
- "status": "requires_action",
670
- "next_action": {
671
- "type": "upi_handle_redirect_or_display_qr_code",
672
- "upi_handle_redirect_or_display_qr_code": {
673
- "hosted_instructions_url": "https://hooks.stripe.com/upi/instructions"
674
- },
675
- },
676
- }
677
- },
678
- ]
679
- )
680
- ctx = {
681
- "stripe_js_id": "stripe-js-test",
682
- "elements_session_id": "elements_session_test",
683
- "elements_session_config_id": "config-test",
684
- "config_id": "config-test",
685
- "init_checksum": "checksum-test",
686
- "checkout_amount": "0",
687
- "locale": "en",
688
- "checkout_ui_mode": "custom",
689
- "stripe_version": app.stripe_version_for("upi"),
690
- }
691
- billing = app.billing_for_link_type("upi", "IN")
692
- pm_id = app.stripe_create_payment_method(
693
- stripe,
694
- "cs_upi_test",
695
- "pk_test_value",
696
- billing,
697
- "upi",
698
- ctx,
699
- {"stripe_hosted_url": "https://checkout.stripe.com/c/pay/cs_upi_test"},
700
- "https://checkout.stripe.com/c/pay/cs_upi_test",
701
- )
702
- app.stripe_confirm(
703
- stripe,
704
- "cs_upi_test",
705
- pm_id,
706
- "pk_test_value",
707
- "upi",
708
- {"init_checksum": "checksum-test", "total_summary": {"due": 0}},
709
- ctx,
710
- {"billing_country": "IN", "processor_entity": "openai_ie"},
711
- app.LongLinkRequest(accessToken="token-value", link_type="upi", billing_country="IN", pmCountry="IN"),
712
- "https://checkout.stripe.com/c/pay/cs_upi_test",
713
- )
714
-
715
- pm_call = stripe.calls[0][1]
716
- pm_body = pm_call["data"]
717
- self.assertEqual(pm_body["type"], "upi")
718
- self.assertNotIn("payment_user_agent", pm_body)
719
- self.assertNotIn("_stripe_version", pm_body)
720
- self.assertEqual(pm_body["billing_details[address][country]"], "IN")
721
- self.assertEqual(pm_body["client_attribution_metadata[checkout_session_id]"], "cs_upi_test")
722
- self.assertIsNone(pm_call["headers"])
723
-
724
- confirm_call = stripe.calls[1][1]
725
- confirm_body = confirm_call["data"]
726
- self.assertEqual(confirm_body["expected_payment_method_type"], "upi")
727
- self.assertEqual(confirm_body["client_attribution_metadata[merchant_integration_version]"], "custom_checkout")
728
- self.assertEqual(confirm_body["link_brand"], "link")
729
- self.assertEqual(confirm_body["elements_session_client[elements_init_source]"], "custom_checkout")
730
- self.assertEqual(confirm_body["_stripe_version"], app.STRIPE_VERSION_FULL)
731
- self.assertEqual(confirm_body["eid"], "NA")
732
- self.assertNotIn("last_displayed_line_item_group_details[subtotal]", confirm_body)
733
- self.assertIn("processor_entity%3Dopenai_ie", confirm_body["return_url"])
734
- self.assertIn("redirect_pm_type=upi", confirm_body["return_url"])
735
- self.assertEqual(confirm_call["timeout"], app.DEFAULT_TIMEOUT)
736
- self.assertIsNone(confirm_call["headers"])
737
-
738
- def test_upi_runs_shared_promotion_refresh_before_zero_amount_guard(self):
739
- req = app.LongLinkRequest(
740
- accessToken="token-value",
741
- link_type="upi",
742
- billing_country="IN",
743
- pmCountry="IN",
744
- checkout_ui_mode="custom",
745
- )
746
- checkout = {
747
- "cs_id": "cs_upi_shared_chain",
748
- "processor_entity": "openai_ie",
749
- "billing_country": "IN",
750
- "currency": "INR",
751
- "stripe_publishable_key": "pk_test_value",
752
- }
753
- before_promotion = {
754
- "currency": "inr",
755
- "total_summary": {"due": 169407},
756
- "stripe_hosted_url": "https://checkout.stripe.com/c/pay/cs_upi_shared_chain",
757
- }
758
- after_promotion = {
759
- "currency": "inr",
760
- "total_summary": {"due": 0},
761
- "payment_method_types": ["upi"],
762
- "stripe_hosted_url": "https://checkout.stripe.com/c/pay/cs_upi_shared_chain",
763
- }
764
- call_order = []
765
-
766
- def fake_stripe_init(*args, **kwargs):
767
- call_order.append("stripe_init")
768
- return before_promotion if call_order.count("stripe_init") == 1 else after_promotion
769
-
770
- def fake_promotion(*args, **kwargs):
771
- call_order.append("promotion")
772
- return {}
773
-
774
- def fake_upi_tax(*args, **kwargs):
775
- call_order.append("upi_tax")
776
-
777
- with (
778
- patch.object(app, "build_chatgpt_session", return_value=object()),
779
- patch.object(app, "create_checkout", return_value=checkout),
780
- patch.object(app, "resolve_stripe_publishable_key", return_value=("pk_test_value", "test")),
781
- patch.object(app, "stripe_init", side_effect=fake_stripe_init),
782
- patch.object(app, "promotion_stage_proxy", return_value=""),
783
- patch.object(app, "update_checkout_promotion", side_effect=fake_promotion),
784
- patch.object(app, "update_upi_tax_context", side_effect=fake_upi_tax),
785
- patch.object(
786
- app,
787
- "create_provider_link",
788
- return_value={
789
- "payment_method_id": "pm_upi_test",
790
- "stripe_redirect_url": "https://hooks.stripe.com/upi/instructions",
791
- "provider_redirect_url": "https://hooks.stripe.com/upi/instructions",
792
- "long_url": "https://hooks.stripe.com/upi/instructions",
793
- },
794
- ),
795
- ):
796
- response = app.build_long_link_response(req)
797
-
798
- self.assertEqual(call_order, ["stripe_init", "promotion", "stripe_init", "upi_tax", "stripe_init"])
799
- self.assertEqual(response.checkout_amount, "0")
800
-
801
- def test_upi_tax_sync_failure_keeps_valid_zero_amount_checkout(self):
802
- req = app.LongLinkRequest(
803
- accessToken="token-value",
804
- link_type="upi",
805
- billing_country="IN",
806
- pmCountry="IN",
807
- checkout_ui_mode="custom",
808
- )
809
- checkout = {
810
- "cs_id": "cs_upi_tax_optional",
811
- "billing_country": "IN",
812
- "currency": "inr",
813
- "processor_entity": "openai_india",
814
- "stripe_publishable_key": "pk_test",
815
- }
816
- init_payload = {
817
- "payment_method_types": ["upi"],
818
- "currency": "inr",
819
- "checkout_amount": "0",
820
- "stripe_hosted_url": "https://checkout.stripe.com/c/pay/cs_upi_tax_optional",
821
- }
822
- with (
823
- patch.object(app, "create_checkout", return_value=checkout),
824
- patch.object(app, "stripe_init", side_effect=[init_payload, init_payload, init_payload]),
825
- patch.object(app, "update_checkout_promotion"),
826
- patch.object(
827
- app,
828
- "update_upi_tax_context",
829
- side_effect=app.HTTPException(status_code=403, detail="tax route blocked"),
830
- ),
831
- patch.object(
832
- app,
833
- "create_provider_link",
834
- return_value={
835
- "payment_method_id": "pm_upi_test",
836
- "stripe_redirect_url": "https://payments.stripe.com/upi/instructions/test",
837
- "provider_redirect_url": "https://payments.stripe.com/upi/instructions/test",
838
- "long_url": "https://payments.stripe.com/upi/instructions/test",
839
- },
840
- ),
841
- ):
842
- response = app.build_long_link_response(req)
843
-
844
- self.assertFalse(response.fallback)
845
- self.assertEqual(response.checkout_amount, "0")
846
- self.assertIn("payments.stripe.com/upi/instructions", response.long_url)
847
- self.assertFalse(response.fallback)
848
-
849
- def test_upi_approve_uses_provider_and_second_confirms_after_empty_poll(self):
850
- provider_proxy = "http://buyer-region-IN-session-provider:secret@proxy.example:8080"
851
- checkout_proxy = "http://buyer-region-IN-session-checkout:secret@proxy.example:8080"
852
- req = app.LongLinkRequest(
853
- accessToken="token-value",
854
- link_type="upi",
855
- billing_country="IN",
856
- pmCountry="IN",
857
- checkoutProxy=checkout_proxy,
858
- approveProxy=checkout_proxy,
859
- providerProxy=provider_proxy,
860
- checkout_ui_mode="custom",
861
- )
862
- confirm_payload = {"submission_attempt": {"state": "requires_approval"}}
863
- refreshed_init = {
864
- "init_checksum": "fresh-checksum",
865
- "currency": "inr",
866
- "total_summary": {"due": 0},
867
- "payment_method_types": ["upi"],
868
- "stripe_hosted_url": "https://checkout.stripe.com/c/pay/cs_upi_test",
869
- }
870
- checkout = {
871
- "cs_id": "cs_upi_test",
872
- "processor_entity": "openai_ie",
873
- "stripe_key_source": "test",
874
- }
875
- applied = []
876
-
877
- with (
878
- patch.object(app, "apply_approve_proxy", side_effect=lambda session, proxy: applied.append(proxy)),
879
- patch.object(app, "chatgpt_approve"),
880
- patch.object(app, "get_runtime_config", return_value=fake_runtime_config()),
881
- patch.object(
882
- app,
883
- "stripe_payment_page_redirect_url",
884
- side_effect=[HTTPException(status_code=504, detail="no redirect"), "https://hooks.stripe.com/upi/instructions"],
885
- ),
886
- patch.object(app, "stripe_init", return_value=refreshed_init),
887
- patch.object(app, "stripe_confirm", return_value={"status": "open", "state": "active"}) as second_confirm,
888
- ):
889
- result = app.redirect_url_after_confirm(
890
- object(),
891
- FakeStripeSession([]),
892
- confirm_payload,
893
- "cs_upi_test",
894
- "pm_upi_test",
895
- "pk_test_value",
896
- {"init_checksum": "old-checksum", "total_summary": {"due": 0}},
897
- {
898
- "stripe_js_id": "stripe-js-test",
899
- "elements_session_id": "elements-session-test",
900
- "elements_session_config_id": "config-test",
901
- "checkout_amount": "0",
902
- "locale": "en",
903
- "checkout_ui_mode": "custom",
904
- },
905
- checkout,
906
- req,
907
- "https://checkout.stripe.com/c/pay/cs_upi_test",
908
- )
909
-
910
- self.assertEqual(applied, [provider_proxy])
911
- self.assertEqual(result, "https://hooks.stripe.com/upi/instructions")
912
- self.assertEqual(second_confirm.call_count, 1)
913
- self.assertEqual(second_confirm.call_args.args[5]["init_checksum"], "fresh-checksum")
914
-
915
- def test_cdk_task_requires_matching_header(self):
916
- code = "CDK-UNITTEST1234"
917
- task = {"owner_role": "cdk", "owner": app.cdk_owner(code)}
918
- good = Request({"type": "http", "headers": [(b"x-cdk", code.encode())]})
919
- self.assertEqual(app.require_task_access(task, good)["role"], "cdk")
920
- bad = Request({"type": "http", "headers": [(b"x-cdk", b"CDK-WRONG")]})
921
- with self.assertRaises(HTTPException) as caught:
922
- app.require_task_access(task, bad)
923
- self.assertEqual(caught.exception.status_code, 403)
924
-
925
- def test_cdk_ideal_success_requires_real_ideal_provider_url(self):
926
- fallback = self.long_link_response(
927
- fallback=True,
928
- provider_error="generic_decline",
929
- )
930
- qr_url = "HTTPS://TX.IDEAL.NL/2/UNITTEST?sig=TEST"
931
- provider_url = f"https://pay.ideal.nl/transactions/{app.quote(qr_url, safe='')}"
932
- extracted = self.long_link_response(
933
- provider_redirect_url=provider_url,
934
- long_url=provider_url,
935
- ideal_qr_url=qr_url,
936
- )
937
- wrong_provider = self.long_link_response(
938
- provider_redirect_url="https://pay.openai.com/c/pay/cs_test",
939
- )
940
- self.assertFalse(app.cdk_ideal_response_succeeded(fallback))
941
- self.assertFalse(app.cdk_ideal_response_succeeded(wrong_provider))
942
- self.assertTrue(app.cdk_ideal_response_succeeded(extracted))
943
-
944
- def test_extracts_bank_qr_payload_from_ideal_payment_page_url(self):
945
- qr_url = "HTTPS://TX.IDEAL.NL/2/AWD3MJ3TP6CU6OPK3GH5EJE6Q44?sig=TESTSIGNATURE"
946
- encoded = app.quote(qr_url, safe="")
947
- provider_url = f"https://pay.ideal.nl/transactions/{encoded}"
948
- self.assertEqual(app.extract_ideal_qr_url(provider_url), qr_url)
949
-
950
- def test_cdk_fallback_task_finishes_as_failed_without_result(self):
951
- response = self.long_link_response(fallback=True, provider_error="generic_decline")
952
- req = app.LongLinkRequest(accessToken="token-value", cdk="CDK-UNITTEST1234", link_type="ideal")
953
- states = []
954
- with (
955
- patch.object(app, "build_long_link_response", return_value=response),
956
- patch.object(app, "request_for_retry_attempt", return_value=req),
957
- patch.object(app, "task_cancel_requested", return_value=False),
958
- patch.object(app, "wait_for_task_resume", return_value="running"),
959
- patch.object(app, "task_log_callback", return_value=lambda _: None),
960
- patch.object(app, "set_task_state", side_effect=lambda task_id, **state: states.append(state)),
961
- patch.object(app.time, "sleep", return_value=None),
962
- ):
963
- app.run_long_link_task_retrying("task_test", req, app.cdk_owner(req.cdk), "cdk")
964
- self.assertEqual(states[-1]["status"], "failed")
965
- self.assertNotIn("result", states[-1])
966
-
967
- def test_cdk_paypal_fallback_finishes_as_failed_without_result(self):
968
- response = self.long_link_response(
969
- link_type="paypal",
970
- payment_method_type="paypal",
971
- fallback=True,
972
- provider_error="generic_decline",
973
- )
974
- req = app.LongLinkRequest(accessToken="token-value", cdk="CDK-UNITTEST1234", link_type="paypal")
975
- states = []
976
- with (
977
- patch.object(app, "build_long_link_response", return_value=response),
978
- patch.object(app, "request_for_retry_attempt", return_value=req),
979
- patch.object(app, "task_cancel_requested", return_value=False),
980
- patch.object(app, "wait_for_task_resume", return_value="running"),
981
- patch.object(app, "task_log_callback", return_value=lambda _: None),
982
- patch.object(app, "set_task_state", side_effect=lambda task_id, **state: states.append(state)),
983
- patch.object(app.time, "sleep", return_value=None),
984
- ):
985
- app.run_long_link_task_retrying("task_paypal_fallback", req, app.cdk_owner(req.cdk), "cdk")
986
- self.assertEqual(states[-1]["status"], "failed")
987
- self.assertNotIn("result", states[-1])
988
-
989
- def test_admin_paypal_fallback_finishes_as_failed_without_result(self):
990
- response = self.long_link_response(
991
- link_type="paypal",
992
- payment_method_type="paypal",
993
- fallback=True,
994
- provider_error="chatgpt approve pending result: 'blocked' keys=result",
995
- )
996
- req = app.LongLinkRequest(accessToken="token-value", link_type="paypal")
997
- states = []
998
- with (
999
- patch.object(app, "build_long_link_response", return_value=response),
1000
- patch.object(app, "request_for_retry_attempt", return_value=req),
1001
- patch.object(app, "task_cancel_requested", return_value=False),
1002
- patch.object(app, "wait_for_task_resume", return_value="running"),
1003
- patch.object(app, "task_log_callback", return_value=lambda _: None),
1004
- patch.object(app, "set_task_state", side_effect=lambda task_id, **state: states.append(state)),
1005
- patch.object(app.time, "sleep", return_value=None),
1006
- ):
1007
- app.run_long_link_task_retrying("task_admin_paypal_fallback", req, "admin", "admin")
1008
- self.assertEqual(states[-1]["status"], "failed")
1009
- self.assertNotIn("result", states[-1])
1010
-
1011
- def test_cdk_paypal_success_consumes_once(self):
1012
- paypal_url = "https://www.paypal.com/checkoutnow?token=UNITTEST"
1013
- response = self.long_link_response(
1014
- link_type="paypal",
1015
- payment_method_type="paypal",
1016
- provider_redirect_url=paypal_url,
1017
- long_url=paypal_url,
1018
- fallback=False,
1019
- )
1020
- req = app.LongLinkRequest(accessToken="token-value", cdk="CDK-UNITTEST1234", link_type="paypal")
1021
- states = []
1022
- with (
1023
- patch.object(app, "build_long_link_response", return_value=response),
1024
- patch.object(app, "request_for_retry_attempt", return_value=req),
1025
- patch.object(app, "task_cancel_requested", return_value=False),
1026
- patch.object(app, "wait_for_task_resume", return_value="running"),
1027
- patch.object(app, "task_log_callback", return_value=lambda _: None),
1028
- patch.object(app, "set_task_state", side_effect=lambda task_id, **state: states.append(state)),
1029
- patch.object(app, "require_cdk_user") as consume,
1030
- patch.object(app, "record_user_success"),
1031
- patch.object(app, "record_proxy_success"),
1032
- patch.object(app, "set_latest_result"),
1033
- ):
1034
- app.run_long_link_task_retrying("task_paypal_success", req, app.cdk_owner(req.cdk), "cdk")
1035
- consume.assert_called_once_with(req.cdk, consume=True)
1036
- self.assertEqual(states[-1]["status"], "done")
1037
- self.assertEqual(states[-1]["result"]["long_url"], paypal_url)
1038
-
1039
- def test_task_metadata_and_callback_logs_do_not_keep_secrets(self):
1040
- req = app.LongLinkRequest(
1041
- accessToken="very-secret-token",
1042
- cdk="CDK-SECRET",
1043
- checkoutProxy="http://user:proxy-secret@proxy.example:8080",
1044
- )
1045
- metadata = app.task_request_metadata(req)
1046
- rendered = json.dumps(metadata)
1047
- self.assertNotIn("very-secret-token", rendered)
1048
- self.assertNotIn("proxy-secret", rendered)
1049
- self.assertNotIn("CDK-SECRET", rendered)
1050
-
1051
- captured = []
1052
- token = app.TASK_LOG_CALLBACK.set(captured.append)
1053
- try:
1054
- app.log_info(
1055
- "test.redaction",
1056
- proxy="http://user:proxy-secret@proxy.example:8080",
1057
- access_token="very-secret-token",
1058
- url="https://example.com/private/path?secret=value",
1059
- )
1060
- finally:
1061
- app.TASK_LOG_CALLBACK.reset(token)
1062
- rendered = json.dumps(captured)
1063
- self.assertNotIn("proxy-secret", rendered)
1064
- self.assertNotIn("very-secret-token", rendered)
1065
- self.assertNotIn("secret=value", rendered)
1066
-
1067
-
1068
- if __name__ == "__main__":
1069
- unittest.main(verbosity=2)