# 快速开始

> 创建项目，在沙盒中跑通账单与带签名的 webhook，然后创建正式凭据，接收第一笔主网真实付款。

## 创建账户

在 [paymos.io](/_public) 用邮箱魔法链接、Google、Telegram（OIDC）或 passkey 登录——无需设置密码。

## 创建项目

打开 [**控制台 → 项目 → 新建项目**](/projects/create)，为项目命名，并开启客户将要使用的资产与网络组合。

同一个表单里还要选**集成方式**：REST API、Low-Code、CMS 插件、收银终端或 Telegram 机器人。默认是 REST API。它随项目一次选定，之后不可更改；需要别的方式，就另建一个项目。

之后能打开什么，取决于它：收银终端屏幕只在收银终端项目里可用，Low-Code SDK 的代码片段只在 Low-Code 项目里可用，CMS 插件面板只在 CMS 项目里可用。用错方式发起的账单请求会返回 `403`。下面的步骤都按 REST API 写。

## 获取测试 API 密钥

进入 [**控制台 → 开发者 → API 密钥**](/developers/api)，生成一对测试密钥：

:::dash-list
- **Payment Key**（`pk_test_…`）——用于创建测试账单和查询账单状态
- **API Secret**（`sk_test_…`）——用于计算 HMAC-SHA256 请求签名（见下方警告）
:::

:::warning
API Secret 绝不离开你的服务器。不要放进请求头、查询字符串或客户端代码。不要提交到 git——一旦泄露立即轮换。
:::

## 注册测试 webhook 端点

把服务器的 webhook 处理器发布到一个 HTTPS 地址，然后在沙盒中打开 [**控制台 → 开发者 → Webhook**](/developers/webhooks) 创建端点：填入 HTTPS 回调地址，选择**账单**类目和你的项目。把只显示一次的 `whsec_test_…` 密钥复制到服务器；它与 API 密钥对相互独立，用于签名测试 webhook 的投递。

## 创建测试账单

使用下面的官方服务器 SDK。它负责序列化请求、生成精确的 HMAC 签名、设置时间戳请求头、执行安全重试，并返回类型化响应。手动签名另见 [认证](/zh-hans/docs/authentication.md)。

```curl
API_KEY_ID="pk_live_xxxxxxxxxxxx"
API_SECRET="sk_live_xxxxxxxxxxxx"
BODY='{"project_id":"prj_xxxxxxxxxxxx","amount":"100.00","currency":"USD","external_order_id":"order-123","client_id":"customer-456"}'

TS=$(date +%s)
BODY_HASH=$(printf '%s' "$BODY" | openssl dgst -sha256 -hex | sed 's/^.* //')
SIGNATURE=$(printf '%s\n%s\n%s\n%s\n%s' "$TS" POST /v1/invoices '' "$BODY_HASH" \
  | openssl dgst -sha256 -hmac "$API_SECRET" -binary | base64)

curl -sS https://api.paymos.io/v1/invoices \
  -H "Authorization: HMAC-SHA256 $API_KEY_ID:$SIGNATURE" \
  -H "X-Request-Timestamp: $TS" \
  -H "Content-Type: application/json" \
  -d "$BODY"
```

```mcp
Setup once in terminal: `npx -y @paymos/mcp setup`

Prompt:
Read `paymos://docs/hosted-checkout` and integrate Paymos invoice
creation into my backend using the official SDK for this project's
stack. Then use `@paymos/mcp` in sandbox to call `create_invoice`
(`project_id`: `prj_xxxxxxxxxxxx`, `amount`: `"100.00"`, `currency`:
`"USD"`, `external_order_id`: `"order-123"`) and run
`simulate_invoice_payment` (`stage`: `"paid"`) to verify the flow.
```

```javascript
import { Paymos, externalOrderId } from '@paymos/sdk';

const paymos = new Paymos({
  apiKey: process.env.PAYMOS_API_KEY,
  apiSecret: process.env.PAYMOS_API_SECRET,
});

