> ## Documentation Index
> Fetch the complete documentation index at: https://ifdocdemo.lumivescence.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Thanh toán từ code

> Thanh toán cho endpoint MPP và x402 từ ứng dụng của riêng bạn bằng các SDK người mua của InFlow dành cho Python, Go, Rust và Node.js.

Thanh toán cho endpoint MPP và x402 từ ứng dụng của riêng bạn bằng một SDK người mua dành cho Node.js, Python, Go hoặc Rust. Mỗi SDK thanh toán từ số dư InFlow của tài khoản sở hữu API key khi người bán cung cấp cách thanh toán này. Người mua x402 ưu tiên scheme `balance`, sau đó đến `exact`. Về các cách thanh toán khác, xem [Cách agent thanh toán](https://ifdocdemo.lumivescence.com/vi/agents/pay-for-a-resource.md#cách-agent-thanh-toán).

## Trước khi bắt đầu

| Mục | Chi tiết |
| - | - |
| Tài khoản | Một tài khoản InFlow và một API key. Tài khoản Developer có thể mua. Tài khoản Seller cũng có thể mua. |
| Biến môi trường | `INFLOW_API_KEY`. |
| Môi trường | Các ví dụ dùng sandbox. Giá trị này phải khớp với dashboard của key. |

Khi một khoản thanh toán cần [phê duyệt của chủ sở hữu](https://ifdocdemo.lumivescence.com/vi/concepts/payments.md#phê-duyệt-của-con-người), khoản thanh toán đó chờ đến khi chủ sở hữu phê duyệt.

## Thanh toán cho một endpoint

> [tab] Python
>
> ### MPP
>
> ```bash theme={null}
> pip install 'inflowpay[mpp]'
> ```
>
> Transport thanh toán trả lời challenge `402` cho mỗi request mà `httpx` gửi.
>
> ```python theme={null}
> import os
>
> import httpx
>
> from inflowpay import ClientOptions
> from inflowpay.mpp.buyer import BuyerMethod, payment_transport
>
>
> async def buy(url: str) -> bytes:
>     async with BuyerMethod(
>         ClientOptions(environment="sandbox", api_key=os.environ["INFLOW_API_KEY"])
>     ) as method:
>         async with httpx.AsyncClient(transport=payment_transport([method])) as http:
>             response = await http.get(url)
>             response.raise_for_status()
>             return response.content
> ```
>
> ### x402
>
> ```bash theme={null}
> pip install 'inflowpay[x402]'
> ```
>
> ```python theme={null}
> import asyncio
> import os
>
> import httpx
> from x402.http.clients.httpx import x402AsyncTransport
>
> from inflowpay import ClientOptions
> from inflowpay.x402.buyer import Buyer
>
>
> async def main():
>     async with (
>         await Buyer.create(
>             ClientOptions(api_key=os.environ["INFLOW_API_KEY"], environment="sandbox")
>         ) as buyer,
>         httpx.AsyncClient(transport=x402AsyncTransport(buyer), follow_redirects=False) as http,
>     ):
>         response = await http.get(os.environ["PAID_RESOURCE_URL"])
>         response.raise_for_status()
>         print(response.text)
>
>
> asyncio.run(main())
> ```
>
> SDK Python cũng hỗ trợ người mua MPP qua MCP. Cài đặt `inflowpay[mpp,mcp]`.

> [tab] Go
>
> ```bash theme={null}
> go get github.com/inflowpayai/inflow-go@v0.3.2
> ```
>
> Phương thức `Do` của người mua Go gửi request, thanh toán một challenge `402` và gửi một lần thử lại có thanh toán. Để tự dùng challenge, dùng `Fulfil` cho MPP hoặc `Sign` cho x402.
>
> ### MPP
>
> `Fulfil` chuyển một challenge MPP thành một credential.
>
> ```go theme={null}
> client, err := buyer.New(buyer.Options{
>     Options: inflow.Options{
>         Environment: inflow.Sandbox,
>         APIKey: os.Getenv("INFLOW_API_KEY"),
>     },
> })
> if err != nil {
>     return err
> }
> credential, err := client.Fulfil(ctx, challenge, buyer.PaymentOptions{})
> ```
>
> ### x402
>
> `Sign` chuyển các yêu cầu thanh toán x402 thành một khoản thanh toán có chữ ký.
>
> ```go theme={null}
> client, err := buyer.New(buyer.Options{
>     Options: inflow.Options{
>         Environment: inflow.Sandbox,
>         APIKey: os.Getenv("INFLOW_API_KEY"),
>     },
> })
> if err != nil {
>     return err
> }
> payment, err := client.Sign(ctx, required, buyer.SignOptions{})
> ```

> [tab] Rust
>
> ### MPP
>
> `inflow-mpp-buyer` dùng một quy trình credential rõ ràng. Ứng dụng chuẩn bị khoản thanh toán, hiển thị phê duyệt cho chủ sở hữu và chờ credential.
>
> ```rust theme={null}
> use inflow_mpp_buyer::{
>     Authentication, Buyer, CancellationToken, ClientOptions, Environment,
>     PaymentChallenge, PaymentOptions, WaitOptions, Credential,
> };
>
> async fn approve(challenge: &PaymentChallenge) -> Result<Credential, Box<dyn std::error::Error>> {
>     let buyer = Buyer::new(ClientOptions {
>         environment: Environment::Sandbox,
>         authentication: Authentication::ApiKey(std::env::var("INFLOW_API_KEY")?),
>         ..Default::default()
>     })?;
>     let cancellation = CancellationToken::new();
>     let payment = buyer.prepare(challenge, PaymentOptions::default(), &cancellation).await?;
>     // The application can display these identifiers while approval is pending.
>     let approval_id = payment.approval_id();
>     let transaction_id = payment.transaction_id();
>     let credential = payment.wait(WaitOptions::default()).await?;
>     Ok(credential)
> }
> ```
>
> Người mua MPP hỗ trợ khoản thu InFlow, gói thuê bao InFlow, khoản thu Tempo và khoản thu Visa CARD. Với x402, dùng `inflow-x402-buyer`.

> [tab] Node.js
>
> ```bash theme={null}
> pnpm add @inflowpayai/mpp-buyer mppx@^0.8.17
> pnpm add @inflowpayai/x402-buyer @x402/core
> ```
>
> Repository `inflow-node` có các ví dụ người mua chạy được. `mpp-buyer-fetch` thay `fetch` toàn cục bằng một wrapper hỗ trợ thanh toán, wrapper này thanh toán cho một response `402`.
>
> Trước tiên, khởi chạy `mpp-seller-express` hoặc `mpp-seller-hono` trong một terminal khác. Người mua gửi request đến `http://localhost:3000/api/widgets`.
>
> ```bash theme={null}
> # at the root of the inflow-node repository
> pnpm install
> pnpm build
> cd examples/mpp-buyer-fetch
> cp .env.example .env
> # fill in INFLOW_API_KEY from https://sandbox.inflowpay.ai
> pnpm start
> ```
>
> Các ví dụ người mua khác là `mpp-buyer-manual`, `x402-buyer-fetch` và `x402-buyer-axios`. `x402-buyer-x402-evm` và `x402-buyer-x402-svm` chỉ dùng các package của x402 foundation.

## Quy tắc cho code người mua

* Không bao giờ ghi log API key hoặc một credential thanh toán.
* Lưu ID giao dịch ngay khi bạn nhận được ID này. Bạn cần ID này để kiểm tra hoặc tiếp tục một khoản thanh toán.
* Hiển thị phê duyệt cho chủ sở hữu trong khi khoản thanh toán chờ.
* Chấp nhận thanh toán Stripe chỉ dành cho người bán. Các SDK người mua của InFlow không tạo token Stripe.

## Trang liên quan

> [card] [Thanh toán bằng CLI](https://ifdocdemo.lumivescence.com/vi/agents/pay-for-a-resource.md)
>
> Thanh toán cho một endpoint từ dòng lệnh.

> [card] [Tham khảo SDK](https://ifdocdemo.lumivescence.com/vi/reference/sdk-packages.md)
>
> Đọc các package, phiên bản và tính năng của từng SDK.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.