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

Common Laravel Package

omnipay/common

Framework-agnostic core for Omnipay payment gateways. Provides shared interfaces, request/response handling, HTTP client integration, and common utilities used by gateway drivers so apps can add and swap payment providers with a consistent API.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup in Laravel
1. **Installation**
   ```bash
   composer require omnipay/common

No additional Laravel-specific configuration is needed—Omnipay is framework-agnostic.

  1. First Use Case: Basic Purchase Flow

    use Omnipay\Omnipay;
    
    // Initialize a gateway (e.g., Stripe, PayPal) using its Omnipay driver
    $gateway = Omnipay::create('Stripe'); // Replace with your provider
    $gateway->setApiKey(config('services.stripe.key')); // Inject config
    
    // Create a purchase request
    $request = $gateway->purchase([
        'amount' => '10.00',
        'currency' => 'USD',
        'description' => 'Laravel Product',
    ]);
    
    // Send the request and handle the response
    try {
        $response = $request->send();
        if ($response->isSuccessful()) {
            // Success: Log transaction, redirect user, etc.
            return redirect()->route('checkout.success');
        }
        // Handle failure (e.g., redirect to error page)
        return back()->withErrors(['payment' => $response->getMessage()]);
    } catch (\Exception $e) {
        // Log and handle exceptions (e.g., network issues)
        Log::error('Payment failed: ' . $e->getMessage());
    }
    
  2. Key Entry Points

    • Gateways: Explore vendor/omnipay/common/src/Omnipay/GatewayInterface for contracts.
    • Requests: Use Omnipay\Common\Message\RequestInterface for standardized flows (e.g., purchase(), authorize()).
    • Responses: Check Omnipay\Common\Message\ResponseInterface for response handling (e.g., isSuccessful(), getTransactionReference()).

Implementation Patterns

1. Gateway Abstraction

  • Pattern: Use a gateway factory to switch providers dynamically (e.g., for testing or multi-provider support).
    // services.php
    'gateways' => [
        'stripe' => \Omnipay\Stripe\Gateway::class,
        'paypal' => \Omnipay\PayPal\Gateway::class,
    ],
    
    // In a service class
    $gateway = app(config('services.gateways.' . $provider));
    $gateway->setApiKey(config("services.{$provider}.key"));
    
  • Laravel Tip: Bind gateways in AppServiceProvider for dependency injection:
    $this->app->bind(\Omnipay\Stripe\Gateway::class, function ($app) {
        $gateway = \Omnipay::create('Stripe');
        $gateway->setApiKey(config('services.stripe.key'));
        return $gateway;
    });
    

2. Request-Response Workflow

  • Pattern: Chain requests for multi-step flows (e.g., authorize() + capture()).
    // Authorize first
    $authorizeRequest = $gateway->authorize(['amount' => '10.00', 'currency' => 'USD']);
    $authorizeResponse = $authorizeRequest->send();
    
    if ($authorizeResponse->isSuccessful()) {
        // Capture later (e.g., after inventory check)
        $captureRequest = $gateway->capture([
            'amount' => '10.00',
            'currency' => 'USD',
            'transactionId' => $authorizeResponse->getTransactionId(),
        ]);
        $captureResponse = $captureRequest->send();
    }
    
  • Laravel Tip: Use queued jobs for async processing (e.g., delayed captures):
    CapturePaymentJob::dispatch($gateway, $transactionId, $amount);
    

3. HTTP Client Integration

  • Pattern: Customize the HTTP client for retries, logging, or middleware.
    $gateway->setHttpClient(new \GuzzleHttp\Client([
        'timeout' => 30,
        'headers' => ['User-Agent' => 'Laravel/' . app()->version()],
    ]));
    
  • Laravel Tip: Wrap Guzzle with Laravel’s HTTP client for middleware (e.g., logging):
    $gateway->setHttpClient(app(\Illuminate\Http\Client\PendingRequest::class)
        ->withOptions(['timeout' => 30])
        ->tap(function ($request) {
            $request->withHeaders(['X-Custom-Header' => 'value']);
        }));
    

4. Parameter Management

  • Pattern: Use getParameters() and validate() for dynamic input handling.
    $request = $gateway->purchase($parameters);
    if (!$request->validate()) {
        throw new \InvalidArgumentException($request->getMessage());
    }
    
  • Laravel Tip: Validate request data before passing to Omnipay:
    $validated = request()->validate([
        'amount' => 'required|numeric',
        'currency' => 'required|string|size:3',
    ]);
    

5. Webhook Handling

  • Pattern: Parse Omnipay responses in Laravel routes/controllers.
    Route::post('/webhook/stripe', function (Request $request) {
        $gateway = app(\Omnipay\Stripe\Gateway::class);
        $response = $gateway->completePurchase()->send();
    
        // Handle webhook-specific logic
        if ($response->isSuccessful()) {
            event(new PaymentSucceeded($response->getTransactionReference()));
        }
    });
    

Gotchas and Tips

1. Common Pitfalls

  • Gateway Initialization:

    • Gotcha: Forgetting to set API credentials (e.g., setApiKey()). Fix: Use Laravel config (config('services.stripe.key')) and validate in AppServiceProvider boot.
    • Gotcha: Using the wrong gateway class (e.g., Omnipay\Stripe\Gateway vs. Omnipay\PayPal\Gateway). Fix: Autoload via Omnipay::create('Stripe') to avoid typos.
  • Request Validation:

    • Gotcha: Omnipay’s validate() may not catch all Laravel validation rules (e.g., required fields). Fix: Validate with Laravel’s validator first, then pass to Omnipay.
  • Response Handling:

    • Gotcha: Assuming isSuccessful() means the payment was captured (it may just be authorized). Fix: Check getTransactionReference() and implement idempotency keys.
    • Gotcha: Ignoring getMessage() for failed responses. Fix: Log errors and redirect users with user-friendly messages:
      return back()->withErrors(['payment' => $response->getMessage() ?? 'Payment failed.']);
      

2. Debugging Tips

  • Enable Logging: Configure the HTTP client to log requests/responses:
    $gateway->setHttpClient(new \GuzzleHttp\Client([
        'debug' => true,
        'handler' => \GuzzleHttp\HandlerStack::create(new \GuzzleHttp\Middleware::tap(
            function ($request, $options) {
                Log::debug('Omnipay Request:', [
                    'url' => (string) $request->getUri(),
                    'method' => $request->getMethod(),
                    'body' => $request->getBody() ? $request->getBody()->getContents() : null,
                ]);
            }
        )),
    ]));
    
  • Test with Sandbox: Use Omnipay’s sandbox modes (e.g., Stripe test cards: 4242 4242 4242 4242).
    $gateway->setTestMode(true);
    

3. Configuration Quirks

  • API Versioning: Some gateways require explicit API version setting (e.g., PayPal):
    $gateway->setApiVersion('2018-11-29');
    
  • Idempotency Keys: For critical transactions, use idempotency keys to avoid duplicate charges:
    $request->setIdempotencyKey(str()->uuid());
    

4. Extension Points

  • Custom Requests: Extend Omnipay\Common\Message\AbstractRequest for provider-specific flows:
    class CustomRequest extends \Omnipay\Common\Message\AbstractRequest {
        public function getData() {
            return [
                'custom_field' => $this->getCustomField(),
            ] + parent::getData();
        }
    }
    
  • Response Decorators: Wrap responses to add Laravel-specific logic:
    $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