-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathNotificationFacade.php
466 lines (374 loc) · 18.4 KB
/
NotificationFacade.php
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
<?php
namespace Kiener\MolliePayments\Controller\Storefront\Webhook;
use Kiener\MolliePayments\Compatibility\Bundles\FlowBuilder\FlowBuilderDispatcherAdapterInterface;
use Kiener\MolliePayments\Compatibility\Bundles\FlowBuilder\FlowBuilderEventFactory;
use Kiener\MolliePayments\Compatibility\Bundles\FlowBuilder\FlowBuilderFactory;
use Kiener\MolliePayments\Components\Subscription\SubscriptionManager;
use Kiener\MolliePayments\Event\MollieOrderBuildEvent;
use Kiener\MolliePayments\Exception\CustomerCouldNotBeFoundException;
use Kiener\MolliePayments\Gateway\MollieGatewayInterface;
use Kiener\MolliePayments\Handler\Method\ApplePayPayment;
use Kiener\MolliePayments\Service\Mollie\MolliePaymentDetails;
use Kiener\MolliePayments\Service\Mollie\MolliePaymentStatus;
use Kiener\MolliePayments\Service\Mollie\OrderStatusConverter;
use Kiener\MolliePayments\Service\Order\OrderStatusUpdater;
use Kiener\MolliePayments\Service\OrderService;
use Kiener\MolliePayments\Service\SettingsService;
use Kiener\MolliePayments\Struct\Order\OrderAttributes;
use Kiener\MolliePayments\Struct\PaymentMethod\PaymentMethodAttributes;
use Kiener\MolliePayments\Subscriber\MollieOrderBuildSubscriber;
use Mollie\Api\Resources\Order;
use Psr\Log\LoggerInterface;
use Shopware\Core\Checkout\Cart\Exception\OrderNotFoundException;
use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity;
use Shopware\Core\Checkout\Order\OrderEntity;
use Shopware\Core\Checkout\Payment\PaymentMethodEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\EntitySearchResult;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\MultiFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
class NotificationFacade
{
/**
* @var MollieGatewayInterface
*/
private $gatewayMollie;
/**
* @var OrderStatusConverter
*/
private $statusConverter;
/**
* @var OrderStatusUpdater
*/
private $statusUpdater;
/**
* @var EntityRepositoryInterface
*/
private $repoPaymentMethods;
/**
* @var EntityRepositoryInterface
*/
private $repoOrderTransactions;
/**
* @var FlowBuilderDispatcherAdapterInterface
*/
private $flowBuilderDispatcher;
/**
* @var FlowBuilderEventFactory
*/
private $flowBuilderEventFactory;
/**
* @var SubscriptionManager
*/
private $subscriptionManager;
/**
* @var MolliePaymentDetails
*/
private $molliePaymentDetails;
/**
* @var OrderService
*/
private $orderService;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var SettingsService
*/
private $settingsService;
/**
* @param MollieGatewayInterface $gatewayMollie
* @param OrderStatusConverter $statusConverter
* @param OrderStatusUpdater $statusUpdater
* @param EntityRepositoryInterface $repoPaymentMethods
* @param EntityRepositoryInterface $repoOrderTransactions
* @param FlowBuilderFactory $flowBuilderFactory
* @param FlowBuilderEventFactory $flowBuilderEventFactory
* @param SettingsService $serviceService
* @param SubscriptionManager $subscription
* @param OrderService $orderService
* @param LoggerInterface $logger
* @throws \Exception
*/
public function __construct(MollieGatewayInterface $gatewayMollie, OrderStatusConverter $statusConverter, OrderStatusUpdater $statusUpdater, EntityRepositoryInterface $repoPaymentMethods, EntityRepositoryInterface $repoOrderTransactions, FlowBuilderFactory $flowBuilderFactory, FlowBuilderEventFactory $flowBuilderEventFactory, SettingsService $serviceService, SubscriptionManager $subscription, OrderService $orderService, LoggerInterface $logger)
{
$this->gatewayMollie = $gatewayMollie;
$this->statusConverter = $statusConverter;
$this->statusUpdater = $statusUpdater;
$this->repoPaymentMethods = $repoPaymentMethods;
$this->repoOrderTransactions = $repoOrderTransactions;
$this->flowBuilderEventFactory = $flowBuilderEventFactory;
$this->subscriptionManager = $subscription;
$this->settingsService = $serviceService;
$this->orderService = $orderService;
$this->logger = $logger;
$this->molliePaymentDetails = new MolliePaymentDetails();
$this->flowBuilderDispatcher = $flowBuilderFactory->createDispatcher();
}
/**
* @param string $swTransactionId
* @param Context $context
* @param string $actionId
* @return void
* @throws CustomerCouldNotBeFoundException
* @throws \Exception
*/
public function onNotify(string $swTransactionId, Context $context, string $actionId): void
{
# -----------------------------------------------------------------------------------------------------
# LOAD TRANSACTION
$swTransaction = $this->getTransaction($swTransactionId, $context);
if (!$swTransaction instanceof OrderTransactionEntity) {
throw new \Exception('Transaction ' . $swTransactionId . ' not found in Shopware');
}
# -----------------------------------------------------------------------------------------------------
$swOrder = $swTransaction->getOrder();
if (!$swOrder instanceof OrderEntity) {
throw new OrderNotFoundException('Shopware Order not found for transaction: ' . $swTransactionId);
}
# --------------------------------------------------------------------------------------------
# now get the correct settings from the sales channel of that order.
# our order might be from a different sales channel, or even a headless sales channel
$settings = $this->settingsService->getSettings($swOrder->getSalesChannelId());
# also set the gateway to our correct sales channel API key
$this->gatewayMollie->switchClient($swOrder->getSalesChannelId());
# --------------------------------------------------------------------------------------------
# now get the latest transaction of that order
# we always need to make sure to use the latest one, because this
# is the one, that is really visible in the administration.
# if we don't add to that one, then the previous one is suddenly visible again
# which causes confusion and troubles in the end
$swTransaction = $this->getOrderTransactions($swOrder->getId(), $context)->last();
# verify if the customer really paid with Mollie in the end
$paymentMethod = $swTransaction->getPaymentMethod();
$paymentMethodAttributes = new PaymentMethodAttributes($paymentMethod);
if (!$paymentMethodAttributes->isMolliePayment()) {
# just skip it if it has been paid
# with another payment provider
# do NOT throw an error
return;
}
# --------------------------------------------------------------------------------------------
$orderAttributes = new OrderAttributes($swOrder);
$mollieOrderId = $orderAttributes->getMollieOrderId();
$this->gatewayMollie->switchClient($swOrder->getSalesChannelId());
$molliePayment = null;
$mollieOrder = null;
if (empty($mollieOrderId)) {
if (str_starts_with($actionId, 'ord')) {
$mollieOrder = $this->gatewayMollie->getOrder($actionId);
$molliePayment = $this->statusConverter->getLatestPayment($mollieOrder);
} elseif (str_starts_with($actionId, 'tr')) {
$molliePayment = $this->gatewayMollie->getPayment($actionId);
if ($molliePayment->orderId != null) {
$mollieOrder = $this->gatewayMollie->getOrder($molliePayment->orderId);
}
}
if ($mollieOrder == null) {
throw new \Exception('No valid order has been found: ' . $swOrder->getOrderNumber());
}
$metadata = json_decode($mollieOrder->metadata, true);
if ($metadata == null) {
throw new \Exception('Order has no metadata: ' . $swOrder->getOrderNumber());
}
$metaShortId = $metadata[MollieOrderBuildEvent::METADATA_SHORT_TRANSACTION_ID_KEY];
$transShortId = substr($swTransactionId, 0, 8);
if ($metaShortId == $transShortId) {
$mollieOrderId = $mollieOrder->id;
}
}
if (!empty($mollieOrderId)) {
# fetch the order of our mollie ID
# from our sales channel mollie profile
$mollieOrder = $this->gatewayMollie->getOrder($mollieOrderId);
$molliePayment = $this->statusConverter->getLatestPayment($mollieOrder);
$status = $this->statusConverter->getMollieOrderStatus($mollieOrder);
} elseif ($orderAttributes->isTypeSubscription()) {
# subscriptions are automatically charged using a payment ID
# so we do not have an order, but a payment instead
$molliePayment = $this->gatewayMollie->getPayment($orderAttributes->getMolliePaymentId());
$status = $this->statusConverter->getMolliePaymentStatus($molliePayment);
} else {
throw new \Exception('Order is neither a Mollie order nor a subscription order: ' . $swOrder->getOrderNumber());
}
# --------------------------------------------------------------------------------------------
$this->logger->info('Webhook for order ' . $swOrder->getOrderNumber() . ' and Mollie ID: ' . $mollieOrderId . ' has been received with Status: ' . $status);
$this->statusUpdater->updatePaymentStatus($swTransaction, $status, $context);
$this->statusUpdater->updateOrderStatus($swOrder, $status, $settings, $context);
# --------------------------------------------------------------------------------------------
# let's check what payment method has been used
# if somehow the user switched to a different one
# then we want to update the one inside Shopware
# If our order is Apple Pay, then DO NOT CONVERT THIS TO CREDIT CARD!
# we want to keep Apple Pay as payment method
if ($swTransaction->getPaymentMethod() instanceof PaymentMethodEntity && $mollieOrder instanceof Order && $swTransaction->getPaymentMethod() instanceof PaymentMethodEntity && $swTransaction->getPaymentMethod()->getHandlerIdentifier() !== ApplePayPayment::class) {
$this->updatePaymentMethod($swTransaction, $mollieOrder, $context);
}
# --------------------------------------------------------------------------------------------
# SUBSCRIPTION
# this will confirm our created subscriptions in all cases of successful payments.
# that path will create the actual subscription inside Mollie which will be used for recurring.
# if our payment expired, then we can also expire our local subscription in the database.
switch ($status) {
case MolliePaymentStatus::MOLLIE_PAYMENT_PAID:
case MolliePaymentStatus::MOLLIE_PAYMENT_PENDING:
case MolliePaymentStatus::MOLLIE_PAYMENT_AUTHORIZED:
# it is very important that we use the mandate from this payment
# for the subscription, because a customer could have different mandates!
# keep in mind, this might be empty here...our confirm endpoint does the final checks
$mandateId = $this->molliePaymentDetails->getMandateId($molliePayment);
$this->subscriptionManager->confirmSubscription($swOrder, $mandateId, $context);
break;
case MolliePaymentStatus::MOLLIE_PAYMENT_EXPIRED:
$this->subscriptionManager->cancelPendingSubscriptions($swOrder, $context);
break;
}
# now update the custom fields of the order
# we want to have as much information as possible in the shopware order
# this includes the Mollie Payment ID and maybe additional references
$this->orderService->updateMollieDataCustomFields(
$swOrder,
$mollieOrderId,
$swTransaction->getId(),
$context
);
# --------------------------------------------------------------------------------------------
# FIRE FLOW BUILDER TRIGGER EVENT
# we have an adapter setup anyway here, so if flow builder is
# not yet supported in this shopware version, then
# this only triggers a dummy dispatcher ;)
$this->fireFlowBuilderEvents($swOrder, $status, $context);
}
/**
* @param string $transactionId
* @param Context $context
* @return null|OrderTransactionEntity
*/
private function getTransaction(string $transactionId, Context $context): ?OrderTransactionEntity
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('id', $transactionId));
$criteria->addAssociation('order');
$criteria->addAssociation('order.lineItems');
$criteria->addAssociation('order.currency');
$criteria->addAssociation('paymentMethod');
return $this->repoOrderTransactions->search($criteria, $context)->first();
}
/**
* @param string $orderID
* @param Context $context
* @return EntitySearchResult<OrderTransactionEntity>
*/
public function getOrderTransactions(string $orderID, Context $context): EntitySearchResult
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('order.id', $orderID));
$criteria->addAssociation('order');
$criteria->addAssociation('paymentMethod');
$criteria->addSorting(new FieldSorting('createdAt'));
return $this->repoOrderTransactions->search($criteria, $context);
}
/**
* @param OrderEntity $order
* @return string
*/
private function getMollieId(OrderEntity $order): string
{
$customFields = $order->getCustomFields();
if (!isset($customFields['mollie_payments'])) {
return "";
}
if (!isset($customFields['mollie_payments']['order_id'])) {
return "";
}
return (string)$customFields['mollie_payments']['order_id'];
}
/**
* @param OrderTransactionEntity $transaction
* @param Order $mollieOrder
* @param Context $context
*/
private function updatePaymentMethod(OrderTransactionEntity $transaction, Order $mollieOrder, Context $context): void
{
$criteria = new Criteria();
$criteria->addFilter(
new MultiFilter(
'AND',
[
new ContainsFilter('handlerIdentifier', 'Kiener\MolliePayments\Handler\Method'),
new EqualsFilter('customFields.mollie_payment_method_name', $mollieOrder->method)
]
)
);
$shopwarePaymentId = $this->repoPaymentMethods->searchIds($criteria, $context)->firstId();
if (is_null($shopwarePaymentId)) {
# if the payment method is not available locally in shopware
# then we just skip the update process
# we do not want to fail our notification because of this
return;
}
$transaction->setPaymentMethodId($shopwarePaymentId);
$this->repoOrderTransactions->update(
[
[
'id' => $transaction->getUniqueIdentifier(),
'paymentMethodId' => $shopwarePaymentId
]
],
$context
);
}
/**
* @param OrderEntity $swOrder
* @param string $status
* @param Context $context
* @return void
*/
private function fireFlowBuilderEvents(OrderEntity $swOrder, string $status, Context $context): void
{
$this->flowBuilderDispatcher->dispatch(
$this->flowBuilderEventFactory->buildWebhookReceivedAll($swOrder, $status, $context)
);
$paymentEvent = null;
switch ($status) {
case MolliePaymentStatus::MOLLIE_PAYMENT_FAILED:
$paymentEvent = $this->flowBuilderEventFactory->buildWebhookReceivedFailedEvent($swOrder, $context);
break;
case MolliePaymentStatus::MOLLIE_PAYMENT_CANCELED:
$paymentEvent = $this->flowBuilderEventFactory->buildWebhookReceivedCancelledEvent($swOrder, $context);
break;
case MolliePaymentStatus::MOLLIE_PAYMENT_EXPIRED:
$paymentEvent = $this->flowBuilderEventFactory->buildWebhookReceivedExpiredEvent($swOrder, $context);
break;
case MolliePaymentStatus::MOLLIE_PAYMENT_PENDING:
$paymentEvent = $this->flowBuilderEventFactory->buildWebhookReceivedPendingEvent($swOrder, $context);
break;
case MolliePaymentStatus::MOLLIE_PAYMENT_AUTHORIZED:
$paymentEvent = $this->flowBuilderEventFactory->buildWebhookReceivedAuthorizedEvent($swOrder, $context);
break;
case MolliePaymentStatus::MOLLIE_PAYMENT_PAID:
$paymentEvent = $this->flowBuilderEventFactory->buildWebhookReceivedPaidEvent($swOrder, $context);
break;
case MolliePaymentStatus::MOLLIE_PAYMENT_COMPLETED:
$paymentEvent = $this->flowBuilderEventFactory->buildWebhookReceivedCompletedEvent($swOrder, $context);
break;
case MolliePaymentStatus::MOLLIE_PAYMENT_CHARGEBACK:
$paymentEvent = $this->flowBuilderEventFactory->buildWebhookReceivedChargebackEvent($swOrder, $context);
break;
case MolliePaymentStatus::MOLLIE_PAYMENT_REFUNDED:
$paymentEvent = $this->flowBuilderEventFactory->buildWebhookReceivedRefundedEvent($swOrder, $context);
break;
case MolliePaymentStatus::MOLLIE_PAYMENT_PARTIALLY_REFUNDED:
$paymentEvent = $this->flowBuilderEventFactory->buildWebhookReceivedPartialRefundedEvent($swOrder, $context);
break;
}
if ($paymentEvent !== null) {
$this->flowBuilderDispatcher->dispatch($paymentEvent);
}
}
}