Weave 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

Sdk Php Laravel Package

online-payments/sdk-php

The Online Payments PHP SDK lets PHP applications communicate with the Online Payments Server API. It wraps API calls in convenient PHP request and response objects, handles authentication and required metadata automatically, and requires PHP 7.4 or above. Install it via Composer with online-payment...

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Laravel Synergy: The SDK’s API-centric design aligns seamlessly with Laravel’s HTTP client, service container, and event system. It can be encapsulated as a dedicated service layer (App\Services\PaymentGateway) with clear interfaces for:
    • Request/Response Handling: Use Laravel’s Http client to wrap SDK calls, enabling middleware for retries, logging, and rate limiting.
    • Event-Driven Architecture: Leverage Laravel’s events (e.g., PaymentProcessed, PaymentFailed) to trigger business logic (e.g., inventory updates, notifications).
    • Configuration Management: Centralize SDK settings in config/services/payment.php with environment-specific overrides (e.g., sandbox/live).
  • Separation of Concerns:
    • Controllers: Delegate to service layer (e.g., PaymentController@charge() → PaymentGateway::create()).
    • Models: Use Eloquent observers to sync SDK responses with database (e.g., Payment::created() → store payment_id).
    • Jobs: Offload async operations (e.g., ProcessRefundJob) to queues.
  • Testing Readiness: The SDK’s structured models enable mockable interfaces for unit tests (e.g., MockPaymentGateway) and integration tests with sandbox environments.

Integration Feasibility

  • HTTP Layer Compatibility:
    • Replace the SDK’s default client with Laravel’s Http client or Guzzle, adding middleware for:
      • Authentication: Inject API keys via AddApiKeyMiddleware.
      • Retry Logic: Use RetryFailedRequests middleware.
      • Request/Response Logging: Integrate with monolog or Laravel Debugbar.
    • Example:
      $client = app(HttpClient::class)->withOptions([
          'base_uri' => config('services.payment.api_url'),
          'headers' => ['Authorization' => 'Bearer ' . config('services.payment.key')],
      ]);
      
  • Database Sync:
    • Use Eloquent models to bridge SDK responses and database records. Example:
      class Payment extends Model {
          protected $casts = ['metadata' => 'array'];
      
          public static function boot() {
              static::created(fn ($payment) => PaymentGateway::create($payment));
          }
      }
      
  • Webhook Handling:
    • Expose a Laravel route (e.g., POST /payment/webhook) with:
      • Signature Validation: Verify HMAC signatures (if SDK supports it) or use Laravel’s signed routes.
      • Event Dispatching: Convert webhook payloads to Laravel events (e.g., PaymentWebhookReceived).
  • Duplicate-in-Flight Response Handling:
    • The 11.2.1 fix causes the SDK to raise IdempotenceException when a duplicate request is detected while the original is still in progress (previously this path did not raise reliably). Integrate this explicitly rather than treating it as an error:
      • Do not map IdempotenceException to a user-facing failure. Treat it as HTTP 409-like semantics and re-poll status or return a "processing" state.
      • Cache in-flight idempotency keys and wrap the retry path in a try/catch (IdempotenceException) inside the service layer, not in controllers.

Technical Risk

  • Undocumented Behavior:
    • Risk: SDK may have hidden dependencies (e.g., PHP 8.2+, specific Guzzle versions) or inconsistent error handling.
    • Mitigation: Test with phpunit and pestphp using mocked SDK responses. Validate against Laravel’s LTS (e.g., 10.x) and PHP 8.1+.
  • Idempotency (updated for 11.2.1):
    • Risk: Duplicate requests (e.g., retries) may cause double-charges.
    • Change: 11.2.1 now correctly raises IdempotenceException for duplicate requests still in progress. This is a behavioral change to error surfaces — any retry middleware that previously swallowed or ignored this path will now receive an exception. Consumers on versions <= 11.2.0 were silently exposed to the in-flight gap; this release closes it.
    • Mitigation: Implement Laravel caching (e.g., Cache::remember) or SDK-specific idempotency keys, and add explicit handling for IdempotenceException as a recoverable, non-terminal state. Add regression tests asserting the exception is caught and the request is not re-submitted blindly.
  • Webhook Reliability:
    • Risk: Missing or malformed webhooks could break workflows.
    • Mitigation: Use Laravel’s failed_jobs table for retries and dead-letter queues.
  • Async Limitations:
    • Risk: SDK may not support async callbacks for long-running operations.
    • Mitigation: Wrap SDK calls in Laravel jobs (e.g., ProcessPaymentJob) with queue monitoring (e.g., Horizon).
  • Model Enum Drift (new, 11.2.1):
    • Risk: The added paymentPattern enum value in MultiplePaymentInformation can arrive on payloads your code does not recognize, producing ValueError/unhandled enum casts if you map SDK enums directly to Eloquent casts or DB enums.
    • Mitigation: Do not cast raw SDK enums to DB-backed enums; store as string and resolve lazily. Add a "unknown enum" fallback branch and cover it in contract tests before pinning the update.

