Skip to content

Fix Stripe Currency bugs #484

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,6 @@ AWS_USE_PATH_STYLE_ENDPOINT=true

JWT_SECRET=2hoccgHb9r1fqW1lU16C6khSHVa7O0eai6FxkWK95UtQ0LqNDTO5mq1RzDwcq18I
JWT_ALGO=HS256

# Only required for SAAS mode and if your're charging fees
# OPEN_EXCHANGE_RATES_APP_ID=
24 changes: 24 additions & 0 deletions backend/app/Helper/Currency.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,30 @@

class Currency
{
private const ZERO_DECIMAL_CURRENCIES = [
'BIF',
'CLP',
'DJF',
'GNF',
'JPY',
'KMF',
'KRW',
'MGA',
'PYG',
'RWF',
'UGX',
'VND',
'VUV',
'XAF',
'XOF',
'XPF'
];

public static function isZeroDecimalCurrency(string $currencyCode): bool
{
return in_array(strtoupper($currencyCode), self::ZERO_DECIMAL_CURRENCIES, true);
}

public static function format(float|int $amount, string $currencyCode, string $locale = 'en_US'): string
{
$currencyCode = strtoupper($currencyCode);
Expand Down
25 changes: 25 additions & 0 deletions backend/app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
use HiEvents\DomainObjects\OrganizerDomainObject;
use HiEvents\Models\Event;
use HiEvents\Models\Organizer;
use HiEvents\Services\Infrastructure\CurrencyConversion\CurrencyConversionClientInterface;
use HiEvents\Services\Infrastructure\CurrencyConversion\NoOpCurrencyConversionClient;
use HiEvents\Services\Infrastructure\CurrencyConversion\OpenExchangeRatesCurrencyConversionClient;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
Expand All @@ -28,6 +31,7 @@ public function register(): void
{
$this->bindDoctrineConnection();
$this->bindStripeClient();
$this->bindCurrencyConversionClient();
}

/**
Expand Down Expand Up @@ -130,4 +134,25 @@ private function disableLazyLoading(): void
{
Model::preventLazyLoading(!app()->isProduction());
}

private function bindCurrencyConversionClient(): void
{
$this->app->bind(
CurrencyConversionClientInterface::class,
function () {
if (config('services.open_exchange_rates.app_id')) {
return new OpenExchangeRatesCurrencyConversionClient(
apiKey: config('services.open_exchange_rates.app_id'),
cache: $this->app->make('cache.store'),
logger: $this->app->make('log')
);
}

// Fallback to no-op client if no other client is available
return new NoOpCurrencyConversionClient(
logger: $this->app->make('log')
);
}
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
use Brick\Math\Exception\NumberFormatException;
use Brick\Math\Exception\RoundingNecessaryException;
use Brick\Money\Exception\UnknownCurrencyException;
use Brick\Money\Money;
use HiEvents\DomainObjects\AccountConfigurationDomainObject;
use HiEvents\DomainObjects\Generated\StripePaymentDomainObjectAbstract;
use HiEvents\DomainObjects\OrderItemDomainObject;
Expand All @@ -23,6 +22,7 @@
use HiEvents\Services\Domain\Payment\Stripe\DTOs\CreatePaymentIntentResponseDTO;
use HiEvents\Services\Domain\Payment\Stripe\StripePaymentIntentCreationService;
use HiEvents\Services\Infrastructure\Session\CheckoutSessionManagementService;
use HiEvents\Values\MoneyValue;
use Stripe\Exception\ApiErrorException;
use Throwable;

Expand Down Expand Up @@ -84,7 +84,7 @@ public function handle(string $orderShortId): CreatePaymentIntentResponseDTO
}

$paymentIntent = $this->stripePaymentService->createPaymentIntent(CreatePaymentIntentRequestDTO::fromArray([
'amount' => Money::of($order->getTotalGross(), $order->getCurrency())->getMinorAmount()->toInt(),
'amount' => MoneyValue::fromFloat($order->getTotalGross(), $order->getCurrency()),
'currencyCode' => $order->getCurrency(),
'account' => $account,
'order' => $order,
Expand Down
9 changes: 7 additions & 2 deletions backend/app/Services/Domain/Order/MarkOrderAsPaidService.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace HiEvents\Services\Domain\Order;

use Brick\Math\Exception\MathException;
use HiEvents\DomainObjects\AccountConfigurationDomainObject;
use HiEvents\DomainObjects\AccountDomainObject;
use HiEvents\DomainObjects\AttendeeDomainObject;
Expand Down Expand Up @@ -142,6 +143,9 @@ private function updateAttendeeStatuses(OrderDomainObject $updatedOrder): void
);
}

/**
* @throws MathException
*/
private function storeApplicationFeePayment(OrderDomainObject $updatedOrder): void
{
/** @var EventDomainObject $event */
Expand All @@ -163,13 +167,14 @@ private function storeApplicationFeePayment(OrderDomainObject $updatedOrder): vo

$this->orderApplicationFeeService->createOrderApplicationFee(
orderId: $updatedOrder->getId(),
applicationFeeAmount: $this->orderApplicationFeeCalculationService->calculateApplicationFee(
applicationFeeAmountMinorUnit: $this->orderApplicationFeeCalculationService->calculateApplicationFee(
$config,
$updatedOrder->getTotalGross(),
$event->getCurrency(),
)->toFloat(),
)->toMinorUnit(),
orderApplicationFeeStatus: OrderApplicationFeeStatus::AWAITING_PAYMENT,
paymentMethod: PaymentProviders::OFFLINE,
currency: $updatedOrder->getCurrency(),
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@

namespace HiEvents\Services\Domain\Order;

use Brick\Money\Currency;
use HiEvents\DomainObjects\AccountConfigurationDomainObject;
use HiEvents\Services\Infrastructure\CurrencyConversion\CurrencyConversionClientInterface;
use HiEvents\Values\MoneyValue;
use Illuminate\Config\Repository;

class OrderApplicationFeeCalculationService
{
private const BASE_CURRENCY = 'USD';

public function __construct(
private readonly Repository $config,
private readonly Repository $config,
private readonly CurrencyConversionClientInterface $currencyConversionClient
)
{
}
Expand All @@ -24,12 +29,28 @@ public function calculateApplicationFee(
return MoneyValue::zero($currency);
}

$fixedFee = $accountConfiguration->getFixedApplicationFee();
$fixedFee = $this->getConvertedFixedFee($accountConfiguration, $currency);
$percentageFee = $accountConfiguration->getPercentageApplicationFee();

return MoneyValue::fromFloat(
amount: $fixedFee + ($orderTotal * $percentageFee / 100),
amount: $fixedFee->toFloat() + ($orderTotal * $percentageFee / 100),
currency: $currency
);
}

private function getConvertedFixedFee(
AccountConfigurationDomainObject $accountConfiguration,
string $currency
): MoneyValue
{
if ($currency === self::BASE_CURRENCY) {
return MoneyValue::fromFloat($accountConfiguration->getFixedApplicationFee(), $currency);
}

return $this->currencyConversionClient->convert(
fromCurrency: Currency::of(self::BASE_CURRENCY),
toCurrency: Currency::of($currency),
amount: $accountConfiguration->getFixedApplicationFee()
);
}
}
11 changes: 10 additions & 1 deletion backend/app/Services/Domain/Order/OrderApplicationFeeService.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use HiEvents\DomainObjects\Enums\PaymentProviders;
use HiEvents\DomainObjects\Generated\OrderApplicationFeeDomainObjectAbstract;
use HiEvents\DomainObjects\Status\OrderApplicationFeeStatus;
use HiEvents\Helper\Currency;
use HiEvents\Repository\Interfaces\OrderApplicationFeeRepositoryInterface;

class OrderApplicationFeeService
Expand All @@ -17,16 +18,24 @@ public function __construct(

public function createOrderApplicationFee(
int $orderId,
float $applicationFeeAmount,
int $applicationFeeAmountMinorUnit,
OrderApplicationFeeStatus $orderApplicationFeeStatus,
PaymentProviders $paymentMethod,
string $currency,
): void
{
$isZeroDecimalCurrency = Currency::isZeroDecimalCurrency($currency);

$applicationFeeAmount = $isZeroDecimalCurrency
? $applicationFeeAmountMinorUnit
: $applicationFeeAmountMinorUnit / 100;

$this->orderApplicationFeeRepository->create([
OrderApplicationFeeDomainObjectAbstract::ORDER_ID => $orderId,
OrderApplicationFeeDomainObjectAbstract::AMOUNT => $applicationFeeAmount,
OrderApplicationFeeDomainObjectAbstract::STATUS => $orderApplicationFeeStatus->value,
OrderApplicationFeeDomainObjectAbstract::PAYMENT_METHOD => $paymentMethod->value,
ORderApplicationFeeDomainObjectAbstract::CURRENCY => $currency,
OrderApplicationFeeDomainObjectAbstract::PAID_AT => $orderApplicationFeeStatus->value === OrderApplicationFeeStatus::PAID->value
? now()->toDateTimeString()
: null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
use HiEvents\DataTransferObjects\BaseDTO;
use HiEvents\DomainObjects\AccountDomainObject;
use HiEvents\DomainObjects\OrderDomainObject;
use HiEvents\Values\MoneyValue;

class CreatePaymentIntentRequestDTO extends BaseDTO
{
public function __construct(
public readonly int $amount,
public readonly string $currencyCode,
public readonly MoneyValue $amount,
public readonly string $currencyCode,
public AccountDomainObject $account,
public OrderDomainObject $order,
public OrderDomainObject $order,
)
{
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,9 +233,10 @@ private function storeApplicationFeePayment(OrderDomainObject $updatedOrder, Pay
{
$this->orderApplicationFeeService->createOrderApplicationFee(
orderId: $updatedOrder->getId(),
applicationFeeAmount: $paymentIntent->application_fee_amount / 100,
applicationFeeAmountMinorUnit: $paymentIntent->application_fee_amount,
orderApplicationFeeStatus: OrderApplicationFeeStatus::PAID,
paymentMethod: PaymentProviders::STRIPE,
currency: $updatedOrder->getCurrency(),
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,12 @@ public function createPaymentIntent(CreatePaymentIntentRequestDTO $paymentIntent

$applicationFee = $this->orderApplicationFeeCalculationService->calculateApplicationFee(
accountConfiguration: $paymentIntentDTO->account->getConfiguration(),
orderTotal: $paymentIntentDTO->amount / 100,
orderTotal: $paymentIntentDTO->amount->toFloat(),
currency: $paymentIntentDTO->currencyCode,
)->toMinorUnit();

$paymentIntent = $this->stripeClient->paymentIntents->create([
'amount' => $paymentIntentDTO->amount,
'amount' => $paymentIntentDTO->amount->toMinorUnit(),
'currency' => $paymentIntentDTO->currencyCode,
'customer' => $this->upsertStripeCustomer($paymentIntentDTO)->getStripeCustomerId(),
'metadata' => [
Expand Down Expand Up @@ -103,6 +103,8 @@ public function createPaymentIntent(CreatePaymentIntentRequestDTO $paymentIntent
'paymentIntentDTO' => $paymentIntentDTO->toArray(['account']),
]);

$this->databaseManager->rollBack();

throw new CreatePaymentIntentFailedException(
__('There was an error communicating with the payment provider. Please try again later.')
);
Expand All @@ -113,18 +115,6 @@ public function createPaymentIntent(CreatePaymentIntentRequestDTO $paymentIntent
}
}

private function getApplicationFee(CreatePaymentIntentRequestDTO $paymentIntentDTO): float
{
if (!$this->config->get('app.saas_mode_enabled')) {
return 0;
}

$fixedFee = $paymentIntentDTO->account->getApplicationFee()->fixedFee;
$percentageFee = $paymentIntentDTO->account->getApplicationFee()->percentageFee;

return ceil(($fixedFee * 100) + ($paymentIntentDTO->amount * $percentageFee / 100));
}

/**
* @throws CreatePaymentIntentFailedException
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace HiEvents\Services\Infrastructure\CurrencyConversion;

use Brick\Money\Currency;
use HiEvents\Values\MoneyValue;

interface CurrencyConversionClientInterface
{
public function convert(Currency $fromCurrency, Currency $toCurrency, float $amount): MoneyValue;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace HiEvents\Services\Infrastructure\CurrencyConversion\Exception;

use Exception;

class CurrencyConversionErrorException extends Exception
{

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace HiEvents\Services\Infrastructure\CurrencyConversion;

use Brick\Money\Currency;
use HiEvents\Values\MoneyValue;
use Psr\Log\LoggerInterface;

class NoOpCurrencyConversionClient implements CurrencyConversionClientInterface
{
private LoggerInterface $logger;

public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}

public function convert(Currency $fromCurrency, Currency $toCurrency, float $amount): MoneyValue
{
$this->logger->warning(
'NoOpCurrencyConversionClient is being used. This should only be used as a last resort fallback. Never in production.',
[
'fromCurrency' => $fromCurrency->getCurrencyCode(),
'toCurrency' => $toCurrency->getCurrencyCode(),
'amount' => $amount,
]
);

return MoneyValue::fromFloat($amount, $toCurrency->getCurrencyCode());
}
}
Loading
Loading