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

Przelewy24 Bundle Laravel Package

allset/przelewy24-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require allset/przelewy24-bundle
    

    Register the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3):

    Allset\Przelewy24Bundle\AllsetPrzelewy24Bundle::class => ['all' => true],
    
  2. Routing: Add to config/routes.yaml:

    allset_przelewy24:
        resource: "@AllsetPrzelewy24Bundle/Resources/config/routing.xml"
    
  3. Configuration: Add to config/packages/allset_przelewy24.yaml:

    allset_przelewy24:
        sandbox: true  # Use true for testing
        merchant_id: "YOUR_MERCHANT_ID"
        crc_key: "YOUR_CRC_KEY"
    
  4. First Use Case: Redirect a user to Przelewy24 payment form:

    use Allset\Przelewy24Bundle\Factory\ProcessFactory;
    use Allset\Przelewy24Bundle\Model\Payment;
    
    public function initiatePayment(ProcessFactory $processFactory)
    {
        $payment = (new Payment())
            ->setCurrency('PLN')
            ->setSessionId('unique_order_token')
            ->setAmount(100.00)
            ->setDescription('Product purchase')
            ->setEmail('user@example.com')
            ->setReturnUrl($this->generateUrl('payment_return', [], UrlGeneratorInterface::ABSOLUTE_URL));
    
        $processFactory->setPayment($payment);
        return $this->redirect($processFactory->createAndGetUrl());
    }
    

Implementation Patterns

Core Workflow

  1. Payment Initiation:

    • Use ProcessFactory to create a payment object and generate a redirect URL.
    • Store the sessionId (e.g., order token) in your database for later reference.
  2. Event-Driven Success Handling:

    • Listen to przelewy24.event.payment_success to process successful payments.
    • Example listener:
      use Allset\Przelewy24Bundle\Event\PaymentEventInterface;
      
      public function onPaymentSuccess(PaymentEventInterface $event)
      {
          $sessionId = $event->getPayment()->getSessionId();
          $this->orderRepository->markAsPaid($sessionId);
      }
      
    • Register the listener in config/services.yaml:
      App\EventListener\Przelewy24Listener:
          tags:
              - { name: kernel.event_listener, event: przelewy24.event.payment_success, method: onPaymentSuccess }
      
  3. Return URL Handling:

    • Configure a route (e.g., payment_return) to handle Przelewy24’s callback.
    • Validate the payment using PaymentValidator:
      use Allset\Przelewy24Bundle\Validator\PaymentValidator;
      
      public function returnAction(PaymentValidator $validator, Request $request)
      {
          $payment = $validator->validate($request->query->all());
          if ($payment->isValid()) {
              // Process successful payment
          }
          return $this->render('payment/return.html.twig');
      }
      

Integration Tips

  • Database Sync: Use the sessionId to link Przelewy24 payments to your orders.
  • Logging: Log payment events for debugging:
    $this->logger->info('Payment success', ['sessionId' => $sessionId, 'amount' => $payment->getAmount()]);
    
  • Testing:
    • Use the sandbox mode (sandbox: true) for development.
    • Simulate success with /p24-fake-success/{sessionId} (dev-only route).

Gotchas and Tips

Pitfalls

  1. Session ID Uniqueness:

    • The sessionId must be unique and stored in your database. Reusing IDs will cause conflicts.
    • Example: Use UUIDs or database auto-increment IDs.
  2. Return URL Validation:

    • Przelewy24 expects an absolute URL for the returnUrl. Use UrlGeneratorInterface::ABSOLUTE_URL:
      $this->generateUrl('route_name', [], UrlGeneratorInterface::ABSOLUTE_URL)
      
  3. Sandbox vs. Production:

    • Forgetting to switch sandbox: false in production will cause payments to fail silently.
    • Test thoroughly in sandbox before deploying.
  4. Event Listener Scope:

    • Ensure your event listener is a service (autowired) to avoid NullReferenceException:
      services:
          App\EventListener\Przelewy24Listener:
              arguments:
                  $orderRepository: '@App\Repository\OrderRepository'
      
  5. CRC Key Sensitivity:

    • The crc_key is case-sensitive. Double-check your configuration.

Debugging Tips

  1. Test Tools:

    • Use /p24-test to verify API connectivity in development.
    • Simulate success with /p24-fake-success/{sessionId} to test event listeners.
  2. Logging:

    • Enable debug mode to log Przelewy24 API responses:
      monolog:
          handlers:
              main:
                  level: debug
      
  3. Common Errors:

    • 403 Forbidden: Invalid merchant_id or crc_key.
    • 500 Server Error: Missing required fields (e.g., sessionId, amount).
    • Redirect Loop: Ensure returnUrl is correct and accessible.

Extension Points

  1. Custom Payment Fields:

    • Extend the Payment model to add custom fields:
      class CustomPayment extends Payment
      {
          private $customField;
      
          public function setCustomField($value): self
          {
              $this->customField = $value;
              return $this;
          }
      }
      
    • Override the ProcessFactory to support custom fields.
  2. Webhook Handling:

    • Przelewy24 supports webhooks for async notifications. Extend the bundle by:
      public function webhookAction(Request $request)
      {
          $validator = new PaymentValidator();
          $payment = $validator->validate($request->request->all());
          if ($payment->isValid()) {
              // Handle webhook (e.g., update order status)
          }
      }
      
  3. Multi-Currency Support:

    • Validate currency codes against Przelewy24’s supported list (e.g., PLN, EUR):
      if (!in_array($payment->getCurrency(), ['PLN', 'EUR'])) {
          throw new \InvalidArgumentException('Unsupported currency');
      }
      
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.
althinect/enum-permission
andydefer/laravel-actions
aimeos/prisma
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
spatie/mailcoach-vapor