forked from mollie/Shopware
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckoutSessionFacade.php
More file actions
352 lines (292 loc) · 11.6 KB
/
CheckoutSessionFacade.php
File metadata and controls
352 lines (292 loc) · 11.6 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
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
<?php
namespace MollieShopware\Facades\CheckoutSession;
use MollieShopware\Components\ApplePayDirect\Handler\ApplePayDirectHandler;
use MollieShopware\Components\Basket\Basket;
use MollieShopware\Components\Basket\BasketInterface;
use MollieShopware\Components\Config;
use MollieShopware\Components\Constants\OrderCreationType;
use MollieShopware\Components\CurrentCustomer;
use MollieShopware\Components\Helpers\LocaleFinder;
use MollieShopware\Components\Order\ShopwareOrderBuilder;
use MollieShopware\Components\Services\CreditCardService;
use MollieShopware\Components\Services\OrderService;
use MollieShopware\Components\Services\PaymentService;
use MollieShopware\Components\SessionManager\SessionManager;
use MollieShopware\Components\Shipping\Shipping;
use MollieShopware\Components\Shipping\ShippingInterface;
use MollieShopware\Components\TransactionBuilder\TransactionBuilder;
use MollieShopware\Exceptions\CustomerNotFoundException;
use MollieShopware\Models\Transaction;
use MollieShopware\Models\TransactionRepository;
use MollieShopware\Services\TokenAnonymizer\TokenAnonymizer;
use Psr\Log\LoggerInterface;
use sBasket;
use Shopware\Components\Model\ModelManager;
use Shopware\Models\Order\Order;
use Shopware_Controllers_Frontend_Payment;
class CheckoutSessionFacade
{
/**
*
*/
const SESSION_EXPIRE_DAYS = 1;
/**
* @var PaymentService
*/
private $paymentService;
/**
* @var OrderService
*/
private $orderService;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var Shopware_Controllers_Frontend_Payment
*/
private $controller;
/**
* @var ModelManager
*/
private $modelManager;
/**
* @var LocaleFinder
*/
private $localeFinder;
/**
* @var null|Order
*/
private $restorableOrder;
/**
* @var sBasket
*/
private $sBasket;
/**
* @var ShopwareOrderBuilder
*/
private $swOrderBuilder;
/**
* @var TokenAnonymizer
*/
private $tokenAnonymizer;
/**
* @var ApplePayDirectHandler
*/
private $applePay;
/**
* @var CreditCardService
*/
private $creditCardService;
/**
* @var SessionManager
*/
private $sessionManager;
/**
* @var TransactionRepository
*/
private $repoTransactions;
/**
* @var TransactionBuilder
*/
private $transactionBuilder;
/**
* @var Config\PaymentConfigResolver
*/
private $paymentConfig;
/**
* CheckoutSessionFacade constructor.
* @param PaymentService $paymentService
* @param OrderService $orderService
* @param LoggerInterface $logger
* @param Shopware_Controllers_Frontend_Payment $controller
* @param ModelManager $modelManager
* @param LocaleFinder $localeFinder
* @param $sBasket
* @param ShopwareOrderBuilder $swOrderBuilder
* @param TokenAnonymizer $anonymizer
* @param ApplePayDirectHandler $applePay
* @param CreditCardService $creditCard
* @param TransactionRepository $repoTransactions
* @param SessionManager $sessionManager
* @param TransactionBuilder $transactionBuilder
* @param Config\PaymentConfigResolver $paymentConfig
*/
public function __construct(PaymentService $paymentService, OrderService $orderService, LoggerInterface $logger, Shopware_Controllers_Frontend_Payment $controller, ModelManager $modelManager, LocaleFinder $localeFinder, $sBasket, ShopwareOrderBuilder $swOrderBuilder, TokenAnonymizer $anonymizer, ApplePayDirectHandler $applePay, CreditCardService $creditCard, TransactionRepository $repoTransactions, SessionManager $sessionManager, TransactionBuilder $transactionBuilder, Config\PaymentConfigResolver $paymentConfig)
{
$this->paymentService = $paymentService;
$this->orderService = $orderService;
$this->logger = $logger;
$this->controller = $controller;
$this->modelManager = $modelManager;
$this->localeFinder = $localeFinder;
$this->sBasket = $sBasket;
$this->swOrderBuilder = $swOrderBuilder;
$this->tokenAnonymizer = $anonymizer;
$this->applePay = $applePay;
$this->creditCardService = $creditCard;
$this->repoTransactions = $repoTransactions;
$this->sessionManager = $sessionManager;
$this->transactionBuilder = $transactionBuilder;
$this->paymentConfig = $paymentConfig;
}
/**
* @return null|Order
*/
public function getRestorableOrder()
{
return $this->restorableOrder;
}
/**
* @param $basketUserId
* @param $paymentShortName
* @param $basketSignature
* @param $currencyShortName
* @param $shopId
* @param $billingAddressID
* @param $shippingAddressID
* @throws \Doctrine\DBAL\Exception
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
* @throws \MollieShopware\Exceptions\MolliePaymentConfigurationNotFound
* @throws \Mollie\Api\Exceptions\ApiException
* @return CheckoutSession
*/
public function startCheckoutSession($basketUserId, $paymentShortName, $basketSignature, $currencyShortName, $shopId, $billingAddressID, $shippingAddressID)
{
# immediately reset our previous order
# just to make sure we don't have a previous one accidentally
$this->restorableOrder = null;
$basketData = $this->sBasket->sGetBasketData();
if (!$this->sBasket->sCountBasket()) {
throw new \Exception('No items in basket');
}
# we have to extend the lifetime of our session handler
# this is required to allow shopware restore user from our restoring cookie.
# this is plain shopware, and only works with an existing session,
$this->sessionManager->extendSessionLifespan(self::SESSION_EXPIRE_DAYS);
# we want to log anonymized tokens
# to see if they are used correctly.
try {
$tokenCreditCard = $this->creditCardService->getCardToken();
} catch (\Exception $exception) {
# prevent the checkout from failing, because at this
# point it's not sure if we need the credit card
# token to finish the payment at Mollie
$tokenCreditCard = '';
}
$tokenApplePay = $this->applePay->getPaymentToken();
# build and create our transaction
# this is the most important line that helps us
# to get the bridge between the mollie payments and the shopware orders.
# it contains all necessary things for upcoming workflows.
$transaction = $this->buildTransaction($basketSignature, $currencyShortName);
$this->modelManager->persist($transaction);
$this->modelManager->flush($transaction);
$this->logger->info(
'Starting checkout for Transaction: ' . $transaction->getId() . ' with payment: ' . $paymentShortName,
[
'basket' => [
'amount' => $basketData['Amount'],
'quantity' => $basketData['Quantity'],
'payment' => $paymentShortName,
'user' => $basketUserId
],
'tokens' => [
'creditcard' => $this->tokenAnonymizer->anonymize($tokenCreditCard),
'applepay' => $this->tokenAnonymizer->anonymize($tokenApplePay),
]
]
);
# to avoid problems on lost sessions, we have to ensure
# that we can restore a session.
# thus we create a payment token, that can be used for this in the returnAction
$paymentToken = $this->sessionManager->generateSessionToken($transaction);
# now check, if we should create the order
# before or after the payment
$orderCreation = $this->paymentConfig->getFinalOrderCreation($paymentShortName, $shopId);
if ($orderCreation === OrderCreationType::BEFORE_PAYMENT) {
# create the order in our system.
# attention, this is the point where the basket is officially "empty"
# because the order is completed in Shopware
$orderNumber = $this->swOrderBuilder->createOrderBeforePayment(
$transaction->getTransactionId(),
$basketSignature
);
$order = $this->orderService->getShopwareOrderByNumber($orderNumber);
if (!$order instanceof Order) {
throw new \Exception('The order with order number ' . $orderNumber . ' could not be found');
}
# now that we have the order, we need to remember it
# this is required to restore the basket from that order in case of
# any additional failures below. otherwise the cart is empty because
# the order is already completed.
$this->restorableOrder = $order;
# now update all required references of our transaction
$transaction->setOrderId($order->getId());
$transaction->setOrderNumber($orderNumber);
$this->repoTransactions->save($transaction);
}
# now start the actual Mollie order.
# we prepare the request and send it to Mollie.
# the response will create an URL that we need to redirect
# the user to for further payment steps.
$checkoutUrl = $this->paymentService->startMollieSession(
$paymentShortName,
$transaction,
$paymentToken,
$billingAddressID,
$shippingAddressID
);
# some payment methods are approved and
# paid immediately and don't require a redirect.
# so we just grab this information using our constant
$redirectRequired = ($checkoutUrl !== PaymentService::CHECKOUT_URL_NO_REDIRECT_TO_MOLLIE_REQUIRED);
return new CheckoutSession(
$redirectRequired,
$transaction,
$checkoutUrl
);
}
/**
* @param $basketSignature
* @param $currency
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
* @return Transaction
*/
private function buildTransaction($basketSignature, $currency)
{
$currentCustomerClass = new CurrentCustomer(
Shopware()->Session(),
Shopware()->Models(),
Shopware()->Container()->get('mollie_shopware.components.logger')
);
$customer = $currentCustomerClass->getCurrent();
$locale = $this->localeFinder->getPaymentLocale(Shopware()->Shop()->getLocale()->getLocale());
$isTaxFree = false;
$isNet = false;
if (isset($this->controller->getUser()['additional']) && (!isset($this->controller->getUser()['additional']['charge_vat']) || empty($this->controller->getUser()['additional']['charge_vat']))) {
$isTaxFree = true;
}
# set transaction as net order
# e.g. show_net = false means its a NET order
if (isset($this->controller->getUser()['additional']) && (!isset($this->controller->getUser()['additional']['show_net']) || empty($this->controller->getUser()['additional']['show_net']))) {
$isNet = true;
}
$shopId = Shopware()->Shop()->getId();
$transaction = $this->transactionBuilder->buildTransaction(
$basketSignature,
$currency,
$this->controller->getAmount(),
$shopId,
$this->controller->getUser(),
$locale,
$customer,
$isTaxFree,
$isNet
);
$this->repoTransactions->save($transaction);
return $transaction;
}
}