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.
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],
];
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'
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,
]);
}
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) }}
Initiate Payment
Use LocawebGateway::createPayment() to generate a payment form. Pass:
'BR54999999999').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
}
Query Transactions Fetch transaction details:
$transaction = $gateway->getTransaction('TRANSACTION_ID');
processReturn() and processNotification() responses using isValid() and isSuccessful().$this->logger->info('Locaweb Transaction', [
'transaction_id' => $response->getTransactionId(),
'status' => $response->getStatus(),
]);
sandbox config to test payments without real charges. Test with Locaweb’s sandbox cards (e.g., 4111111111111111).// 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]);
}
}
Missing Dependencies
<!-- 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>
Sandbox vs. Production
sandbox config must match your testing environment. Using sandbox: true in production will fail payments.# config/packages/dev/bfos_gateway_locaweb.yaml
sandbox: true
# config/packages/prod/bfos_gateway_locaweb.yaml
sandbox: false
Notification URL Validation
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');
}
}
Amount Precision
1000 for R$10.00). Passing floats or incorrect values will cause failures.$amount = (int) round($request->request->get('amount') * 100);
Transaction ID Collisions
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);
}
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(),
]);
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));
Common Error Codes
00: Success.01: Invalid merchant or key.02: Invalid amount or currency.03: Transaction not found.{% 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 %}
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
How can I help you explore Laravel packages today?