Key Questions

  1. Provider Abstraction: Does the SDK abstract all provider-specific logic (e.g., 3D Secure flows), or will custom logic be required?
  2. Error Granularity: Are SDK exceptions detailed enough for Laravel’s error handling (e.g., PaymentGatewayException with HTTP status codes)?
  3. Webhook Validation: How does the SDK validate webhook signatures? Can Laravel’s middleware handle this (e.g., HMAC verification)?
  4. Localization Support: Does the SDK handle currency formatting, or must Laravel’s Number package intervene?
  5. Audit Trails: How are payment logs stored? Can Laravel’s logs table or a custom payments table integrate with SDK events?
  6. Deprecation Plan: Is the SDK actively maintained? If not, what’s the migration path to the provider’s official SDK?
  7. Testing Coverage: Are there sandbox/test modes? If not, how will integration tests be conducted?
  8. IdempotenceException Contract (new): What is the documented retry/backoff guidance when this exception is raised? Does the SDK expose the original request key so we can correlate and poll status?
  9. paymentPattern Semantics (new): What does the new enum value represent, and is it emitted only for multi-payment information payloads? Does any existing match/switch in our code become non-exhaustive?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Service Container: Bind the SDK to Laravel’s container with configurable options:
      $app->singleton(PaymentGateway::class, fn () => new OnlinePayments(
          config('services.payment.key'),
          config('services.payment.secret'),
          config('services.payment.env')
      ));
      
    • Facades: Expose critical methods via a facade (e.g., Payment::charge()) while keeping core logic in a service class.
    • Policies: Use Laravel’s authorization (e.g., Gate::define('create_payment')) to restrict access.
  • HTTP Layer:
    • Replace the SDK’s client with Laravel’s Http client, adding middleware for:
      • Logging: LogRequests middleware.
      • Retries: RetryFailedRequests middleware — configure this to exclude IdempotenceException from retry, since the SDK now surfaces it for in-flight duplicates; blind retry defeats the fix.
      • Rate Limiting: ThrottleRequests middleware.
    • Example:
      $client = app(HttpClient::class)->withOptions([
          'base_uri' => config('services.payment.api_url'),
          'headers' => ['X-API-Key' => config('services.payment.key')],
      ]);
      
  • Database:
    • Use Eloquent models to sync SDK responses with database records. Example:
      class Payment extends Model {
          protected $dispatchesEvents = [
              'created' => PaymentCharged::class,
              'updated' => PaymentRefunded::class,
          ];
      }
      
    • Keep paymentPattern stored as a plain string column to absorb the 11.2.1 enum addition without a migration.

Migration Path

  1. Phase 1: Proof of Concept (1–2 weeks)
    • Isolate SDK usage in a module (e.g., Modules/Payments).
    • Test core flows: charge, refund, subscription.
    • Mock the SDK in unit tests; use sandbox for integration tests.
  2. Phase 2: Integration (2–3 weeks)
    • Replace hardcoded SDK calls with Laravel’s service container.
    • Add middleware for cross-cutting concerns (e.g., logging, auth).
    • Implement webhook handlers as Laravel events/jobs.
  3. Phase 3: Productionization (1–2 weeks)
    • Configure monitoring (e.g., Horizon for queues, Sentry for errors).
    • Set up rollback plan (e.g., feature flag to toggle SDK usage).
    • Document provider-specific edge cases (e.g., "SDK requires amount in cents").
  4. Phase 4: 11.2.1 Uptake (1–3 days)
    • Upgrade in a branch; assert IdempotenceException is surfaced (write a test that forces a duplicate in-flight request).
    • Audit every catch/retry around SDK calls for the new exception type.
    • Sweep paymentPattern usages for non-exhaustive match expressions; add default branches.

Compatibility

  • Version Pinning:
    • Lock SDK to specific PHP (e.g., ^8.1) and Laravel (e.g., ^10.0) versions in composer.json.
    • Use platform-check to resolve dependency conflicts (e.g., Guzzle, Symfony components).
    • 11.2.1 is a patch-level release (no deprecations, no signature changes indicated), so it is adoptable under an existing ^11.2 constraint; treat the exception-raising change as a behavioral patch requiring code review even though the version is minor.
  • Testing Matrix:
    Environment PHP Laravel SDK Version Notes
    Local (Docker) 8.2 10.x 11.2.1 Use valet or laravel-sail
    CI (GitHub Actions) 8.1 9.x 11.2.1 Test oldest supported
    Staging 8.1 10.x 11.2.1 Mirror production; run duplicate-request test

Sequencing

  1. Setup:
    • Install SDK via Composer; publish config (php artisan vendor:publish --tag=payment-config).
    • Configure .env with provider credentials.
  2. Core Integration:
    • Create PaymentService class to wrap SDK methods.
    • Add facade for controller access (e.g., Payment::charge()).
  3. Async Workflows:
    • Implement jobs for long-running operations (e.g., ProcessRefundJob).
    • Configure queues (e.g., database or redis).
  4. Webhooks:
    • Expose an endpoint (e.g., POST /payment/webhook) with Laravel’s Route::post.
    • Validate signatures; dispatch events (e.g., PaymentWebhookHandled).
  5. Observability:
    • Add logging (e.g., monolog channel for payment events).
    • Instrument with metrics (e.g., laravel-metrics for success/failure rates).
  6. 11.2.1 Rollout:
    • Release the upgrade after the IdempotenceException handling and enum fallback ship — do not bundle the dependency bump with the error-handling change in a single deploy.

Operational Impact

Maintenance

  • Configuration Management:
    • Centralize SDK settings in config/services/payment.php with environment overrides.
    • Use Laravel’s config:cache for runtime optimization.
  • Dependency Updates:
    • Schedule monthly patch reviews; 11.2.1 is a low-risk consume-once-tested update. Note the SDK is active enough to ship targeted transactional fixes — a positive maintenance signal.
    • Track upstream changelogs for IdempotenceException semantics and paymentPattern enum growth; both are areas where our contract tests must stay ahead of the SDK.
  • Code Ownership: Assign a payments domain owner responsible for reviewing SDK releases for behavioral (not just version) changes; 11.2.1 is exactly the class of release that passes semver but alters runtime control flow.

Support

  • Escalation Path: Maintain a documented runbook for IdempotenceException — what the customer sees, when to re-poll, when to contact the provider. Frontline support must not treat it as a failed payment.
  • Vendor Engagement: Keep a channel open for enum additions; unexpected paymentPattern values are a silent-support-ticket generator if unhandled.
  • Incident Classification: Duplicate-charge incidents should be re-baselined post-11.2.1 — the in-flight gap is closed by the SDK, so future duplicates point at our retry logic, simplifying root-cause analysis.

Scaling

  • Throughput: Idempotency-key caching (Redis) per request becomes mandatory rather than optional, adding a small dependency on cache availability in the payment hot path. Size the cache for peak TPS × idempotency TTL.
  • Queue Depth: IdempotenceException handling encourages status-polling, which adds read volume; monitor provider rate limits under load.
  • Multi-tenant: If tenants share credentials, idempotency key namespacing must be tenant-scoped to avoid cross-tenant collision on in-flight detection.

Failure Modes

  • Unhandled IdempotenceException: If not caught, in-flight duplicates surface as 500s in Laravel’s exception handler. Mitigation: dedicated exception handler mapping to a 202 Accepted/processing response.
  • Non-exhaustive Enum Match: New paymentPattern value hits a match without a default → UnhandledMatchError on multi-payment info flows. Mitigation: default branch + string storage + alerting on unknown values.
  • Retry Middleware Interaction: Retry middleware re-issuing on the new exception re-creates the duplicate storm the fix was meant to prevent. Mitigation: exclude the exception class from retryable exceptions.
  • Cache Outage: Losing the idempotency cache degrades to provider-side dedupe only; acceptable but should be alarmed.

Ramp-up

  • Engineering: ~1 day per developer to understand the service-layer wrapper; ~half day specifically on idempotency semantics post-11.2.1.
  • QA: Add two regression cases (duplicate in-flight request; unknown paymentPattern) to the standard suite — small effort, high leverage.
  • Ops/Support: 1-hour briefing on payment states, specifically the difference between "processing (duplicate detected)" and "failed."
  • Documentation Debt: Update the payments runbook with the 11.2.1 behavioral change; note it in the internal changelog so future upgrades aren't re-litigated.
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.
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log
hsluv/hsluv
seampact/codegen
seampact/hooks
seampact/ir
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk