(
*,
api_url: str,
api_key: Optional[str],
payload: dict,
proxy: Optional[str] = None,
)
| 1414 | |
| 1415 | |
| 1416 | def _invoke_third_party_bind_api( |
| 1417 | *, |
| 1418 | api_url: str, |
| 1419 | api_key: Optional[str], |
| 1420 | payload: dict, |
| 1421 | proxy: Optional[str] = None, |
| 1422 | ) -> tuple[dict, str]: |
| 1423 | headers = { |
| 1424 | "Accept": "*/*", |
| 1425 | "Content-Type": "application/json", |
| 1426 | "User-Agent": "codex-console2/third-party-bind", |
| 1427 | } |
| 1428 | key = str(api_key or "").strip() |
| 1429 | if key: |
| 1430 | headers["X-API-Key"] = key |
| 1431 | headers["Authorization"] = f"Bearer {key}" |
| 1432 | |
| 1433 | url_candidates = _build_third_party_bind_api_candidates(api_url) |
| 1434 | if not url_candidates: |
| 1435 | raise RuntimeError("第三方绑卡 API 地址无效") |
| 1436 | |
| 1437 | proxy_candidates: List[Optional[str]] = [] |
| 1438 | for value in (proxy, None): |
| 1439 | if value not in proxy_candidates: |
| 1440 | proxy_candidates.append(value) |
| 1441 | |
| 1442 | errors: List[str] = [] |
| 1443 | for candidate_url in url_candidates: |
| 1444 | for proxy_item in proxy_candidates: |
| 1445 | proxies = {"http": proxy_item, "https": proxy_item} if proxy_item else None |
| 1446 | for attempt in range(1, 3): |
| 1447 | try: |
| 1448 | resp = cffi_requests.post( |
| 1449 | candidate_url, |
| 1450 | headers=headers, |
| 1451 | json=payload, |
| 1452 | proxies=proxies, |
| 1453 | timeout=120, |
| 1454 | impersonate="chrome110", |
| 1455 | ) |
| 1456 | |
| 1457 | if resp.status_code >= 400: |
| 1458 | body = (resp.text or "")[:500] |
| 1459 | err = f"{candidate_url} status={resp.status_code} proxy={'on' if proxy_item else 'off'} body={body}" |
| 1460 | errors.append(err) |
| 1461 | retryable = resp.status_code in (408, 409, 425, 429, 500, 502, 503, 504) |
| 1462 | endpoint_maybe_wrong = resp.status_code in (404, 405) |
| 1463 | if attempt < 2 and retryable: |
| 1464 | time.sleep(0.6 * attempt) |
| 1465 | continue |
| 1466 | if endpoint_maybe_wrong: |
| 1467 | break |
| 1468 | raise RuntimeError(f"第三方绑卡请求失败: HTTP {resp.status_code} - {body}") |
| 1469 | |
| 1470 | parsed = _parse_third_party_response(resp) |
| 1471 | if isinstance(parsed, dict): |
| 1472 | parsed["_meta_endpoint"] = candidate_url |
| 1473 | parsed["_meta_proxy"] = "on" if proxy_item else "off" |
no test coverage detected