---
title: "MPP 快速开始"
description: "使用 Tempo USDC 与 mppx 客户端为 TwexAPI 高级搜索分页付费。"
---

# MPP 快速开始

无需 TwexAPI API 密钥即可发起按次付费的高级搜索请求。本指南使用 `mppx` 客户端响应 HTTP 402 挑战、用 Tempo USDC 付款并自动重试请求。

## 步骤 1：安装客户端依赖

```bash
npm install mppx viem
```

`mppx` 处理 MPP 挑战与支付。`viem` 将 Tempo 私钥转换为客户端使用的钱包账户。

## 步骤 2：创建并充值 Tempo 钱包

创建本地 MPP 账户，再导出私钥：

```bash
mppx account create
mppx account export
```

向打印的地址在 Tempo 上充值 USDC。将导出的 `0x...` 私钥存入环境变量：

```bash
export TEMPO_PRIVATE_KEY="0x..."
```

:::warning
  切勿提交私钥。请放在密钥管理器或 shell 环境中，且仅按集成允许额度充值钱包。
:::

## 步骤 3：发起 MPP 请求

创建 `mpp-search.ts`：

```ts
import { Mppx, tempo } from "mppx/client";
import { privateKeyToAccount } from "viem/accounts";

Mppx.create({
  methods: [
    tempo({
      account: privateKeyToAccount(
        process.env.TEMPO_PRIVATE_KEY as `0x${string}`,
      ),
    }),
  ],
});

const response = await fetch(
  "https://api.twexapi.io/twitter/advanced_search/page",
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      searchTerms: ["openai"],
      sortBy: "Latest",
    }),
  },
);

if (!response.ok) {
  throw new Error(`TwexAPI request failed: ${response.status}`);
}

console.log(await response.json());
```

`Mppx.create()` 配置 `fetch` 以处理 MPP `402 Payment Required` 挑战。对符合条件的端点，它会支付服务器提供的 Tempo 报价，并以支付凭据重试同一请求。需要记录结算时请检查 `response.headers.get("Payment-Receipt")`。

从上一页继续时，在 JSON 体中传入 `next_cursor`：

```json
{
  "searchTerms": ["openai"],
  "sortBy": "Latest",
  "next_cursor": "cursor-from-the-previous-response"
}
```

## 步骤 4：实现原始 HTTP 流程

不使用 `mppx` 时，先正常请求搜索页：

```bash
curl -i --request POST 'https://api.twexapi.io/twitter/advanced_search/page' \
  --header 'Content-Type: application/json' \
  --data '{"searchTerms":["openai"],"sortBy":"Latest"}'
```

收到 `402` 后，用兼容的 Tempo MPP 实现处理 `WWW-Authenticate: Payment` 挑战，再以生成的凭据重试完全相同的请求：

```bash
curl -i --request POST 'https://api.twexapi.io/twitter/advanced_search/page' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: Payment eyJjaGFsbGVuZ2UiOnsi...' \
  --data '{"searchTerms":["openai"],"sortBy":"Latest"}'
```

成功响应包含 TwexAPI 常用的 JSON 封装与 `Payment-Receipt` 响应头。若应用需要对账，请将回执与自有请求记录一并保存。

## 下一步

- [机器支付协议](/mpp/machine-payments-protocol) — 了解支持的操作、支付序列与 API 密钥对比。
- [API 概览](/api-reference/overview) — 浏览 API 密钥认证与完整端点目录。
