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

Omnipay Bundle Laravel Package

andchir/omnipay-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require andchir/omnipay-bundle
    
  2. Configure (config/packages/omnipay.yaml):
    omnipay:
        success_url: '/success'
        fail_url: '/fail'
        return_url: '/return'
        notify_url: '/notify'
        cancel_url: '/cancel'
        gateways:
            PayPal_Express:
                parameters:
                    username: '%env(PAYPAL_USERNAME)%'
                    password: '%env(PAYPAL_PASSWORD)%'
                    signature: '%env(PAYPAL_SIGNATURE)%'
    
  3. First Use Case:
    • Create a Payment entity (e.g., via Doctrine) with required fields (userId, email, orderId, amount, currency).
    • Initialize the service and send a purchase:
      $omnipayService = $this->get('omnipay');
      $payment = (new Payment())->setAmount(100)->setCurrency('USD')->setEmail('user@example.com');
      $omnipayService->initialize($payment);
      $response = $omnipayService->sendPurchase($payment);
      

Key Files to Review

  • config/packages/omnipay.yaml: Central configuration for gateways and URLs.
  • src/Service/OmnipayService.php: Core service for payment operations.
  • src/Controller/DefaultController.php: Example controller for handling return/notify routes.

Implementation Patterns

Workflows

  1. Payment Creation:

    • Store payment details in your Payment entity (e.g., Doctrine).
    • Use OmnipayService::initialize() to map entity fields to Omnipay parameters.
    • Example:
      $payment->setOptions([
          'gatewayName' => 'YandexMoney',
          'dataKeys' => ['customerEmail' => 'customerNumber']
      ]);
      $omnipayService->initialize($payment);
      
  2. Processing Payments:

    • Purchase: Redirect user to gateway:
      $response = $omnipayService->sendPurchase($payment);
      return $response->redirect();
      
    • Complete: Handle return/notify URLs (e.g., /omnipay_return):
      public function returnAction(Request $request, OmnipayService $omnipayService) {
          $payment = $omnipayService->completePurchase($request);
          // Update payment status, log transaction, etc.
      }
      
  3. Webhook Handling:

    • Use notify_url to validate IPN/POST requests:
      public function notifyAction(Request $request, OmnipayService $omnipayService) {
          $payment = $omnipayService->handleNotify($request);
          if ($payment->isValid()) {
              // Process successful payment
          }
      }
      

Integration Tips

  • Gateway-Specific Logic:

    • Configure prefersAuthorize for gateways like Sberbank (e.g., Sberbank: prefersAuthorize: true).
    • Override default parameters per action (e.g., purchase vs. complete):
      gateways:
          RoboKassa:
              purchase:
                  testMode: true
              complete:
                  testMode: false
      
  • Data Mapping:

    • Use data_keys to map custom fields (e.g., customerEmail: ['customerNumber', 'Email']).
    • Extend OmnipayService to add custom mappers for complex logic.
  • Testing:

    • Set testMode: true in gateway configs and use sandbox environments (e.g., PayPal sandbox).

Gotchas and Tips

Pitfalls

  1. Deprecated Dependencies:

    • The bundle relies on older Omnipay packages (e.g., omnipay/sberbank@^3.2). Ensure compatibility with your Omnipay version.
    • Fix: Pin versions in composer.json or update to newer Omnipay packages manually.
  2. URL Configuration:

    • Hardcoded URLs in the bundle (e.g., /omnipay_return) may conflict with your routing.
    • Fix: Override routes in config/routes.yaml or extend the DefaultController.
  3. Sberbank Gateway:

    • The bundle previously bundled omnipay-sberbank but removed it in v1.0.18. Ensure you install it separately:
      composer require andrewnovikof/omnipay-sberbank
      
  4. Doctrine Mismatch:

    • The bundle was updated for Doctrine 2.0 (v1.0.23), but older versions may fail with Doctrine 1.x.
    • Fix: Use the latest version or downgrade Doctrine.
  5. Symfony 5+ Compatibility:

    • Some deprecated code was removed in v1.0.19, but edge cases may arise with newer Symfony versions.
    • Fix: Check for deprecation warnings and extend the bundle if needed.

Debugging Tips

  • Log Omnipay Responses:
    • Extend OmnipayService to log raw responses for debugging:
      public function sendPurchase(Payment $payment) {
          $response = parent::sendPurchase($payment);
          $this->logger->debug('Omnipay Response:', ['data' => $response->getData()]);
          return $response;
      }
      
  • Validate Gateway Configs:
    • Use OmnipayService::getGateway() to inspect configured gateways:
      $gateway = $omnipayService->getGateway('PayPal_Express');
      $this->logger->debug('Gateway Config:', ['config' => $gateway->getParameters()]);
      
  • Handle Exceptions:
    • Wrap Omnipay calls in try-catch blocks to log gateway-specific errors:
      try {
          $response = $omnipayService->sendPurchase($payment);
      } catch (\Omnipay\Common\Exception\InvalidRequestException $e) {
          $this->logger->error('Invalid Request: ' . $e->getMessage());
      }
      

Extension Points

  1. Custom Gateways:

    • Extend OmnipayService to add support for unsupported gateways:
      public function addCustomGateway(string $name, array $config) {
          $this->gateways[$name] = Omnipay::create($name, $config);
      }
      
    • Register the gateway in config/packages/omnipay.yaml:
      gateways:
          Custom_Gateway:
              parameters: { /* ... */ }
      
  2. Pre/Post-Processing:

    • Override methods like initialize() or completePurchase() to add custom logic:
      public function completePurchase(Request $request) {
          $payment = parent::completePurchase($request);
          // Add custom validation or business logic
          return $payment;
      }
      
  3. Event Listeners:

    • Dispatch events for critical steps (e.g., payment creation, completion):
      // In OmnipayService
      $eventDispatcher->dispatch(new PaymentEvent($payment, 'pre.purchase'));
      $response = $this->getGateway()->purchase($parameters);
      $eventDispatcher->dispatch(new PaymentEvent($payment, 'post.purchase'));
      
    • Listen in your app:
      $eventDispatcher->addListener('pre.purchase', function (PaymentEvent $event) {
          // Pre-purchase logic
      });
      
  4. Testing Utilities:

    • Create a test service to mock Omnipay responses:
      public function createMockResponse(array $data) {
          $response = $this->getMockBuilder('Omnipay\Common\Message\AbstractResponse')
              ->disableOriginalConstructor()
              ->getMock();
          $response->method('getData')->willReturn($data);
          return $response;
      }
      
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