const invoice = await paymos.invoices.create({
  projectId: 'prj_xxxxxxxxxxxx',
  amount: '100.00',
  currency: 'USD',
  externalOrderId: externalOrderId('order'),
  clientId: 'customer-456',
});

console.log(invoice.invoiceId, invoice.paymentUrl);
```

```python
import os

from paymos import Paymos

paymos = Paymos(
    api_key=os.environ["PAYMOS_API_KEY"],
    api_secret=os.environ["PAYMOS_API_SECRET"],
)
invoice = paymos.invoices.create(
    project_id="prj_xxxxxxxxxxxx",
    amount="100.00",
    currency="USD",
    external_order_id="order-123",
    client_id="customer-456",
)

print(invoice["invoice_id"], invoice["payment_url"])
```

```php
<?php
use Paymos\Client;
use Paymos\ClientConfig;
use Paymos\IdempotencyKey;

$paymos = new Client(new ClientConfig(
    getenv('PAYMOS_API_KEY'),
    getenv('PAYMOS_API_SECRET')
));
$invoice = $paymos->invoices()->create(array(
    'project_id' => 'prj_xxxxxxxxxxxx',
    'amount' => '100.00',
    'currency' => 'USD',
    'external_order_id' => IdempotencyKey::externalOrderId('order'),
    'client_id' => 'customer-456',
));

echo $invoice['invoice_id'] . ' ' . $invoice['payment_url'];
```

```go
package main

import (
	"context"
	"fmt"
	"os"

	paymos "github.com/Paymos-labs/go-sdk/v2"
)

