Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Api Php Sdk Laravel Package

cryptomus/api-php-sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install the Package

    composer require cryptomus/api-php-sdk
    

    Ensure your composer.json includes "php": "^5.6.0" and extensions json and curl.

  2. Configure API Keys Store your PAYMENT_KEY, PAYOUT_KEY, and MERCHANT_UUID in .env or a secure config file:

    CRYPTOMUS_PAYMENT_KEY=your_payment_key_here
    CRYPTOMUS_PAYOUT_KEY=your_payout_key_here
    CRYPTOMUS_MERCHANT_UUID=your_merchant_uuid
    
  3. Initialize the Client

    use Cryptomus\Api\Client;
    
    $paymentClient = Client::payment(config('cryptomus.payment_key'), config('cryptomus.merchant_uuid'));
    $payoutClient = Client::payout(config('cryptomus.payout_key'), config('cryptomus.merchant_uuid'));
    
  4. First Use Case: Create a Payment

    $data = [
        'amount' => '10',
        'currency' => 'USD',
        'network' => 'BTC',
        'order_id' => 'order_123',
        'url_return' => 'https://your-site.com/return',
        'url_callback' => 'https://your-site.com/callback'
    ];
    
    try {
        $result = $paymentClient->create($data);
        // Redirect user to $result['url'] for payment.
    } catch (\Cryptomus\Api\RequestBuilderException $e) {
        Log::error("Payment creation failed: " . $e->getMessage());
    }
    
  5. Verify with Webhook Implement a route to handle callbacks (e.g., POST /cryptomus/callback) and validate the signature using Cryptomus’s webhook docs.


Implementation Patterns

Core Workflows

1. Payment Processing

  • Create Payment: Use payment->create() for one-time payments. Always include order_id, url_return, and url_callback.
    $paymentData = [
        'amount' => '25.50',
        'currency' => 'USD',
        'network' => 'ETH',
        'order_id' => 'inv_' . uniqid(),
        'url_return' => route('payment.return'),
        'url_callback' => route('payment.callback'),
        'lifetime' => '3600', // Expires in 1 hour (default: 7200)
    ];
    $payment = $paymentClient->create($paymentData);
    return redirect($payment['url']);
    
  • Check Payment Status: Poll payment->info() with order_id or uuid to verify status (e.g., paid, failed).
    $status = $paymentClient->info(['order_id' => 'inv_abc123']);
    if ($status['status'] === 'paid') {
        // Fulfill order.
    }
    
  • Handle Callbacks: Validate the webhook payload signature (Cryptomus sends a signature header). Use Laravel’s middleware for this:
    // app/Http/Middleware/ValidateCryptomusWebhook.php
    public function handle($request, Closure $next) {
        $signature = $request->header('X-Signature');
        $payload = $request->getContent();
        $secret = config('cryptomus.webhook_secret');
        if (!hash_equals($signature, hash_hmac('sha256', $payload, $secret))) {
            abort(403, 'Invalid signature');
        }
        return $next($request);
    }
    

2. Payout Automation

  • Send Payouts: Use payout->create() for affiliate payouts or withdrawals. Set is_subtract to 1 to deduct from your balance.
    $payoutData = [
        'amount' => '5.00',
        'currency' => 'USDT',
        'network' => 'TRC20',
        'address' => 'TXYZ...',
        'order_id' => 'payout_456',
        'is_subtract' => '1',
        'url_callback' => route('payout.callback'),
    ];
    $payout = $payoutClient->create($payoutData);
    
  • Track Payouts: Use payout->info() to check status (e.g., process, completed, failed).
    $payoutStatus = $payoutClient->info(['order_id' => 'payout_456']);
    if ($payoutStatus['status'] === 'completed') {
        // Update affiliate database.
    }
    

3. Wallet Management

  • Create Wallets: Use payment->createWallet() for dynamic wallets (e.g., per-user or per-transaction).
    $walletData = [
        'network' => 'TRON',
        'currency' => 'USDT',
        'order_id' => 'wallet_789',
        'url_callback' => route('wallet.callback'),
    ];
    $wallet = $paymentClient->createWallet($walletData);
    // Store $wallet['address'] in your DB for future use.
    

4. Balance and History

  • Check Balances: Use payment->balance() to fetch merchant/user balances across currencies.
    $balances = $paymentClient->balance();
    $merchantBtcBalance = $balances[0]['balance']['merchant'][0]['balance'];
    
  • Fetch Transaction History: Use payment->history() with pagination for auditing.
    $history = $paymentClient->history(1); // Page 1
    foreach ($history['items'] as $transaction) {
        if ($transaction['payment_status'] === 'paid') {
            // Process transaction.
        }
    }
    

Integration Tips

  1. Laravel Service Provider Bind the clients to the container for easy dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->singleton('cryptomus.payment', function ($app) {
            return Client::payment(config('cryptomus.payment_key'), config('cryptomus.merchant_uuid'));
        });
        $this->app->singleton('cryptomus.payout', function ($app) {
            return Client::payout(config('cryptomus.payout_key'), config('cryptomus.merchant_uuid'));
        });
    }
    

    Then inject via constructor:

    public function __construct(private PaymentClient $paymentClient) {}
    
  2. Retry Logic Wrap API calls in a retry mechanism for transient failures (e.g., network issues):

    use Illuminate\Support\Facades\Http;
    
    public function withRetry($callback, $maxAttempts = 3) {
        $attempts = 0;
        while ($attempts < $maxAttempts) {
            try {
                return $callback();
            } catch (\Cryptomus\Api\RequestBuilderException $e) {
                $attempts++;
                if ($attempts === $maxAttempts) throw $e;
                sleep(2 ** $attempts); // Exponential backoff
            }
        }
    }
    
    // Usage:
    $result = $this->withRetry(function () {
        return $paymentClient->create($data);
    });
    
  3. Logging and Monitoring Log all API responses and errors for debugging:

    try {
        $result = $paymentClient->create($data);
        Log::info('Cryptomus payment created', ['data' => $data, 'result' => $result]);
    } catch (\Exception $e) {
        Log::error('Cryptomus API error', [
            'error' => $e->getMessage(),
            'method' => $e->getMethod(),
            'data' => $data,
        ]);
        throw $e;
    }
    
  4. Testing Use Laravel’s HTTP testing to mock API responses:

    // tests/Feature/CryptomusPaymentTest.php
    public function test_payment_creation() {
        Http::fake([
            'api.cryptomus.com/*' => Http::response([
                'uuid' => 'test-uuid',
                'url' => 'https://pay.cryptomus.com/test',
            ], 200),
        ]);
    
        $result = $this->paymentClient->create(['amount' => '10', 'currency' => 'USD']);
        $result->assertSee('test-uuid');
    }
    
  5. Environment-Specific Config Use Laravel’s config system to switch between sandbox and live keys:

    # .env
    CRYPTOMUS_ENV=sandbox
    CRYPTOMUS_SANDBOX_PAYMENT
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky