Skip to content

feat: Add payment provider plugin system for external gateway integrations - #4458

Open
jekkos wants to merge 1 commit into
masterfrom
feature/payment-provider-system
Open

jekkos wants to merge 1 commit into
masterfrom
feature/payment-provider-system

Conversation

@jekkos

@jekkos jekkos commented Apr 1, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR introduces a comprehensive payment provider architecture to enable seamless integration with external payment gateways like SumUp and PayPal/Zettle. This builds on the existing event system and provides a foundation for addressable issues around payment type enhancements.

Related Issues

Fixes #4346 (SumUp integration)
Fixes #4322 (PayPal In Store/POS/Zettle Integration)
Addresses #3232 (Configurable payment types with custom options)
Addresses #3789 (Third-party integration standard architecture)
Addresses #3790 (Payment type stored as translated string)
Addresses #2275 (Customer balance and payment tracking)

Architecture Overview

Core Components

Component Location Purpose
PaymentProviderInterface app/Libraries/Payments/ Contract for all payment providers
PaymentProviderBase app/Libraries/Payments/ Abstract base with common functionality
PaymentProviderRegistry app/Libraries/Payments/ Singleton registry for provider management
PaymentTransaction app/Models/ Transaction tracking model
Webhook app/Controllers/Payments/ Endpoint for external callbacks

Events Added

Event Location Purpose
payment_options locale_helper.php Allow plugins to register payment types
payment_initiated Sales::postAddPayment() When payment is added to sale
sale_completed Sales::postComplete() After successful sale completion
payment_completed Provider-triggered After successful external payment
payment_failed Provider-triggered After failed external payment

Database Schema

New ospos_payment_transactions table tracks provider transactions:

  • id, provider_id, sale_id, transaction_id
  • amount, currency, status (pending/authorized/completed/failed/refunded/cancelled)
  • metadata (JSON), timestamps

Provider Stubs Included

SumUpProvider

  • Card reader terminal integration
  • Transaction status tracking
  • Refund and cancel operations

PayPalProvider

  • Card reader (Zettle) support
  • QR code payment mode
  • Webhook event handling

View Integration

Added payment_provider_content() helper hook in register.php:

<?= payment_provider_content('register_payment_actions', ['amount_due' => $amount_due]) ?>

Usage Example

// Register a payment provider
$sumup = new SumUpProvider(['apiKey' => 'xxx']);
PaymentProviderRegistry::getInstance()->register($sumup);

// Listen for payment events
Events::on('sale_completed', function($data) {
    // Process external payment completion
});

// Webhook endpoint (no auth required)
POST /payments/webhook/sumup

Testing Recommendations

  1. Run database migration: php spark migrate
  2. Verify events are triggered correctly in sales workflow
  3. Test webhook endpoint with mock provider responses
  4. Verify payment options filter passes through event system

Checklist

  • Code follows PSR-12 coding standards
  • New files have proper namespaces
  • Migration file follows existing naming convention
  • Events integrate with existing CodeIgniter Events system
  • No breaking changes to existing payment workflow

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for multiple payment providers (PayPal, SumUp) with webhook processing capabilities.
    • Implemented payment transaction tracking and status monitoring system.
    • Enhanced sales workflow with payment-related event logging.
    • Added payment provider configuration and management infrastructure.
  • Database

    • New payment transactions table for storing and tracking payment details.

…tions

This commit introduces a comprehensive payment provider architecture to enable
seamless integration with external payment gateways like SumUp and PayPal/Zettle.

Architecture:
- PaymentProviderInterface: Contract for all payment providers
- PaymentProviderBase: Abstract base class with common functionality
- PaymentProviderRegistry: Singleton registry for provider management
- PaymentTransaction model: Transaction tracking and status management

Infrastructure:
- Webhook controller: Endpoint for external payment callbacks
- Payment events: payment_initiated, payment_completed, sale_completed
- payment_helper.php: Helper functions for payment provider content
- Migration for ospos_payment_transactions table

Core changes:
- Add Events::trigger('payment_options') in locale_helper.php
- Add Events::trigger('sale_completed') in Sales controller
- Add Events::trigger('payment_initiated') in postAddPayment()
- Add webhook routes for /payments/webhook/{provider}

Provider stubs:
- SumUpProvider: Card reader terminal integration
- PayPalProvider: Card reader and QR code payment integration

Related issues: #4346, #4322, #3232, #3789, #3790, #2275
@coderabbitai

coderabbitai Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request implements a comprehensive payment provider architecture for the point-of-sale system. It introduces webhook endpoints for payment callbacks, a payment provider interface with registry for managing multiple payment processors, concrete implementations for PayPal and SumUp, database persistence for transactions, and an event system to notify the application of payment lifecycle state changes.

Changes

Cohort / File(s) Summary
Payment Routing & Webhooks
app/Config/Routes.php, app/Controllers/Payments/Webhook.php
Added webhook routes for payment provider callbacks (POST payments/webhook/:provider) and status queries (GET payments/status/:provider/:transactionId), with controller implementation handling provider resolution, callback processing, error handling, and HTTP responses.
Provider Framework
app/Libraries/Payments/PaymentProviderInterface.php, app/Libraries/Payments/PaymentProviderBase.php, app/Libraries/Payments/PaymentProviderRegistry.php
Introduced interface defining payment provider contract (initiatePayment, processCallback, getPaymentStatus, refund, cancel, settings management), abstract base class with transaction logging/lookup, settings persistence, and event firing, plus singleton registry for provider registration, lookup, and aggregation.
Concrete Provider Implementations
app/Libraries/Payments/Providers/PayPalProvider.php, app/Libraries/Payments/Providers/SumUpProvider.php
Implemented PayPal and SumUp payment providers with payment type metadata, initiation, webhook callback processing (event-type routing), status queries, refund/cancel operations, and config views.
Database & Model
app/Database/Migrations/20260401000000_PaymentTransactions.php, app/Models/PaymentTransaction.php
Created payment_transactions table migration with provider/sale/transaction IDs, amount/currency, status (enum), metadata, and timestamps; added model with status constants and helper methods for querying by transaction/sale/status.
Event System
app/Events/PaymentEvents.php, app/Controllers/Sales.php
Registered event listeners for payment_initiated, payment_completed, payment_failed, and sale_completed with structured log handlers; integrated event dispatching into Sales controller's postAddPayment() and postComplete() methods.
Helpers & View Integration
app/Helpers/payment_helper.php, app/Helpers/locale_helper.php, app/Views/sales/register.php
Added payment helper with global functions for provider management and event-driven content rendering; modified locale helper to allow event-based payment option overrides; updated register view to conditionally include payment provider actions UI.

Sequence Diagram(s)

