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

Payment Laravel Package

sylius/payment

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require sylius/payment
    

    Add to config/app.php under providers:

    Sylius\Component\Payment\PaymentComponent::class,
    
  2. First Use Case: Basic Payment Flow

    • Define a PaymentMethod (e.g., credit card, PayPal):
      $paymentMethod = new PaymentMethod('credit_card', 'Credit Card');
      
    • Create a Payment entity for an order:
      $payment = new Payment();
      $payment->setAmount(1000); // 1000 cents = $10.00
      $payment->setCurrencyCode('USD');
      $payment->setMethod($paymentMethod);
      
    • Transition to New state (default):
      $payment->complete(); // Transitions to 'completed' state
      
  3. Where to Look First

    • Component Documentation
    • src/Resources/config/payment.yaml (default state machine config)
    • src/PaymentMethodInterface.php and src/PaymentInterface.php (core interfaces)

Implementation Patterns

Core Workflows

  1. Payment State Management Use the state machine to handle transitions (e.g., newcompletedcancelled):

    $payment->complete(); // Validates amount, currency, and method
    $payment->cancel();  // Reverts to 'cancelled' state
    
    • Custom Transitions: Extend PaymentStates or override the state machine in config.
  2. Payment Methods

    • Register dynamically:
      $paymentMethodRepository->add(new PaymentMethod('paypal', 'PayPal'));
      
    • Fetch by code:
      $paypalMethod = $paymentMethodRepository->findOneBy(['code' => 'paypal']);
      
  3. Integration with Gateways (e.g., Payum)

    • Use PaymentGatewayInterface to abstract gateway logic:
      $gateway = new PayumGateway(); // Example (not part of Sylius/Payment)
      $payment->setGateway($gateway);
      $payment->execute(); // Delegates to gateway
      
  4. Events for Extensibility Listen to payment state changes:

    $dispatcher->addListener(
        PaymentEvents::PAYMENT_COMPLETED,
        function (PaymentCompletedEvent $event) {
            // Send confirmation email, update inventory, etc.
        }
    );
    

Common Patterns

  • Validation: Use PaymentValidator to check amounts/currencies before transitions.
  • Retry Logic: Implement PaymentRetryStrategy for failed payments.
  • Logging: Log transitions via PaymentEvents (e.g., PAYMENT_FAILED).

Gotchas and Tips

Pitfalls

  1. State Machine Quirks

    • Transitions may fail silently if pre-conditions (e.g., amount validation) aren’t met. Always check $payment->getState() after transitions.
    • Fix: Override PaymentStates to add custom validation:
      # config/payment.yaml
      sylius_payment:
          states:
              completed:
                  transitions:
                      cancel:
                          to: cancelled
                          guard: 'paymentGuard' # Custom guard method
      
  2. Currency/Amount Handling

    • Amounts are stored in cents (e.g., $10.00 = 1000). Use Money class for conversions:
      $money = new Money(1000, 'USD');
      $payment->setAmount($money->getAmount());
      
    • Gotcha: Floating-point precision errors. Use bcmath or gmp for calculations.
  3. Gateway Integration

    • Sylius/Payment does not include gateways. You must integrate with Payum or another library.
    • Tip: Use PaymentGatewayInterface to decouple logic:
      interface PaymentGatewayInterface {
          public function execute(Payment $payment): void;
      }
      
  4. Thread Safety

    • The state machine is not thread-safe. Avoid concurrent transitions on the same Payment instance.

Debugging Tips

  • State Transitions: Enable debug mode to log transitions:
    $payment->setDebug(true); // Logs transitions to Symfony's logger
    
  • Validation Errors: Check PaymentValidationContext for errors:
    $validator = new PaymentValidator();
    $errors = $validator->validate($payment);
    
  • Event Debugging: Use PaymentEvents to trace flow:
    $dispatcher->addListener(PaymentEvents::PAYMENT_CREATED, function ($event) {
        \Log::debug('Payment created:', [$event->getPayment()->getId()]);
    });
    

Extension Points

  1. Custom States/Transitions Extend the state machine in config:

    sylius_payment:
        states:
            pending_review:
                type: workflow
                transitions:
                    approve:
                        to: completed
    
  2. Payment Methods Create dynamic methods via PaymentMethodRegistry:

    $registry->add('stripe', function () {
        return new StripePaymentMethod();
    });
    
  3. Validation Add custom rules to PaymentValidationContext:

    $context->addConstraint(new CustomPaymentConstraint());
    
  4. Gateways Implement PaymentGatewayInterface for custom providers:

    class CustomGateway implements PaymentGatewayInterface {
        public function execute(Payment $payment) {
            // Custom logic (e.g., API calls)
        }
    }
    
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