

# 整合 AgentCore 付款與瀏覽器工具
<a name="payments-browser"></a>

您的代理程式有兩種方式可以存取 x402 付費內容：透過[瀏覽器工具](browser-tool.md)或透過標準 HTTP 呼叫。

## 瀏覽器工具整合 (Playwright)
<a name="payments-agent-integration-browser-playwright"></a>

AgentCore 瀏覽器工具可在 AgentCore 執行時間內為您的代理程式提供受管無周邊 Chromium 瀏覽器工作階段。您的代理程式會使用 Chrome DevTools Protocol (CDP) 透過 WebSocket 連線，使其能夠在網路層級導覽頁面、執行 JavaScript 和攔截 HTTP 回應。若要開始使用，請參閱[瀏覽器入門指南](browser-tool.md)。

此選項使用 Strands SDK 搭配瀏覽器工具和付款工具來瀏覽網站和處理付款。當代理程式使用瀏覽器工具導覽網站時，會使用 Playwright 的回應攔截功能來自動偵測 paywall 網站：

1.  **瀏覽器導覽** — 代理程式使用由 Playwright 提供`browse_with_payment`的工具。

1.  **自動 402 偵測** — Playwright 攔截所有 HTTP 回應，並觸發代理程式的回應處理常式來偵測 402 狀態碼。

1.  **x402 擷取** — 付款工具會自動從回應標頭/內文剖析 x402 付款詳細資訊。這也可以透過客服人員業務邏輯來完成。

1.  **付款處理** — AgentCore 付款處理器使用設定的 CDP 錢包建立加密簽章。

1.  **重試** — 付款工具注入授權標頭，並在相同的瀏覽器工作階段中重試請求。

```
from agentcore.payments import PaymentClient
from agentcore.browser import browser_tool

@tool
async def browse_with_payment(url: str, auto_pay: bool = True) -> dict:
    payment_requirements = None

    async def handle_response(response):
        nonlocal payment_requirements
        if response.status == 402:
            payment_requirements = await extract_x402_requirements(response)

    async def add_payment_header(route, request):
        headers = {**request.headers, **payment_result["authorization"]}
        await route.continue_(headers=headers)

    async with async_playwright() as p:
        # 1. Browser setup
        browser = await p.chromium.connect_over_cdp(AGENTCORE_BROWSER_WS_URL)
        page = await browser.contexts[0].new_page()

        # 2. Register response interceptor
        page.on("response", handle_response)

        # 3. Initial navigation (handle_response runs automatically here)
        response = await page.goto(url)

        # 4. Payment processing logic (runs AFTER navigation completes)
        if response.status == 402 and payment_requirements and auto_pay:
            payment_result = payment_client.process_payment(
                payment_session,
                payment_instrument,
                payment_requirements=payment_requirements
            )

            if payment_result["success"]:
                await page.route("**/*", add_payment_header)
                response = await page.goto(url)  # Retry with payment
            else:
                raise PaymentError(f"Payment failed: {payment_result['error_message']}")

        # 5. Capture content, cleanup, and return
        content = await page.content()
        await browser.close()
        return {"content": content, "status": response.status}
```

## 非瀏覽器 HTTP 整合
<a name="payments-agent-integration-browser-http"></a>

對於直接 API 呼叫和無周邊案例，開發人員可以使用 Strands SDK 搭配標準 HTTP 請求程式庫撰寫自訂工具邏輯，以處理 x402 偵測的付款：

1. 客服人員使用自訂工具進行直接 HTTP 呼叫。

1. 工具會監控 HTTP 回應狀態碼以偵測 402。

1. 工具會擷取 x402 要求並處理付款。

1. 工具會使用付款授權標頭重試 HTTP 請求。

```
@tool
async def make_payment(method, url, headers, body) -> dict:
    # Make initial HTTP request
    response = requests.request(method, url, headers=headers, data=body)

    # Check for 402 Payment Required
    if response.status_code == 402:
        payment_requirements = extract_x402_requirements(response)
        payment_result = payment_client.process_payment(
            payment_session,
            payment_instrument,
            payment_requirements=payment_requirements
        )

        if payment_result["success"]:
            # Retry request with payment authorization
            headers.update(payment_result["authorization"])
            response = requests.request(method, url, headers=headers, data=body)
        else:
            raise PaymentError(f"Payment failed: {payment_result['error_message']}")
```