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

Netopia Mobilpay Bundle Laravel Package

birkof/netopia-mobilpay-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require birkof/netopia-mobilpay-bundle
    

    For Laravel, manually create a service wrapper (since the bundle is Symfony-specific).

  2. Configuration: Add to .env:

    NETOPIA_MOBILPAY_PAYMENT_URL=https://api.mobilpay.ro
    NETOPIA_MOBILPAY_PUBLIC_CERT=file://path/to/cert.pem
    NETOPIA_MOBILPAY_PRIVATE_KEY=file://path/to/key.pem
    NETOPIA_MOBILPAY_SIGNATURE=your_signature_key
    
  3. First Use Case: Create a Laravel service to wrap the bundle’s core logic (e.g., app/Services/MobilPayService.php):

    use birkof\NetopiaMobilPay\Client;
    use birkof\NetopiaMobilPay\Config;
    
    class MobilPayService {
        protected $client;
    
        public function __construct() {
            $config = new Config([
                'payment_url' => env('NETOPIA_MOBILPAY_PAYMENT_URL'),
                'public_cert' => env('NETOPIA_MOBILPAY_PUBLIC_CERT'),
                'private_key' => env('NETOPIA_MOBILPAY_PRIVATE_KEY'),
                'signature' => env('NETOPIA_MOBILPAY_SIGNATURE'),
            ]);
            $this->client = new Client($config);
        }
    
        public function createPayment(array $data) {
            return $this->client->createPayment($data);
        }
    }
    
  4. Register the Service: Bind the service in AppServiceProvider:

    public function register() {
        $this->app->singleton(MobilPayService::class, function ($app) {
            return new MobilPayService();
        });
    }
    
  5. Usage in Controller:

    use App\Services\MobilPayService;
    
    public function checkout(MobilPayService $mobilPay) {
        $payment = $mobilPay->createPayment([
            'amount' => 100,
            'currency' => 'RON',
            'description' => 'Order #123',
        ]);
        return redirect($payment['redirect_url']);
    }
    

Implementation Patterns

Workflows

  1. Synchronous Payments:

    • Use the service to initiate payments and redirect users to MobilPay’s payment page.
    • Example flow:
      // 1. Create payment
      $payment = $mobilPay->createPayment($data);
      
      // 2. Redirect to MobilPay
      return redirect($payment['redirect_url']);
      
      // 3. Handle callback (after payment)
      public function callback(MobilPayService $mobilPay) {
          $response = $mobilPay->verifyPayment($_POST);
          if ($response['status'] === 'success') {
              // Update order status
          }
      }
      
  2. Webhook Handling:

    • MobilPay sends asynchronous notifications (e.g., payment confirmations) to a webhook endpoint.
    • Validate signatures and process updates:
      public function webhook(MobilPayService $mobilPay) {
          $isValid = $mobilPay->verifySignature($_POST);
          if ($isValid) {
              // Process payment update
          }
      }
      
  3. Recurring Payments:

    • If MobilPay supports subscriptions, use the service to create recurring profiles:
      $profile = $mobilPay->createRecurringProfile([
          'amount' => 50,
          'currency' => 'RON',
          'start_date' => now()->addDay(),
      ]);
      

Integration Tips

  1. Configuration:

    • Store certificates/keys securely using Laravel’s Vault or encrypted .env.
    • Example for file-based certs:
      $config = new Config([
          'public_cert' => storage_path('certs/mobilpay_cert.pem'),
          'private_key' => storage_path('certs/mobilpay_key.pem'),
      ]);
      
  2. Error Handling:

    • Wrap MobilPay calls in try-catch blocks to handle API errors gracefully:
      try {
          $payment = $mobilPay->createPayment($data);
      } catch (\Exception $e) {
          Log::error("MobilPay error: " . $e->getMessage());
          return back()->with('error', 'Payment failed');
      }
      
  3. Testing:

    • Use Laravel’s Http facade to mock MobilPay API responses in tests:
      $response = Http::fake([
          'api.mobilpay.ro' => Http::response(['status' => 'success'], 200),
      ]);
      
  4. Logging:

    • Log payment requests/responses for auditing:
      Log::info('MobilPay payment request', ['data' => $data]);
      Log::info('MobilPay payment response', ['response' => $payment]);
      
  5. Middleware for Webhooks:

    • Protect webhook endpoints with middleware to validate signatures:
      public function handleWebhook(Request $request, MobilPayService $mobilPay) {
          if (!$mobilPay->verifySignature($request->all())) {
              abort(403, 'Invalid signature');
          }
          // Process webhook
      }
      

