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

Gateway Locaweb Bundle Laravel Package

brazilianfriendsofsymfony/gateway-locaweb-bundle

Symfony 2 bundle que simplifica a integração com o gateway de pagamentos da Locaweb. Inclui dependências para front-end usando jQuery e RequireJS, facilitando a implementação do fluxo de pagamento em aplicações Symfony.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your Symfony project via Composer:

    composer require brazilianfriendsofsymfony/gateway-locaweb-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        BrazilianFriendsOfSymfony\GatewayLocawebBundle\BrazilianFriendsOfSymfonyGatewayLocawebBundle::class => ['all' => true],
    ];
    
  2. Configuration Configure the bundle in config/packages/bfos_gateway_locaweb.yaml:

    bfos_gateway_locaweb:
        merchant_id: 'YOUR_MERCHANT_ID'
        merchant_key: 'YOUR_MERCHANT_KEY'
        sandbox: true # Set to false for production
        return_url: 'https://yourdomain.com/payment/return'
        notification_url: 'https://yourdomain.com/payment/notification'
    
  3. First Use Case: Creating a Payment Form Use the LocawebGateway service to generate a payment form in a controller:

    use BrazilianFriendsOfSymfony\GatewayLocawebBundle\Service\LocawebGateway;
    
    public function createPayment(LocawebGateway $gateway)
    {
        $payment = $gateway->createPayment(
            1000, // Amount in cents
            'BR54999999999', // Customer CPF
            'https://yourdomain.com/payment/success', // Success URL
            'https://yourdomain.com/payment/failure'  // Failure URL
        );
    
        return $this->render('payment/form.html.twig', [
            'payment' => $payment,
        ]);
    }
    
  4. Frontend Setup Include jQuery and RequireJS in your base template (as per requirements). Use the generated form in your Twig template:

    {{ form_start(payment.form) }}
        {{ form_widget(payment.form) }}
        <button type="submit">Pagar</button>
    {{ form_end(payment.form) }}
    

Implementation Patterns

Workflow: Handling Payments

  1. Initiate Payment Use LocawebGateway::createPayment() to generate a payment form. Pass:

    • Amount (in cents).
    • Customer CPF (as a string, e.g., 'BR54999999999').
    • Success/failure URLs (optional, defaults to config).
  2. Process Return/Notification Handle return URLs in your controller:

    public function handleReturn(Request $request, LocawebGateway $gateway)
    {
        $response = $gateway->processReturn($request);
        if ($response->isSuccessful()) {
            // Payment successful
        } else {
            // Payment failed
        }
    }
    

    Handle notifications via a webhook endpoint:

    public function handleNotification(Request $request, LocawebGateway $gateway)
    {
        $response = $gateway->processNotification($request);
        // Validate and log the transaction
    }
    
  3. Query Transactions Fetch transaction details:

    $transaction = $gateway->getTransaction('TRANSACTION_ID');
    

Integration Tips

  • Validation: Always validate processReturn() and processNotification() responses using isValid() and isSuccessful().
  • Logging: Log transaction IDs and responses for debugging:
    $this->logger->info('Locaweb Transaction', [
        'transaction_id' => $response->getTransactionId(),
        'status' => $response->getStatus(),
    ]);
    
  • Sandbox Testing: Use the sandbox config to test payments without real charges. Test with Locaweb’s sandbox cards (e.g., 4111111111111111).
  • Twig Integration: Extend the bundle’s Twig functions by creating a custom Twig extension:
    // src/Twig/LocawebExtension.php
    class LocawebExtension extends \Twig\Extension\AbstractExtension
    {
        public function getFunctions()
        {
            return [
                new \Twig\TwigFunction('locaweb_payment_form', [$this, 'renderPaymentForm']),
            ];
        }
    
        public function renderPaymentForm(LocawebGateway $gateway, int $amount, string $cpf)
        {
            $payment = $gateway->createPayment($amount, $cpf);
            return $this->renderView('payment/_form.html.twig', ['payment' => $payment]);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Missing Dependencies

    • The bundle requires jQuery and RequireJS for the frontend form to work. Forgetting to include them will break the payment form.
    • Fix: Add these to your base layout:
      <!-- Include in your base.html.twig -->
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
      <script data-main="path/to/requirejs-config.js" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
      
  2. Sandbox vs. Production

    • The sandbox config must match your testing environment. Using sandbox: true in production will fail payments.
    • Fix: Use environment variables or separate configs for dev/prod:
      # config/packages/dev/bfos_gateway_locaweb.yaml
      sandbox: true
      # config/packages/prod/bfos_gateway_locaweb.yaml
      sandbox: false
      
  3. Notification URL Validation

    • Locaweb’s webhook will send a notification parameter to your notification_url. Always validate this parameter to prevent CSRF attacks:
      public function handleNotification(Request $request)
      {
          if (!$request->query->has('notification') || $request->query->get('notification') !== 'YOUR_SECRET_KEY') {
              throw $this->createAccessDeniedException('Invalid notification');
          }
      }
      
  4. Amount Precision

    • Amounts are expected in cents (e.g., 1000 for R$10.00). Passing floats or incorrect values will cause failures.
    • Fix: Use integers and validate input:
      $amount = (int) round($request->request->get('amount') * 100);
      
  5. Transaction ID Collisions

    • Locaweb’s processReturn() and processNotification() may return duplicate transaction IDs. Always deduplicate in your database:
      $transaction = $gateway->getTransaction($transactionId);
      if (!$this->transactionRepository->exists($transactionId)) {
          $this->transactionRepository->save($transaction);
      }
      

Debugging Tips

  1. Enable Verbose Logging Configure Monolog to log Locaweb requests/responses:

    # config/packages/monolog.yaml
    handlers:
        main:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.log"
            level: debug
            channels: ["!event"]
    

    Then log responses in your controller:

    $this->logger->debug('Locaweb Response', [
        'raw_data' => $response->getRawData(),
    ]);
    
  2. Inspect Raw Responses The LocawebResponse object provides raw data via getRawData(). Use this to debug unexpected responses:

    $raw = $gateway->processReturn($request)->getRawData();
    $this->logger->error('Raw Response: ' . print_r($raw, true));
    
  3. Common Error Codes

    • 00: Success.
    • 01: Invalid merchant or key.
    • 02: Invalid amount or currency.
    • 03: Transaction not found.
    • Fix: Map these to user-friendly messages in your Twig templates:
      {% if payment.error %}
          {% set errorMessage = {
              '01': 'Credenciais inválidas',
              '02': 'Valor ou moeda inválidos',
              '03': 'Transação não encontrada',
          }[payment.error] %}
          {{ errorMessage|default('Erro desconhecido') }}
      {% endif %}
      

Extension Points

  1. Custom Response Handling Extend the LocawebResponse class to add custom logic:
    // src/Service/CustomLocawebResponse.php
    class CustomLocawebResponse extends \BrazilianFriendsOfSymfony\GatewayLocawebBundle\Service\LocawebResponse
    {
        public function isFraudulent()
        {
            return $this->getStatus() === 'FRAUD';
        }
    }
    
    Override the service in config/services.yaml:
    services:
        BrazilianFriendsOfSymfony\GatewayLocawebBundle\Service\LocawebGateway:
            arguments:
                $responseClass: App\Service\CustomLocaweb
    
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
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