在 Laravel 中接收加密货币付款(Tron)
用 Laravel 搭建接收 TRX 与 TRC20 代币付款的网关:每个付款会话一个地址、Chaingateway Webhook、签名校验与交易验证,并说明失败通知的重试方法。本教程提供完整代码,但仅作演示,不可直接用于生产环境。
审核: Maurice Sobiera
Laravel 加密支付网关为每个付款会话创建一个区块链地址,在该地址上注册 Webhook,并在收到已验证的通知时将会话标记为已付款。本教程借助 Chaingateway API,为 Tron 上的 TRX 和 JST 代币(TRC20)构建这一流程。代码仅为演示,不是生产系统。
同样的模式也适用于比特币、以太坊、BNB 智能链和 Polygon,只需对端点做少量修改。演示代码可在 chaingateway-crypto-payment-demo-laravel 仓库中获取。
请勿在生产环境中使用这段代码。演示代码以明文存储私钥,这在生产环境中绝不能发生。Chaingateway 也可以创建受密码保护的地址,此时您无需存储私钥,只需发送一个
password。
本教程要构建什么?
成果是一个小型支付网关,包含以下部分:
- 一个表单,用于以金额和币种(TRX 或 JST)启动一个付款会话。
- 为每个会话生成的新钱包地址。
- 一个会话页面,显示地址、状态、应付金额和已收到的金额。
- 一个 Webhook 端点,负责校验签名、检查交易、更新会话,并可选地将资金转入冷钱包。
如何获取 API 密钥?
您在 Chaingateway 账户面板中创建 API 令牌。登录 app.chaingateway.io,打开用户设置并选择 API Tokens。点击 Create Token,为其命名(例如“Payment Gateway”),然后复制该值。每个请求都以 Bearer 令牌的形式发送它。开发者门户和 API 参考详细描述了各个端点。
您还需要一个配置好数据库的 Laravel 项目。如果从零开始,请遵循 Laravel 安装指南。掌握模型、迁移、控制器和路由的基础知识即可。
第 1 步:如何配置 API 客户端?
在 config/app.php 中添加基础 URL、令牌、网络以及冷钱包地址。X-Network 请求头用于选择网络:开发时使用 testnet,生产时使用 mainnet。
'Chaingateway' => [ 'api_url' => env('Chaingateway_API_URL', 'https://app.chaingateway.io/api/v2'), 'api_key' => env('Chaingateway_API_KEY'), 'network' => env('Chaingateway_NETWORK', 'testnet'), // Use 'mainnet' for production 'cold_wallet' => env('COLD_WALLET'), 'webhook_secret' => env('Chaingateway_WEBHOOK_SECRET'),],然后将这些值添加到您的 .env 文件中:
Chaingateway_API_URL=https://app.chaingateway.io/api/v2Chaingateway_API_KEY=your_api_key_hereChaingateway_NETWORK=testnetCOLD_WALLET=your_cold_wallet_addressChaingateway_WEBHOOK_SECRET=your_personal_secretWebhook 密钥就是您在 Chaingateway 个人资料设置中的个人密钥。设置之后,每个 Webhook 都会携带 X-Signature 请求头,第 4 步会对其进行验证。
第 2 步:如何定义路由?
四条路由覆盖整个流程:付款页面、启动会话、会话视图和 Webhook 接收端。请将它们添加到 routes/web.php。Webhook 路由需要一个名称,因为控制器通过 route('handleWebhook') 构建其 URL。
use App\Http\Controllers\PaymentController;
Route::get('/payment', [PaymentController::class, 'showPaymentPage']);Route::post('/start-payment-session', [PaymentController::class, 'startPaymentSession']);Route::get('/payment-session/{id}', [PaymentController::class, 'showPaymentSession'])->name('showPaymentSession');Route::post('/webhook', [PaymentController::class, 'handleWebhook'])->name('handleWebhook');Laravel 会拒绝没有 CSRF 令牌的 POST 请求,而 Chaingateway 无法发送该令牌。请在 bootstrap/app.php 中将 Webhook 路由排除在外。Laravel CSRF 文档对旧版本描述了相同的设置。
use Illuminate\Foundation\Application;use Illuminate\Foundation\Configuration\Exceptions;use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { // Exclude the webhook route from CSRF protection $middleware->validateCsrfTokens(except: [ 'webhook', ]); }) ->withExceptions(function (Exceptions $exceptions) { // })->create();您的 Webhook URL 必须能从公共互联网访问。在本地开发时,请通过隧道暴露开发服务器。
第 3 步:需要哪些模型和迁移?
您需要两张表:保存钱包及其密钥的 wallets,以及保存付款会话及其状态的 payment_sessions。为两者生成模型和迁移。
php artisan make:model Wallet -mphp artisan make:model PaymentSession -m在 database/migrations/<timestamp>_create_wallets_table.php 中:
Schema::create('wallets', function (Blueprint $table) { $table->id(); $table->string('address')->unique(); // Wallet address $table->string('private_key'); // Demo only: never store keys in plain text $table->timestamps();});在 database/migrations/<timestamp>_create_payment_sessions_table.php 中:
Schema::create('payment_sessions', function (Blueprint $table) { $table->id(); $table->string('status')->default('Pending'); // Pending, Completed, Failed, overpaid, underpaid $table->foreignId('wallet_id')->constrained()->onDelete('cascade'); $table->decimal('amount', 18, 8)->nullable(); // Amount the customer should send $table->string('currency')->default('TRX'); $table->decimal('received_amount', 18, 8)->nullable(); // Amount that arrived $table->string('webhook_id')->nullable(); $table->timestamps();});运行 php artisan migrate,然后设置可填充字段并定义关联关系。
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Wallet extends Model{ protected $fillable = ['address', 'private_key'];
public function paymentSessions() { return $this->hasMany(PaymentSession::class); }}namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class PaymentSession extends Model{ protected $fillable = ['wallet_id', 'status', 'amount', 'currency', 'received_amount', 'webhook_id'];
public function wallet() { return $this->belongsTo(Wallet::class); }}第 4 步:PaymentController 如何工作?
控制器负责创建钱包、注册 Webhook 并处理传入的通知。使用 php artisan make:controller PaymentController 生成它。
创建会话需要两次 API 调用。POST /api/v2/tron/addresses 返回一个新地址,若未设置密码,还会返回其私钥。POST /api/v2/tron/webhooks 为发往该地址的交易注册 Webhook,并在 data.webhook 中返回 Webhook ID。
Webhook 处理程序按顺序执行四件事。它验证 X-Signature 请求头。它按接收地址查找会话。它向 API 请求该交易,并检查 ret[0].contractRet 是否为 SUCCESS。只有在此之后,它才会更新会话。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Client\PendingRequest;use Illuminate\Http\Request;use Illuminate\Support\Facades\Http;use App\Models\PaymentSession;use App\Models\Wallet;
class PaymentController extends Controller{ private $apiUrl; private $apiKey; private $network; private $coldWallet; private $webhookSecret;
public function __construct() { $this->apiUrl = config('app.Chaingateway.api_url'); $this->apiKey = config('app.Chaingateway.api_key'); $this->network = config('app.Chaingateway.network'); $this->coldWallet = config('app.Chaingateway.cold_wallet'); $this->webhookSecret = config('app.Chaingateway.webhook_secret'); }
private function api(): PendingRequest { return Http::withHeaders([ 'Authorization' => "Bearer {$this->apiKey}", 'Content-Type' => 'application/json', 'X-Network' => $this->network, ]); }
public function showPaymentPage() { return view('payment'); }
/** * Creates a wallet address and a webhook for it, then stores the session. */ public function startPaymentSession(Request $request) { $validated = $request->validate([ 'amount' => 'required|numeric|gt:0', 'currency' => 'required|in:TRX,JST', ]);
$response = $this->api()->post("{$this->apiUrl}/tron/addresses");
if (! $response->successful()) { return back()->withErrors(['error' => 'Failed to create payment session.']); }
$walletData = $response->json()['data'];
$wallet = Wallet::create([ 'address' => $walletData['address'], 'private_key' => $walletData['privateKey'], ]);
$webhookResponse = $this->api()->post("{$this->apiUrl}/tron/webhooks", [ 'to' => $wallet->address, 'url' => route('handleWebhook'), ]);
if (! $webhookResponse->successful()) { return back()->withErrors(['error' => 'Failed to create webhook.']); }
$paymentSession = PaymentSession::create([ 'wallet_id' => $wallet->id, 'webhook_id' => $webhookResponse->json()['data']['webhook'], 'amount' => $validated['amount'], 'currency' => $validated['currency'], 'status' => 'Pending', ]);
return redirect()->route('showPaymentSession', ['id' => $paymentSession->id]); }
public function showPaymentSession($id) { $paymentSession = PaymentSession::with('wallet')->findOrFail($id); return view('payment-session', compact('paymentSession')); }
public function handleWebhook(Request $request) { $transactionData = $request->all();
// 1. Verify that Chaingateway sent the notification (see the signature section) if (! $this->signatureIsValid($transactionData['txid'] ?? '', $request->header('X-Signature', ''))) { return response()->json(['error' => 'Invalid signature'], 401); }
// 2. Find the session for the receiving address $wallet = Wallet::where('address', $transactionData['to'])->first(); if (! $wallet) { return response()->json(['error' => 'Wallet not found'], 404); }
$paymentSession = PaymentSession::where('wallet_id', $wallet->id)->first(); if (! $paymentSession) { return response()->json(['error' => 'Payment session not found'], 404); }
// A notification can arrive twice. Acknowledge it without processing it again. if ($paymentSession->status !== 'Pending') { return response()->json(['status' => 'already processed']); }
// 3. Check on chain that the transaction succeeded $txResponse = $this->api()->get("{$this->apiUrl}/tron/transactions/{$transactionData['txid']}"); $contractRet = $txResponse->json('data.transaction.ret.0.contractRet');
if ($txResponse->successful() && $contractRet === 'SUCCESS') { $paymentSession->status = 'Completed'; $paymentSession->received_amount = $transactionData['amount'];
// Compare the received amount with the expected one and allow a margin. // Check in a test notification whether `amount` is in the token's smallest unit // or already a decimal value, and convert before you compare. $allowedDifference = $paymentSession->amount * 0.10; if (abs($paymentSession->amount - $transactionData['amount']) >= $allowedDifference) { $paymentSession->status = $transactionData['amount'] > $paymentSession->amount ? 'overpaid' : 'underpaid'; }
// For tokens, check that the contract is the one you expect (JST on Tron mainnet) if ($paymentSession->currency == 'JST' && ($transactionData['contractaddress'] ?? null) != 'TF17BgPaZYbz8oxbjhriubPDsA7ArKoLX3') { $paymentSession->status = 'Wrong currency received'; }
/** * Optional: forward the funds to a cold wallet. * A TRC20 transfer needs Energy, so the address must hold TRX or staked resources. * Chaingateway's Tron Paymaster is deprecated. Use TronFuel (https://tronfuel.dev) * if you do not want to handle the fees yourself. * * $endpoint = $transactionData['contractaddress'] * ? "{$this->apiUrl}/tron/transactions/trc20" * : "{$this->apiUrl}/tron/transactions"; * * $this->api()->post($endpoint, [ * 'amount' => $transactionData['amount'], * 'privatekey' => $wallet->private_key, * 'to' => $this->coldWallet, * 'from' => $transactionData['to'], * 'contractaddress' => $transactionData['contractaddress'], * ]); */ } else { $paymentSession->status = 'Failed'; }
// Delete the webhook if you will not reuse the address $this->api()->delete("{$this->apiUrl}/tron/webhooks/{$paymentSession->webhook_id}");
$paymentSession->save(); return response()->json(['status' => 'success']); }
private function signatureIsValid(string $txid, string $received): bool { if (! $this->webhookSecret) { return false; }
$expected = base64_encode(hash_hmac('sha256', $txid, $this->webhookSecret, true)); return hash_equals($expected, $received); }}Pending 检查可以防范重复的通知,当您重新发送失败的通知时,就可能出现重复。您的服务器未接受的通知不会自动重试。它会出现在 GET /api/v2/tron/webhooks/notifications/failed 的失败通知列表中,您可以通过 POST /api/v2/tron/webhooks/notifications/{id}/retry 重新发送。
如何验证 Webhook 签名?
使用您的个人密钥对 txid 计算 HMAC-SHA256,并与 X-Signature 请求头进行比较。该请求头保存的是 Base64 编码的结果。HMAC 的规范见 RFC 2104。上面的 signatureIsValid 方法使用 hash_hmac 实现了这一点,并使用 hash_equals 进行比较,后者耗时恒定。签名文档列出了其他语言中的相同校验方法。
如果没有配置密钥,演示代码会拒绝每一条通知。没有有效签名的请求,可能来自任何知道您 Webhook URL 的人,因此您不应跳过这项检查。
第 5 步:如何构建视图?
两个 Blade 视图就够了:一个用于启动会话的表单,以及一个显示会话状态的页面。在 resources/views/payment.blade.php 中:
<!DOCTYPE html><html> <head> <title>Start Payment Session</title> </head> <body> <h2>Start a New Payment Session</h2> <form action="/start-payment-session" method="POST"> @csrf <label for="amount">Amount:</label> <input type="number" step="0.01" name="amount" id="amount" required /> <br /> <label for="currency">Currency:</label> <select name="currency" id="currency" required> <option value="TRX">TRX</option> <option value="JST">JST (TRC20)</option> </select> <br /> <button type="submit">Start Payment Session</button> </form> </body></html>在真实的商店中,启动会话的是结账流程,而不是一个表单。下面的会话页面显示地址和状态。真实的页面会通过轮询或 WebSocket 刷新状态。在 resources/views/payment-session.blade.php 中:
<!DOCTYPE html><html> <head> <title>Payment Session</title> </head> <body> <h2>Payment Session</h2> <p> Send <strong>{{ $paymentSession->amount }} {{ $paymentSession->currency }}</strong> to the address below: </p> <p><strong>{{ $paymentSession->wallet->address }}</strong></p> <p>Status: <strong>{{ $paymentSession->status }}</strong></p> <p> Received: <strong>{{ $paymentSession->received_amount }} {{ $paymentSession->currency }}</strong> </p> </body></html>第 6 步:如何测试流程?
先在测试网上测试。使用 php artisan serve 启动服务器,然后按以下步骤操作。
- 打开
/payment并启动一个新会话。 - 向会话页面上的钱包地址发送测试网资金。
- 等待 Webhook,或自己向
/webhook发送一条已签名的通知。 - 重新加载会话页面,检查状态是否已变更。
要模拟一条通知,请使用 Webhook 文档中的类似负载,并附上有效的 X-Signature 请求头。请记住,交易检查会就 txid 调用 API,因此一个虚构的交易 ID 最终会得到 Failed 状态。
上线生产前还需要增加什么?
在接收真实付款之前,请替换演示中的捷径。
- 创建带密码的地址,使您的数据库中不存储任何私钥。
- 只有在达到您的风险政策所要求的确认数之后,才为付款入账。
- 以代币的最小单位比较金额,并为每种代币核对合约地址。
- 定期将未完成的会话与 API 进行对账,因为 Webhook 可能会漏收。
如需更详细地了解充值流程,请阅读加密支付 Webhook 的工作原理和Webhook 投递保证。如有问题,请参阅支持页面。
准备好自己动手构建了吗? 获取你的 API key — 7 天试用,无需信用卡 — 或查看 Tron API 获取完整的 endpoint 参考。