文档 / 入门
快速开始
15 分钟内在沙盒中完成第一笔支付。您需要一台运行 Node.js、PHP、Python 或 Go 的服务器 —— 四种语言都有示例。
最终效果您的网站创建账单,顾客在 Coinetic 页面上付款(沙盒中点击按钮即可),您的服务器收到 Webhook 并且只交付一次订单。
1. 获取沙盒密钥
- 在沙盒后台注册并开启双重验证(2FA)。
- 「密钥与 Webhook」→「创建密钥」:保存
key_id(ak_…)和 secret。 - 「密钥与 Webhook」→「添加 Endpoint」:填写处理程序的 URL,例如
https://shop.example/webhooks/coinetic(沙盒中可以使用http://localhost:3000/…)。保存 Webhook 签名密钥。
密钥只显示一次。请将它们写入服务器的环境变量:
.env(切勿提交!)
API_KEY=ak_...
API_SECRET=...
WEBHOOK_SECRET=...2. 下载客户端
客户端是一个没有外部依赖的单文件:请求签名、创建和查询账单、验证 Webhook。下载适合您语言的版本 →
3. 创建账单
价格以字符串表示,币种可为 USD、EUR、USDT 或 USDC。Idempotency-Key 基于订单号生成:超时后重试会返回同一张账单。
create-invoice.js
import { CoineticClient } from "./cryptopay.js";
const cp = new CoineticClient({ baseUrl: "https://sandbox.coinetic.money", keyId: process.env.API_KEY, secret: process.env.API_SECRET });
const invoice = await cp.createInvoice({
order_id: "ORDER-1001", // 您的订单号,在商户内唯一
price_amount: "25.00", // 字符串,而不是数字
price_currency: "USD",
return_url: "https://shop.example/orders/ORDER-1001",
metadata: { user_id: "42" },
}, "order-ORDER-1001"); // Idempotency-Key
console.log(invoice.checkout_url); // https://sandbox.coinetic.money/pay/inv_…#t=…create-invoice.php
require 'Cryptopay.php';
$cp = new \Cryptopay\Client('https://sandbox.coinetic.money', getenv('API_KEY'), getenv('API_SECRET'));
$invoice = $cp->createInvoice([
'order_id' => 'ORDER-1001',
'price_amount' => '25.00',
'price_currency' => 'USD',
'return_url' => 'https://shop.example/orders/ORDER-1001',
'metadata' => ['user_id' => '42'],
], 'order-ORDER-1001');
echo $invoice['checkout_url'];create_invoice.py
import os
from cryptopay import CoineticClient
cp = CoineticClient("https://sandbox.coinetic.money", os.environ["API_KEY"], os.environ["API_SECRET"])
invoice = cp.create_invoice({
"order_id": "ORDER-1001",
"price_amount": "25.00",
"price_currency": "USD",
"return_url": "https://shop.example/orders/ORDER-1001",
"metadata": {"user_id": "42"},
}, "order-ORDER-1001")
print(invoice["checkout_url"])main.go
cp := &cryptopayclient.Client{
BaseURL: "https://sandbox.coinetic.money",
KeyID: os.Getenv("API_KEY"),
Secret: os.Getenv("API_SECRET"),
HTTP: &http.Client{Timeout: 10 * time.Second},
}
inv, err := cp.CreateInvoice(ctx, cryptopayclient.CreateInvoice{
OrderID: "ORDER-1001",
PriceAmount: "25.00",
PriceCurrency: "USD",
ReturnURL: "https://shop.example/orders/ORDER-1001",
Metadata: map[string]string{"user_id": "42"},
}, "order-ORDER-1001")
if err != nil {
return err
}
fmt.Println(inv.CheckoutURL)4. 引导顾客付款
将浏览器重定向到 invoice.checkout_url(HTTP 303)。顾客选择币种后会看到地址、金额和二维码。在沙盒中,付款信息下方有测试支付按钮:「精确支付」「少付 10%」「多付 10%」「支付一半」「补付余款」。
请勿嵌入 iframe支付页面禁止被嵌入,以防地址被篡改。请在同一标签页或 App 的系统浏览器中打开。
5. 接收 Webhook
处理顺序始终如下:验证签名 → 丢弃重复事件 → 通过 API 复核状态 → 只交付一次订单 → 返回 2xx。
webhook.js
import express from "express";
import { verifyWebhook } from "./cryptopay.js";
// cp —— 第 3 步中的客户端。alreadyProcessed / markProcessed / fulfil —— 您自己的函数。
const app = express();
// express.raw:签名基于原始字节计算 —— 此路由不要挂载 express.json()
app.post("/webhooks/coinetic", express.raw({ type: "application/json" }), async (req, res) => {
let event;
try {
event = verifyWebhook(process.env.WEBHOOK_SECRET, req.headers, req.body);
} catch (e) {
return res.status(e.status ?? 400).end(); // 401 —— 签名不匹配,400 —— timestamp 过期
}
try {
const eventId = req.headers["x-webhook-id"];
if (await alreadyProcessed(eventId)) return res.sendStatus(200);
const inv = await cp.getInvoice(event.data.invoice_id); // 状态以 API 为准,而不是 Webhook
if (inv.status === "paid" || inv.status === "overpaid") await fulfil(inv.order_id);
await markProcessed(eventId);
res.sendStatus(200);
} catch (e) {
console.error(e);
res.sendStatus(500); // 非 2xx —— Coinetic 会重新投递
}
});
app.listen(3000);webhook.php
require 'Cryptopay.php';
$headers = array_change_key_case(getallheaders(), CASE_LOWER);
$raw = file_get_contents('php://input'); // 原始请求体,在 json_decode 之前
try {
$event = \Cryptopay\verify_webhook(getenv('WEBHOOK_SECRET'), $headers, $raw);
} catch (\Cryptopay\CryptopayException $e) {
http_response_code($e->status);
exit;
}
if (already_processed($headers['x-webhook-id'])) { http_response_code(200); exit; }
$inv = $cp->getInvoice($event['data']['invoice_id']); // 状态以 API 为准
if (in_array($inv['status'], \Cryptopay\PAID_STATUSES, true)) {
fulfil($inv['order_id']);
}
mark_processed($headers['x-webhook-id']);
http_response_code(200);webhook.py
import os
from flask import Flask, request
from cryptopay import verify_webhook, CryptopayError, PAID_STATUSES
app = Flask(__name__)
@app.post("/webhooks/coinetic")
def webhook():
headers = {k.lower(): v for k, v in request.headers.items()}
try:
event = verify_webhook(os.environ["WEBHOOK_SECRET"], headers, request.get_data())
except CryptopayError as e:
return "", e.status
if already_processed(headers["x-webhook-id"]):
return "", 200
inv = cp.get_invoice(event["data"]["invoice_id"]) # 状态以 API 为准
if inv["status"] in PAID_STATUSES:
fulfil(inv["order_id"])
mark_processed(headers["x-webhook-id"])
return "", 200webhook.go
func webhook(w http.ResponseWriter, r *http.Request) {
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if err := cryptopayclient.VerifyWebhook(os.Getenv("WEBHOOK_SECRET"), r.Header, raw, time.Now(), 5*time.Minute); err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
var ev struct {
Data struct{ InvoiceID string `json:"invoice_id"` } `json:"data"`
}
if err := json.Unmarshal(raw, &ev); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
inv, err := cp.GetInvoice(r.Context(), ev.Data.InvoiceID) // 状态以 API 为准
if err != nil {
w.WriteHeader(http.StatusInternalServerError) // Coinetic 会重试
return
}
if cryptopayclient.PaidStatuses[inv.Status] {
fulfilOnce(inv.OrderID)
}
w.WriteHeader(http.StatusOK)
}6. 引导顾客返回
付款完成后,页面上会出现「返回商店」按钮,跳转到您的 return_url。请在该页面展示您自己数据库中的订单状态。如果 Webhook 尚未到达,请通过 GET /v1/invoices/{id} 复核。
下一步
- 在沙盒中跑通所有场景 —— 少付、多付、账单过期。
- 处理其余事件 ——
underpaid、expired、reorged。 - 在接收真实资金前,完成上线检查清单。