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

Pagamento Digital Bundle Laravel Package

brazilianfriendsofsymfony/pagamento-digital-bundle

Symfony bundle integrating Pagamento Digital payment services for Brazilian e-commerce apps. Provides configuration and helper services to communicate with the gateway, handle checkout requests and notifications, and streamline payment workflow integration within Symfony projects.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the bundle via Composer:

    composer require brazilianfriendsosymfony/pagamento-digital-bundle
    

    Enable it in config/bundles.php:

    return [
        // ...
        BrazilianFriendsOfSymfony\PagamentoDigitalBundle\BFOSPagamentoDigitalBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console bfos:pagamento-digital:install
    

    Update config/packages/bfos_pagamento_digital.yaml with your Pagamento Digital API credentials (e.g., api_key, merchant_id).

  3. First Use Case: Creating a Payment Use the Payment service to generate a transaction:

    use BrazilianFriendsOfSymfony\PagamentoDigitalBundle\Service\PaymentService;
    
    $paymentService = $this->container->get(PaymentService::class);
    $payment = $paymentService->createPayment(
        100.00, // Amount
        'BRL',  // Currency
        'customer@example.com', // Customer email
        'Order #123' // Description
    );
    

    The response will include a payment_id and payment_url for redirecting the user.


Implementation Patterns

Common Workflows

  1. Payment Creation & Redirection

    • Use PaymentService to create a payment and redirect users to the Pagamento Digital gateway:
      $payment = $paymentService->createPayment($amount, $currency, $email, $description);
      return $this->redirect($payment->getPaymentUrl());
      
  2. Webhook Handling

    • Configure a Symfony controller to handle Pagamento Digital webhooks (e.g., POST /webhook/payment):
      use BrazilianFriendsOfSymfony\PagamentoDigitalBundle\Event\PaymentEvent;
      
      #[Route('/webhook/payment', name: 'pagamento_digital_webhook', methods: ['POST'])]
      public function handleWebhook(Request $request, PaymentService $paymentService): Response
      {
          $data = json_decode($request->getContent(), true);
          $paymentService->handleWebhook($data); // Validates and processes events (e.g., PAYMENT_CONFIRMED)
          return new Response('OK');
      }
      
    • Subscribe to events (e.g., PaymentConfirmedEvent) in your services.yaml:
      services:
          App\EventListener\PaymentListener:
              tags:
                  - { name: 'kernel.event_listener', event: 'bfos.pagamento_digital.payment.confirmed', method: 'onPaymentConfirmed' }
      
  3. Refunds & Cancellations

    • Use RefundService to process refunds:
      $refundService = $this->container->get(RefundService::class);
      $refund = $refundService->createRefund($paymentId, 50.00, 'Partial refund');
      
  4. Subscription Management

    • Create/subscribe to plans using SubscriptionService:
      $subscriptionService = $this->container->get(SubscriptionService::class);
      $subscription = $subscriptionService->createSubscription(
          $customerId,
          'monthly_plan_id',
          'customer@example.com'
      );
      

Integration Tips

  • Symfony Forms: Bind payment fields to a form for user input:
    $builder->add('amount', MoneyType::class, ['currency' => 'BRL']);
    $builder->add('email', EmailType::class);
    
  • Doctrine Entities: Extend the bundle’s Payment entity or create a custom one to map to your database:
    #[ORM\Entity]
    class AppPayment {
        #[ORM\OneToOne(targetEntity: \BrazilianFriendsOfSymfony\PagamentoDigitalBundle\Entity\Payment::class)]
        private ?Payment $pagamentoDigitalPayment = null;
    }
    
  • Testing: Use the bundle’s PaymentService in tests with mocked API responses:
    $paymentService->setClient($mockedClient); // Inject a mocked Guzzle client
    

Gotchas and Tips

Pitfalls

  1. API Rate Limits

    • Pagamento Digital may throttle requests. Cache responses for non-critical operations (e.g., plan listings) and implement retries with exponential backoff:
      $client->setDefaultOption('timeout', 30);
      $client->setDefaultOption('connect_timeout', 10);
      
  2. Webhook Verification

    • Always validate webhook signatures using the api_secret from your config:
      $isValid = $paymentService->validateWebhookSignature($request->getContent(), $request->headers->get('X-Signature'));
      if (!$isValid) throw new \RuntimeException('Invalid webhook signature');
      
  3. Currency & Amount Precision

    • Ensure amounts are passed as floats with 2 decimal places (e.g., 100.00, not 100). Use number_format() or bcdiv() for calculations.
  4. Idempotency

    • Pagamento Digital supports idempotency keys for payments/refunds. Generate unique keys (e.g., UUID) to avoid duplicate transactions:
      $paymentService->createPayment(..., null, 'unique-idempotency-key');
      

Debugging

  • Enable API Logging Configure the Guzzle client to log requests/responses:

    # config/packages/bfos_pagamento_digital.yaml
    services:
        BrazilianFriendsOfSymfony\PagamentoDigitalBundle\Client\PagamentoDigitalClient:
            arguments:
                $logger: '@logger'
    

    Check logs at var/log/dev.log for API errors.

  • Test Mode Use the test_mode: true config to avoid real charges during development.

Extension Points

  1. Custom Events Extend the bundle’s events (e.g., PaymentFailedEvent) to trigger custom logic:

    // src/EventListener/CustomPaymentListener.php
    class CustomPaymentListener {
        public function onPaymentFailed(PaymentFailedEvent $event): void {
            // Send email, update CRM, etc.
        }
    }
    
  2. API Client Overrides Replace the default PagamentoDigitalClient with a custom implementation for additional features (e.g., logging, metrics):

    # config/services.yaml
    services:
        App\Client\CustomPagamentoDigitalClient:
            decorates: 'BrazilianFriendsOfSymfony\PagamentoDigitalBundle\Client\PagamentoDigitalClient'
            arguments:
                $decorated: '@.inner'
    
  3. Database Migrations The bundle doesn’t include migrations. Manually create tables for Payment, Refund, and Subscription entities or use Doctrine migrations:

    php bin/console make:migration
    php bin/console doctrine:migrations:migrate
    

Pro Tips

  • Use Symfony’s Messenger Component Dispatch async events (e.g., PaymentConfirmedEvent) to a queue for background processing:
    $eventDispatcher->dispatch(new PaymentConfirmedEvent($payment));
    
  • Localization The bundle supports multiple languages. Override translation files in translations/:
    # config/packages/bfos_pagamento_digital.yaml
    twig:
        default_locale: 'pt_BR'
    
  • Documentation Gaps The package lacks detailed docs. Refer to Pagamento Digital’s API docs for undocumented endpoints (e.g., pix transfers).
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