PHP项目USDC与Circle

wen PHP项目 2

本文目录导读:

PHP项目USDC与Circle

  1. 项目概述
  2. 基础依赖安装
  3. Circle API配置
  4. 核心功能实现
  5. API路由配置
  6. 关键注意事项
  7. 测试建议

我来帮你分析PHP项目中集成USDC和Circle API的相关内容。

项目概述

USDC (USD Coin) 是由Circle发行的稳定币,可通过Circle API进行集成。

基础依赖安装

composer require circle/platform-sdk
composer require guzzlehttp/guzzle
composer require web3/web3

Circle API配置

环境配置

// config/circle.php
return [
    'api_key' => env('CIRCLE_API_KEY'),
    'wallet_id' => env('CIRCLE_WALLET_ID'),
    'endpoint' => env('CIRCLE_ENDPOINT', 'https://api.circle.com/v1'),
    'webhook_secret' => env('CIRCLE_WEBHOOK_SECRET'),
];

核心功能实现

1 Circle API客户端

<?php
namespace App\Services;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
class CircleService
{
    private $client;
    private $apiKey;
    private $endpoint;
    public function __construct()
    {
        $this->apiKey = config('circle.api_key');
        $this->endpoint = config('circle.endpoint');
        $this->client = new Client([
            'base_uri' => $this->endpoint,
            'headers' => [
                'Authorization' => "Bearer {$this->apiKey}",
                'Content-Type' => 'application/json',
            ],
        ]);
    }
    // 创建支付
    public function createPayment(array $paymentData)
    {
        try {
            $response = $this->client->post('/payments', [
                'json' => $paymentData
            ]);
            return json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            Log::error('Circle payment creation failed: ' . $e->getMessage());
            throw $e;
        }
    }
    // 获取支付状态
    public function getPaymentStatus(string $paymentId)
    {
        $response = $this->client->get("/payments/{$paymentId}");
        return json_decode($response->getBody(), true);
    }
    // 创建转账
    public function createTransfer(array $transferData)
    {
        try {
            $response = $this->client->post('/transfers', [
                'json' => $transferData
            ]);
            return json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            Log::error('Circle transfer failed: ' . $e->getMessage());
            throw $e;
        }
    }
}

2 USDC交易处理

<?php
namespace App\Services;
use App\Models\Transaction;
use Illuminate\Support\Facades\DB;
class USDCService
{
    private $circleService;
    public function __construct(CircleService $circleService)
    {
        $this->circleService = $circleService;
    }
    // 发送USDC
    public function sendUSDC($fromWallet, $toAddress, $amount, $options = [])
    {
        DB::beginTransaction();
        try {
            // 创建转账数据
            $transferData = [
                'idempotencyKey' => uniqid('tx_', true),
                'source' => [
                    'type' => 'wallet',
                    'id' => $fromWallet
                ],
                'destination' => [
                    'type' => 'blockchain',
                    'address' => $toAddress,
                    'chain' => 'ETH' // 或 'AVAX', 'SOL' 等
                ],
                'amount' => [
                    'amount' => $amount,
                    'currency' => 'USD'
                ],
                'token' => 'USDC',
            ];
            // 记录交易
            $transaction = $this->createTransaction([
                'from_wallet' => $fromWallet,
                'to_address' => $toAddress,
                'amount' => $amount,
                'currency' => 'USDC',
                'status' => 'pending',
                'type' => 'send'
            ]);
            // 调用Circle API
            $result = $this->circleService->createTransfer($transferData);
            // 更新交易状态
            $transaction->update([
                'circle_transfer_id' => $result['data']['id'],
                'status' => 'submitted'
            ]);
            DB::commit();
            return $transaction;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('USDC send failed: ' . $e->getMessage());
            throw $e;
        }
    }
    // 创建交易记录
    private function createTransaction($data)
    {
        return Transaction::create($data);
    }
}

3 钱包管理

<?php
namespace App\Services;
class WalletService
{
    private $circleService;
    public function __construct(CircleService $circleService)
    {
        $this->circleService = $circleService;
    }
    // 创建钱包
    public function createWallet(array $walletData)
    {
        try {
            $response = $this->circleService->client->post('/wallets', [
                'json' => [
                    'idempotencyKey' => uniqid(),
                    'description' => $walletData['description'],
                    'name' => $walletData['name']
                ]
            ]);
            return json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            Log::error('Wallet creation failed: ' . $e->getMessage());
            throw $e;
        }
    }
    // 获取钱包余额
    public function getWalletBalance($walletId)
    {
        try {
            $response = $this->circleService->client->get("/wallets/{$walletId}/balances");
            return json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            Log::error('Get wallet balance failed: ' . $e->getMessage());
            throw $e;
        }
    }
    // 获取交易历史
    public function getTransactionHistory($walletId, $limit = 10)
    {
        $response = $this->circleService->client->get("/wallets/{$walletId}/transactions", [
            'query' => ['limit' => $limit]
        ]);
        return json_decode($response->getBody(), true);
    }
}

4 Webhook处理

<?php
namespace App\Http\Controllers;
use App\Services\USDCService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class WebhookController extends Controller
{
    public function handleCircleWebhook(Request $request)
    {
        $payload = $request->all();
        $signature = $request->header('X-Circle-Signature');
        // 验证签名
        if (!$this->verifySignature($payload, $signature)) {
            return response('Invalid signature', 401);
        }
        switch ($payload['notificationType']) {
            case 'payment': {
                $this->handlePaymentEvent($payload);
                break;
            }
            case 'transfer': {
                $this->handleTransferEvent($payload);
                break;
            }
            case 'wallet': {
                $this->handleWalletEvent($payload);
                break;
            }
        }
        return response('OK', 200);
    }
    private function handlePaymentEvent($payload)
    {
        $paymentId = $payload['data']['id'];
        $status = $payload['data']['status'];
        Log::info("Payment {$paymentId} status changed to: {$status}");
        // 更新数据库中的支付状态
        // ...
    }
    private function verifySignature($payload, $signature)
    {
        $secret = config('circle.webhook_secret');
        $calculatedSignature = hash_hmac('sha256', json_encode($payload), $secret);
        return hash_equals($calculatedSignature, $signature);
    }
}

API路由配置

// routes/api.php
use App\Http\Controllers\WebhookController;
Route::prefix('circle')->group(function () {
    Route::post('/webhook', [WebhookController::class, 'handleCircleWebhook']);
});
Route::middleware('auth:sanctum')->group(function () {
    Route::post('/usdc/send', [USDCController::class, 'send']);
    Route::post('/usdc/receive', [USDCController::class, 'receive']);
    Route::get('/balance', [USDCController::class, 'getBalance']);
    Route::get('/transactions', [USDCController::class, 'getTransactions']);
});

关键注意事项

安全性

  • 使用环境变量存储API密钥
  • 实现请求签名验证
  • 实施IP白名单
  • 使用HTTPS

错误处理

// 自定义异常
class CircleApiException extends \Exception
{
    public function __construct($message, $code = 0, $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }
}
// 全局异常处理
public function render($request, \Throwable $exception)
{
    if ($exception instanceof CircleApiException) {
        return response()->json([
            'error' => $exception->getMessage(),
            'code' => $exception->getCode()
        ], 400);
    }
    return parent::render($request, $exception);
}

性能优化

  • 实现缓存机制
  • 使用队列处理交易
  • 批量处理webhook

测试建议

// tests/Unit/USDCServiceTest.php
class USDCServiceTest extends TestCase
{
    public function test_send_usdc()
    {
        $mock = Mockery::mock(CircleService::class);
        $mock->shouldReceive('createTransfer')
             ->once()
             ->andReturn(['data' => ['id' => 'test_transfer']]);
        $service = new USDCService($mock);
        $result = $service->sendUSDC('wallet_1', '0x123...', 100);
        $this->assertInstanceOf(Transaction::class, $result);
    }
}

这个架构提供了完整的USDC集成方案,包括API调用、钱包管理、交易处理和webhook处理,需要根据具体需求调整配置和实现细节。

抱歉,评论功能暂时关闭!