Open-source event management and ticket selling platform — perfect for concerts, conferences, and everything in between 🎟️ If you find this project helpful, please consider giving us a star ⭐️
PHP attendize-alternativedoor-managementevent-check-inevent-managementevent-registrationevent-ticketingeventbrite-alternativeeventslaravelopen-sourcephpreactself-hostedsell-ticketssell-tickets-onlineticket-sellingticketing-systemtickettailor-alternativetito-alternative
Feature: Store Stripe platform fees (#869)
Dave Earley60c3f4c6d4ec
diff --git a/backend/app/DomainObjects/Generated/OrderPaymentPlatformFeeDomainObjectAbstract.php b/backend/app/DomainObjects/Generated/OrderPaymentPlatformFeeDomainObjectAbstract.phpnew file mode 100644index 000000000..1b0627db1--- /dev/null+++ b/backend/app/DomainObjects/Generated/OrderPaymentPlatformFeeDomainObjectAbstract.php@@ -0,0 +1,188 @@+<?php++namespace HiEvents\DomainObjects\Generated;++/**+ * THIS FILE IS AUTOGENERATED - DO NOT EDIT IT DIRECTLY.+ * @package HiEvents\DomainObjects\Generated+ */+abstract class OrderPaymentPlatformFeeDomainObjectAbstract extends \HiEvents\DomainObjects\AbstractDomainObject+{+ final public const SINGULAR_NAME = 'order_payment_platform_fee';+ final public const PLURAL_NAME = 'order_payment_platform_fees';+ final public const ID = 'id';+ final public const ORDER_ID = 'order_id';+ final public const PAYMENT_PLATFORM = 'payment_platform';+ final public const FEE_ROLLUP = 'fee_rollup';+ final public const PAYMENT_PLATFORM_FEE_AMOUNT = 'payment_platform_fee_amount';+ final public const APPLICATION_FEE_AMOUNT = 'application_fee_amount';+ final public const CURRENCY = 'currency';+ final public const TRANSACTION_ID = 'transaction_id';+ final public const PAID_AT = 'paid_at';+ final public const DELETED_AT = 'deleted_at';+ final public const CREATED_AT = 'created_at';+ final public const UPDATED_AT = 'updated_at';++ protected int $id;+ protected int $order_id;+ protected string $payment_platform;+ protected array|string|null $fee_rollup = null;+ protected float $payment_platform_fee_amount;+ protected float $application_fee_amount = 0.0;+ protected string $currency = 'USD';+ protected ?string $transaction_id = null;+ protected ?string $paid_at = null;+ protected ?string $deleted_at = null;+ protected ?string $created_at = null;+ protected ?string $updated_at = null;++ public function toArray(): array+ {+ return [+ 'id' => $this->id ?? null,+ 'order_id' => $this->order_id ?? null,+ 'payment_platform' => $this->payment_platform ?? null,+ 'fee_rollup' => $this->fee_rollup ?? null,+ 'payment_platform_fee_amount' => $this->payment_platform_fee_amount ?? null,+ 'application_fee_amount' => $this->application_fee_amount ?? null,+ 'currency' => $this->currency ?? null,+ 'transaction_id' => $this->transaction_id ?? null,+ 'paid_at' => $this->paid_at ?? null,+ 'deleted_at' => $this->deleted_at ?? null,+ 'created_at' => $this->created_at ?? null,+ 'updated_at' => $this->updated_at ?? null,+ ];+ }++ public function setId(int $id): self+ {+ $this->id = $id;+ return $this;+ }++ public function getId(): int+ {+ return $this->id;+ }++ public function setOrderId(int $order_id): self+ {+ $this->order_id = $order_id;+ return $this;+ }++ public function getOrderId(): int+ {+ return $this->order_id;+ }++ public function setPaymentPlatform(string $payment_platform): self+ {+ $this->payment_platform = $payment_platform;+ return $this;+ }++ public function getPaymentPlatform(): string+ {+ return $this->payment_platform;+ }++ public function setFeeRollup(array|string|null $fee_rollup): self+ {+ $this->fee_rollup = $fee_rollup;+ return $this;+ }++ public function getFeeRollup(): array|string|null+ {+ return $this->fee_rollup;+ }++ public function setPaymentPlatformFeeAmount(float $payment_platform_fee_amount): self+ {+ $this->payment_platform_fee_amount = $payment_platform_fee_amount;+ return $this;+ }++ public function getPaymentPlatformFeeAmount(): float+ {+ return $this->payment_platform_fee_amount;+ }++ public function setApplicationFeeAmount(float $application_fee_amount): self+ {+ $this->application_fee_amount = $application_fee_amount;+ return $this;+ }++ public function getApplicationFeeAmount(): float+ {+ return $this->application_fee_amount;+ }++ public function setCurrency(string $currency): self+ {+ $this->currency = $currency;+ return $this;+ }++ public function getCurrency(): string+ {+ return $this->currency;+ }++ public function setTransactionId(?string $transaction_id): self+ {+ $this->transaction_id = $transaction_id;+ return $this;+ }++ public function getTransactionId(): ?string+ {+ return $this->transaction_id;+ }++ public function setPaidAt(?string $paid_at): self+ {+ $this->paid_at = $paid_at;+ return $this;+ }++ public function getPaidAt(): ?string+ {+ return $this->paid_at;+ }++ public function setDeletedAt(?string $deleted_at): self+ {+ $this->deleted_at = $deleted_at;+ return $this;+ }++ public function getDeletedAt(): ?string+ {+ return $this->deleted_at;+ }++ public function setCreatedAt(?string $created_at): self+ {+ $this->created_at = $created_at;+ return $this;+ }++ public function getCreatedAt(): ?string+ {+ return $this->created_at;+ }++ public function setUpdatedAt(?string $updated_at): self+ {+ $this->updated_at = $updated_at;+ return $this;+ }++ public function getUpdatedAt(): ?string+ {+ return $this->updated_at;+ }+}diff --git a/backend/app/DomainObjects/OrderPaymentPlatformFeeDomainObject.php b/backend/app/DomainObjects/OrderPaymentPlatformFeeDomainObject.phpnew file mode 100644index 000000000..9c2c591bf--- /dev/null+++ b/backend/app/DomainObjects/OrderPaymentPlatformFeeDomainObject.php@@ -0,0 +1,7 @@+<?php++namespace HiEvents\DomainObjects;++class OrderPaymentPlatformFeeDomainObject extends Generated\OrderPaymentPlatformFeeDomainObjectAbstract+{+}diff --git a/backend/app/Models/OrderItem.php b/backend/app/Models/OrderItem.phpindex 788ccb6c5..f9a2d3630 100644--- a/backend/app/Models/OrderItem.php+++ b/backend/app/Models/OrderItem.php@@ -34,11 +34,6 @@ class OrderItem extends BaseModel];}- protected function getFillableFields(): array- {- return [];- }-public function product_price(): HasOne{return $this->hasOne(ProductPrice::class);diff --git a/backend/app/Models/OrderPaymentPlatformFee.php b/backend/app/Models/OrderPaymentPlatformFee.phpnew file mode 100644index 000000000..66468a593--- /dev/null+++ b/backend/app/Models/OrderPaymentPlatformFee.php@@ -0,0 +1,23 @@+<?php++namespace HiEvents\Models;++use Illuminate\Database\Eloquent\Relations\BelongsTo;+use Illuminate\Database\Eloquent\SoftDeletes;++class OrderPaymentPlatformFee extends BaseModel+{+ use SoftDeletes;++ protected function getCastMap(): array+ {+ return [+ 'fee_rollup' => 'array',+ ];+ }++ public function order(): BelongsTo+ {+ return $this->belongsTo(Order::class);+ }+}diff --git a/backend/app/Providers/RepositoryServiceProvider.php b/backend/app/Providers/RepositoryServiceProvider.phpindex 387c4dfe4..200079b8a 100644--- a/backend/app/Providers/RepositoryServiceProvider.php+++ b/backend/app/Providers/RepositoryServiceProvider.php@@ -23,6 +23,7 @@ use HiEvents\Repository\Eloquent\InvoiceRepository;use HiEvents\Repository\Eloquent\MessageRepository;use HiEvents\Repository\Eloquent\OrderApplicationFeeRepository;use HiEvents\Repository\Eloquent\OrderItemRepository;+use HiEvents\Repository\Eloquent\OrderPaymentPlatformFeeRepository;use HiEvents\Repository\Eloquent\OrderRefundRepository;use HiEvents\Repository\Eloquent\OrderRepository;use HiEvents\Repository\Eloquent\OrganizerRepository;@@ -62,6 +63,7 @@ use HiEvents\Repository\Interfaces\InvoiceRepositoryInterface;use HiEvents\Repository\Interfaces\MessageRepositoryInterface;use HiEvents\Repository\Interfaces\OrderApplicationFeeRepositoryInterface;use HiEvents\Repository\Interfaces\OrderItemRepositoryInterface;+use HiEvents\Repository\Interfaces\OrderPaymentPlatformFeeRepositoryInterface;use HiEvents\Repository\Interfaces\OrderRefundRepositoryInterface;use HiEvents\Repository\Interfaces\OrderRepositoryInterface;use HiEvents\Repository\Interfaces\OrganizerRepositoryInterface;@@ -123,6 +125,7 @@ class RepositoryServiceProvider extends ServiceProviderWebhookRepositoryInterface::class => WebhookRepository::class,WebhookLogRepositoryInterface::class => WebhookLogRepository::class,OrderApplicationFeeRepositoryInterface::class => OrderApplicationFeeRepository::class,+ OrderPaymentPlatformFeeRepositoryInterface::class => OrderPaymentPlatformFeeRepository::class,AccountConfigurationRepositoryInterface::class => AccountConfigurationRepository::class,QuestionAndAnswerViewRepositoryInterface::class => QuestionAndAnswerViewRepository::class,OutgoingMessageRepositoryInterface::class => OutgoingMessageRepository::class,diff --git a/backend/app/Repository/Eloquent/OrderPaymentPlatformFeeRepository.php b/backend/app/Repository/Eloquent/OrderPaymentPlatformFeeRepository.phpnew file mode 100644index 000000000..7cfa12cfa--- /dev/null+++ b/backend/app/Repository/Eloquent/OrderPaymentPlatformFeeRepository.php@@ -0,0 +1,20 @@+<?php++namespace HiEvents\Repository\Eloquent;++use HiEvents\DomainObjects\OrderPaymentPlatformFeeDomainObject;+use HiEvents\Models\OrderPaymentPlatformFee;+use HiEvents\Repository\Interfaces\OrderPaymentPlatformFeeRepositoryInterface;++class OrderPaymentPlatformFeeRepository extends BaseRepository implements OrderPaymentPlatformFeeRepositoryInterface+{+ protected function getModel(): string+ {+ return OrderPaymentPlatformFee::class;+ }++ public function getDomainObject(): string+ {+ return OrderPaymentPlatformFeeDomainObject::class;+ }+}diff --git a/backend/app/Repository/Interfaces/OrderPaymentPlatformFeeRepositoryInterface.php b/backend/app/Repository/Interfaces/OrderPaymentPlatformFeeRepositoryInterface.phpnew file mode 100644index 000000000..86aa5190a--- /dev/null+++ b/backend/app/Repository/Interfaces/OrderPaymentPlatformFeeRepositoryInterface.php@@ -0,0 +1,14 @@+<?php++namespace HiEvents\Repository\Interfaces;++use HiEvents\DomainObjects\OrderPaymentPlatformFeeDomainObject;+use HiEvents\Repository\Eloquent\BaseRepository;++/**+ * @extends BaseRepository<OrderPaymentPlatformFeeDomainObject>+ */+interface OrderPaymentPlatformFeeRepositoryInterface extends RepositoryInterface+{++}diff --git a/backend/app/Services/Application/Handlers/Order/Payment/Stripe/IncomingWebhookHandler.php b/backend/app/Services/Application/Handlers/Order/Payment/Stripe/IncomingWebhookHandler.phpindex 4eef8a6e0..b5deb944b 100644--- a/backend/app/Services/Application/Handlers/Order/Payment/Stripe/IncomingWebhookHandler.php+++ b/backend/app/Services/Application/Handlers/Order/Payment/Stripe/IncomingWebhookHandler.php@@ -6,6 +6,7 @@ use HiEvents\Exceptions\CannotAcceptPaymentException;use HiEvents\Services\Application\Handlers\Order\Payment\Stripe\DTO\StripeWebhookDTO;use HiEvents\Services\Domain\Payment\Stripe\EventHandlers\AccountUpdateHandler;use HiEvents\Services\Domain\Payment\Stripe\EventHandlers\ChargeRefundUpdatedHandler;+use HiEvents\Services\Domain\Payment\Stripe\EventHandlers\ChargeSucceededHandler;use HiEvents\Services\Domain\Payment\Stripe\EventHandlers\PaymentIntentFailedHandler;use HiEvents\Services\Domain\Payment\Stripe\EventHandlers\PaymentIntentSucceededHandler;use Illuminate\Cache\Repository;@@ -25,10 +26,13 @@ class IncomingWebhookHandlerEvent::PAYMENT_INTENT_PAYMENT_FAILED,Event::ACCOUNT_UPDATED,Event::REFUND_UPDATED,+ Event::CHARGE_SUCCEEDED,+ Event::CHARGE_UPDATED,];public function __construct(private readonly ChargeRefundUpdatedHandler $refundEventHandlerService,+ private readonly ChargeSucceededHandler $chargeSucceededHandler,private readonly PaymentIntentSucceededHandler $paymentIntentSucceededHandler,private readonly PaymentIntentFailedHandler $paymentIntentFailedHandler,private readonly AccountUpdateHandler $accountUpdateHandler,@@ -70,7 +74,7 @@ class IncomingWebhookHandlerreturn;}- $this->logger->debug('Stripe event received', $event->data->object->toArray());+ $this->logger->debug('Stripe event received: ' . $event->type, $event->data->object->toArray());switch ($event->type) {case Event::PAYMENT_INTENT_SUCCEEDED:@@ -79,6 +83,10 @@ class IncomingWebhookHandlercase Event::PAYMENT_INTENT_PAYMENT_FAILED:$this->paymentIntentFailedHandler->handleEvent($event->data->object);break;+ case Event::CHARGE_SUCCEEDED:+ case Event::CHARGE_UPDATED:+ $this->chargeSucceededHandler->handleEvent($event->data->object);+ break;case Event::REFUND_UPDATED:$this->refundEventHandlerService->handleEvent($event->data->object);break;diff --git a/backend/app/Services/Domain/EventStatistics/EventStatisticsIncrementService.php b/backend/app/Services/Domain/EventStatistics/EventStatisticsIncrementService.phpindex 47921a279..d6b7a1b82 100644--- a/backend/app/Services/Domain/EventStatistics/EventStatisticsIncrementService.php+++ b/backend/app/Services/Domain/EventStatistics/EventStatisticsIncrementService.php@@ -48,10 +48,10 @@ class EventStatisticsIncrementService->findById($order->getId());$this->retrier->retry(- callableAction: function (int $attempt) use ($order): void {- $this->databaseManager->transaction(function () use ($order, $attempt): void {- $this->incrementAggregateStatistics($order, $attempt);- $this->incrementDailyStatistics($order, $attempt);+ callableAction: function () use ($order): void {+ $this->databaseManager->transaction(function () use ($order): void {+ $this->incrementAggregateStatistics($order);+ $this->incrementDailyStatistics($order);$this->incrementPromoCodeUsage($order);$this->incrementProductStatistics($order);});diff --git a/backend/app/Services/Domain/Order/OrderPaymentPlatformFeeService.php b/backend/app/Services/Domain/Order/OrderPaymentPlatformFeeService.phpnew file mode 100644index 000000000..05af58ed2--- /dev/null+++ b/backend/app/Services/Domain/Order/OrderPaymentPlatformFeeService.php@@ -0,0 +1,48 @@+<?php++namespace HiEvents\Services\Domain\Order;++use HiEvents\DomainObjects\Generated\OrderPaymentPlatformFeeDomainObjectAbstract;+use HiEvents\Helper\Currency;+use HiEvents\Repository\Interfaces\OrderPaymentPlatformFeeRepositoryInterface;++class OrderPaymentPlatformFeeService+{+ public function __construct(+ private readonly OrderPaymentPlatformFeeRepositoryInterface $orderPaymentPlatformFeeRepository,+ )+ {+ }++ public function createOrderPaymentPlatformFee(+ int $orderId,+ string $paymentPlatform,+ ?array $feeRollup,+ int $paymentPlatformFeeAmountMinorUnit,+ int $applicationFeeAmountMinorUnit,+ string $currency,+ ?string $transactionId = null,+ ): void+ {+ $isZeroDecimalCurrency = Currency::isZeroDecimalCurrency($currency);++ $paymentPlatformFeeAmount = $isZeroDecimalCurrency+ ? $paymentPlatformFeeAmountMinorUnit+ : $paymentPlatformFeeAmountMinorUnit / 100;++ $applicationFeeAmount = $isZeroDecimalCurrency+ ? $applicationFeeAmountMinorUnit+ : $applicationFeeAmountMinorUnit / 100;++ $this->orderPaymentPlatformFeeRepository->create([+ OrderPaymentPlatformFeeDomainObjectAbstract::ORDER_ID => $orderId,+ OrderPaymentPlatformFeeDomainObjectAbstract::PAYMENT_PLATFORM => $paymentPlatform,+ OrderPaymentPlatformFeeDomainObjectAbstract::FEE_ROLLUP => $feeRollup,+ OrderPaymentPlatformFeeDomainObjectAbstract::PAYMENT_PLATFORM_FEE_AMOUNT => $paymentPlatformFeeAmount,+ OrderPaymentPlatformFeeDomainObjectAbstract::APPLICATION_FEE_AMOUNT => $applicationFeeAmount,+ OrderPaymentPlatformFeeDomainObjectAbstract::CURRENCY => strtoupper($currency),+ OrderPaymentPlatformFeeDomainObjectAbstract::TRANSACTION_ID => $transactionId,+ OrderPaymentPlatformFeeDomainObjectAbstract::PAID_AT => now()->toDateTimeString(),+ ]);+ }+}diff --git a/backend/app/Services/Domain/Payment/Stripe/EventHandlers/ChargeSucceededHandler.php b/backend/app/Services/Domain/Payment/Stripe/EventHandlers/ChargeSucceededHandler.phpnew file mode 100644index 000000000..fdaee890e--- /dev/null+++ b/backend/app/Services/Domain/Payment/Stripe/EventHandlers/ChargeSucceededHandler.php@@ -0,0 +1,71 @@+<?php++namespace HiEvents\Services\Domain\Payment\Stripe\EventHandlers;++use HiEvents\DomainObjects\Generated\StripePaymentDomainObjectAbstract;+use HiEvents\DomainObjects\OrderDomainObject;+use HiEvents\DomainObjects\StripePaymentDomainObject;+use HiEvents\Repository\Eloquent\StripePaymentsRepository;+use HiEvents\Repository\Eloquent\Value\Relationship;+use HiEvents\Services\Domain\Payment\Stripe\StripePaymentPlatformFeeExtractionService;+use Psr\Log\LoggerInterface;+use Stripe\Charge;++class ChargeSucceededHandler+{+ public function __construct(+ private readonly StripePaymentsRepository $stripePaymentsRepository,+ private readonly StripePaymentPlatformFeeExtractionService $platformFeeExtractionService,+ private readonly LoggerInterface $logger,+ )+ {+ }++ public function handleEvent(Charge $charge): void+ {+ $this->logger->info(__('Processing charge event'), [+ 'charge_id' => $charge->id,+ 'payment_intent_id' => $charge->payment_intent,+ 'status' => $charge->status,+ ]);++ if ($charge->status !== 'succeeded') {+ $this->logger->info(__('Charge not in succeeded status, skipping'), [+ 'charge_id' => $charge->id,+ 'status' => $charge->status,+ ]);+ return;+ }++ /**@var StripePaymentDomainObject $stripePayment */+ $stripePayment = $this->stripePaymentsRepository+ ->loadRelation(new Relationship(OrderDomainObject::class, name: 'order'))+ ->findFirstWhere([+ StripePaymentDomainObjectAbstract::PAYMENT_INTENT_ID => $charge->payment_intent,+ ]);++ if (!$stripePayment) {+ $this->logger->warning(__('Stripe payment not found for charge'), [+ 'charge_id' => $charge->id,+ 'payment_intent_id' => $charge->payment_intent,+ ]);+ return;+ }++ $order = $stripePayment->getOrder();+ if (!$order) {+ $this->logger->warning(__('Order not found for charge'), [+ 'charge_id' => $charge->id,+ 'payment_intent_id' => $charge->payment_intent,+ 'stripe_payment_id' => $stripePayment->getId(),+ ]);+ return;+ }++ $this->platformFeeExtractionService->extractAndStorePlatformFee(+ order: $order,+ charge: $charge,+ stripePayment: $stripePayment+ );+ }+}diff --git a/backend/app/Services/Domain/Payment/Stripe/EventHandlers/PaymentIntentSucceededHandler.php b/backend/app/Services/Domain/Payment/Stripe/EventHandlers/PaymentIntentSucceededHandler.phpindex 5cb290978..790bb84a8 100644--- a/backend/app/Services/Domain/Payment/Stripe/EventHandlers/PaymentIntentSucceededHandler.php+++ b/backend/app/Services/Domain/Payment/Stripe/EventHandlers/PaymentIntentSucceededHandler.php@@ -39,17 +39,17 @@ use Throwable;class PaymentIntentSucceededHandler{public function __construct(- private readonly OrderRepositoryInterface $orderRepository,- private readonly StripePaymentsRepository $stripePaymentsRepository,- private readonly AffiliateRepositoryInterface $affiliateRepository,- private readonly ProductQuantityUpdateService $quantityUpdateService,- private readonly StripeRefundExpiredOrderService $refundExpiredOrderService,- private readonly AttendeeRepositoryInterface $attendeeRepository,- private readonly DatabaseManager $databaseManager,- private readonly LoggerInterface $logger,- private readonly Repository $cache,- private readonly DomainEventDispatcherService $domainEventDispatcherService,- private readonly OrderApplicationFeeService $orderApplicationFeeService,+ private readonly OrderRepositoryInterface $orderRepository,+ private readonly StripePaymentsRepository $stripePaymentsRepository,+ private readonly AffiliateRepositoryInterface $affiliateRepository,+ private readonly ProductQuantityUpdateService $quantityUpdateService,+ private readonly StripeRefundExpiredOrderService $refundExpiredOrderService,+ private readonly AttendeeRepositoryInterface $attendeeRepository,+ private readonly DatabaseManager $databaseManager,+ private readonly LoggerInterface $logger,+ private readonly Repository $cache,+ private readonly DomainEventDispatcherService $domainEventDispatcherService,+ private readonly OrderApplicationFeeService $orderApplicationFeeService,){}diff --git a/backend/app/Services/Domain/Payment/Stripe/StripePaymentPlatformFeeExtractionService.php b/backend/app/Services/Domain/Payment/Stripe/StripePaymentPlatformFeeExtractionService.phpnew file mode 100644index 000000000..6446a6047--- /dev/null+++ b/backend/app/Services/Domain/Payment/Stripe/StripePaymentPlatformFeeExtractionService.php@@ -0,0 +1,164 @@+<?php++namespace HiEvents\Services\Domain\Payment\Stripe;++use HiEvents\DomainObjects\Enums\PaymentProviders;+use HiEvents\DomainObjects\Generated\OrderPaymentPlatformFeeDomainObjectAbstract;+use HiEvents\DomainObjects\OrderDomainObject;+use HiEvents\DomainObjects\StripePaymentDomainObject;+use HiEvents\Repository\Interfaces\OrderPaymentPlatformFeeRepositoryInterface;+use HiEvents\Services\Domain\Order\OrderPaymentPlatformFeeService;+use HiEvents\Services\Infrastructure\Stripe\StripeClientFactory;+use Psr\Log\LoggerInterface;+use Stripe\Charge;+use Throwable;++class StripePaymentPlatformFeeExtractionService+{+ public function __construct(+ private readonly StripeClientFactory $stripeClientFactory,+ private readonly OrderPaymentPlatformFeeService $orderPaymentPlatformFeeService,+ private readonly OrderPaymentPlatformFeeRepositoryInterface $orderPaymentPlatformFeeRepository,+ private readonly LoggerInterface $logger,+ )+ {+ }++ public function extractAndStorePlatformFee(+ OrderDomainObject $order,+ Charge $charge,+ StripePaymentDomainObject $stripePayment+ ): void+ {+ try {+ $this->logger->info(__('Extracting platform fee for order'), [+ 'order_id' => $order->getId(),+ 'charge_id' => $charge->id,+ ]);++ if (!$charge->balance_transaction || is_string($charge->balance_transaction)) {+ $this->logger->info(__('Retrieving balance transaction from Stripe'), [+ 'charge_id' => $charge->id,+ 'order_id' => $order->getId(),+ 'connected_account_id' => $stripePayment->getConnectedAccountId(),+ 'balance_transaction_type' => gettype($charge->balance_transaction),+ ]);++ $stripeClient = $this->stripeClientFactory->createForPlatform(+ $stripePayment->getStripePlatformEnum()+ );++ $params = ['expand' => ['balance_transaction']];+ $opts = [];++ if ($stripePayment->getConnectedAccountId()) {+ $opts['stripe_account'] = $stripePayment->getConnectedAccountId();+ }++ $charge = $stripeClient->charges->retrieve($charge->id, $params, $opts);+ }++ if (!$charge->balance_transaction || is_string($charge->balance_transaction)) {+ $this->logger->warning(__('No balance transaction found for charge'), [+ 'charge_id' => $charge->id,+ 'order_id' => $order->getId(),+ ]);+ return;+ }++ $balanceTransaction = $charge->balance_transaction;++ $existingRecord = $this->orderPaymentPlatformFeeRepository->findFirstWhere([+ OrderPaymentPlatformFeeDomainObjectAbstract::ORDER_ID => $order->getId(),+ OrderPaymentPlatformFeeDomainObjectAbstract::TRANSACTION_ID => $balanceTransaction->id,+ ]);++ if ($existingRecord) {+ $this->logger->info(__('Platform fee already stored for this transaction'), [+ 'order_id' => $order->getId(),+ 'transaction_id' => $balanceTransaction->id,+ 'charge_id' => $charge->id,+ ]);+ return;+ }+ $feeDetails = $this->extractFeeDetails($balanceTransaction);++ $totalFee = $balanceTransaction->fee ?? 0;+ $applicationFee = $this->extractApplicationFee($feeDetails);+ $paymentPlatformFee = $this->extractStripeFee($feeDetails);++ $this->orderPaymentPlatformFeeService->createOrderPaymentPlatformFee(+ orderId: $order->getId(),+ paymentPlatform: PaymentProviders::STRIPE->value,+ feeRollup: [+ 'total_fee' => $totalFee,+ 'payment_platform_fee' => $paymentPlatformFee,+ 'application_fee' => $applicationFee,+ 'fee_details' => $feeDetails,+ 'net' => $balanceTransaction->net ?? 0,+ 'exchange_rate' => $balanceTransaction->exchange_rate ?? null,+ ],+ paymentPlatformFeeAmountMinorUnit: $paymentPlatformFee,+ applicationFeeAmountMinorUnit: $applicationFee,+ currency: $balanceTransaction->currency ?? $order->getCurrency(),+ transactionId: $balanceTransaction->id ?? null,+ );++ $this->logger->info(__('Platform fee stored successfully'), [+ 'order_id' => $order->getId(),+ 'total_fee' => $totalFee,+ 'payment_platform_fee' => $paymentPlatformFee,+ 'application_fee' => $applicationFee,+ 'currency' => strtoupper($balanceTransaction->currency ?? $order->getCurrency()),+ ]);+ } catch (Throwable $exception) {+ $this->logger->error(__('Failed to store platform fee'), [+ 'exception' => $exception->getMessage(),+ 'order_id' => $order->getId(),+ 'charge_id' => $charge->id,+ ]);++ throw $exception;+ }+ }++ private function extractFeeDetails($balanceTransaction): array+ {+ $feeDetails = [];++ if (isset($balanceTransaction->fee_details)) {+ foreach ($balanceTransaction->fee_details as $feeDetail) {+ $feeDetails[] = [+ 'type' => $feeDetail->type ?? null,+ 'amount' => $feeDetail->amount ?? 0,+ 'currency' => $feeDetail->currency ?? $balanceTransaction->currency,+ 'description' => $feeDetail->description ?? null,+ ];+ }+ }++ return $feeDetails;+ }++ private function extractStripeFee(array $feeDetails): int+ {+ foreach ($feeDetails as $detail) {+ if ($detail['type'] === 'stripe_fee') {+ return $detail['amount'];+ }+ }++ return 0;+ }++ private function extractApplicationFee(array $feeDetails): int+ {+ foreach ($feeDetails as $detail) {+ if ($detail['type'] === 'application_fee') {+ return $detail['amount'];+ }+ }++ return 0;+ }+}diff --git a/backend/database/migrations/2025_10_30_081843_create_order_payment_platform_fees_table.php b/backend/database/migrations/2025_10_30_081843_create_order_payment_platform_fees_table.phpnew file mode 100644index 000000000..a565b6e60--- /dev/null+++ b/backend/database/migrations/2025_10_30_081843_create_order_payment_platform_fees_table.php@@ -0,0 +1,40 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++return new class extends Migration+{+ /**+ * Run the migrations.+ */+ public function up(): void+ {+ Schema::create('order_payment_platform_fees', static function (Blueprint $table) {+ $table->id();++ $table->foreignId('order_id')+ ->constrained('orders')+ ->onDelete('cascade');+ $table->string('payment_platform', 50);+ $table->jsonb('fee_rollup')->nullable();+ $table->decimal('payment_platform_fee_amount', 10, 2);+ $table->decimal('application_fee_amount', 10, 2)->default(0);+ $table->string('currency', 10)->default('USD');+ $table->string('transaction_id')->nullable();+ $table->timestamp('paid_at')->nullable();++ $table->softDeletes();+ $table->timestamps();+ });+ }++ /**+ * Reverse the migrations.+ */+ public function down(): void+ {+ Schema::dropIfExists('order_payment_platform_fees');+ }+};diff --git a/backend/tests/Unit/Services/Domain/Payment/Stripe/StripePaymentPlatformFeeExtractionServiceTest.php b/backend/tests/Unit/Services/Domain/Payment/Stripe/StripePaymentPlatformFeeExtractionServiceTest.phpnew file mode 100644index 000000000..bc0985594--- /dev/null+++ b/backend/tests/Unit/Services/Domain/Payment/Stripe/StripePaymentPlatformFeeExtractionServiceTest.php@@ -0,0 +1,222 @@+<?php++namespace Tests\Unit\Services\Domain\Payment\Stripe;++use HiEvents\DomainObjects\OrderDomainObject;+use HiEvents\DomainObjects\StripePaymentDomainObject;+use HiEvents\Repository\Interfaces\OrderPaymentPlatformFeeRepositoryInterface;+use HiEvents\Services\Domain\Order\OrderPaymentPlatformFeeService;+use HiEvents\Services\Domain\Payment\Stripe\StripePaymentPlatformFeeExtractionService;+use HiEvents\Services\Infrastructure\Stripe\StripeClientFactory;+use Mockery as m;+use Psr\Log\LoggerInterface;+use Stripe\Charge;+use Tests\TestCase;++class StripePaymentPlatformFeeExtractionServiceTest extends TestCase+{+ private StripePaymentPlatformFeeExtractionService $service;+ private StripeClientFactory $stripeClientFactory;+ private OrderPaymentPlatformFeeService $orderPaymentPlatformFeeService;+ private OrderPaymentPlatformFeeRepositoryInterface $orderPaymentPlatformFeeRepository;+ private LoggerInterface $logger;++ protected function setUp(): void+ {+ parent::setUp();++ $this->stripeClientFactory = m::mock(StripeClientFactory::class);+ $this->orderPaymentPlatformFeeService = m::mock(OrderPaymentPlatformFeeService::class);+ $this->orderPaymentPlatformFeeRepository = m::mock(OrderPaymentPlatformFeeRepositoryInterface::class);+ $this->logger = m::mock(LoggerInterface::class);++ $this->service = new StripePaymentPlatformFeeExtractionService(+ $this->stripeClientFactory,+ $this->orderPaymentPlatformFeeService,+ $this->orderPaymentPlatformFeeRepository,+ $this->logger+ );+ }++ public function testExtractAndStorePlatformFeeNoBalanceTransaction(): void+ {+ $order = m::mock(OrderDomainObject::class);+ $order->shouldReceive('getId')->andReturn(123);++ $stripePayment = m::mock(StripePaymentDomainObject::class);+ $stripePayment->shouldReceive('getStripePlatformEnum')->andReturn(null);+ $stripePayment->shouldReceive('getConnectedAccountId')->andReturn(null);++ $charge = Charge::constructFrom([+ 'id' => 'ch_123',+ 'balance_transaction' => null,+ ]);++ $this->orderPaymentPlatformFeeRepository->shouldReceive('findFirstWhere')+ ->never();++ $this->logger->shouldReceive('info')+ ->with(__('Extracting platform fee for order'), [+ 'order_id' => 123,+ 'charge_id' => 'ch_123',+ ])+ ->once();++ $this->logger->shouldReceive('info')+ ->with(__('Retrieving balance transaction from Stripe'), [+ 'charge_id' => 'ch_123',+ 'order_id' => 123,+ 'connected_account_id' => null,+ 'balance_transaction_type' => 'NULL',+ ])+ ->once();++ $stripeClient = m::mock(\Stripe\StripeClient::class);+ $chargesService = m::mock();+ $stripeClient->charges = $chargesService;++ $this->stripeClientFactory->shouldReceive('createForPlatform')+ ->with(null)+ ->andReturn($stripeClient);++ $chargesService->shouldReceive('retrieve')+ ->with('ch_123', ['expand' => ['balance_transaction']], [])+ ->andReturn(Charge::constructFrom([+ 'id' => 'ch_123',+ 'balance_transaction' => null,+ ]));++ $this->logger->shouldReceive('warning')+ ->with(__('No balance transaction found for charge'), [+ 'charge_id' => 'ch_123',+ 'order_id' => 123,+ ])+ ->once();++ $this->orderPaymentPlatformFeeService->shouldNotReceive('createOrderPaymentPlatformFee');++ $this->service->extractAndStorePlatformFee($order, $charge, $stripePayment);++ $this->assertTrue(true);+ }++ public function testExtractAndStorePlatformFeeWithConnectedAccount(): void+ {+ $order = m::mock(OrderDomainObject::class);+ $order->shouldReceive('getId')->andReturn(123);++ $stripePayment = m::mock(StripePaymentDomainObject::class);+ $stripePayment->shouldReceive('getStripePlatformEnum')->andReturn(null);+ $stripePayment->shouldReceive('getConnectedAccountId')->andReturn('acct_123');++ $charge = Charge::constructFrom([+ 'id' => 'ch_123',+ 'balance_transaction' => null,+ ]);++ $this->orderPaymentPlatformFeeRepository->shouldReceive('findFirstWhere')+ ->never();++ $this->logger->shouldReceive('info')+ ->with(__('Extracting platform fee for order'), [+ 'order_id' => 123,+ 'charge_id' => 'ch_123',+ ])+ ->once();++ $this->logger->shouldReceive('info')+ ->with(__('Retrieving balance transaction from Stripe'), [+ 'charge_id' => 'ch_123',+ 'order_id' => 123,+ 'connected_account_id' => 'acct_123',+ 'balance_transaction_type' => 'NULL',+ ])+ ->once();++ $stripeClient = m::mock(\Stripe\StripeClient::class);+ $chargesService = m::mock();+ $stripeClient->charges = $chargesService;++ $this->stripeClientFactory->shouldReceive('createForPlatform')+ ->with(null)+ ->andReturn($stripeClient);++ $chargesService->shouldReceive('retrieve')+ ->with(+ 'ch_123',+ ['expand' => ['balance_transaction']],+ ['stripe_account' => 'acct_123']+ )+ ->andReturn(Charge::constructFrom([+ 'id' => 'ch_123',+ 'balance_transaction' => null,+ ]));++ $this->logger->shouldReceive('warning')+ ->with(__('No balance transaction found for charge'), [+ 'charge_id' => 'ch_123',+ 'order_id' => 123,+ ])+ ->once();++ $this->orderPaymentPlatformFeeService->shouldNotReceive('createOrderPaymentPlatformFee');++ $this->service->extractAndStorePlatformFee($order, $charge, $stripePayment);++ $this->assertTrue(true);+ }++ public function testExtractAndStorePlatformFeeHandlesException(): void+ {+ $order = m::mock(OrderDomainObject::class);+ $order->shouldReceive('getId')->andReturn(123);++ $stripePayment = m::mock(StripePaymentDomainObject::class);+ $stripePayment->shouldReceive('getStripePlatformEnum')->andReturn(null);+ $stripePayment->shouldReceive('getConnectedAccountId')->andReturn(null);++ $charge = Charge::constructFrom([+ 'id' => 'ch_123',+ 'balance_transaction' => null,+ ]);++ $this->orderPaymentPlatformFeeRepository->shouldReceive('findFirstWhere')+ ->never();++ $this->logger->shouldReceive('info')+ ->with(__('Extracting platform fee for order'), [+ 'order_id' => 123,+ 'charge_id' => 'ch_123',+ ])+ ->once();++ $this->logger->shouldReceive('info')+ ->with(__('Retrieving balance transaction from Stripe'), [+ 'charge_id' => 'ch_123',+ 'order_id' => 123,+ 'connected_account_id' => null,+ 'balance_transaction_type' => 'NULL',+ ])+ ->once();++ $this->stripeClientFactory->shouldReceive('createForPlatform')+ ->with(null)+ ->andThrow(new \Exception('Stripe API error'));++ $this->logger->shouldReceive('error')+ ->with(__('Failed to store platform fee'), m::type('array'))+ ->once();++ $this->orderPaymentPlatformFeeService->shouldNotReceive('createOrderPaymentPlatformFee');++ $this->expectException(\Exception::class);++ $this->service->extractAndStorePlatformFee($order, $charge, $stripePayment);+ }++ protected function tearDown(): void+ {+ m::close();+ parent::tearDown();+ }+}