func main() {
	client, err := paymos.NewClient(os.Getenv("PAYMOS_API_KEY"), os.Getenv("PAYMOS_API_SECRET"))
	if err != nil {
		panic(err)
	}
	invoice, err := client.Invoices.Create(context.Background(), paymos.CreateInvoiceParams{
		ProjectID:       "prj_xxxxxxxxxxxx",
		Amount:          "100.00",
		Currency:        "USD",
		ExternalOrderID: "order-123",
		ClientID:        stringPointer("customer-456"),
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(invoice.InvoiceID, invoice.PaymentURL)
}

func stringPointer(value string) *string { return &value }
```

```csharp
using Paymos;

using var paymos = new PaymosClient(
    Environment.GetEnvironmentVariable("PAYMOS_API_KEY")!,
    Environment.GetEnvironmentVariable("PAYMOS_API_SECRET")!);

var invoice = await paymos.Invoices.CreateAsync(new CreateInvoiceRequest(
    ProjectId: "prj_xxxxxxxxxxxx",
    Amount: "100.00",
    Currency: "USD",
    ExternalOrderId: "order-123",
    ClientId: "customer-456"));

Console.WriteLine($"{invoice.InvoiceId} {invoice.PaymentUrl}");
```

```java
import io.paymos.CreateInvoiceRequest;
import io.paymos.Invoice;
import io.paymos.PaymosClient;

PaymosClient paymos = new PaymosClient(
    System.getenv("PAYMOS_API_KEY"),
    System.getenv("PAYMOS_API_SECRET"));

Invoice invoice = paymos.invoices.create(
    CreateInvoiceRequest.builder()
        .projectId("prj_xxxxxxxxxxxx")
        .amount("100.00")
        .currency("USD")
        .externalOrderId("order-123")
        .clientId("customer-456")
        .build());

System.out.println(invoice.invoiceId() + " " + invoice.paymentUrl());
```

```ruby
require 'paymos'

paymos = Paymos::Client.new(
  api_key: ENV.fetch('PAYMOS_API_KEY'),
  api_secret: ENV.fetch('PAYMOS_API_SECRET')
)
invoice = paymos.invoices.create(
  project_id: 'prj_xxxxxxxxxxxx',
  amount: '100.00',
  currency: 'USD',
  external_order_id: 'order-123',
  client_id: 'customer-456'
)

puts "#{invoice.invoice_id} #{invoice.payment_url}"
```

```rust
use paymos::{CreateInvoiceRequest, PaymosClient};

let paymos = PaymosClient::new(
    std::env::var("PAYMOS_API_KEY")?,
    std::env::var("PAYMOS_API_SECRET")?,
)?;
let invoice = paymos
    .invoices()
    .create(&CreateInvoiceRequest {
        project_id: "prj_xxxxxxxxxxxx".to_owned(),
        amount: "100.00".to_owned(),
        currency: "USD".to_owned(),
        external_order_id: "order-123".to_owned(),
        network: None,
        customer_fee_percent: None,
        client_id: Some("customer-456".to_owned()),
        products: None,
    })
    .await?;

println!("{} {}", invoice.invoice_id, invoice.payment_url);
```

## 打开收银台

响应中包含 `payment_url`。把客户重定向过去，或用 `?embed=true` 嵌入同一 URL：

```json
{
  "invoice_id": "inv_5CcyDYmMUGtzYL10q0Iimr",
  "project_id": "prj_xFukZuAJZR06pLVBh3uwzv",
  "status": "awaiting_client",
  "is_final": false,
  "is_test": true,
  "payment_url": "https://checkout.paymos.io/invoice/inv_5CcyDYmMUGtzYL10q0Iimr",
  "order": {
    "external_id": "order-123",
    "client_id": "customer-456",
    "amount": "100.00",
    "currency": "USD"
  },
  "created_at": 1743594000,
  "updated_at": 1743594000,
  "expires_at": 1743597600
}
```

客户会看到带钱包地址、QR 码和倒计时器的付款页。他们可以用项目已启用的任意资产 + 网络付款——见 [支持的币种](/zh-hans/docs/supported-currencies.md)。

如果项目的渠道是 Telegram 机器人，这个链接会把客户带到 Paymos 机器人。付款人在那里选择资产和网络、拿到地址和二维码、查看状态变化，全程不离开 Telegram，也不需要 Paymos 账户。

重定向模式、iframe 嵌入模式和浏览器事件处理见 [托管收银台](/zh-hans/docs/hosted-checkout.md)。

## 处理 webhook

付款确认后，Paymos 向你注册的 webhook URL 发送 POST：

```json
{
  "event_id": "evt_J7EEYeL9pZJukfj2c5OQ44",
  "event_type": "invoice.paid",
  "version": 1,
  "occurred_at": 1739281200,
  "data": {
    "invoice_id": "inv_5CcyDYmMUGtzYL10q0Iimr",
    "project_id": "prj_xFukZuAJZR06pLVBh3uwzv",
    "status": "paid",
    "is_final": true,
    "is_test": false,
    "payment_url": "https://checkout.paymos.io/invoice/inv_5CcyDYmMUGtzYL10q0Iimr",
    "order": {
      "external_id": "order-12345",
      "client_id": "customer-67890",
      "amount": "100.00",
      "currency": "USD"
    },
    "payment": {
      "currency": "USDT",
      "network": "TRC20",
      "chain_id": 728126428,
      "contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
      "expected": "50.00",
      "address": "TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9",
      "exchange_rate": "2.00",
      "paid": "50.00",
      "remaining": "0",
      "fee": "0.50",
      "net": "49.50",
      "transfers": [
        {
          "tx_hash": "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890",
          "amount": "50.00",
          "status": "confirmed",
          "created_at": 1739281020,
          "confirmed_at": 1739281200,
          "required_confirmations": 19,
          "estimated_confirmation_at": 1739281080,
          "explorer_url": "https://tronscan.org/#/transaction/abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890"
        }
      ]
    },
    "expires_at": 1739284200,
    "completed_at": 1739281200,
    "created_at": 1739277600,
    "updated_at": 1739281200
  }
}
```

验证 `X-Webhook-Signature` 请求头，然后履约订单。

:::danger
绝不要依据浏览器事件（`paymos:succeeded` 或 iframe `postMessage`）履约订单。只有带签名的服务端 webhook 才是权威依据——浏览器信号可以被伪造。
:::

```javascript
import { WebhookVerifier } from '@paymos/sdk';

const verifier = new WebhookVerifier(process.env.PAYMOS_WEBHOOK_SECRET);

// Keep the body as a Buffer until verification succeeds.
const event = verifier.constructEvent(signatureHeader, rawBody);
console.log(event.eventId, event.eventType, event.data);
```

```mcp
Setup once in terminal: `npx -y @paymos/mcp setup`

Prompt:
Read `paymos://docs/webhooks` and add a Paymos webhook endpoint to my
backend that verifies `X-Webhook-Signature` over the unparsed raw
request body using `WebhookVerifier` from the official SDK and
deduplicates deliveries by `event_id`. Use `@paymos/mcp` tool
`verify_webhook_signature` to test valid and tampered signatures.
```

```python
import os

from paymos import WebhookVerifier

verifier = WebhookVerifier(os.environ["PAYMOS_WEBHOOK_SECRET"])

# Keep raw_body as bytes until verification succeeds.
event = verifier.construct_event(signature_header, raw_body)
print(event["event_id"], event["event_type"], event["data"])
```

```php
<?php
use Paymos\Webhook\WebhookEvent;
use Paymos\Webhook\WebhookVerifier;

$verifier = new WebhookVerifier(getenv('PAYMOS_WEBHOOK_SECRET'));

// Keep $rawBody unchanged until verification succeeds.
$payload = $verifier->decodeVerifiedPayload($signatureHeader, $rawBody);
$event = new WebhookEvent($payload);
echo $event->id() . ' ' . $event->type();
```

```go
package main

import (
	"fmt"
	"os"
	"time"

	paymos "github.com/Paymos-labs/go-sdk/v2"
)

type invoiceEventData struct {
	InvoiceID string `json:"invoice_id"`
}

func handleWebhook(signatureHeader string, rawBody []byte) error {
	verifier, err := paymos.NewWebhookVerifier(os.Getenv("PAYMOS_WEBHOOK_SECRET"), 5*time.Minute)
	if err != nil {
		return err
	}
	var event paymos.WebhookEvent[invoiceEventData]
	if err := verifier.ConstructEvent(signatureHeader, rawBody, time.Now(), &event); err != nil {
		return err
	}
	fmt.Println(event.EventID, event.EventType, event.Data.InvoiceID)
	return nil
}
```

```csharp
using Paymos;

var verifier = new WebhookVerifier(
    Environment.GetEnvironmentVariable("PAYMOS_WEBHOOK_SECRET")!);

// Keep rawBody as ReadOnlySpan<byte> until verification succeeds.
var webhook = verifier.ConstructEvent<InvoiceEventData>(signatureHeader, rawBody);
Console.WriteLine($"{webhook.EventId} {webhook.EventType} {webhook.Data.InvoiceId}");

public sealed record InvoiceEventData(string InvoiceId);
```

```java
import com.fasterxml.jackson.databind.JsonNode;
import io.paymos.WebhookEvent;
import io.paymos.WebhookVerifier;
import java.time.Instant;

WebhookVerifier verifier = new WebhookVerifier(System.getenv("PAYMOS_WEBHOOK_SECRET"));

// Keep rawBody as byte[] until verification succeeds.
WebhookEvent<JsonNode> event =
    verifier.constructEvent(signatureHeader, rawBody, Instant.now());
System.out.println(event.eventId() + " " + event.eventType() + " " + event.data());
```

```ruby
require 'paymos'

verifier = Paymos::WebhookVerifier.new(ENV.fetch('PAYMOS_WEBHOOK_SECRET'))

# Keep raw_body as the original String until verification succeeds.
event = verifier.construct_event(signature_header, raw_body)
puts "#{event.event_id} #{event.event_type} #{event.data}"
```

```rust
use paymos::{Invoice, WebhookEvent, WebhookVerifier};

let verifier = WebhookVerifier::new(std::env::var("PAYMOS_WEBHOOK_SECRET")?)?;

// Keep raw_body as &[u8] until verification succeeds.
let event: WebhookEvent<Invoice> = verifier.construct_event(signature_header, raw_body)?;
println!("{} {} {}", event.event_id, event.event_type, event.data.invoice_id);
```

## 模拟测试付款

用[付款模拟器](/zh-hans/docs/invoices/simulate-payment.md)把测试账单标记为已支付。不要向测试账单发送真实资产。确认注册的端点收到了带签名的事件，并且服务器在履约订单之前已用 `whsec_test_…` 验签。

## 切换到正式环境

沙盒（控制台里显示为 **Test**）请求和带签名的 webhook 都跑通后，在控制台切换到 **Live**（正式环境）。没有人工审批环节。切换环境不会自动生成密钥：打开 **控制台 → 开发者 → API 密钥**，另行创建正式凭据（`pk_live_…` 和 `sk_live_…`）。正式 webhook 端点需要单独注册，其 `whsec_live_…` 密钥与测试密钥分开保存。

生产环境下，所有入账付款和出账转出都会自动经过免费的 AML / KYT 地址筛查；沙盒 / Test 环境不做筛查（详见 [AML/KYC 政策](/aml)）。

## 接收第一笔主网真实付款

用正式凭据重复一次账单请求，打开返回的 `payment_url`（视项目类型，它是收银台页面或 Paymos 机器人），在已开启的主网网络上发送受支持的资产。Paymos 检测到转账，完成生产环境自动 AML 筛查和所需确认数后，发送带签名的正式 webhook。

从注册到第一笔主网真实付款，常规自助流程约需 10 分钟。这是上线参考值，不是 SLA：确认耗时仍取决于网络、金额和当前链上状况。

## 下一步

:::dash-list
- [API 密钥](/zh-hans/docs/api-keys.md)——凭证类型、作用域、生命周期
- [服务器 SDK](/zh-hans/docs/server-sdks.md)——八种语言的官方客户端
- [MCP 服务器](/zh-hans/docs/mcp.md)——编码助手的 OAuth 2.1 工具与离线文档
- [退款](/zh-hans/docs/refunds/create.md)——服务端计算的账单全额与多付退款
- [托管收银台](/zh-hans/docs/hosted-checkout.md)——重定向与 iframe 嵌入选项
- [测试](/zh-hans/docs/testing.md)——如何在沙箱中测试
- [Webhooks](/zh-hans/docs/webhooks.md)——签名验证与重试策略
:::

## 快速图文指南

1. **创建分权 API 密钥。** 在**开发者 → API 密钥**页面分别管理 **Payment**（`pk_...`）和 **Payout**（`rk_...`）密钥，为转出密钥配置 IP 白名单，并对照查看 HMAC-SHA256 签名请求头。

   ![Paymos API 密钥页面，展示生产环境 Payment 与 Payout 密钥、IP 白名单和 HMAC-SHA256 请求头说明](/img/guides/host-to-host/01-api-keys.webp)

2. **排查签名 Webhook 投递记录。** 进入**开发者 → Webhook**点开任意事件，即可查看完整 JSON 载荷（`invoice.paid`、金额、网络与手续费）以及 HTTP 投递状态和耗时。

   ![Paymos Webhook 事件详情页，展示带签名的 invoice.paid JSON 载荷与 HTTP 200 投递结果](/img/guides/host-to-host/02-webhooks-delivered.webp)

3. **在内置 Playground 调试接口。** 切换到控制台文档里的 **Playground** 标签，填写 `POST /v1/invoices` 参数即可预览签名请求头与 JSON 请求体，并在沙箱环境直接发送测试请求。

   ![Paymos 控制台内置 API Playground，正在构建 POST /v1/invoices 请求并实时预览请求头和 JSON](/img/guides/host-to-host/03-endpoint-playground.webp)
