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 Bundle Laravel Package

cometcult/braintree-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cometcult/braintree-bundle
    

    Add to AppKernel.php:

    new CometCult\BraintreeBundle\CometCultBraintreeBundle(),
    
  2. Configure (config.yml):

    comet_cult_braintree:
        environment: sandbox  # or production
        merchant_id: "your_merchant_id"
        public_key: "your_public_key"
        private_key: "your_private_key"
    
  3. First Use Case: Inject the Braintree_Service into a controller/service:

    use CometCult\BraintreeBundle\Braintree\BraintreeService;
    
    class PaymentController extends Controller
    {
        public function __construct(BraintreeService $braintree)
        {
            $this->braintree = $braintree;
        }
    
        public function createClientToken()
        {
            $clientToken = $this->braintree->getClientToken();
            return new Response($clientToken);
        }
    }
    

Implementation Patterns

Common Workflows

  1. Client-Side Token Generation: Use getClientToken() for JavaScript SDK integration:

    $clientToken = $this->braintree->getClientToken();
    

    Render in Twig:

    <script src="https://js.braintreegateway.com/js/braintree-2.32.0.min.js"></script>
    <script>
        braintree.setup("{{ clientToken }}", "dropin", { ... });
    </script>
    
  2. Server-Side Transactions:

    $result = $this->braintree->getTransactionService()->sale([
        'amount' => '10.00',
        'paymentMethodNonce' => $nonceFromClient, // From Braintree Drop-in
        'options' => ['submitForSettlement' => true]
    ]);
    
  3. Subscription Management:

    $subscription = $this->braintree->getSubscriptionService()->create([
        'paymentMethodToken' => $token,
        'planId' => 'monthly_plan_id',
        'customerId' => $customerId
    ]);
    

Integration Tips

  • Dependency Injection: Prefer constructor injection for BraintreeService in controllers/services.
  • Configuration: Use environment variables (e.g., .env) for sensitive keys (e.g., BRAINTREE_PRIVATE_KEY).
  • Error Handling: Wrap Braintree calls in try-catch:
    try {
        $result = $this->braintree->getTransactionService()->sale([...]);
    } catch (\Braintree\Exception\GatewayRejectedException $e) {
        // Handle declined transactions
    }
    
  • Testing: Use sandbox environment and Braintree’s test cards.

Gotchas and Tips

Pitfalls

  1. Configuration Overrides:

    • Ensure config.yml keys match Braintree’s expected format (e.g., environment must be sandbox/production).
    • Fix: Validate config with:
      $this->braintree->getGateway()->isEnvironmentLive(); // Returns bool
      
  2. Nonce Validation:

    • Always validate nonces server-side (client-side tokens can be spoofed).
    • Tip: Use Braintree_Transaction::validate() for additional checks.
  3. Deprecated Methods:

  4. CORS Issues:

    • If using Drop-in, ensure your server allows requests to https://*.braintreegateway.com (common in production).

Debugging

  • Enable Logging: Configure Braintree’s logger in config.yml:

    comet_cult_braintree:
        logger:
            enabled: true
            level: debug
    

    Logs appear in var/log/dev.log.

  • Common Errors:

    • Invalid Merchant ID: Verify merchant_id in config matches your Braintree account.
    • Authentication Failed: Check private_key and public_key for typos or whitespace.
    • Invalid Amount: Ensure amounts are strings (e.g., "10.00", not 10).

Extension Points

  1. Custom Services: Extend the bundle by creating a custom service that wraps Braintree calls:

    class CustomPaymentService
    {
        public function __construct(BraintreeService $braintree) { ... }
    
        public function processRefund($transactionId, $amount)
        {
            return $this->braintree->getTransactionService()->refund($transactionId, $amount);
        }
    }
    
  2. Event Listeners: Listen to Braintree webhooks (e.g., subscription cancellations) via Symfony’s event dispatcher:

    // src/EventListener/BraintreeWebhookListener.php
    class BraintreeWebhookListener
    {
        public function onKernelRequest(GetResponseEvent $event)
        {
            if ($event->isMasterRequest() && $event->getRequest()->getPathInfo() === '/braintree/webhook') {
                $this->braintree->getWebhookNotificationService()->process();
            }
        }
    }
    
  3. Override Templates: The bundle doesn’t include frontend templates, but you can integrate with Braintree’s Drop-in UI or build custom forms using the clientToken.

Pro Tips

  • Idempotency: Use Braintree’s idempotency keys for retry-safe transactions:
    $result = $this->braintree->getTransactionService()->sale([
        'amount' => '10.00',
        'paymentMethodNonce' => $nonce,
        'options' => ['idempotencyKey' => uniqid()]
    ]);
    
  • Customer Management: Store customerId in your database to link transactions/subscriptions to users:
    $customer = $this->braintree->getCustomerService()->create([
        'firstName' => 'John',
        'lastName' => 'Doe',
        'email' => 'john@example.com'
    ]);
    
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai