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

Darvin Payment Bundle Laravel Package

darvinstudio/darvin-payment-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require darvinstudio/darvin-payment-bundle
    php bin/console darvin:payment:install
    
    • Verify Darvin\PaymentBundle\DarvinPaymentBundle is enabled in config/bundles.php.
  2. Configure Gateway Edit config/packages/darvin_payment.yaml to define your Omnipay gateway (e.g., Stripe, PayPal):

    darvin_payment:
        gateway: stripe
        stripe:
            secret: '%env(STRIPE_SECRET_KEY)%'
            publishable: '%env(STRIPE_PUBLISHABLE_KEY)%'
    
  3. First Use Case: Create a Payment Inject PaymentFactoryInterface and create a payment for an order:

    use Darvin\PaymentBundle\Payment\Factory\PaymentFactoryInterface;
    use Darvin\PaymentBundle\Payment\PaidOrder;
    use Darvin\PaymentBundle\Payment\Client;
    
    $payment = $paymentFactory->createPayment(
        new PaidOrder($orderId, Order::class, $orderNumber),
        $order->getTotal(),
        new Client($userId, User::class, $user->getEmail()),
        'USD'
    );
    
  4. Trigger Purchase Use the Twig helper to generate a purchase link:

    <a href="{{ payment_purchase_urls(payment)['stripe'] }}">Pay with Stripe</a>
    

Implementation Patterns

Core Workflows

  1. Payment Creation & State Management

    • Use PaymentFactoryInterface to create payments tied to orders/users.
    • Leverage Symfony’s Workflow Component for state transitions (e.g., createdapprovedpaid).
    • Example workflow:
      $payment->approve(); // Transitions state via workflow
      $payment->purchase(); // Executes Omnipay purchase
      
  2. Webhooks & Notifications

    • Configure darvin_payment.yaml to enable email notifications:
      darvin_payment:
          notifications:
              enabled: true
              from_email: 'payments@example.com'
      
    • Extend PaymentEventListener to customize email templates or logic.
  3. Multi-Gateway Support

    • Define multiple gateways in config:
      darvin_payment:
          gateways:
              stripe: ~
              paypal:
                  username: '%env(PAYPAL_USERNAME)%'
                  password: '%env(PAYPAL_PASSWORD)%'
      
    • Generate links for all gateways:
      {{ payment_purchase_widget(order) }} {# Renders buttons for all configured gateways #}
      
  4. Refunds/Cancellations

    • Use the PaymentInterface methods:
      $payment->refund($amount); // Partial/refund-all
      $payment->cancel(); // Void the payment
      

Integration Tips

  • Order Synchronization: Listen to PaymentEvent (e.g., payment.paid) to update order status:
    use Darvin\PaymentBundle\Event\PaymentEvent;
    
    $eventDispatcher->addListener(PaymentEvent::PAID, function (PaymentEvent $event) {
        $order = $event->getPayment()->getPaidOrder();
        $order->markAsPaid();
    });
    
  • Receipts: Implement ReceiptInterface to attach receipts to payments:
    $payment->addReceipt(new FileReceipt('/path/to/receipt.pdf'));
    
  • Testing: Use the PaymentFactory with mock gateways (e.g., Omnipay’s MockGateway) in PHPUnit.

Gotchas and Tips

Pitfalls

  1. Workflow Misconfigurations

    • Ensure config/packages/workflow.yaml includes the payment workflow:
      payment_workflow:
          type: 'state_machine'
          supports:
              - Darvin\PaymentBundle\Entity\Payment
          initial_marking: created
          transitions:
              approve: { from: created, to: approved }
              purchase: { from: approved, to: paid }
      
    • Debug Tip: Run php bin/console debug:workflow payment_workflow to inspect states.
  2. Gateway-Specific Quirks

    • Stripe: Ensure publishable_key is set for frontend integration.
    • PayPal: Use sandbox mode in development:
      paypal:
          environment: sandbox
      
    • Error Handling: Wrap Omnipay calls in try-catch:
      try {
          $payment->purchase();
      } catch (\Omnipay\Common\Exception\InvalidRequestException $e) {
          // Log and retry or notify user
      }
      
  3. Event Dispatching

    • Events like payment.created are dispatched after the payment entity is persisted. Avoid relying on event data for immediate DB operations.
  4. Currency/Amount Precision

    • Omnipay uses integers for cents. Convert floats to cents manually:
      $amountInCents = (int)round($order->getTotal() * 100);
      

Debugging Tips

  • Log Payments: Enable logging in config/packages/monolog.yaml:
    handlers:
        payment:
            type: stream
            path: var/log/payment.log
            level: debug
    
  • Workflow Debugging: Use the Symfony Workflow component’s debug command:
    php bin/console debug:workflow payment_workflow
    
  • Omnipay Debugging: Enable Omnipay’s logger:
    \Omnipay\Common\CreditCard::setValidationMode(\Omnipay\Common\CreditCard::VALIDATE_MODE_NONE);
    

Extension Points

  1. Custom States/Transitions

    • Extend the workflow by adding new states/transitions in config/packages/workflow.yaml:
      transitions:
          authorize: { from: approved, to: authorized }
      
    • Create a custom PaymentStateMachine service to override logic.
  2. Custom Receipts

    • Implement ReceiptInterface for PDF/email receipts:
      class EmailReceipt implements ReceiptInterface {
          public function generate(PaymentInterface $payment): string {
              return $this->twig->render('payment/receipt_email.html.twig', [...]);
          }
      }
      
  3. Gateway-Specific Logic

    • Override the default PaymentGatewayFactory to inject custom gateways:
      services:
          Darvin\PaymentBundle\Payment\Gateway\PaymentGatewayFactory:
              arguments:
                  $gateways: ['@custom_stripe_gateway']
      
  4. Testing

    • Mock the PaymentFactory and PaymentGateway in tests:
      $paymentFactory = $this->createMock(PaymentFactoryInterface::class);
      $paymentFactory->method('createPayment')->willReturn($mockPayment);
      
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
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