-
-
Notifications
You must be signed in to change notification settings - Fork 592
Expand file tree
/
Copy pathPaymentIntentSucceededHandler.php
More file actions
242 lines (214 loc) · 10.1 KB
/
PaymentIntentSucceededHandler.php
File metadata and controls
242 lines (214 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
<?php
namespace HiEvents\Services\Domain\Payment\Stripe\EventHandlers;
use Brick\Math\Exception\MathException;
use Brick\Math\Exception\NumberFormatException;
use Brick\Math\Exception\RoundingNecessaryException;
use Brick\Money\Exception\UnknownCurrencyException;
use Carbon\Carbon;
use HiEvents\DomainObjects\Enums\PaymentProviders;
use HiEvents\DomainObjects\Generated\OrderDomainObjectAbstract;
use HiEvents\DomainObjects\Generated\StripePaymentDomainObjectAbstract;
use HiEvents\DomainObjects\OrderDomainObject;
use HiEvents\DomainObjects\OrderItemDomainObject;
use HiEvents\DomainObjects\Status\AttendeeStatus;
use HiEvents\DomainObjects\Status\OrderApplicationFeeStatus;
use HiEvents\DomainObjects\Status\OrderPaymentStatus;
use HiEvents\DomainObjects\Status\OrderStatus;
use HiEvents\Events\OrderStatusChangedEvent;
use HiEvents\Exceptions\CannotAcceptPaymentException;
use HiEvents\Repository\Eloquent\StripePaymentsRepository;
use HiEvents\Repository\Eloquent\Value\Relationship;
use HiEvents\Repository\Interfaces\AttendeeRepositoryInterface;
use HiEvents\Repository\Interfaces\OrderRepositoryInterface;
use HiEvents\Services\Domain\Order\OrderApplicationFeeService;
use HiEvents\Services\Domain\Payment\Stripe\StripeRefundExpiredOrderService;
use HiEvents\Services\Domain\Product\ProductQuantityUpdateService;
use HiEvents\Services\Infrastructure\DomainEvents\DomainEventDispatcherService;
use HiEvents\Services\Infrastructure\DomainEvents\Enums\DomainEventType;
use HiEvents\Services\Infrastructure\DomainEvents\Events\OrderEvent;
use Illuminate\Cache\Repository;
use Illuminate\Database\DatabaseManager;
use Psr\Log\LoggerInterface;
use Stripe\Exception\ApiErrorException;
use Stripe\PaymentIntent;
use Throwable;
class PaymentIntentSucceededHandler
{
public function __construct(
private readonly OrderRepositoryInterface $orderRepository,
private readonly StripePaymentsRepository $stripePaymentsRepository,
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,
)
{
}
/**
* @throws Throwable
*/
public function handleEvent(PaymentIntent $paymentIntent): void
{
if ($this->isPaymentIntentAlreadyHandled($paymentIntent)) {
$this->logger->info('Payment intent already handled', [
'payment_intent' => $paymentIntent->id,
]);
return;
}
$this->databaseManager->transaction(function () use ($paymentIntent) {
/** @var StripePaymentDomainObjectAbstract $stripePayment */
$stripePayment = $this->stripePaymentsRepository
->loadRelation(new Relationship(OrderDomainObject::class, name: 'order'))
->findFirstWhere([
StripePaymentDomainObjectAbstract::PAYMENT_INTENT_ID => $paymentIntent->id,
]);
if (!$stripePayment) {
$this->logger->error('Payment intent not found when handling payment intent succeeded event', [
'paymentIntent' => $paymentIntent->toArray(),
]);
return;
}
$this->validatePaymentAndOrderStatus($stripePayment, $paymentIntent);
$this->updateStripePaymentInfo($paymentIntent, $stripePayment);
$updatedOrder = $this->updateOrderStatuses($stripePayment);
$this->updateAttendeeStatuses($updatedOrder);
$this->quantityUpdateService->updateQuantitiesFromOrder($updatedOrder);
OrderStatusChangedEvent::dispatch($updatedOrder);
$this->domainEventDispatcherService->dispatch(
new OrderEvent(
type: DomainEventType::ORDER_CREATED,
orderId: $updatedOrder->getId()
),
);
$this->markPaymentIntentAsHandled($paymentIntent, $updatedOrder);
$this->storeApplicationFeePayment($updatedOrder, $paymentIntent);
});
}
private function updateOrderStatuses(StripePaymentDomainObjectAbstract $stripePayment): OrderDomainObject
{
return $this->orderRepository
->loadRelation(OrderItemDomainObject::class)
->updateFromArray($stripePayment->getOrderId(), [
OrderDomainObjectAbstract::PAYMENT_STATUS => OrderPaymentStatus::PAYMENT_RECEIVED->name,
OrderDomainObjectAbstract::STATUS => OrderStatus::COMPLETED->name,
OrderDomainObjectAbstract::PAYMENT_PROVIDER => PaymentProviders::STRIPE->value,
]);
}
private function updateStripePaymentInfo(PaymentIntent $paymentIntent, StripePaymentDomainObjectAbstract $stripePayment): void
{
$this->stripePaymentsRepository->updateWhere(
attributes: [
StripePaymentDomainObjectAbstract::LAST_ERROR => $paymentIntent->last_payment_error?->toArray(),
StripePaymentDomainObjectAbstract::AMOUNT_RECEIVED => $paymentIntent->amount_received,
StripePaymentDomainObjectAbstract::APPLICATION_FEE => $paymentIntent->application_fee_amount ?? 0,
StripePaymentDomainObjectAbstract::PAYMENT_METHOD_ID => is_string($paymentIntent->payment_method)
? $paymentIntent->payment_method
: $paymentIntent->payment_method?->id,
StripePaymentDomainObjectAbstract::CHARGE_ID => is_string($paymentIntent->latest_charge)
? $paymentIntent->latest_charge
: $paymentIntent->latest_charge?->id,
],
where: [
StripePaymentDomainObjectAbstract::PAYMENT_INTENT_ID => $paymentIntent->id,
StripePaymentDomainObjectAbstract::ORDER_ID => $stripePayment->getOrderId(),
]);
}
/**
* If the order has expired (reserved_until is in the past), refund the payment and throw an exception.
* This does seem quite extreme, but it ensures we don't oversell products. As far as I can see
* this is how Ticketmaster and other ticketing systems work.
*
* @throws ApiErrorException
* @throws RoundingNecessaryException
* @throws CannotAcceptPaymentException
* @throws MathException
* @throws UnknownCurrencyException
* @throws NumberFormatException
* @todo We could check to see if there are products available, and if so, complete the order.
* This would be a better user experience.
*
*/
private function handleExpiredOrder(
StripePaymentDomainObjectAbstract $stripePayment,
PaymentIntent $paymentIntent,
): void
{
if ((new Carbon($stripePayment->getOrder()?->getReservedUntil()))->isPast()) {
$this->refundExpiredOrderService->refundExpiredOrder(
paymentIntent: $paymentIntent,
stripePayment: $stripePayment,
order: $stripePayment->getOrder(),
);
throw new CannotAcceptPaymentException(
__('Payment was successful, but order has expired. Order: :id', [
'id' => $stripePayment->getOrderId()
])
);
}
}
/**
* @throws ApiErrorException
* @throws RoundingNecessaryException
* @throws CannotAcceptPaymentException
* @throws MathException
* @throws UnknownCurrencyException
* @throws NumberFormatException
*/
private function validatePaymentAndOrderStatus(
StripePaymentDomainObjectAbstract $stripePayment,
PaymentIntent $paymentIntent
): void
{
if (!in_array($stripePayment->getOrder()?->getPaymentStatus(), [
OrderPaymentStatus::AWAITING_PAYMENT->name,
OrderPaymentStatus::PAYMENT_FAILED->name,
], true)) {
throw new CannotAcceptPaymentException(
__('Order is not awaiting payment. Order: :id',
['id' => $stripePayment->getOrderId()]
)
);
}
$this->handleExpiredOrder($stripePayment, $paymentIntent);
}
private function updateAttendeeStatuses(OrderDomainObject $updatedOrder): void
{
$this->attendeeRepository->updateWhere(
attributes: [
'status' => AttendeeStatus::ACTIVE->name,
],
where: [
'order_id' => $updatedOrder->getId(),
'status' => AttendeeStatus::AWAITING_PAYMENT->name,
],
);
}
private function markPaymentIntentAsHandled(PaymentIntent $paymentIntent, OrderDomainObject $updatedOrder): void
{
$this->logger->info('Stripe payment intent succeeded event handled', [
'payment_intent' => $paymentIntent->id,
'order_id' => $updatedOrder->getId(),
'amount_received' => $paymentIntent->amount_received,
'currency' => $paymentIntent->currency,
]);
$this->cache->put('payment_intent_handled_' . $paymentIntent->id, true, 3600);
}
private function isPaymentIntentAlreadyHandled(PaymentIntent $paymentIntent): bool
{
return $this->cache->has('payment_intent_handled_' . $paymentIntent->id);
}
private function storeApplicationFeePayment(OrderDomainObject $updatedOrder, PaymentIntent $paymentIntent): void
{
$this->orderApplicationFeeService->createOrderApplicationFee(
orderId: $updatedOrder->getId(),
applicationFeeAmountMinorUnit: $paymentIntent->application_fee_amount,
orderApplicationFeeStatus: OrderApplicationFeeStatus::PAID,
paymentMethod: PaymentProviders::STRIPE,
currency: $updatedOrder->getCurrency(),
);
}
}