Gotchas and Tips

Pitfalls

  1. Symfony Dependencies:

    • The bundle uses Symfony’s HttpFoundation and DependencyInjection. Replace these with Laravel equivalents:
      • Symfony\Component\HttpFoundation\RequestIlluminate\Http\Request.
      • Symfony\Component\DependencyInjection → Laravel’s bind() or AppServiceProvider.
  2. Certificate Paths:

    • If using file paths for certificates/keys, ensure Laravel can access them (e.g., store in storage/app/certs/ and set proper permissions).
  3. Signature Validation:

    • MobilPay’s signature validation is strict. Ensure you’re passing the exact data format expected (e.g., sorted query parameters).
    • Example of incorrect validation:
      // Wrong: Missing sorting or incorrect data
      $mobilPay->verifySignature($_POST);
      
      Fix: Sort and stringify data as per MobilPay’s docs.
  4. Webhook Retries:

    • MobilPay may retry failed webhook deliveries. Implement idempotency in your handler to avoid duplicate processing.
  5. PHP Version:

    • The bundle requires PHP 8+. Ensure your Laravel project uses PHP 8+ to avoid compatibility issues.

Debugging

  1. API Errors:

    • Enable Guzzle logging to debug API calls:
      $client = new Client($config, [
          'http_client' => Http::withOptions(['debug' => true]),
      ]);
      
    • Check Laravel logs for MobilPay-specific errors.
  2. Signature Mismatches:

    • If signatures fail, verify:
      • The exact data being signed (order of fields, encoding).
      • The private key and signature key are correct.
      • No extra whitespace or hidden characters in the data.
  3. Webhook Failures:

    • Ensure your webhook endpoint:
      • Returns a 200 OK status.
      • Has a valid SSL certificate (MobilPay may reject non-HTTPS endpoints).
      • Processes requests quickly (timeout after ~30 seconds).

Tips

  1. Use Facades:

    • Create a facade for cleaner usage:
      // app/Facades/MobilPay.php
      public static function createPayment(array $data) {
          return app(MobilPayService::class)->createPayment($data);
      }
      
    • Now use it anywhere:
      $payment = MobilPay::createPayment($data);
      
  2. Environment-Specific Config:

    • Use Laravel’s config() helper to manage different environments (e.g., sandbox vs. live):
      $config = new Config([
          'payment_url' => config('services.mobilpay.payment_url'),
      ]);
      
  3. Queue Webhook Processing:

    • Offload webhook processing to a queue to handle spikes:
      public function webhook(Request $request) {
          ProcessWebhook::dispatch($request->all());
      }
      
  4. Sandbox Testing:

    • Use MobilPay’s sandbox environment for testing:
      NETOPIA_MOBILPAY_PAYMENT_URL=https://sandbox.mobilpay.ro
      
    • Test with sandbox credentials before going live.
  5. PCI Compliance:

    • Ensure private keys are stored securely (e.g., Laravel Vault or encrypted storage).
    • Never log or expose sensitive data like signatures or keys.
  6. Custom Exceptions:

    • Extend the bundle’s exceptions for Laravel-specific handling:
      class MobilPayException extends \Exception {}
      
    • Throw custom exceptions in your service wrapper for consistent error handling.
  7. Documentation:

    • Since the bundle’s docs are Symfony-focused, create a README.md in your project for Laravel-specific usage (e.g., service setup, webhook
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