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

Braintree Php Laravel Package

braintree/braintree_php

Official Braintree PHP SDK for integrating Braintree payments into PHP apps. Supports transactions, customer and payment method management, subscriptions, webhooks, and more, with configuration for sandbox/production and comprehensive API coverage.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require braintree/braintree_php
    

    Add the package to your composer.json and run composer install.

  2. Configuration: Create a .env entry for Braintree credentials:

    BRAINTREE_ENVIRONMENT=sandbox  # or production
    BRAINTREE_MERCHANT_ID=your_merchant_id
    BRAINTREE_PUBLIC_KEY=your_public_key
    BRAINTREE_PRIVATE_KEY=your_private_key
    

    Publish the config file (if using Laravel):

    php artisan vendor:publish --provider="Braintree\Gateway\ServiceProvider"
    
  3. First Use Case: Initialize the gateway in a service or controller:

    use Braintree\Gateway;
    
    $gateway = new Gateway([
        'environment' => env('BRAINTREE_ENVIRONMENT'),
        'merchantId' => env('BRAINTREE_MERCHANT_ID'),
        'publicKey' => env('BRAINTREE_PUBLIC_KEY'),
        'privateKey' => env('BRAINTREE_PRIVATE_KEY')
    ]);
    

    Test with a simple client token generation:

    $clientToken = $gateway->clientToken()->generate();
    

    Use this token in your frontend (e.g., Drop-in UI) to collect payment details.


Implementation Patterns

Common Workflows

1. Client-Side Integration (Drop-in UI)

  • Generate a client token in your backend:
    $clientToken = $gateway->clientToken()
        ->generate(['customerId' => $customerId]);
    
  • Pass the token to your frontend (e.g., via API) and initialize Braintree Drop-in:
    braintree.setup(clientToken, { id: 'dropin-container' }, responseHandler);
    
  • Handle the payment submission in your backend:
    $result = $gateway->transaction()->sale([
        'amount' => '10.00',
        'paymentMethodNonce' => $request->input('payment_method_nonce'),
        'options' => [
            'submitForSettlement' => true,
        ],
    ]);
    

2. Server-Side Payments (Direct API Calls)

  • Create a payment method (e.g., credit card) directly:
    $paymentMethod = $gateway->paymentMethod()->create([
        'paymentMethodNonce' => $nonceFromForm,
        'options' => [
            'makeDefault' => true,
        ],
    ]);
    
  • Process a transaction:
    $transaction = $gateway->transaction()->sale([
        'amount' => '20.00',
        'paymentMethodToken' => $paymentMethod->token,
    ]);
    

3. Customer Management

  • Create/update a customer:
    $customer = $gateway->customer()->create([
        'firstName' => 'John',
        'lastName' => 'Doe',
        'email' => 'john@example.com',
    ]);
    
  • Attach a payment method to a customer:
    $gateway->customer()->update($customer->id, [
        'paymentMethodToken' => $paymentMethod->token,
    ]);
    

4. Subscription Management

  • Create a subscription:
    $subscription = $gateway->subscription()->create([
        'planId' => 'monthly_plan_id',
        'customerId' => $customer->id,
    ]);
    
  • Cancel a subscription:
    $gateway->subscription()->cancel($subscription->id);
    

5. Webhooks

  • Configure webhook endpoints in your Braintree dashboard.
  • Validate and handle webhooks in Laravel:
    use Braintree\WebhookNotification;
    
    $notification = new WebhookNotification($request->getContent());
    $kind = $notification->kind;
    
    if ($notification->isValid()) {
        switch ($kind) {
            case 'subscription_canceled':
                // Handle cancellation
                break;
            case 'subscription_charged_successfully':
                // Handle successful charge
                break;
        }
    }
    

Integration Tips

  • Laravel Service Provider: Bind the gateway to the container for easy dependency injection:

    // In AppServiceProvider@boot()
    $this->app->singleton(Gateway::class, function () {
        return new Gateway([
            'environment' => env('BRAINTREE_ENVIRONMENT'),
            'merchantId' => env('BRAINTREE_MERCHANT_ID'),
            'publicKey' => env('BRAINTREE_PUBLIC_KEY'),
            'privateKey' => env('BRAINTREE_PRIVATE_KEY'),
        ]);
    });
    

    Now inject Gateway directly into controllers/services.

  • Request Validation: Use Laravel's validation to ensure required fields (e.g., payment_method_nonce) are present:

    $request->validate([
        'payment_method_nonce' => 'required|string',
    ]);
    
  • Logging: Enable logging for debugging:

    $gateway = new Gateway([...], [
        'logger' => new Monolog\Logger('braintree'),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Environment Mismatch:

    • Ensure BRAINTREE_ENVIRONMENT matches your dashboard settings (e.g., sandbox vs. production).
    • Test thoroughly in sandbox before switching to production.
  2. Nonce Expiry:

    • Client-side nonces (e.g., from Drop-in) expire after 30 minutes. Regenerate if the user takes too long.
  3. Idempotency:

    • Use idempotencyKey for critical transactions (e.g., subscriptions) to avoid duplicate charges:
      $gateway->transaction()->sale([
          'amount' => '10.00',
          'paymentMethodNonce' => $nonce,
          'options' => [
              'idempotencyKey' => Str::uuid()->toString(),
          ],
      ]);
      
  4. Webhook Validation:

    • Always validate webhook signatures to prevent spoofing:
      if (!$notification->isValid()) {
          abort(403, 'Invalid webhook signature');
      }
      
  5. Currency and Amount:

    • Amounts must be strings (e.g., "10.00", not 10.00 or 10).
    • Ensure the currency matches your plan/subscription settings.
  6. Customer Lookup:

    • Use customer->find() to avoid duplicate customers:
      $customer = $gateway->customer()->find($customerId);
      if (!$customer) {
          $customer = $gateway->customer()->create([...]);
      }
      

Debugging

  • Enable Debug Mode:
    $gateway = new Gateway([...], [
        'logger' => new \Braintree\Logger\FileLogger('/path/to/braintree.log'),
        'debug' => true,
    ]);
    
  • Test Transactions: Use Braintree's test credit cards in sandbox.

Extension Points

  1. Custom Fields: Add metadata to transactions/customers for tracking:

    $gateway->transaction()->sale([
        'amount' => '10.00',
        'paymentMethodNonce' => $nonce,
        'options' => [
            'submitForSettlement' => true,
        ],
        'customer' => [
            'customFields' => [
                'order_id' => $order->id,
                'user_id' => auth()->id(),
            ],
        ],
    ]);
    
  2. Advanced Fraud Tools: Enable Kount or 3D Secure via the dashboard and configure in the SDK:

    $gateway->transaction()->sale([
        'amount' => '10.00',
        'paymentMethodNonce' => $nonce,
        'options' => [
            'threeDSecure' => [
                'required' => true,
            ],
        ],
    ]);
    
  3. Custom Error Handling: Catch specific exceptions for granular control:

    try {
        $result = $gateway->transaction()->sale([...]);
    } catch (\Braintree\Exception\ValidationException $e) {
        // Handle validation errors (e.g., invalid nonce)
    } catch (\Braintree\Exception\GatewayException $e) {
        // Handle gateway errors (e.g., network issues)
    }
    
  4. Plan Management: Dynamically create plans for subscriptions:

    $plan = $gateway->subscription()->plan()->create([
        'id' => 'custom_plan_' . Str::uuid(),
        'name' => '
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation
uri-template/tests