sequenceDiagram
    actor Client
    participant Webhook as Webhook Controller
    participant Registry as PaymentProviderRegistry
    participant Provider as PaymentProvider
    participant Database as PaymentTransaction
    participant Events as Events System

    Client->>Webhook: POST /payments/webhook/paypal
    Webhook->>Registry: getProvider('paypal')
    Registry-->>Webhook: PayPalProvider
    Webhook->>Webhook: Parse request body (JSON/form)
    Webhook->>Provider: processCallback(data)
    Provider->>Database: getTransaction(transactionId)
    Database-->>Provider: transaction record
    Provider->>Database: updateTransactionStatus(...)
    Provider->>Events: fire('payment_completed', ...)
    Events->>Events: onPaymentCompleted()
    Events->>Events: log_message('info', ...)
    Provider-->>Webhook: {success: true, status: 'completed'}
    Webhook-->>Client: 200 JSON response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related issues

Poem

🐰 Bouncing with glee, a new system takes flight,
Webhooks and providers, all working just right!
From PayPal to SumUp, the transactions now flow,
Events and helpers make payments a breeze below! 🎉

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.27% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main feature: introducing a payment provider plugin system for external gateway integrations.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/payment-provider-system

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 14

🧹 Nitpick comments (8)
app/Controllers/Sales.php (1)

798-805: Extract duplicated sale_completed trigger payload into a private helper.

Both branches build the same event payload; centralizing this reduces drift risk for future payload changes.

Also applies to: 891-898

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Controllers/Sales.php` around lines 798 - 805, The code duplicates the
payload for Events::trigger('sale_completed'); extract the array construction
into a private helper on the Sales controller (e.g., private function
buildSaleCompletedPayload(array $data, $customer_id, $employee_id, $sale_type):
array) that returns the payload with keys sale_id, customer_id, employee_id,
total, payments, sale_type, then replace both direct array usages (the current
Events::trigger('sale_completed', [...]) occurrences) with
Events::trigger('sale_completed', $this->buildSaleCompletedPayload($data,
$customer_id, $employee_id, $sale_type)).
app/Libraries/Payments/PaymentProviderRegistry.php (3)

69-78: getProviderForPaymentType() may return disabled providers.

This method searches all registered providers regardless of availability status. If a disabled provider happens to match the payment type key, it will be returned. Consider whether this is intentional or if it should filter by isAvailable() like getEnabledProviders() does.

♻️ Proposed fix to check availability
 public function getProviderForPaymentType(string $paymentTypeKey): ?PaymentProviderInterface
 {
     foreach ($this->providers as $provider) {
+        if (!$provider->isAvailable()) {
+            continue;
+        }
         $types = $provider->getPaymentTypes();
         if (isset($types[$paymentTypeKey])) {
             return $provider;
         }
     }
     return null;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Libraries/Payments/PaymentProviderRegistry.php` around lines 69 - 78,
getProviderForPaymentType currently returns any provider matching the payment
type key even if it's disabled; update getProviderForPaymentType to skip
providers for which isAvailable() is false (e.g., call $provider->isAvailable()
and continue when false) so it only returns an available provider—mirror the
availability filtering used by getEnabledProviders() and return null if no
enabled provider matches.

9-9: Remove unused $initialized field.

The $initialized property is declared but never read or written anywhere in the class. This appears to be leftover code from an incomplete lazy-initialization pattern.

