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

Midtrans Php Laravel Package

midtrans/midtrans-php

Official Midtrans PHP wrapper for Core API and Snap (including Snap-bi). Composer-ready library to create transactions, get Snap tokens, handle notifications, and process payments in sandbox or production. Configure via Midtrans\Config and start integrating quickly.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Laravel Compatibility: The package is PHP-native and Composer-based, making it highly compatible with Laravel. It integrates seamlessly with Laravel’s dependency injection, service containers, and HTTP routing (e.g., for webhook handling).
  • Payment Abstraction: Midtrans provides three payment flows (Snap, Snap Redirect, Core API), allowing flexibility in UX (embedded vs. redirect-based). This aligns well with Laravel’s modularity, enabling feature flags or A/B testing for different payment methods.
  • Event-Driven Design: Midtrans’ asynchronous notifications (webhooks) fit Laravel’s event system (e.g., Illuminate\Events\Dispatcher). The package’s notification handler can trigger Laravel events (e.g., PaymentSucceeded, PaymentFailed) for downstream processing (e.g., order fulfillment, inventory updates).

Integration Feasibility

  • Low Coupling: The package is stateless (config-driven) and doesn’t enforce Laravel-specific patterns, reducing tight coupling. Configuration (e.g., serverKey, isProduction) can be injected via Laravel’s config files or environment variables.
  • HTTP Layer: Midtrans uses RESTful APIs, which Laravel’s Http facade or Guzzle (via Laravel HTTP client) can consume. Webhook handling can leverage Laravel’s route model binding or middleware (e.g., VerifyMidtransSignature).
  • Database Agnostic: The package doesn’t dictate database schema, allowing integration with Laravel’s Eloquent models (e.g., Payment, Order) for transaction tracking.

Technical Risk

  • Webhook Security: Midtrans notifications require HMAC validation (via signature_key). Laravel’s middleware can enforce this, but misconfiguration risks replay attacks. Mitigation: Use Laravel’s VerifyCsrfToken or custom middleware.
  • Idempotency: Midtrans supports idempotency keys, but Laravel must deduplicate requests (e.g., via database constraints on order_id). Risk: Duplicate charges if not handled.
  • 3DS Flow Complexity: Core API’s 3DS authentication requires frontend JavaScript (Snap.js) and backend coordination. Risk: Frontend/backend desync if not tested rigorously.
  • Deprecation Risk: Midtrans may deprecate APIs. The package’s last release (2025-03-18) suggests active maintenance, but Laravel’s long-term support (LTS) may outpace Midtrans’ roadmap. Mitigation: Monitor Midtrans’ API changelog and abstract the client behind a facade or repository pattern.

Key Questions

  1. Payment Flow Preference:
    • Should Laravel default to Snap (embedded) or Snap Redirect? Snap requires frontend JS, while Redirect is simpler but less seamless.
    • Does the team need Core API (VT-Direct) for custom UX (e.g., tokenization)?
  2. Webhook Handling:
    • How should Laravel validate Midtrans signatures? (e.g., custom middleware vs. package integration).
    • Should notifications trigger Laravel events or queued jobs (e.g., dispatch(new ProcessPayment($payload)))?
  3. Error Resilience:
    • How should Laravel handle Midtrans API rate limits or timeouts? (e.g., retries with exponential backoff).
    • Should failed transactions be requeued or logged for manual review?
  4. Testing Strategy:
    • How will Laravel test asynchronous notifications? (e.g., mocking Midtrans webhooks in PHPUnit).
    • Should sandbox mode be toggled via Laravel’s .env (e.g., MIDTRANS_SANDBOX=true)?
  5. Monitoring:
    • Should Laravel log Midtrans responses to a database table (e.g., payment_logs) for auditing?
    • How will the team monitor fraud challenges (e.g., Slack alerts for fraud_status=challenge)?

Integration Approach

Stack Fit

  • Laravel Ecosystem:

    • Composer: Native support via composer require midtrans/midtrans-php.
    • Service Container: Bind Midtrans client to Laravel’s container for dependency injection:
      $this->app->singleton(Midtrans\Config::class, function ($app) {
          $config = new Midtrans\Config();
          $config->serverKey = config('services.midtrans.server_key');
          $config->isProduction = config('services.midtrans.production');
          return $config;
      });
      
    • HTTP Client: Use Laravel’s Http facade or Guzzle for API calls (e.g., Transaction::status()).
    • Routing: Dedicate a route for webhooks (e.g., POST /midtrans/webhook) with middleware for signature validation.
    • Events: Dispatch Laravel events for transaction status changes (e.g., PaymentProcessed, PaymentFailed).
  • Frontend Integration:

    • Snap.js: Include Midtrans’ JS SDK in Laravel Blade templates or Vue/React components. Use Laravel Mix/Vite to bundle.
    • Core API: For VT-Direct, use Laravel’s Blade or Inertia.js to render checkout forms and handle token_id submission.

Migration Path

  1. Phase 1: Configuration

    • Add Midtrans credentials to config/services.php:
      'midtrans' => [
          'server_key' => env('MIDTRANS_SERVER_KEY'),
          'client_key' => env('MIDTRANS_CLIENT_KEY'),
          'production' => env('MIDTRANS_PRODUCTION', false),
          'sandbox' => env('MIDTRANS_SANDBOX', true),
      ],
      
    • Publish config file if using Laravel packages:
      php artisan vendor:publish --tag=midtrans-config
      
  2. Phase 2: Core API Integration

    • Implement a PaymentService facade to abstract Midtrans calls:
      namespace App\Services;
      
      use Midtrans\CoreApi;
      
      class PaymentService {
          public function charge(array $params) {
              return CoreApi::charge($params);
          }
      }
      
    • Use dependency injection in controllers:
      public function checkout(PaymentService $paymentService) {
          $response = $paymentService->charge($transactionData);
          // Handle response...
      }
      
  3. Phase 3: Webhook Handling

    • Create a webhook route with middleware:
      Route::post('/midtrans/webhook', [MidtransController::class, 'handleWebhook'])
           ->middleware('verify.midtrans.signature');
      
    • Implement signature validation middleware:
      public function handle($request, Closure $next) {
          $signature = $request->header('X-Midtrans-Signature');
          $isValid = \Midtrans\Config::validateSignature($request->getContent(), $signature);
          if (!$isValid) abort(403);
          return $next($request);
      }
      
    • Dispatch events or jobs in the webhook handler:
      public function handleWebhook(Request $request) {
          $notif = new \Midtrans\Notification($request->all());
          event(new PaymentWebhookReceived($notif));
      }
      
  4. Phase 4: Frontend Integration

    • For Snap, include the JS SDK in Blade:
      <script src="https://app.sandbox.midtrans.com/snap/snap.js"
              data-client-key="{{ config('services.midtrans.client_key') }}"></script>
      
    • For Core API, render a form to submit token_id to Laravel’s backend.
  5. Phase 5: Testing

    • Use Midtrans’ sandbox environment for testing.
    • Mock webhooks in PHPUnit:
      $this->post('/midtrans/webhook', [
          'transaction_status' => 'capture',
          'fraud_status' => 'accept',
      ])->assertOk();
      

Compatibility

  • Laravel Versions: Tested with Laravel 8+ (PHP 8.0+). No major breaking changes expected.
  • PHP Extensions: Requires php-curl and php-openssl (for HTTPS and signature validation).
  • Database: No schema changes required, but recommend adding a payments table for tracking:
    Schema::create('payments', function (Blueprint $table) {
        $table->id();
        $table->string('order_id');
        $table->string('transaction_id')->nullable();
        $table->string('status');
        $table->string('fraud_status')->nullable();
        $table->json('metadata');
        $table->timestamps();
    });
    

Sequencing

Step Task Dependencies Owner
1 Add Midtrans config to .env - DevOps
2 Publish config file Step 1 TPM
3 Create PaymentService facade - Backend
4 Implement webhook route/middleware Step
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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