🧹 Proposed fix
 class PaymentProviderRegistry
 {
     private static ?PaymentProviderRegistry $instance = null;
     private array $providers = [];
-    private bool $initialized = false;
 
     private function __construct()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Libraries/Payments/PaymentProviderRegistry.php` at line 9, Remove the
unused property by deleting the private bool $initialized declaration from the
PaymentProviderRegistry class; this field is never read or written and appears
to be leftover from a lazy-initialization attempt, so removing it (referencing
the PaymentProviderRegistry class and the $initialized symbol) will clean up
dead code without changing behavior.

23-29: Silent registration failure may hide configuration issues.

When a provider with a duplicate ID is registered, the method silently ignores it. Consider logging a warning or throwing an exception during development to help catch misconfiguration where multiple providers share the same ID.

🔧 Proposed fix to add logging
 public function register(PaymentProviderInterface $provider): void
 {
     $providerId = $provider->getProviderId();
     if (!isset($this->providers[$providerId])) {
         $this->providers[$providerId] = $provider;
+    } else {
+        log_message('warning', "Payment provider '{$providerId}' already registered, ignoring duplicate.");
     }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Libraries/Payments/PaymentProviderRegistry.php` around lines 23 - 29, The
register method in PaymentProviderRegistry currently ignores duplicate provider
IDs; update register(PaymentProviderInterface $provider) to surface duplicates
by either logging a warning or throwing a descriptive exception: add a
LoggerInterface $logger to PaymentProviderRegistry (via constructor) and call
$this->logger->warning("Duplicate payment provider registration", ['providerId'
=> $providerId, 'existing' => get_class($this->providers[$providerId]),
'attempt' => get_class($provider)]) when a duplicate is detected, or
alternatively throw a new DuplicateProviderException("Provider ID
'{$providerId}' already registered by " .
get_class($this->providers[$providerId])); ensure you reference the register
method, the $providers property, PaymentProviderInterface, and create
DuplicateProviderException if choosing the exception approach.
app/Libraries/Payments/Providers/PayPalProvider.php (2)

85-107: Consider sanitizing callback data before storing in metadata.

Similar to SumUpProvider, the raw webhook payload is stored in transaction metadata (lines 88 and 98). PayPal webhooks may contain customer PII or payment details that shouldn't be persisted. Consider filtering to only essential fields.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Libraries/Payments/Providers/PayPalProvider.php` around lines 85 - 107,
The webhook handler in PayPalProvider stores raw $data in transaction metadata
via updateTransactionStatus and then fires events using $data/ $transaction (see
updateTransactionStatus and fire calls), so sanitize the callback payload before
persisting: implement a small sanitizer that whitelists only essential fields
(e.g., event type, resource.id/sale_id, amount, status) and strips PII (payer
info, full payment method details), call that sanitizer on $data prior to
passing it into updateTransactionStatus and fire, and ensure logs/events use the
sanitized payload (not the raw $data).

37-40: Consider differentiating icons by payment type.

The $paymentType parameter is ignored, but PayPal has distinct branding for card (Zettle) vs QR payments. This could be an opportunity to return payment-type-specific icons for better UX.

🎨 Example implementation
 public function getIcon(?string $paymentType = null): ?string
 {
-    return base_url('images/payment_providers/paypal.svg');
+    return match ($paymentType) {
+        'paypal_qr' => base_url('images/payment_providers/paypal_qr.svg'),
+        default => base_url('images/payment_providers/paypal.svg'),
+    };
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Libraries/Payments/Providers/PayPalProvider.php` around lines 37 - 40,
The getIcon method in PayPalProvider ignores the $paymentType parameter; update
getIcon(?string $paymentType = null): ?string to branch on $paymentType (e.g.,
'card', 'qr', 'zettle' or other provider-specific keys) and return a
type-specific SVG path via base_url — for example
'images/payment_providers/paypal-card.svg' for card/Zettle,
'images/payment_providers/paypal-qr.svg' for QR, and fall back to
'images/payment_providers/paypal.svg' as the default; ensure the branches live
in the PayPalProvider::getIcon method and handle null/unknown values gracefully.
app/Libraries/Payments/PaymentProviderBase.php (1)

16-19: Default getProviderId() returns FQCN which may be too verbose.

The default implementation returns static::class (e.g., App\Libraries\Payments\Providers\SumUpProvider), which would create very long settings prefixes like payment_App\Libraries\Payments\Providers\SumUpProvider_enabled. While concrete providers override this, consider whether the base implementation should throw an exception or use a shorter derived name.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Libraries/Payments/PaymentProviderBase.php` around lines 16 - 19, The
base PaymentProviderBase::getProviderId() currently returns static::class
(fully-qualified class name) which yields overly long settings keys; update the
method so it either throws a clear exception (e.g., throw new
\LogicException('Concrete provider must implement getProviderId()')) or returns
a compact default identifier such as the class short name (use
ReflectionClass(static::class)->getShortName() or a class_basename helper) so
settings prefixes are concise; choose one approach and apply it to
getProviderId() in PaymentProviderBase.
app/Libraries/Payments/Providers/SumUpProvider.php (1)

79-99: Consider sanitizing callback data before storing in metadata.

The entire $data array from the webhook callback is stored in transaction metadata (lines 81 and 90). Depending on what the SumUp API includes, this could contain sensitive information (card details, PII). Consider filtering or sanitizing the data before persistence.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Libraries/Payments/Providers/SumUpProvider.php` around lines 79 - 99, The
webhook handler is currently passing the raw $data into updateTransactionStatus
and fire, which can persist sensitive callback fields; before calling
updateTransactionStatus($checkoutId, ...) and before passing payload to
fire(...), filter/sanitize $data by whitelisting only non-sensitive keys (e.g.,
amount, currency, status, sale_id, timestamps) or explicitly remove sensitive
fields (e.g., card_number, pan, cvv, expiry, full_pan, customer_ssn, tokens,
payment_method_details) and any PII, and pass the sanitized array (e.g.,
$sanitizedData) instead of $data to both updateTransactionStatus and fire so
only safe metadata is stored and emitted.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@app/Config/Routes.php`:
- Around line 15-16: The CSRF filter in Filters.php is currently exempting only
the login route, which blocks external callbacks to your Payments\Webhook
controller (methods handle and status). Update the 'csrf' filter's except list
in Filters.php to include wildcard patterns for the webhook endpoints (e.g., add
entries for payments/webhook* and payments/status*) so POST to
Payments\Webhook::handle and GET to Payments\Webhook::status are exempted from
CSRF validation.

In `@app/Controllers/Payments/Webhook.php`:
- Around line 49-63: The status() endpoint currently returns payment status
based only on URL params, allowing unauthenticated probing; modify the
status(string $providerId, string $transactionId) method to enforce
authentication or a signed-token check before calling
PaymentProviderRegistry::getInstance()->getProvider and
$provider->getPaymentStatus. Specifically: validate/sanitize providerId and
transactionId formats (reject unexpected chars/lengths), extract and verify an
auth credential (e.g., Authorization header bearer token or a signed query
token) and return 401/403 when missing/invalid, and only then proceed to fetch
the provider and call getPaymentStatus; ensure error responses do not leak
sensitive details.
- Around line 23-29: When the webhook reads $rawInput and decodes with
json_decode into $data, invalid JSON is currently collapsed to [] and passed on;
change the logic in the Webhook controller so that if $rawInput is non-empty and
json_decode returns null/empty with json_last_error() != JSON_ERROR_NONE you
reject the request (respond with a 400/BadRequest) instead of falling back to or
forwarding an empty $data; only when $rawInput is empty should you fall back to
$this->request->getPost() for form-encoded payloads. Ensure you check
json_last_error() after json_decode and return an appropriate error response
from the Webhook handler (do not proceed to provider processing with malformed
JSON).

In `@app/Controllers/Sales.php`:
- Around line 475-480: The Events::trigger('payment_initiated', ...) is firing
even when validation fails; update the flow in Sales.php so the trigger is
executed only after a successful payment add. Move the Events::trigger call to
after the call that adds the payment (e.g. after
$this->sale_lib->add_payment(...) / wherever payment persistence occurs) and
guard it by checking that no validation error exists (ensure $data['error'] is
false/empty) and/or that the add_payment returned success before calling
Events::trigger('payment_initiated', ...).

In `@app/Database/Migrations/20260401000000_PaymentTransactions.php`:
- Around line 68-70: Add a composite unique index on provider_id and
transaction_id in the PaymentTransactions migration to prevent duplicate
transaction identities: update the migration where $forge defines keys (the
PaymentTransactions migration class) to add a unique key for ['provider_id',
'transaction_id'] (use your framework's API, e.g.
$forge->addUniqueKey(['provider_id','transaction_id']) or equivalent) and remove
or adjust the separate non-unique index on transaction_id so the composite
uniqueness is enforced for lookups/updates.
- Around line 11-13: The migration uses \Config\Services::forge() which isn't
initialized in Migration context and causes null errors; replace all uses of
\Config\Services::forge() (e.g. the variable $forge and calls like
$forge->addField(...), $forge->addKey(...), $forge->createTable(...)) with the
Migration-provided $this->forge instance (e.g. $this->forge->addField(...),
$this->forge->addKey(...), $this->forge->createTable(...)) and remove any local
$forge variable declarations so the class uses $this->forge consistently.

In `@app/Events/PaymentEvents.php`:
- Around line 51-56: The info log in the log_message call currently serializes
the full payments array which may expose sensitive identifiers; update the code
in PaymentEvents.php where log_message('info', sprintf(...)) is called to redact
sensitive fields by replacing payment identifiers with masked values or by
logging only safe aggregates (e.g., count of payments, total per payment method,
masked last4 or provider type) instead of json_encode($data['payments']); ensure
the new payload preserves context (sale_id and total) and uses a deterministic
masking strategy for any included payment token fields.
- Around line 11-17: Payment event handlers never get registered because
PaymentEvents::initialize() is not invoked; import the class and instantiate it
in the global event registration code and call initialize to register
handlers—specifically add a use App\Events\PaymentEvents; (or appropriate
namespace) and then create $paymentEvents = new PaymentEvents(); followed by
$paymentEvents->initialize(); so the Events::on registrations in PaymentEvents
(onPaymentInitiated, onPaymentCompleted, onPaymentFailed, onSaleCompleted) are
executed.

In `@app/Libraries/Payments/PaymentProviderBase.php`:
- Around line 68-79: The saveSettings method is passing the wrong shape to
Appconfig::save; instead of an array with 'key' and 'value' keys you must pass
an associative array where the config key maps to its value. Update
PaymentProviderBase::saveSettings (use $settingsModel and getSettingsPrefix())
to call Appconfig::save with [$fullKey => $value] for each entry (i.e., use the
full composed key as the array key and the setting value as its value) so
Appconfig::save receives the expected [$key => $value] format.
- Around line 68-79: The saveSettings() method currently always returns true
even if individual $settingsModel->save(...) calls fail; update saveSettings()
to track each save result (call return value or wrap save in try/catch) and set
a failure flag if any save returns false or throws, then return false when any
failure occurred and true only if all saves succeeded; reference the
saveSettings() function, the $settingsModel variable
(model(\App\Models\Appconfig::class)), the save(...) calls, and
getSettingsPrefix() so you locate and update the loop to check/save results and
handle exceptions accordingly.

In `@app/Libraries/Payments/Providers/PayPalProvider.php`:
- Around line 127-150: The refund() method in PayPalProvider accepts any amount
without validating it against the original transaction; update the refund flow
in refund(string $transactionId, float $amount, string $reason = '') to (1)
fetch the original transaction via getTransaction($transactionId), (2) verify
$amount is positive and does not exceed the transaction's original amount (e.g.,
$transaction['amount'] or equivalent field), and (3) return a failure array like
['success' => false, 'error' => 'Invalid refund amount'] when validation fails;
only call updateTransactionStatus($transactionId, 'refunded', ...) and return
success when the amount is valid.

In `@app/Libraries/Payments/Providers/SumUpProvider.php`:
- Around line 119-142: The refund() method currently allows any $amount, risking
over-refunds; modify refund() to first read the original transaction amount from
getTransaction($transactionId) (e.g., $transaction['amount']) and any existing
refunded amount if tracked, validate that $amount is > 0 and does not exceed the
remaining refundable balance (original amount minus already refunded), and
return a failure array like ['success' => false, 'error' => 'Refund amount
exceeds original transaction amount'] when validation fails; only call
updateTransactionStatus($transactionId, 'refunded', ...) and return success when
the amount is valid (consider updating how refunded totals are stored if partial
refunds are supported).

In `@app/Models/PaymentTransaction.php`:
- Around line 35-47: getTransaction currently allows a null $providerId which
lets the query match only on transaction_id and risk cross-provider collisions;
change getTransaction(string $transactionId, ?string $providerId = null) so the
provider is always enforced: either make $providerId a required string parameter
(remove the ? and default) or add an explicit guard that throws an
InvalidArgumentException when $providerId is null, and then always call
$builder->where('provider_id', $providerId) before executing
get()->getRowArray(); reference the getTransaction method and the
builder->where('provider_id', ...) call when making the fix.
- Around line 75-77: The metadata merge is not guarded against json_decode
returning null: ensure the result of json_decode($existing['metadata'] ?? '{}',
true) is an array before calling array_merge on $existingMetadata; if it is null
or not an array, treat it as an empty array, and likewise ensure
$additionalData['metadata'] is an array (or decode it) before merging, then
json_encode the merged array into $data['metadata']; look for the code in the
PaymentTransaction class around the $existingMetadata and $data['metadata']
assignments to apply this defensive check.

---

Nitpick comments:
In `@app/Controllers/Sales.php`:
- Around line 798-805: The code duplicates the payload for
Events::trigger('sale_completed'); extract the array construction into a private
helper on the Sales controller (e.g., private function
buildSaleCompletedPayload(array $data, $customer_id, $employee_id, $sale_type):
array) that returns the payload with keys sale_id, customer_id, employee_id,
total, payments, sale_type, then replace both direct array usages (the current
Events::trigger('sale_completed', [...]) occurrences) with
Events::trigger('sale_completed', $this->buildSaleCompletedPayload($data,
$customer_id, $employee_id, $sale_type)).

In `@app/Libraries/Payments/PaymentProviderBase.php`:
- Around line 16-19: The base PaymentProviderBase::getProviderId() currently
returns static::class (fully-qualified class name) which yields overly long
settings keys; update the method so it either throws a clear exception (e.g.,
throw new \LogicException('Concrete provider must implement getProviderId()'))
or returns a compact default identifier such as the class short name (use
ReflectionClass(static::class)->getShortName() or a class_basename helper) so
settings prefixes are concise; choose one approach and apply it to
getProviderId() in PaymentProviderBase.

In `@app/Libraries/Payments/PaymentProviderRegistry.php`:
- Around line 69-78: getProviderForPaymentType currently returns any provider
matching the payment type key even if it's disabled; update
getProviderForPaymentType to skip providers for which isAvailable() is false
(e.g., call $provider->isAvailable() and continue when false) so it only returns
an available provider—mirror the availability filtering used by
getEnabledProviders() and return null if no enabled provider matches.
- Line 9: Remove the unused property by deleting the private bool $initialized
declaration from the PaymentProviderRegistry class; this field is never read or
written and appears to be leftover from a lazy-initialization attempt, so
removing it (referencing the PaymentProviderRegistry class and the $initialized
symbol) will clean up dead code without changing behavior.
- Around line 23-29: The register method in PaymentProviderRegistry currently
ignores duplicate provider IDs; update register(PaymentProviderInterface
$provider) to surface duplicates by either logging a warning or throwing a
descriptive exception: add a LoggerInterface $logger to PaymentProviderRegistry
(via constructor) and call $this->logger->warning("Duplicate payment provider
registration", ['providerId' => $providerId, 'existing' =>
get_class($this->providers[$providerId]), 'attempt' => get_class($provider)])
when a duplicate is detected, or alternatively throw a new
DuplicateProviderException("Provider ID '{$providerId}' already registered by "
. get_class($this->providers[$providerId])); ensure you reference the register
method, the $providers property, PaymentProviderInterface, and create
DuplicateProviderException if choosing the exception approach.

In `@app/Libraries/Payments/Providers/PayPalProvider.php`:
- Around line 85-107: The webhook handler in PayPalProvider stores raw $data in
transaction metadata via updateTransactionStatus and then fires events using
$data/ $transaction (see updateTransactionStatus and fire calls), so sanitize
the callback payload before persisting: implement a small sanitizer that
whitelists only essential fields (e.g., event type, resource.id/sale_id, amount,
status) and strips PII (payer info, full payment method details), call that
sanitizer on $data prior to passing it into updateTransactionStatus and fire,
and ensure logs/events use the sanitized payload (not the raw $data).
- Around line 37-40: The getIcon method in PayPalProvider ignores the
$paymentType parameter; update getIcon(?string $paymentType = null): ?string to
branch on $paymentType (e.g., 'card', 'qr', 'zettle' or other provider-specific
keys) and return a type-specific SVG path via base_url — for example
'images/payment_providers/paypal-card.svg' for card/Zettle,
'images/payment_providers/paypal-qr.svg' for QR, and fall back to
'images/payment_providers/paypal.svg' as the default; ensure the branches live
in the PayPalProvider::getIcon method and handle null/unknown values gracefully.

In `@app/Libraries/Payments/Providers/SumUpProvider.php`:
- Around line 79-99: The webhook handler is currently passing the raw $data into
updateTransactionStatus and fire, which can persist sensitive callback fields;
before calling updateTransactionStatus($checkoutId, ...) and before passing
payload to fire(...), filter/sanitize $data by whitelisting only non-sensitive
keys (e.g., amount, currency, status, sale_id, timestamps) or explicitly remove
sensitive fields (e.g., card_number, pan, cvv, expiry, full_pan, customer_ssn,
tokens, payment_method_details) and any PII, and pass the sanitized array (e.g.,
$sanitizedData) instead of $data to both updateTransactionStatus and fire so
only safe metadata is stored and emitted.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 90c4cee5-a0c0-4a19-b7a9-b96fbc64546e

📥 Commits

Reviewing files that changed from the base of the PR and between 5667027 and 4d8e244.

📒 Files selected for processing (14)
  • app/Config/Routes.php
  • app/Controllers/Payments/Webhook.php
  • app/Controllers/Sales.php
  • app/Database/Migrations/20260401000000_PaymentTransactions.php
  • app/Events/PaymentEvents.php
  • app/Helpers/locale_helper.php
  • app/Helpers/payment_helper.php
  • app/Libraries/Payments/PaymentProviderBase.php
  • app/Libraries/Payments/PaymentProviderInterface.php
  • app/Libraries/Payments/PaymentProviderRegistry.php
  • app/Libraries/Payments/Providers/PayPalProvider.php
  • app/Libraries/Payments/Providers/SumUpProvider.php
  • app/Models/PaymentTransaction.php
  • app/Views/sales/register.php

Comment thread app/Config/Routes.php
Comment on lines +15 to +16
$routes->post('payments/webhook/(:segment)', 'Payments\Webhook::handle/$1');
$routes->get('payments/status/(:segment)/(:segment)', 'Payments\Webhook::status/$1/$2');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify webhook route exists and CSRF exceptions do not include it.
rg -n "payments/webhook|payments/status" app/Config/Routes.php
rg -n "csrf|except" app/Config/Filters.php

Repository: opensourcepos/opensourcepos

Length of output: 572


🏁 Script executed:

cat -n app/Config/Filters.php | head -100

Repository: opensourcepos/opensourcepos

Length of output: 3845


🏁 Script executed:

# Check if there are any other files that might configure CSRF exceptions
rg -n "webhook|csrf" app/ --type php | grep -E "(webhook|except)" | head -20

Repository: opensourcepos/opensourcepos

Length of output: 332


🏁 Script executed:

# Check if the webhook routes have any specific middleware or handler configurations
grep -r "webhook\|Webhook" app/Config/ app/Controllers/Payments/ --include="*.php" | head -20

Repository: opensourcepos/opensourcepos

Length of output: 991


🏁 Script executed:

cat -n app/Config/Filters.php | tail -50

Repository: opensourcepos/opensourcepos

Length of output: 2044


🏁 Script executed:

# Check if there are any pattern-based CSRF exemptions for webhook routes
rg -A 5 -B 5 "except.*webhook|webhook.*except" app/Config/Filters.php

Repository: opensourcepos/opensourcepos

Length of output: 53


Add webhook routes to CSRF exemptions to allow external provider callbacks.

The POST webhook route and GET status route will be blocked by the global CSRF filter. Currently, only the login route is exempted. External payment providers cannot provide CSRF tokens, so their callbacks will fail. Add payments/webhook and payments/status to the CSRF exceptions in app/Config/Filters.php line 73:

'csrf' => ['except' => ['login', 'payments/webhook*', 'payments/status*']],
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Config/Routes.php` around lines 15 - 16, The CSRF filter in Filters.php
is currently exempting only the login route, which blocks external callbacks to
your Payments\Webhook controller (methods handle and status). Update the 'csrf'
filter's except list in Filters.php to include wildcard patterns for the webhook
endpoints (e.g., add entries for payments/webhook* and payments/status*) so POST
to Payments\Webhook::handle and GET to Payments\Webhook::status are exempted
from CSRF validation.

Comment on lines +23 to +29
$rawInput = $this->request->getBody();
$data = json_decode($rawInput, true) ?? [];

if (empty($rawInput)) {
$data = $this->request->getPost();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Reject malformed JSON payloads instead of forwarding empty data.

For non-empty raw bodies, invalid JSON currently becomes [] and still goes through provider processing, which can produce incorrect state transitions.

🛠️ Proposed fix
         $rawInput = $this->request->getBody();
-        $data = json_decode($rawInput, true) ?? [];
-        
-        if (empty($rawInput)) {
+        $data = [];
+        if (!empty($rawInput)) {
+            $data = json_decode($rawInput, true);
+            if (json_last_error() !== JSON_ERROR_NONE) {
+                return $this->response->setStatusCode(400)->setJSON([
+                    'success' => false,
+                    'error' => 'Invalid JSON payload'
+                ]);
+            }
+        } else {
             $data = $this->request->getPost();
         }

As per coding guidelines {app/Controllers/**/*.php,app/Models/**/*.php}: Validate and sanitize all user input.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Controllers/Payments/Webhook.php` around lines 23 - 29, When the webhook
reads $rawInput and decodes with json_decode into $data, invalid JSON is
currently collapsed to [] and passed on; change the logic in the Webhook
controller so that if $rawInput is non-empty and json_decode returns null/empty
with json_last_error() != JSON_ERROR_NONE you reject the request (respond with a
400/BadRequest) instead of falling back to or forwarding an empty $data; only
when $rawInput is empty should you fall back to $this->request->getPost() for
form-encoded payloads. Ensure you check json_last_error() after json_decode and
return an appropriate error response from the Webhook handler (do not proceed to
provider processing with malformed JSON).

Comment on lines +49 to +63
public function status(string $providerId, string $transactionId): ResponseInterface
{
$provider = PaymentProviderRegistry::getInstance()->getProvider($providerId);

if ($provider === null) {
return $this->response->setStatusCode(404)->setJSON([
'success' => false,
'error' => 'Provider not found'
]);
}

try {
$result = $provider->getPaymentStatus($transactionId);
return $this->response->setStatusCode(200)->setJSON($result);
} catch (\Exception $e) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Protect status() endpoint with authentication or a signed token.

Returning payment status by URL parameters alone enables transaction-status probing by unauthenticated callers.

As per coding guidelines {app/Controllers/**/*.php,app/Models/**/*.php}: Validate and sanitize all user input.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Controllers/Payments/Webhook.php` around lines 49 - 63, The status()
endpoint currently returns payment status based only on URL params, allowing
unauthenticated probing; modify the status(string $providerId, string
$transactionId) method to enforce authentication or a signed-token check before
calling PaymentProviderRegistry::getInstance()->getProvider and
$provider->getPaymentStatus. Specifically: validate/sanitize providerId and
transactionId formats (reject unexpected chars/lengths), extract and verify an
auth credential (e.g., Authorization header bearer token or a signed query
token) and return 401/403 when missing/invalid, and only then proceed to fetch
the provider and call getPaymentStatus; ensure error responses do not leak
sensitive details.

Comment thread app/Controllers/Sales.php
Comment on lines +475 to +480
Events::trigger('payment_initiated', [
'payment_type' => $payment_type,
'amount' => $amount_tendered ?? 0,
'sale_id' => $this->sale_lib->get_sale_id(),
'customer_id' => $this->sale_lib->get_customer(),
]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Emit payment_initiated only after payment is actually added.

This trigger currently runs even when validation fails and $data['error'] is set, which emits false positives to listeners.

🛠️ Proposed fix
-        Events::trigger('payment_initiated', [
-            'payment_type' => $payment_type,
-            'amount' => $amount_tendered ?? 0,
-            'sale_id' => $this->sale_lib->get_sale_id(),
-            'customer_id' => $this->sale_lib->get_customer(),
-        ]);
+        if (!isset($data['error'])) {
+            Events::trigger('payment_initiated', [
+                'payment_type' => $payment_type,
+                'amount' => $amount_tendered ?? 0,
+                'sale_id' => $this->sale_lib->get_sale_id(),
+                'customer_id' => $this->sale_lib->get_customer(),
+            ]);
+        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Events::trigger('payment_initiated', [
'payment_type' => $payment_type,
'amount' => $amount_tendered ?? 0,
'sale_id' => $this->sale_lib->get_sale_id(),
'customer_id' => $this->sale_lib->get_customer(),
]);
if (!isset($data['error'])) {
Events::trigger('payment_initiated', [
'payment_type' => $payment_type,
'amount' => $amount_tendered ?? 0,
'sale_id' => $this->sale_lib->get_sale_id(),
'customer_id' => $this->sale_lib->get_customer(),
]);
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Controllers/Sales.php` around lines 475 - 480, The
Events::trigger('payment_initiated', ...) is firing even when validation fails;
update the flow in Sales.php so the trigger is executed only after a successful
payment add. Move the Events::trigger call to after the call that adds the
payment (e.g. after $this->sale_lib->add_payment(...) / wherever payment
persistence occurs) and guard it by checking that no validation error exists
(ensure $data['error'] is false/empty) and/or that the add_payment returned
success before calling Events::trigger('payment_initiated', ...).

Comment on lines +11 to +13
$forge = \Config\Services::forge();

$forge->addField([

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify migration is using service-based forge (problematic) vs migration-native forge.
rg -n "Services::forge\\(|\\$this->forge" app/Database/Migrations/20260401000000_PaymentTransactions.php

Repository: opensourcepos/opensourcepos

Length of output: 164


🏁 Script executed:

head -20 app/Database/Migrations/20260401000000_PaymentTransactions.php

Repository: opensourcepos/opensourcepos

Length of output: 537


🏁 Script executed:

rg -n "class.*Migration|extends" app/Database/Migrations/20260401000000_PaymentTransactions.php | head -5

Repository: opensourcepos/opensourcepos

Length of output: 126


🏁 Script executed:

find app/Database/Migrations -name "*.php" -type f | head -5

Repository: opensourcepos/opensourcepos

Length of output: 366


🏁 Script executed:

rg -n "forge" app/Database/Migrations/ -A 1 | head -40

Repository: opensourcepos/opensourcepos

Length of output: 3274


🌐 Web query:

CodeIgniter 4 Migration class $this->forge property

💡 Result:

In CodeIgniter 4 Migration classes (which extend CodeIgniter\Database\Migration), the $this->forge property provides access to the Database Forge class instance. This allows schema modifications like creating/dropping tables, adding fields, and keys within the up and down methods. Example from official documentation: public function up { $this->forge->addField([ 'blog_id' => [ 'type' => 'INT', 'constraint' => 5, 'unsigned' => true, 'auto_increment' => true, ], // other fields... ]); $this->forge->addKey('blog_id', true); $this->forge->createTable('blog'); } public function down { $this->forge->dropTable('blog'); } The Forge class is automatically available as $this->forge in migration classes, alongside $this->db for direct queries. This changed from CI3's $this->dbforge->add_field to $this->forge->addField (camelCase methods).

Citations:


🏁 Script executed:

rg -n "\\$this->forge" app/Database/Migrations/ | head -20

Repository: opensourcepos/opensourcepos

Length of output: 53


Replace Services::forge() with $this->forge in migration class.

CodeIgniter 4 migrations automatically provide the $this->forge property via the Migration base class. Using \Config\Services::forge() is not initialized in the migration context and causes runtime failures (the pipeline error addField() on null at line 13 confirms this). Replace all instances at lines 11, 78, and any other uses with $this->forge.

Diff
-        $forge = \Config\Services::forge();
-        
-        $forge->addField([
+        $this->forge->addField([
             'id' => [
@@
-        $forge->addKey('id', true);
-        $forge->addKey('provider_id');
-        $forge->addKey('sale_id');
-        $forge->addKey('transaction_id');
-        $forge->addKey('status');
-        
-        $forge->createTable('payment_transactions', true);
+        $this->forge->addKey('id', true);
+        $this->forge->addKey('provider_id');
+        $this->forge->addKey('sale_id');
+        $this->forge->addKey('transaction_id');
+        $this->forge->addKey('status');
+        
+        $this->forge->createTable('payment_transactions', true);
@@
-        $forge = \Config\Services::forge();
-        $forge->dropTable('payment_transactions', true);
+        $this->forge->dropTable('payment_transactions', true);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$forge = \Config\Services::forge();
$forge->addField([
$this->forge->addField([
🧰 Tools
🪛 GitHub Actions: PHPUnit Tests

[error] 13-13: Database migration failed during test setup: Call to a member function addField() on null in migration file.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Database/Migrations/20260401000000_PaymentTransactions.php` around lines
11 - 13, The migration uses \Config\Services::forge() which isn't initialized in
Migration context and causes null errors; replace all uses of
\Config\Services::forge() (e.g. the variable $forge and calls like
$forge->addField(...), $forge->addKey(...), $forge->createTable(...)) with the
Migration-provided $this->forge instance (e.g. $this->forge->addField(...),
$this->forge->addKey(...), $this->forge->createTable(...)) and remove any local
$forge variable declarations so the class uses $this->forge consistently.

Comment on lines +68 to +79
public function saveSettings(array $settings): bool
{
$settingsModel = model(\App\Models\Appconfig::class);
$prefix = $this->getSettingsPrefix();

foreach ($settings as $key => $value) {
$fullKey = $prefix . '_' . $key;
$settingsModel->save(['key' => $fullKey, 'value' => $value]);
}

return true;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: saveSettings() passes incorrect data format to Appconfig::save().

Based on the Appconfig::save() method signature (from context snippet at app/Models/Appconfig.php:77-90), it expects an associative array like [$key => $value], but this code passes ['key' => $fullKey, 'value' => $value]. The Appconfig model extracts the first key-value pair using array_keys($data)[0], so it will interpret 'key' as the config key name and the actual key string as the value.

This will cause all provider settings to be saved incorrectly, breaking isAvailable() and all configuration functionality.

🐛 Proposed fix
 public function saveSettings(array $settings): bool
 {
     $settingsModel = model(\App\Models\Appconfig::class);
     $prefix = $this->getSettingsPrefix();
     
     foreach ($settings as $key => $value) {
         $fullKey = $prefix . '_' . $key;
-        $settingsModel->save(['key' => $fullKey, 'value' => $value]);
+        $settingsModel->save([$fullKey => $value]);
     }
     
     return true;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Libraries/Payments/PaymentProviderBase.php` around lines 68 - 79, The
saveSettings method is passing the wrong shape to Appconfig::save; instead of an
array with 'key' and 'value' keys you must pass an associative array where the
config key maps to its value. Update PaymentProviderBase::saveSettings (use
$settingsModel and getSettingsPrefix()) to call Appconfig::save with [$fullKey
=> $value] for each entry (i.e., use the full composed key as the array key and
the setting value as its value) so Appconfig::save receives the expected [$key
=> $value] format.

⚠️ Potential issue | 🟡 Minor

saveSettings() always returns true regardless of save failures.

Individual save operations may fail, but the method unconditionally returns true. Consider tracking failures and returning false if any save operation fails.

🛡️ Proposed fix to track save failures
 public function saveSettings(array $settings): bool
 {
     $settingsModel = model(\App\Models\Appconfig::class);
     $prefix = $this->getSettingsPrefix();
+    $success = true;
     
     foreach ($settings as $key => $value) {
         $fullKey = $prefix . '_' . $key;
-        $settingsModel->save([$fullKey => $value]);
+        if (!$settingsModel->save([$fullKey => $value])) {
+            $success = false;
+        }
     }
     
-    return true;
+    return $success;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public function saveSettings(array $settings): bool
{
$settingsModel = model(\App\Models\Appconfig::class);
$prefix = $this->getSettingsPrefix();
foreach ($settings as $key => $value) {
$fullKey = $prefix . '_' . $key;
$settingsModel->save(['key' => $fullKey, 'value' => $value]);
}
return true;
}
public function saveSettings(array $settings): bool
{
$settingsModel = model(\App\Models\Appconfig::class);
$prefix = $this->getSettingsPrefix();
$success = true;
foreach ($settings as $key => $value) {
$fullKey = $prefix . '_' . $key;
if (!$settingsModel->save(['key' => $fullKey, 'value' => $value])) {
$success = false;
}
}
return $success;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Libraries/Payments/PaymentProviderBase.php` around lines 68 - 79, The
saveSettings() method currently always returns true even if individual
$settingsModel->save(...) calls fail; update saveSettings() to track each save
result (call return value or wrap save in try/catch) and set a failure flag if
any save returns false or throws, then return false when any failure occurred
and true only if all saves succeeded; reference the saveSettings() function, the
$settingsModel variable (model(\App\Models\Appconfig::class)), the save(...)
calls, and getSettingsPrefix() so you locate and update the loop to check/save
results and handle exceptions accordingly.

Comment on lines +127 to +150
public function refund(string $transactionId, float $amount, string $reason = ''): array
{
$transaction = $this->getTransaction($transactionId);

if (!$transaction) {
return ['success' => false, 'error' => 'Transaction not found'];
}

if ($transaction['status'] !== 'completed') {
return ['success' => false, 'error' => 'Transaction cannot be refunded'];
}

$this->updateTransactionStatus($transactionId, 'refunded', [
'refund_amount' => $amount,
'refund_reason' => $reason,
]);

return [
'success' => true,
'transaction_id' => $transactionId,
'status' => 'refunded',
'refund_amount' => $amount,
];
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Missing validation: refund amount may exceed original transaction amount.

Same issue as in SumUpProvider: the refund() method accepts any amount without validating it against the original transaction amount.

🛡️ Proposed fix to validate refund amount
 public function refund(string $transactionId, float $amount, string $reason = ''): array
 {
     $transaction = $this->getTransaction($transactionId);
     
     if (!$transaction) {
         return ['success' => false, 'error' => 'Transaction not found'];
     }

     if ($transaction['status'] !== 'completed') {
         return ['success' => false, 'error' => 'Transaction cannot be refunded'];
     }

+    if ($amount <= 0 || $amount > (float)$transaction['amount']) {
+        return ['success' => false, 'error' => 'Invalid refund amount'];
+    }
+
     $this->updateTransactionStatus($transactionId, 'refunded', [
         'refund_amount' => $amount,
         'refund_reason' => $reason,
     ]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public function refund(string $transactionId, float $amount, string $reason = ''): array
{
$transaction = $this->getTransaction($transactionId);
if (!$transaction) {
return ['success' => false, 'error' => 'Transaction not found'];
}
if ($transaction['status'] !== 'completed') {
return ['success' => false, 'error' => 'Transaction cannot be refunded'];
}
$this->updateTransactionStatus($transactionId, 'refunded', [
'refund_amount' => $amount,
'refund_reason' => $reason,
]);
return [
'success' => true,
'transaction_id' => $transactionId,
'status' => 'refunded',
'refund_amount' => $amount,
];
}
public function refund(string $transactionId, float $amount, string $reason = ''): array
{
$transaction = $this->getTransaction($transactionId);
if (!$transaction) {
return ['success' => false, 'error' => 'Transaction not found'];
}
if ($transaction['status'] !== 'completed') {
return ['success' => false, 'error' => 'Transaction cannot be refunded'];
}
if ($amount <= 0 || $amount > (float)$transaction['amount']) {
return ['success' => false, 'error' => 'Invalid refund amount'];
}
$this->updateTransactionStatus($transactionId, 'refunded', [
'refund_amount' => $amount,
'refund_reason' => $reason,
]);
return [
'success' => true,
'transaction_id' => $transactionId,
'status' => 'refunded',
'refund_amount' => $amount,
];
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Libraries/Payments/Providers/PayPalProvider.php` around lines 127 - 150,
The refund() method in PayPalProvider accepts any amount without validating it
against the original transaction; update the refund flow in refund(string
$transactionId, float $amount, string $reason = '') to (1) fetch the original
transaction via getTransaction($transactionId), (2) verify $amount is positive
and does not exceed the transaction's original amount (e.g.,
$transaction['amount'] or equivalent field), and (3) return a failure array like
['success' => false, 'error' => 'Invalid refund amount'] when validation fails;
only call updateTransactionStatus($transactionId, 'refunded', ...) and return
success when the amount is valid.

Comment on lines +119 to +142
public function refund(string $transactionId, float $amount, string $reason = ''): array
{
$transaction = $this->getTransaction($transactionId);

if (!$transaction) {
return ['success' => false, 'error' => 'Transaction not found'];
}

if ($transaction['status'] !== 'completed') {
return ['success' => false, 'error' => 'Transaction cannot be refunded'];
}

$this->updateTransactionStatus($transactionId, 'refunded', [
'refund_amount' => $amount,
'refund_reason' => $reason,
]);

return [
'success' => true,
'transaction_id' => $transactionId,
'status' => 'refunded',
'refund_amount' => $amount,
];
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Missing validation: refund amount may exceed original transaction amount.

The refund() method accepts any $amount value without validating that it doesn't exceed the original transaction amount. This could result in over-refunding or invalid refund records.

🛡️ Proposed fix to validate refund amount
 public function refund(string $transactionId, float $amount, string $reason = ''): array
 {
     $transaction = $this->getTransaction($transactionId);
     
     if (!$transaction) {
         return ['success' => false, 'error' => 'Transaction not found'];
     }

     if ($transaction['status'] !== 'completed') {
         return ['success' => false, 'error' => 'Transaction cannot be refunded'];
     }

+    if ($amount <= 0 || $amount > (float)$transaction['amount']) {
+        return ['success' => false, 'error' => 'Invalid refund amount'];
+    }
+
     $this->updateTransactionStatus($transactionId, 'refunded', [
         'refund_amount' => $amount,
         'refund_reason' => $reason,
     ]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public function refund(string $transactionId, float $amount, string $reason = ''): array
{
$transaction = $this->getTransaction($transactionId);
if (!$transaction) {
return ['success' => false, 'error' => 'Transaction not found'];
}
if ($transaction['status'] !== 'completed') {
return ['success' => false, 'error' => 'Transaction cannot be refunded'];
}
$this->updateTransactionStatus($transactionId, 'refunded', [
'refund_amount' => $amount,
'refund_reason' => $reason,
]);
return [
'success' => true,
'transaction_id' => $transactionId,
'status' => 'refunded',
'refund_amount' => $amount,
];
}
public function refund(string $transactionId, float $amount, string $reason = ''): array
{
$transaction = $this->getTransaction($transactionId);
if (!$transaction) {
return ['success' => false, 'error' => 'Transaction not found'];
}
if ($transaction['status'] !== 'completed') {
return ['success' => false, 'error' => 'Transaction cannot be refunded'];
}
if ($amount <= 0 || $amount > (float)$transaction['amount']) {
return ['success' => false, 'error' => 'Invalid refund amount'];
}
$this->updateTransactionStatus($transactionId, 'refunded', [
'refund_amount' => $amount,
'refund_reason' => $reason,
]);
return [
'success' => true,
'transaction_id' => $transactionId,
'status' => 'refunded',
'refund_amount' => $amount,
];
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Libraries/Payments/Providers/SumUpProvider.php` around lines 119 - 142,
The refund() method currently allows any $amount, risking over-refunds; modify
refund() to first read the original transaction amount from
getTransaction($transactionId) (e.g., $transaction['amount']) and any existing
refunded amount if tracked, validate that $amount is > 0 and does not exceed the
remaining refundable balance (original amount minus already refunded), and
return a failure array like ['success' => false, 'error' => 'Refund amount
exceeds original transaction amount'] when validation fails; only call
updateTransactionStatus($transactionId, 'refunded', ...) and return success when
the amount is valid (consider updating how refunded totals are stored if partial
refunds are supported).

Comment on lines +35 to +47
public function getTransaction(string $transactionId, ?string $providerId = null): ?array
{
$builder = $this->builder();
$builder->where('transaction_id', $transactionId);

if ($providerId !== null) {
$builder->where('provider_id', $providerId);
}

$result = $builder->get()->getRowArray();

return $result;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Scope getTransaction() by provider to avoid cross-provider record mismatches.

When Line 40 is skipped, lookup is only by transaction_id, which can return the wrong row if IDs collide across providers. This risks updating/refunding the wrong transaction.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Models/PaymentTransaction.php` around lines 35 - 47, getTransaction
currently allows a null $providerId which lets the query match only on
transaction_id and risk cross-provider collisions; change getTransaction(string
$transactionId, ?string $providerId = null) so the provider is always enforced:
either make $providerId a required string parameter (remove the ? and default)
or add an explicit guard that throws an InvalidArgumentException when
$providerId is null, and then always call $builder->where('provider_id',
$providerId) before executing get()->getRowArray(); reference the getTransaction
method and the builder->where('provider_id', ...) call when making the fix.

Comment on lines +75 to +77
$existingMetadata = json_decode($existing['metadata'] ?? '{}', true);
$data['metadata'] = json_encode(array_merge($existingMetadata, $additionalData['metadata']));
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Guard metadata merge against malformed/empty JSON.

If json_decode() returns null on Line 75, array_merge() on Line 76 will throw a TypeError in PHP 8.1+.

🛠️ Proposed fix
-                $existingMetadata = json_decode($existing['metadata'] ?? '{}', true);
-                $data['metadata'] = json_encode(array_merge($existingMetadata, $additionalData['metadata']));
+                $existingMetadata = json_decode($existing['metadata'] ?? '{}', true);
+                if (!is_array($existingMetadata)) {
+                    $existingMetadata = [];
+                }
+                $incomingMetadata = is_array($additionalData['metadata']) ? $additionalData['metadata'] : [];
+                $data['metadata'] = json_encode(array_merge($existingMetadata, $incomingMetadata));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$existingMetadata = json_decode($existing['metadata'] ?? '{}', true);
$data['metadata'] = json_encode(array_merge($existingMetadata, $additionalData['metadata']));
}
$existingMetadata = json_decode($existing['metadata'] ?? '{}', true);
if (!is_array($existingMetadata)) {
$existingMetadata = [];
}
$incomingMetadata = is_array($additionalData['metadata']) ? $additionalData['metadata'] : [];
$data['metadata'] = json_encode(array_merge($existingMetadata, $incomingMetadata));
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/Models/PaymentTransaction.php` around lines 75 - 77, The metadata merge
is not guarded against json_decode returning null: ensure the result of
json_decode($existing['metadata'] ?? '{}', true) is an array before calling
array_merge on $existingMetadata; if it is null or not an array, treat it as an
empty array, and likewise ensure $additionalData['metadata'] is an array (or
decode it) before merging, then json_encode the merged array into
$data['metadata']; look for the code in the PaymentTransaction class around the
$existingMetadata and $data['metadata'] assignments to apply this defensive
check.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: SumUp integration. [Feature]: PayPal In Store (POS/Zettle) Integration

2 participants