From b2f0001dfca882ae262773f78d99c8a63b426a00 Mon Sep 17 00:00:00 2001
From: Simon Schurter
Date: Wed, 13 Mar 2019 11:32:57 +0100
Subject: [PATCH 1/6] Create pending orders.
---
resources/lib/createTransaction.php | 11 ++-
resources/lib/updateTransaction.php | 45 ++++++++++++
src/Controllers/PaymentProcessController.php | 18 +++--
src/Methods/AbstractPaymentMethod.php | 28 +++++++-
src/Providers/WalleeServiceProvider.php | 18 ++---
src/Services/PaymentService.php | 76 ++++++++++++--------
6 files changed, 150 insertions(+), 46 deletions(-)
create mode 100644 resources/lib/updateTransaction.php
diff --git a/resources/lib/createTransaction.php b/resources/lib/createTransaction.php
index ebec77d..01ab476 100644
--- a/resources/lib/createTransaction.php
+++ b/resources/lib/createTransaction.php
@@ -227,6 +227,11 @@ function collectTransactionData($transactionRequest, $client)
$pendingTransaction->setFailedUrl(SdkRestApi::getParam('failedUrl') . '/' . $createdTransaction->getId());
$transactionResponse = $service->update($spaceId, $pendingTransaction);
-return [
- 'id' => $transactionResponse->getId()
-];
+$possiblePaymentMethods = $service->fetchPossiblePaymentMethods($spaceId, $transactionResponse->getId());
+if ($possiblePaymentMethods != null && ! empty($possiblePaymentMethods)) {
+ return [
+ 'id' => $transactionResponse->getId()
+ ];
+} else {
+ throw new \Exception('The selected payment method is not available.');
+}
\ No newline at end of file
diff --git a/resources/lib/updateTransaction.php b/resources/lib/updateTransaction.php
new file mode 100644
index 0000000..dcc3684
--- /dev/null
+++ b/resources/lib/updateTransaction.php
@@ -0,0 +1,45 @@
+setCurrency($transaction->getCurrency());
+ $transactionRequest->setCustomerId($transaction->getCustomerId());
+ $transactionRequest->setMerchantReference($order['id']);
+ $transactionRequest->setSuccessUrl(SdkRestApi::getParam('successUrl'));
+ $transactionRequest->setFailedUrl(SdkRestApi::getParam('checkoutUrl'));
+ $transactionRequest->setLanguage($transaction->getLanguage());
+ $transactionRequest->setLineItems($transaction->getLineItems());
+ $transactionRequest->setBillingAddress($transaction->getBillingAddress());
+ $transactionRequest->setShippingAddress($transaction->getShippingAddress());
+ $transactionRequest->setAllowedPaymentMethodConfigurations($transaction->getAllowedPaymentMethodConfigurations());
+}
+
+$spaceId = SdkRestApi::getParam('spaceId');
+
+$service = new TransactionService($client);
+
+for ($i = 0; $i < 5; $i ++) {
+ try {
+ $transaction = $service->read($spaceId, SdkRestApi::getParam('id'));
+
+ $transactionRequest = new TransactionPending();
+ $transactionRequest->setId($transaction->getId());
+ $transactionRequest->setVersion($transaction->getVersion());
+ collectTransactionData($transaction, $transactionRequest, $client);
+ $confirmedTransaction = $service->confirm($spaceId, $transactionRequest);
+
+ return WalleeSdkHelper::convertData($confirmedTransaction);
+ } catch (VersioningException $e) {}
+}
+
+throw new VersioningException();
\ No newline at end of file
diff --git a/src/Controllers/PaymentProcessController.php b/src/Controllers/PaymentProcessController.php
index 0d33bef..d5b0d40 100644
--- a/src/Controllers/PaymentProcessController.php
+++ b/src/Controllers/PaymentProcessController.php
@@ -7,6 +7,7 @@
use Plenty\Plugin\Http\Response;
use Plenty\Plugin\Log\Loggable;
use Wallee\Services\WalleeSdkService;
+use Wallee\Helper\PaymentHelper;
class PaymentProcessController extends Controller
{
@@ -37,6 +38,12 @@ class PaymentProcessController extends Controller
*/
private $notificationService;
+ /**
+ *
+ * @var PaymentHelper
+ */
+ private $paymentHelper;
+
/**
* PaymentController constructor.
*
@@ -44,14 +51,16 @@ class PaymentProcessController extends Controller
* @param Response $response
* @param WalleeSdkService $sdkService
* @param NotificationService $notificationService
+ * @param PaymentHelper $paymentHelper
*/
- public function __construct(Request $request, Response $response, WalleeSdkService $sdkService, NotificationService $notificationService)
+ public function __construct(Request $request, Response $response, WalleeSdkService $sdkService, NotificationService $notificationService, PaymentHelper $paymentHelper)
{
parent::__construct();
$this->request = $request;
$this->response = $response;
$this->sdkService = $sdkService;
$this->notificationService = $notificationService;
+ $this->paymentHelper = $paymentHelper;
}
/**
@@ -60,13 +69,14 @@ public function __construct(Request $request, Response $response, WalleeSdkServi
*/
public function failTransaction(int $id)
{
- $transaction = $this->sdkService->call('getTransactionByMerchantReference', [
- 'merchantReference' => $id
+ $transaction = $this->sdkService->call('getTransaction', [
+ 'id' => $id
]);
$this->getLogger(__METHOD__)->debug('wallee:failTransaction', $transaction);
if (is_array($transaction) && ! isset($transaction['error']) && isset($transaction['userFailureMessage']) && ! empty($transaction['userFailureMessage'])) {
$this->notificationService->error($transaction['userFailureMessage']);
+ $this->paymentHelper->updatePlentyPayment($transaction);
}
- return $this->response->redirectTo('checkout');
+ return $this->response->redirectTo('confirmation');
}
}
\ No newline at end of file
diff --git a/src/Methods/AbstractPaymentMethod.php b/src/Methods/AbstractPaymentMethod.php
index d410af7..a4a70ae 100644
--- a/src/Methods/AbstractPaymentMethod.php
+++ b/src/Methods/AbstractPaymentMethod.php
@@ -4,6 +4,8 @@
use Plenty\Modules\Payment\Method\Contracts\PaymentMethodService;
use Plenty\Plugin\ConfigRepository;
use Wallee\Services\PaymentService;
+use Plenty\Modules\Payment\Contracts\PaymentRepositoryContract;
+use Plenty\Modules\Payment\Models\Payment;
abstract class AbstractPaymentMethod extends PaymentMethodService
{
@@ -20,16 +22,24 @@ abstract class AbstractPaymentMethod extends PaymentMethodService
*/
protected $paymentService;
+ /**
+ *
+ * @var PaymentRepositoryContract
+ */
+ protected $paymentRepository;
+
/**
* Constructor.
*
* @param ConfigRepository $configRepo
* @param PaymentService $paymentService
+ * @param PaymentRepositoryContract $paymentRepository
*/
- public function __construct(ConfigRepository $configRepo, PaymentService $paymentService)
+ public function __construct(ConfigRepository $configRepo, PaymentService $paymentService, PaymentRepositoryContract $paymentRepository)
{
$this->configRepo = $configRepo;
$this->paymentService = $paymentService;
+ $this->paymentRepository = $paymentRepository;
}
protected function getBaseIconPath()
@@ -48,4 +58,20 @@ protected function getImagePath($fileName)
{
return $this->getBaseIconPath() . $fileName . '?' . time();
}
+
+ public function isSwitchableTo($orderId)
+ {
+ return false;
+ }
+
+ public function isSwitchableFrom($orderId)
+ {
+ $payments = $this->paymentRepository->getPaymentsByOrderId($orderId);
+ foreach ($payments as $payment) {
+ if ($payment->status != Payment::STATUS_CANCELED) {
+ return false;
+ }
+ }
+ return true;
+ }
}
\ No newline at end of file
diff --git a/src/Providers/WalleeServiceProvider.php b/src/Providers/WalleeServiceProvider.php
index b1bc3a6..6bece45 100644
--- a/src/Providers/WalleeServiceProvider.php
+++ b/src/Providers/WalleeServiceProvider.php
@@ -46,6 +46,7 @@
use Wallee\Repositories\WebhookRepository;
use IO\Services\BasketService;
use Plenty\Modules\Basket\Contracts\BasketRepositoryContract;
+use Plenty\Modules\Order\Contracts\OrderRepositoryContract;
class WalleeServiceProvider extends ServiceProvider
{
@@ -62,7 +63,7 @@ public function register()
*
* @param PaymentMethodContainer $payContainer
*/
- public function boot(Dispatcher $eventDispatcher, PaymentHelper $paymentHelper, PaymentService $paymentService, BasketRepositoryContract $basketRepository, PaymentMethodContainer $payContainer, PaymentMethodRepositoryContract $paymentMethodService, EventProceduresService $eventProceduresService, CronContainer $cronContainer)
+ public function boot(Dispatcher $eventDispatcher, PaymentHelper $paymentHelper, PaymentService $paymentService, BasketRepositoryContract $basketRepository, OrderRepositoryContract $orderRepository, PaymentMethodContainer $payContainer, PaymentMethodRepositoryContract $paymentMethodService, EventProceduresService $eventProceduresService, CronContainer $cronContainer)
{
$this->registerPaymentMethod($payContainer, 1457546097615, AlipayPaymentMethod::class);
$this->registerPaymentMethod($payContainer, 1457546097602, BankTransferPaymentMethod::class);
@@ -99,18 +100,17 @@ public function boot(Dispatcher $eventDispatcher, PaymentHelper $paymentHelper,
$eventDispatcher->listen(GetPaymentMethodContent::class, function (GetPaymentMethodContent $event) use ($paymentHelper, $basketRepository, $paymentService, $paymentMethodService) {
if ($paymentHelper->isWalleePaymentMopId($event->getMop())) {
- $content = $paymentService->getPaymentContent($basketRepository->load(), pluginApp(BasketService::class)->getBasketForTemplate(), $paymentMethodService->findByPaymentMethodId($event->getMop()));
- $event->setValue(isset($content['content']) ? $content['content'] : null);
- $event->setType(isset($content['type']) ? $content['type'] : '');
+ $result = $paymentService->getPaymentContent($basketRepository->load(), pluginApp(BasketService::class)->getBasketForTemplate(), $paymentMethodService->findByPaymentMethodId($event->getMop()));
+ $event->setValue(isset($result['content']) ? $result['content'] : null);
+ $event->setType(isset($result['type']) ? $result['type'] : '');
}
});
- $eventDispatcher->listen(ExecutePayment::class, function (ExecutePayment $event) use ($paymentHelper, $paymentService) {
+ $eventDispatcher->listen(ExecutePayment::class, function (ExecutePayment $event) use ($paymentHelper, $orderRepository, $paymentService, $paymentMethodService) {
if ($paymentHelper->isWalleePaymentMopId($event->getMop())) {
- $result = $paymentService->executePayment($event->getOrderId());
-
- $event->setType($result['type']);
- $event->setValue($result['value']);
+ $result = $paymentService->executePayment($orderRepository->findOrderById($event->getOrderId()), $paymentMethodService->findByPaymentMethodId($event->getMop()));
+ $event->setValue(isset($result['content']) ? $result['content'] : null);
+ $event->setType(isset($result['type']) ? $result['type'] : '');
}
});
diff --git a/src/Services/PaymentService.php b/src/Services/PaymentService.php
index fbca92a..0ba4a24 100644
--- a/src/Services/PaymentService.php
+++ b/src/Services/PaymentService.php
@@ -105,7 +105,8 @@ public function __construct(WalleeSdkService $sdkService, ConfigRepository $conf
/**
* Returns the payment method's content.
*
- * @param array $basket
+ * @param Basket $basket
+ * @param array $basketForTemplate
* @param PaymentMethod $paymentMethod
* @return string[]
*/
@@ -116,14 +117,14 @@ public function getPaymentContent(Basket $basket, array $basketForTemplate, Paym
'basketForTemplate' => $basketForTemplate,
'paymentMethod' => $paymentMethod,
'basketItems' => $this->getBasketItems($basket),
- 'billingAddress' => $this->getAddress($this->getBillingAddress($basket)),
- 'shippingAddress' => $this->getAddress($this->getShippingAddress($basket)),
+ 'billingAddress' => $this->getAddress($this->getBasketBillingAddress($basket)),
+ 'shippingAddress' => $this->getAddress($this->getBasketShippingAddress($basket)),
'language' => $this->session->getLocaleSettings()->language,
'successUrl' => $this->getSuccessUrl(),
'failedUrl' => $this->getFailedUrl(),
'checkoutUrl' => $this->getCheckoutUrl()
];
- $this->getLogger(__METHOD__)->debug('wallee::TransactionParameters', $parameters);
+ $this->getLogger(__METHOD__)->error('wallee::TransactionParameters', $parameters);
$transaction = $this->sdkService->call('createTransaction', $parameters);
@@ -136,24 +137,12 @@ public function getPaymentContent(Basket $basket, array $basketForTemplate, Paym
];
}
- $this->getLogger(__METHOD__)->debug('wallee::transaction result', $transaction);
+ $this->getLogger(__METHOD__)->error('wallee::transaction result', $transaction);
$this->session->getPlugin()->setValue('walleeTransactionId', $transaction['id']);
- $paymentPageUrl = $this->sdkService->call('buildPaymentPageUrl', [
- 'id' => $transaction['id']
- ]);
- if (is_array($paymentPageUrl) && isset($paymentPageUrl['error'])) {
- return [
- 'type' => GetPaymentMethodContent::RETURN_TYPE_ERROR,
- 'content' => $paymentPageUrl['error_msg']
- ];
- }
- $this->getLogger(__METHOD__)->debug('wallee::before redirect', $paymentPageUrl);
-
return [
- 'type' => GetPaymentMethodContent::RETURN_TYPE_REDIRECT_URL,
- 'content' => $paymentPageUrl
+ 'type' => GetPaymentMethodContent::RETURN_TYPE_CONTINUE
];
}
@@ -172,32 +161,61 @@ private function createWebhook()
/**
* Creates the payment in plentymarkets.
*
- * @param number $orderId
+ * @param Order $order
+ * @param PaymentMethod $paymentMethod
* @return string[]
*/
- public function executePayment($orderId)
+ public function executePayment(Order $order, PaymentMethod $paymentMethod): array
{
$transactionId = $this->session->getPlugin()->getValue('walleeTransactionId');
+ $parameters = [
+ 'id' => $transactionId,
+ 'order' => $order,
+ 'paymentMethod' => $paymentMethod,
+ 'billingAddress' => $this->getAddress($order->billingAddress),
+ 'shippingAddress' => $this->getAddress($order->deliveryAddress),
+ 'language' => $this->session->getLocaleSettings()->language,
+ 'successUrl' => $this->getSuccessUrl(),
+ 'failedUrl' => $this->getFailedUrl(),
+ 'checkoutUrl' => $this->getCheckoutUrl()
+ ];
+ $this->getLogger(__METHOD__)->error('wallee::TransactionParameters', $parameters);
+
+ // $transaction = $this->sdkService->call('updateTransaction', $parameters);
+
$transaction = $this->sdkService->call('getTransaction', [
'id' => $transactionId
]);
+ $this->getLogger(__METHOD__)->error('wallee::ConfirmTransaction', $transaction);
+
if (is_array($transaction) && $transaction['error']) {
return [
'type' => 'error',
- 'value' => $transaction['error_msg']
+ 'content' => $transaction['error_msg']
];
}
+ $this->session->getPlugin()->setValue('walleeTransactionId', null);
+
$payment = $this->paymentHelper->createPlentyPayment($transaction);
- $this->paymentHelper->assignPlentyPaymentToPlentyOrder($payment, $orderId);
+ $this->paymentHelper->assignPlentyPaymentToPlentyOrder($payment, $order->id);
- $this->session->getPlugin()->setValue('walleeTransactionId', null);
+ $paymentPageUrl = $this->sdkService->call('buildPaymentPageUrl', [
+ 'id' => $transaction['id']
+ ]);
+ if (is_array($paymentPageUrl) && isset($paymentPageUrl['error'])) {
+ return [
+ 'type' => GetPaymentMethodContent::RETURN_TYPE_ERROR,
+ 'content' => $paymentPageUrl['error_msg']
+ ];
+ }
+ $this->getLogger(__METHOD__)->error('wallee::before redirect', $paymentPageUrl);
return [
- 'type' => 'success',
- 'value' => 'The payment has been executed successfully.'
+ 'type' => GetPaymentMethodContent::RETURN_TYPE_REDIRECT_URL,
+ 'content' => $paymentPageUrl
];
}
@@ -206,7 +224,7 @@ public function executePayment($orderId)
* @param Basket $basket
* @return Address
*/
- private function getBillingAddress(Basket $basket): Address
+ private function getBasketBillingAddress(Basket $basket): Address
{
$addressId = $basket->customerInvoiceAddressId;
return $this->addressRepository->findAddressById($addressId);
@@ -217,13 +235,13 @@ private function getBillingAddress(Basket $basket): Address
* @param Basket $basket
* @return Address
*/
- private function getShippingAddress(Basket $basket)
+ private function getBasketShippingAddress(Basket $basket)
{
$addressId = $basket->customerShippingAddressId;
if ($addressId != null && $addressId != - 99) {
return $this->addressRepository->findAddressById($addressId);
} else {
- return $this->getBillingAddress($basket);
+ return $this->getBasketBillingAddress($basket);
}
}
@@ -296,7 +314,7 @@ private function getBasketItemName(BasketItem $basketItem): string
*/
private function getSuccessUrl(): string
{
- return $this->webstoreHelper->getCurrentWebstoreConfiguration()->domainSsl . '/place-order';
+ return $this->webstoreHelper->getCurrentWebstoreConfiguration()->domainSsl . '/confirmation';
}
/**
From 51e18b4b87c421f9ac14a1e2548d9f67cf1b6349 Mon Sep 17 00:00:00 2001
From: Simon Schurter
Date: Fri, 15 Mar 2019 15:27:00 +0100
Subject: [PATCH 2/6] - Show links to download invoice and packing slip on
confirmation page. - Add note that payment has been received to confirmation
page.
---
plugin.json | 8 ++
resources/lib/getInvoiceDocument.php | 13 +++
resources/lib/getPackingSlip.php | 13 +++
resources/views/PaymentInformation.twig | 11 +++
.../PaymentTransactionController.php | 91 +++++++++++++++++++
.../DataProvider/PaymentInformation.php | 54 +++++++++++
src/Providers/WalleeRouteServiceProvider.php | 2 +
7 files changed, 192 insertions(+)
create mode 100644 resources/lib/getInvoiceDocument.php
create mode 100644 resources/lib/getPackingSlip.php
create mode 100644 resources/views/PaymentInformation.twig
create mode 100644 src/Controllers/PaymentTransactionController.php
create mode 100644 src/Providers/DataProvider/PaymentInformation.php
diff --git a/plugin.json b/plugin.json
index e3f44d2..1d71abf 100644
--- a/plugin.json
+++ b/plugin.json
@@ -38,5 +38,13 @@
"runOnBuild": [
"Wallee\\Migrations\\CreatePaymentMethods",
"Wallee\\Migrations\\CreateWebhookTable"
+ ],
+ "dataProviders": [
+ {
+ "key": "Wallee\\Providers\\DataProvider\\PaymentInformation",
+ "name": "wallee Payment Information",
+ "description": "Display information about the wallee payment on the checkout page.",
+ "defaultLayoutContainer": "Ceres::OrderConfirmation.AdditionalPaymentInformation"
+ }
]
}
diff --git a/resources/lib/getInvoiceDocument.php b/resources/lib/getInvoiceDocument.php
new file mode 100644
index 0000000..5688db9
--- /dev/null
+++ b/resources/lib/getInvoiceDocument.php
@@ -0,0 +1,13 @@
+getInvoiceDocument($spaceId, SdkRestApi::getParam('id'));
+
+return WalleeSdkHelper::convertData($invoiceDocument);
\ No newline at end of file
diff --git a/resources/lib/getPackingSlip.php b/resources/lib/getPackingSlip.php
new file mode 100644
index 0000000..ad65a33
--- /dev/null
+++ b/resources/lib/getPackingSlip.php
@@ -0,0 +1,13 @@
+getPackingSlip($spaceId, SdkRestApi::getParam('id'));
+
+return WalleeSdkHelper::convertData($invoiceDocument);
\ No newline at end of file
diff --git a/resources/views/PaymentInformation.twig b/resources/views/PaymentInformation.twig
new file mode 100644
index 0000000..6f81d97
--- /dev/null
+++ b/resources/views/PaymentInformation.twig
@@ -0,0 +1,11 @@
+
+
+ {% if payment.status == 1 and (transaction.state == 'AUTHORIZED' or transaction.state == 'COMPLETED' or transaction.state == 'FULFILL') %}
+
Your payment has been received. The order's status will be updated shortly.
+ {% endif %}
+
+ {% if transaction.state == 'FULFILL' %}
+
Download Invoice
+
Download Packing Slip
+ {% endif %}
+
\ No newline at end of file
diff --git a/src/Controllers/PaymentTransactionController.php b/src/Controllers/PaymentTransactionController.php
new file mode 100644
index 0000000..1d23f38
--- /dev/null
+++ b/src/Controllers/PaymentTransactionController.php
@@ -0,0 +1,91 @@
+request = $request;
+ $this->response = $response;
+ $this->sdkService = $sdkService;
+ }
+
+ public function downloadInvoice(int $id)
+ {
+ $transaction = $this->sdkService->call('getTransaction', [
+ 'id' => $id
+ ]);
+ $this->getLogger(__METHOD__)->error('wallee::transaction', $transaction);
+ if (is_array($transaction) && ! isset($transaction['error'])) {
+ $invoiceDocument = $this->sdkService->call('getInvoiceDocument', [
+ 'id' => $id
+ ]);
+ $this->getLogger(__METHOD__)->error('wallee::invoice document', $invoiceDocument);
+ if (is_array($invoiceDocument) && ! isset($invoiceDocument['error'])) {
+ return $this->download($invoiceDocument);
+ }
+ }
+ }
+
+ public function downloadPackingSlip(int $id)
+ {
+ $transaction = $this->sdkService->call('getTransaction', [
+ 'id' => $id
+ ]);
+ $this->getLogger(__METHOD__)->error('wallee::transaction', $transaction);
+ if (is_array($transaction) && ! isset($transaction['error'])) {
+ $packingSlip = $this->sdkService->call('getPackingSlip', [
+ 'id' => $id
+ ]);
+ $this->getLogger(__METHOD__)->error('wallee::packing slip', $packingSlip);
+ if (is_array($packingSlip) && ! isset($packingSlip['error'])) {
+ return $this->download($packingSlip);
+ }
+ }
+ }
+
+ private function download($document)
+ {
+ return $this->response->make(base64_decode($document['data']), 200, [
+ 'Pragma' => 'public',
+ 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
+ 'Content-type' => 'application/pdf',
+ 'Content-Disposition' => 'attachment; filename=' . $document['title'] . '.pdf',
+ 'Content-Description' => $document['title']
+ ]);
+ }
+}
\ No newline at end of file
diff --git a/src/Providers/DataProvider/PaymentInformation.php b/src/Providers/DataProvider/PaymentInformation.php
new file mode 100644
index 0000000..8904076
--- /dev/null
+++ b/src/Providers/DataProvider/PaymentInformation.php
@@ -0,0 +1,54 @@
+getLogger('Wallee', __METHOD__);
+
+ $order = $arg[0];
+ $logger->error('wallee::payment information order', $order);
+
+ $payments = pluginApp(PaymentRepositoryContract::class)->getPaymentsByOrderId($order['id']);
+ foreach ($payments as $payment) {
+ $logger->error('wallee::payment information payment', $payment);
+ if ($payment->status != Payment::STATUS_CANCELED) {
+ $transactionId = null;
+ foreach ($payment->properties as $property) {
+ if ($property->typeId == PaymentProperty::TYPE_TRANSACTION_ID) {
+ $transactionId = $property->value;
+ }
+ }
+ $logger->error('wallee::payment information transaction id', $transactionId);
+ if (! empty($transactionId)) {
+ $transaction = pluginApp(WalleeSdkService::class)->call('getTransaction', [
+ 'id' => $transactionId
+ ]);
+ if (is_array($transaction) && isset($transaction['error'])) {
+ return "";
+ } else {
+ $logger->error('wallee::payment information transaction', $transaction);
+ return $twig->render('wallee::PaymentInformation', [
+ 'order' => $order,
+ 'transaction' => $transaction,
+ 'payment' => $payment
+ ]);
+ }
+ } else {
+ return "";
+ }
+ }
+ }
+
+ return "";
+ }
+}
\ No newline at end of file
diff --git a/src/Providers/WalleeRouteServiceProvider.php b/src/Providers/WalleeRouteServiceProvider.php
index 132694a..60c3656 100644
--- a/src/Providers/WalleeRouteServiceProvider.php
+++ b/src/Providers/WalleeRouteServiceProvider.php
@@ -15,5 +15,7 @@ public function map(Router $router)
{
$router->post('wallee/update-transaction', 'Wallee\Controllers\PaymentNotificationController@updateTransaction');
$router->get('wallee/fail-transaction/{id}', 'Wallee\Controllers\PaymentProcessController@failTransaction')->where('id', '\d+');
+ $router->get('wallee/download-invoice/{id}', 'Wallee\Controllers\PaymentTransactionController@downloadInvoice')->where('id', '\d+');
+ $router->get('wallee/download-packing-slip/{id}', 'Wallee\Controllers\PaymentTransactionController@downloadPackingSlip')->where('id', '\d+');
}
}
\ No newline at end of file
From 84701134e84fe0cab642335dcb66bb0a435b76b4 Mon Sep 17 00:00:00 2001
From: Simon Schurter
Date: Mon, 18 Mar 2019 15:15:00 +0100
Subject: [PATCH 3/6] - Create transaction from order. - Allow to change
payment method.
---
...on.php => createTransactionFromBasket.php} | 0
resources/lib/createTransactionFromOrder.php | 214 +++++++++++++++++
resources/lib/updateTransaction.php | 45 ----
resources/views/Failure.twig | 27 +++
src/Controllers/PaymentProcessController.php | 227 +++++++++++++++++-
src/Helper/OrderHelper.php | 50 ++++
src/Helper/PaymentHelper.php | 6 +-
src/Methods/AbstractPaymentMethod.php | 8 +-
src/Providers/WalleeRouteServiceProvider.php | 3 +
src/Services/PaymentService.php | 52 ++--
10 files changed, 550 insertions(+), 82 deletions(-)
rename resources/lib/{createTransaction.php => createTransactionFromBasket.php} (100%)
create mode 100644 resources/lib/createTransactionFromOrder.php
delete mode 100644 resources/lib/updateTransaction.php
create mode 100644 resources/views/Failure.twig
create mode 100644 src/Helper/OrderHelper.php
diff --git a/resources/lib/createTransaction.php b/resources/lib/createTransactionFromBasket.php
similarity index 100%
rename from resources/lib/createTransaction.php
rename to resources/lib/createTransactionFromBasket.php
diff --git a/resources/lib/createTransactionFromOrder.php b/resources/lib/createTransactionFromOrder.php
new file mode 100644
index 0000000..79c8c3d
--- /dev/null
+++ b/resources/lib/createTransactionFromOrder.php
@@ -0,0 +1,214 @@
+setUniqueId($uniqueId);
+ $lineItem->setSku($sku);
+ $lineItem->setName(mb_substr($orderItem['orderItemName'], 0, 40, "UTF-8"));
+ $lineItem->setQuantity((int) $orderItem['quantity']);
+ if ($basketNetPrices) {
+ $lineItem->setAmountIncludingTax(WalleeSdkHelper::roundAmount($orderItem['amounts'][0]['priceNet'], $currencyDecimalPlaces));
+ } else {
+ $lineItem->setAmountIncludingTax(WalleeSdkHelper::roundAmount($orderItem['amounts'][0]['priceGross'], $currencyDecimalPlaces));
+ }
+ if (isset($orderItem['vatRate']) && ! empty($orderItem['vatRate'])) {
+ $lineItem->setTaxes([
+ new TaxCreate([
+ 'rate' => $orderItem['vatRate'],
+ 'title' => 'Tax'
+ ])
+ ]);
+ }
+ $lineItem->setType($type);
+ return $lineItem;
+}
+
+function collectTransactionData($transactionRequest, $client)
+{
+ $spaceId = SdkRestApi::getParam('spaceId');
+ $order = SdkRestApi::getParam('order');
+
+ $transactionRequest->setCurrency($order['amounts'][0]['currency']);
+ $transactionRequest->setCustomerId(SdkRestApi::getParam('customerId')); // FIXME: only set customer id if customer has account.
+ $transactionRequest->setMerchantReference($order['id']);
+ $transactionRequest->setSuccessUrl(SdkRestApi::getParam('successUrl'));
+ $transactionRequest->setFailedUrl(SdkRestApi::getParam('checkoutUrl'));
+
+ $service = new LanguageService($client);
+ $languages = $service->all();
+ foreach ($languages as $language) {
+ if ($language->getIso2Code() == SdkRestApi::getParam('language') && $language->getPrimaryOfGroup()) {
+ $transactionRequest->setLanguage($language->getIetfCode());
+ }
+ }
+
+ $currencyService = new CurrencyService($client);
+ $currencyDecimalPlaces = 2;
+ $currencies = $currencyService->all();
+ foreach ($currencies as $currency) {
+ if ($currency->getCurrencyCode() == $order['amounts'][0]['currency']) {
+ $currencyDecimalPlaces = $currency->getFractionDigits();
+ break;
+ }
+ }
+
+ $netPrices = $order['amounts'][0]['isNet'];
+ $lineItems = [];
+ foreach ($order['orderItems'] as $orderItem) {
+ if ($orderItem['typeId'] == 1 || $orderItem['typeId'] == 2 || $orderItem['typeId'] == 3) {
+ // VARIANTION
+ $lineItem = buildLineItem($orderItem, $orderItem['itemVariationId'], $orderItem['itemVariationId'], LineItemType::PRODUCT, $netPrices, $currencyDecimalPlaces);
+ $lineItem->setShippingRequired(true);
+ $lineItems[] = $lineItem;
+ } elseif ($orderItem['typeId'] == 4 || $orderItem['typeId'] == 5) {
+ // GIFT_CARD
+ $lineItem = buildLineItem($orderItem, $orderItem['itemVariationId'], $orderItem['itemVariationId'], LineItemType::DISCOUNT, $netPrices, $currencyDecimalPlaces);
+ $lineItems[] = $lineItem;
+ } elseif ($orderItem['typeId'] == 6) {
+ // SHIPPING
+ $lineItems[] = buildLineItem($orderItem, 'shipping', 'shipping', LineItemType::SHIPPING, false, $currencyDecimalPlaces);
+ } elseif ($orderItem['typeId'] == 7) {
+ // PAYMENT SURCHARGE
+ $lineItems[] = buildLineItem($orderItem, 'payment-fee', 'payment-fee', LineItemType::FEE, $netPrices, $currencyDecimalPlaces);
+ } elseif ($orderItem['typeId'] == 8) {
+ // GIFT WRAP
+ $lineItems[] = buildLineItem($orderItem, 'gift-wrap', 'gift-wrap', LineItemType::FEE, $netPrices, $currencyDecimalPlaces);
+ }
+ }
+
+ $lineItemTotalAmount = WalleeSdkHelper::calculateLineItemTotalAmount($lineItems);
+ $basketAmount = $netPrices ? $order['amounts'][0]['netTotal'] : $order['amounts'][0]['grossTotal'];
+ if (WalleeSdkHelper::roundAmount($lineItemTotalAmount, $currencyDecimalPlaces) > WalleeSdkHelper::roundAmount($basketAmount, $currencyDecimalPlaces)) {
+ $lineItem = new LineItemCreate();
+ $lineItem->setUniqueId('adjustment');
+ $lineItem->setSku('adjustment');
+ $lineItem->setName('Adjustment');
+ $lineItem->setQuantity(1);
+ $lineItem->setAmountIncludingTax(WalleeSdkHelper::roundAmount($basketAmount - $lineItemTotalAmount, $currencyDecimalPlaces));
+ $lineItem->setType('DISCOUNT');
+ $lineItems[] = $lineItem;
+ } elseif ($lineItemTotalAmount < $basketAmount) {
+ $lineItem = new LineItemCreate();
+ $lineItem->setUniqueId('adjustment');
+ $lineItem->setSku('adjustment');
+ $lineItem->setName('Adjustment');
+ $lineItem->setQuantity(1);
+ $lineItem->setAmountIncludingTax(WalleeSdkHelper::roundAmount($basketAmount - $lineItemTotalAmount, $currencyDecimalPlaces));
+ $lineItem->setType('FEE');
+ $lineItems[] = $lineItem;
+ }
+ $transactionRequest->setLineItems($lineItems);
+
+ $basketBillingAddress = SdkRestApi::getParam('billingAddress');
+ $billingAddress = new AddressCreate();
+ $billingAddress->setCity(mb_substr($basketBillingAddress['city'], 0, 100, "UTF-8"));
+ $billingAddress->setCountry($basketBillingAddress['country']);
+ $billingAddress->setDateOfBirth($basketBillingAddress['dateOfBirth']);
+ $billingAddress->setEmailAddress(mb_substr($basketBillingAddress['emailAddress'], 0, 254, "UTF-8"));
+ $billingAddress->setFamilyName(mb_substr($basketBillingAddress['familyName'], 0, 100, "UTF-8"));
+ $billingAddress->setGivenName(mb_substr($basketBillingAddress['givenName'], 0, 100, "UTF-8"));
+ $billingAddress->setOrganizationName(mb_substr($basketBillingAddress['organisationName'], 0, 100, "UTF-8"));
+ $billingAddress->setPhoneNumber($basketBillingAddress['phoneNumber']);
+ $billingAddress->setPostCode(mb_substr($basketBillingAddress['postCode'], 0, 40, "UTF-8"));
+ $billingAddress->setStreet(mb_substr($basketBillingAddress['street'], 0, 300, "UTF-8"));
+
+ if (isset($basketBillingAddress['gender'])) {
+ if (strtolower($basketBillingAddress['gender']) == 'male') {
+ $billingAddress->setGender(Gender::MALE);
+ } else if (strtolower($basketBillingAddress['gender']) == 'female') {
+ $billingAddress->setGender(Gender::FEMALE);
+ }
+ }
+
+ $transactionRequest->setBillingAddress($billingAddress);
+
+ $basketShippingAddress = SdkRestApi::getParam('shippingAddress');
+ $shippingAddress = new AddressCreate();
+ $shippingAddress->setCity(mb_substr($basketShippingAddress['city'], 0, 100, "UTF-8"));
+ $shippingAddress->setCountry($basketShippingAddress['country']);
+ $shippingAddress->setDateOfBirth($basketShippingAddress['dateOfBirth']);
+ $shippingAddress->setEmailAddress(mb_substr($basketShippingAddress['emailAddress'], 0, 254, "UTF-8"));
+ $shippingAddress->setFamilyName(mb_substr($basketShippingAddress['familyName'], 0, 100, "UTF-8"));
+ $shippingAddress->setGivenName(mb_substr($basketShippingAddress['givenName'], 0, 100, "UTF-8"));
+ $shippingAddress->setOrganizationName(mb_substr($basketShippingAddress['organisationName'], 0, 100, "UTF-8"));
+ $shippingAddress->setPhoneNumber($basketShippingAddress['phoneNumber']);
+ $shippingAddress->setPostCode(mb_substr($basketShippingAddress['postCode'], 0, 40, "UTF-8"));
+ $shippingAddress->setStreet(mb_substr($basketShippingAddress['street'], 0, 300, "UTF-8"));
+
+ if (isset($basketShippingAddress['gender'])) {
+ if (strtolower($basketShippingAddress['gender']) == 'male') {
+ $shippingAddress->setGender(Gender::MALE);
+ } else if (strtolower($basketShippingAddress['gender']) == 'female') {
+ $shippingAddress->setGender(Gender::FEMALE);
+ }
+ }
+
+ $transactionRequest->setShippingAddress($shippingAddress);
+
+ $paymentMethod = SdkRestApi::getParam('paymentMethod');
+ $paymentMethodId = (int) $paymentMethod['paymentKey'];
+
+ $paymentMethodConfigurationService = new PaymentMethodConfigurationService($client);
+ $query = new EntityQuery();
+ $query->setNumberOfEntities(20);
+ $filter = new EntityQueryFilter();
+ $filter->setType(\Wallee\Sdk\Model\EntityQueryFilterType::_AND);
+ $filter->setChildren([
+ WalleeSdkHelper::createEntityFilter('state', \Wallee\Sdk\Model\CreationEntityState::ACTIVE),
+ WalleeSdkHelper::createEntityFilter('paymentMethod', $paymentMethodId)
+ ]);
+ $query->setFilter($filter);
+ $paymentMethodConfigurations = $paymentMethodConfigurationService->search($spaceId, $query);
+
+ $allowedPaymentMethodConfigurations = [];
+ foreach ($paymentMethodConfigurations as $paymentMethodConfiguration) {
+ $allowedPaymentMethodConfigurations[] = $paymentMethodConfiguration->getId();
+ }
+
+ $transactionRequest->setAllowedPaymentMethodConfigurations($allowedPaymentMethodConfigurations);
+}
+
+$spaceId = SdkRestApi::getParam('spaceId');
+
+$transactionRequest = new TransactionCreate();
+collectTransactionData($transactionRequest, $client);
+$transactionRequest->setAutoConfirmationEnabled(false);
+$transactionRequest->setCustomersPresence(\Wallee\Sdk\Model\CustomersPresence::VIRTUAL_PRESENT);
+
+$service = new TransactionService($client);
+$createdTransaction = $service->create($spaceId, $transactionRequest);
+
+$pendingTransaction = new TransactionPending();
+$pendingTransaction->setId($createdTransaction->getId());
+$pendingTransaction->setVersion($createdTransaction->getVersion());
+collectTransactionData($pendingTransaction, $client);
+$pendingTransaction->setFailedUrl(SdkRestApi::getParam('failedUrl') . '/' . $createdTransaction->getId());
+$transactionResponse = $service->confirm($spaceId, $pendingTransaction);
+
+$possiblePaymentMethods = $service->fetchPossiblePaymentMethods($spaceId, $transactionResponse->getId());
+if ($possiblePaymentMethods != null && ! empty($possiblePaymentMethods)) {
+ return WalleeSdkHelper::convertData($transactionResponse);
+} else {
+ throw new \Exception('The selected payment method is not available.');
+}
\ No newline at end of file
diff --git a/resources/lib/updateTransaction.php b/resources/lib/updateTransaction.php
deleted file mode 100644
index dcc3684..0000000
--- a/resources/lib/updateTransaction.php
+++ /dev/null
@@ -1,45 +0,0 @@
-setCurrency($transaction->getCurrency());
- $transactionRequest->setCustomerId($transaction->getCustomerId());
- $transactionRequest->setMerchantReference($order['id']);
- $transactionRequest->setSuccessUrl(SdkRestApi::getParam('successUrl'));
- $transactionRequest->setFailedUrl(SdkRestApi::getParam('checkoutUrl'));
- $transactionRequest->setLanguage($transaction->getLanguage());
- $transactionRequest->setLineItems($transaction->getLineItems());
- $transactionRequest->setBillingAddress($transaction->getBillingAddress());
- $transactionRequest->setShippingAddress($transaction->getShippingAddress());
- $transactionRequest->setAllowedPaymentMethodConfigurations($transaction->getAllowedPaymentMethodConfigurations());
-}
-
-$spaceId = SdkRestApi::getParam('spaceId');
-
-$service = new TransactionService($client);
-
-for ($i = 0; $i < 5; $i ++) {
- try {
- $transaction = $service->read($spaceId, SdkRestApi::getParam('id'));
-
- $transactionRequest = new TransactionPending();
- $transactionRequest->setId($transaction->getId());
- $transactionRequest->setVersion($transaction->getVersion());
- collectTransactionData($transaction, $transactionRequest, $client);
- $confirmedTransaction = $service->confirm($spaceId, $transactionRequest);
-
- return WalleeSdkHelper::convertData($confirmedTransaction);
- } catch (VersioningException $e) {}
-}
-
-throw new VersioningException();
\ No newline at end of file
diff --git a/resources/views/Failure.twig b/resources/views/Failure.twig
new file mode 100644
index 0000000..abdb7ba
--- /dev/null
+++ b/resources/views/Failure.twig
@@ -0,0 +1,27 @@
+{% extends getPartial('page-design') %}
+
+{% block PageBody %}
+ {{ transaction.userFailureMessage }}
+
+ Transaction Id: {{ transaction.id }}
+
+ Order Id: {{ order.id }}
+
+ Payment State: {{ payment.status }}
+
+ Current Payment Method: {{ currentPaymentMethodId }}
+
+ {% if allowSwitchPaymentMethod %}
+
+
Switch payment method:
+
+ {% for method in paymentMethodListForSwitch %}
+ -
+ {{ method | json_encode() }} {% if method.id == currentPaymentMethodId %}[current]{% endif %}
+ Pay
+
+ {% endfor %}
+
+
+ {% endif %}
+{% endblock %}
\ No newline at end of file
diff --git a/src/Controllers/PaymentProcessController.php b/src/Controllers/PaymentProcessController.php
index d5b0d40..90b25ea 100644
--- a/src/Controllers/PaymentProcessController.php
+++ b/src/Controllers/PaymentProcessController.php
@@ -8,6 +8,21 @@
use Plenty\Plugin\Log\Loggable;
use Wallee\Services\WalleeSdkService;
use Wallee\Helper\PaymentHelper;
+use Plenty\Plugin\Templates\Twig;
+use Plenty\Modules\Payment\Contracts\PaymentRepositoryContract;
+use Plenty\Modules\Order\Contracts\OrderRepositoryContract;
+use Plenty\Modules\Payment\Contracts\PaymentOrderRelationRepositoryContract;
+use Plenty\Modules\Payment\Models\PaymentProperty;
+use IO\Services\OrderService;
+use Plenty\Modules\Authorization\Services\AuthHelper;
+use IO\Constants\OrderPaymentStatus;
+use Plenty\Modules\Order\Models\Order;
+use Plenty\Modules\Order\Property\Models\OrderProperty;
+use Plenty\Modules\Frontend\PaymentMethod\Contracts\FrontendPaymentMethodRepositoryContract;
+use Plenty\Modules\Order\Property\Models\OrderPropertyType;
+use Plenty\Modules\Payment\Method\Contracts\PaymentMethodRepositoryContract;
+use Wallee\Services\PaymentService;
+use Plenty\Modules\Payment\Events\Checkout\GetPaymentMethodContent;
class PaymentProcessController extends Controller
{
@@ -38,6 +53,12 @@ class PaymentProcessController extends Controller
*/
private $notificationService;
+ /**
+ *
+ * @var PaymentService
+ */
+ private $paymentService;
+
/**
*
* @var PaymentHelper
@@ -45,38 +66,234 @@ class PaymentProcessController extends Controller
private $paymentHelper;
/**
- * PaymentController constructor.
+ *
+ * @var PaymentRepositoryContract
+ */
+ private $paymentRepository;
+
+ /**
+ *
+ * @var OrderRepositoryContract
+ */
+ private $orderRepository;
+
+ /**
+ *
+ * @var PaymentOrderRelationRepositoryContract
+ */
+ private $paymentOrderRelationRepository;
+
+ /**
+ *
+ * @var OrderService
+ */
+ private $orderService;
+
+ /**
+ *
+ * @var FrontendPaymentMethodRepositoryContract
+ */
+ private $frontendPaymentMethodRepository;
+
+ /**
+ *
+ * @var PaymentMethodRepositoryContract
+ */
+ private $paymentMethodService;
+
+ /**
+ * Constructor.
*
* @param Request $request
* @param Response $response
* @param WalleeSdkService $sdkService
* @param NotificationService $notificationService
+ * @param PaymentService $paymentService
* @param PaymentHelper $paymentHelper
+ * @param PaymentRepositoryContract $paymentRepository
+ * @param OrderRepositoryContract $orderRepository
+ * @param PaymentOrderRelationRepositoryContract $paymentOrderRelationRepository
+ * @param OrderService $orderService
+ * @param FrontendPaymentMethodRepositoryContract $frontendPaymentMethodRepository
+ * @param PaymentMethodRepositoryContract $paymentMethodService
*/
- public function __construct(Request $request, Response $response, WalleeSdkService $sdkService, NotificationService $notificationService, PaymentHelper $paymentHelper)
+ public function __construct(Request $request, Response $response, WalleeSdkService $sdkService, NotificationService $notificationService, PaymentService $paymentService, PaymentHelper $paymentHelper, PaymentRepositoryContract $paymentRepository, OrderRepositoryContract $orderRepository, PaymentOrderRelationRepositoryContract $paymentOrderRelationRepository, OrderService $orderService, FrontendPaymentMethodRepositoryContract $frontendPaymentMethodRepository, PaymentMethodRepositoryContract $paymentMethodService)
{
parent::__construct();
$this->request = $request;
$this->response = $response;
$this->sdkService = $sdkService;
$this->notificationService = $notificationService;
+ $this->paymentService = $paymentService;
$this->paymentHelper = $paymentHelper;
+ $this->paymentRepository = $paymentRepository;
+ $this->orderRepository = $orderRepository;
+ $this->paymentOrderRelationRepository = $paymentOrderRelationRepository;
+ $this->orderService = $orderService;
+ $this->frontendPaymentMethodRepository = $frontendPaymentMethodRepository;
+ $this->paymentMethodService = $paymentMethodService;
}
/**
*
* @param int $id
*/
- public function failTransaction(int $id)
+ public function failTransaction(Twig $twig, int $id)
{
$transaction = $this->sdkService->call('getTransaction', [
'id' => $id
]);
+ if (is_array($transaction) && isset($transaction['error'])) {
+ // TODO: Handle transaction fetching error.
+ }
$this->getLogger(__METHOD__)->debug('wallee:failTransaction', $transaction);
- if (is_array($transaction) && ! isset($transaction['error']) && isset($transaction['userFailureMessage']) && ! empty($transaction['userFailureMessage'])) {
+
+ $payments = $this->paymentRepository->getPaymentsByPropertyTypeAndValue(PaymentProperty::TYPE_TRANSACTION_ID, $transaction['id']);
+ $payment = $payments[0];
+ $this->getLogger(__METHOD__)->error('wallee:failTransaction', $payment);
+
+ $orderRelation = $this->paymentOrderRelationRepository->findOrderRelation($payment);
+ $order = $this->orderRepository->findOrderById($orderRelation->orderId);
+ $this->getLogger(__METHOD__)->error('wallee:failTransaction', $order);
+
+ $paymentMethodId = $this->getOrderPropertyValue($order, OrderPropertyType::PAYMENT_METHOD);
+
+ if (isset($transaction['userFailureMessage']) && ! empty($transaction['userFailureMessage'])) {
$this->notificationService->error($transaction['userFailureMessage']);
$this->paymentHelper->updatePlentyPayment($transaction);
}
- return $this->response->redirectTo('confirmation');
+
+ // return $this->response->redirectTo('confirmation');
+ return $twig->render('wallee::Failure', [
+ 'transaction' => $transaction,
+ 'payment' => $payment,
+ 'order' => $order,
+ 'currentPaymentMethodId' => $paymentMethodId,
+ 'allowSwitchPaymentMethod' => $this->allowSwitchPaymentMethod($order->id),
+ 'paymentMethodListForSwitch' => $this->getPaymentMethodListForSwitch($paymentMethodId, $order->id)
+ ]);
+ }
+
+ /**
+ *
+ * @param int $id
+ * @param int $paymentMethodId
+ */
+ public function payOrder(int $id, int $paymentMethodId)
+ {
+ $this->getLogger(__METHOD__)->error('wallee:retryPayment', $paymentMethodId);
+
+ /** @var AuthHelper $authHelper */
+ $authHelper = pluginApp(AuthHelper::class);
+ $orderRepo = $this->orderRepository;
+ $order = $order = $authHelper->processUnguarded(function () use ($id, $orderRepo) {
+ return $orderRepo->findOrderById($id);
+ });
+
+ $this->switchPaymentMethodForOrder($order, $paymentMethodId);
+ $result = $this->paymentService->executePayment($order, $this->paymentMethodService->findByPaymentMethodId($paymentMethodId));
+
+ if ($result['type'] == GetPaymentMethodContent::RETURN_TYPE_REDIRECT_URL) {
+ return $this->response->redirectTo($result['content']);
+ } else {
+ // TODO
+ }
+ }
+
+ private function switchPaymentMethodForOrder(Order $order, $paymentMethodId)
+ {
+ $orderId = $order->id;
+ $orderRepo = $this->orderRepository;
+ $currentPaymentMethodId = 0;
+ $newOrderProperties = [];
+ $orderProperties = $order->properties;
+
+ if (count($orderProperties)) {
+ foreach ($orderProperties as $key => $orderProperty) {
+ $newOrderProperties[$key] = [
+ 'typeId' => $orderProperty->typeId,
+ 'value' => (string) $orderProperty->value
+ ];
+ if ($orderProperty->typeId == OrderPropertyType::PAYMENT_METHOD) {
+ $currentPaymentMethodId = (int) $orderProperty->value;
+ $newOrderProperties[$key]['value'] = (string) $paymentMethodId;
+ }
+ }
+ }
+
+ if ($paymentMethodId !== $currentPaymentMethodId) {
+ /** @var AuthHelper $authHelper */
+ $authHelper = pluginApp(AuthHelper::class);
+ $order = $authHelper->processUnguarded(function () use ($orderId, $newOrderProperties, $orderRepo) {
+ return $orderRepo->updateOrder([
+ 'properties' => $newOrderProperties
+ ], $orderId);
+ });
+
+ if (! is_null($order)) {
+ return $order;
+ }
+ } else {
+ return $order;
+ }
+ }
+
+ private function getPaymentMethodListForSwitch($paymentMethodId, $orderId)
+ {
+ $paymentMethods = $this->frontendPaymentMethodRepository->getCurrentPaymentMethodsList();
+ $paymentMethodsForSwitch = [];
+ foreach ($paymentMethods as $paymentMethod) {
+ if ($paymentMethod->pluginKey == 'wallee') {
+ $paymentMethodsForSwitch[] = $paymentMethod;
+ }
+ }
+ return $paymentMethodsForSwitch;
+ }
+
+ private function allowSwitchPaymentMethod($orderId)
+ {
+ /** @var AuthHelper $authHelper */
+ $authHelper = pluginApp(AuthHelper::class);
+ $orderRepo = $this->orderRepository;
+
+ $order = $authHelper->processUnguarded(function () use ($orderId, $orderRepo) {
+ return $orderRepo->findOrderById($orderId);
+ });
+
+ if ($order->paymentStatus !== OrderPaymentStatus::UNPAID) {
+ // order was paid
+ return false;
+ }
+
+ $statusId = $order->statusId;
+ $orderCreatedDate = $order->createdAt;
+
+ if (! ($statusId <= 3.4 || ($statusId == 5 && $orderCreatedDate->toDateString() == date('Y-m-d')))) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ *
+ * @param Order $order
+ * @param int $propertyType
+ * @return null|string
+ */
+ public function getOrderPropertyValue($order, $propertyType)
+ {
+ $properties = $order->properties;
+ if (($properties->count() > 0) || (is_array($properties) && count($properties) > 0)) {
+ /** @var OrderProperty $property */
+ foreach ($properties as $property) {
+ if ($property instanceof OrderProperty) {
+ if ($property->typeId == $propertyType) {
+ return $property->value;
+ }
+ }
+ }
+ }
+ return null;
}
}
\ No newline at end of file
diff --git a/src/Helper/OrderHelper.php b/src/Helper/OrderHelper.php
new file mode 100644
index 0000000..7d8a6b0
--- /dev/null
+++ b/src/Helper/OrderHelper.php
@@ -0,0 +1,50 @@
+relations;
+ if (($relations->count() > 0) || (is_array($relations) && count($relations) > 0)) {
+ /** @var OrderRelationReference $relation */
+ foreach ($relations as $relation) {
+ if ($relation instanceof OrderRelationReference) {
+ if ($relation->referenceType == $referenceType) {
+ return $relation->referenceId;
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ *
+ * @param Order $order
+ * @param int $propertyType
+ * @return null|string
+ */
+ public function getOrderPropertyValue(Order $order, $propertyType)
+ {
+ $properties = $order->properties;
+ if (($properties->count() > 0) || (is_array($properties) && count($properties) > 0)) {
+ /** @var OrderProperty $property */
+ foreach ($properties as $property) {
+ if ($property instanceof OrderProperty) {
+ if ($property->typeId == $propertyType) {
+ return $property->value;
+ }
+ }
+ }
+ }
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/src/Helper/PaymentHelper.php b/src/Helper/PaymentHelper.php
index 32be3a1..d5188d7 100644
--- a/src/Helper/PaymentHelper.php
+++ b/src/Helper/PaymentHelper.php
@@ -275,18 +275,16 @@ public function mapRefundState(string $state)
/**
* Returns a PaymentProperty with the given params
*
- * @param Payment $payment
- * @param array $data
+ * @param int $typeId
+ * @param mixed $data
* @return PaymentProperty
*/
private function getPaymentProperty($typeId, $value)
{
/** @var PaymentProperty $paymentProperty */
$paymentProperty = pluginApp(\Plenty\Modules\Payment\Models\PaymentProperty::class);
-
$paymentProperty->typeId = $typeId;
$paymentProperty->value = (string) $value;
-
return $paymentProperty;
}
diff --git a/src/Methods/AbstractPaymentMethod.php b/src/Methods/AbstractPaymentMethod.php
index a4a70ae..0a5385b 100644
--- a/src/Methods/AbstractPaymentMethod.php
+++ b/src/Methods/AbstractPaymentMethod.php
@@ -66,12 +66,6 @@ public function isSwitchableTo($orderId)
public function isSwitchableFrom($orderId)
{
- $payments = $this->paymentRepository->getPaymentsByOrderId($orderId);
- foreach ($payments as $payment) {
- if ($payment->status != Payment::STATUS_CANCELED) {
- return false;
- }
- }
- return true;
+ return false;
}
}
\ No newline at end of file
diff --git a/src/Providers/WalleeRouteServiceProvider.php b/src/Providers/WalleeRouteServiceProvider.php
index 60c3656..42bda63 100644
--- a/src/Providers/WalleeRouteServiceProvider.php
+++ b/src/Providers/WalleeRouteServiceProvider.php
@@ -15,6 +15,9 @@ public function map(Router $router)
{
$router->post('wallee/update-transaction', 'Wallee\Controllers\PaymentNotificationController@updateTransaction');
$router->get('wallee/fail-transaction/{id}', 'Wallee\Controllers\PaymentProcessController@failTransaction')->where('id', '\d+');
+ $router->get('wallee/pay-order/{id}/{paymentMethodId}', 'Wallee\Controllers\PaymentProcessController@payOrder')
+ ->where('id', '\d+')
+ ->where('paymentMethodId', '\d+');
$router->get('wallee/download-invoice/{id}', 'Wallee\Controllers\PaymentTransactionController@downloadInvoice')->where('id', '\d+');
$router->get('wallee/download-packing-slip/{id}', 'Wallee\Controllers\PaymentTransactionController@downloadPackingSlip')->where('id', '\d+');
}
diff --git a/src/Services/PaymentService.php b/src/Services/PaymentService.php
index 0ba4a24..60010fb 100644
--- a/src/Services/PaymentService.php
+++ b/src/Services/PaymentService.php
@@ -16,6 +16,9 @@
use Plenty\Modules\Payment\Method\Models\PaymentMethod;
use Plenty\Modules\Order\Models\Order;
use Plenty\Modules\Order\Contracts\OrderRepositoryContract;
+use Wallee\Helper\OrderHelper;
+use Plenty\Modules\Item\Variation\Contracts\VariationRepositoryContract;
+use Plenty\Modules\Order\RelationReference\Models\OrderRelationReference;
class PaymentService
{
@@ -40,6 +43,12 @@ class PaymentService
*/
private $itemRepository;
+ /**
+ *
+ * @var VariationRepositoryContract
+ */
+ private $variationRepository;
+
/**
*
* @var FrontendSessionStorageFactoryContract
@@ -70,6 +79,12 @@ class PaymentService
*/
private $paymentHelper;
+ /**
+ *
+ * @var OrderHelper
+ */
+ private $orderHelper;
+
/**
*
* @var OrderRepositoryContract
@@ -82,23 +97,27 @@ class PaymentService
* @param WalleeSdkService $sdkService
* @param ConfigRepository $config
* @param ItemRepositoryContract $itemRepository
+ * @param VariationRepositoryContract $variationRepository
* @param FrontendSessionStorageFactoryContract $session
* @param AddressRepositoryContract $addressRepository
* @param CountryRepositoryContract $countryRepository
* @param WebstoreHelper $webstoreHelper
* @param PaymentHelper $paymentHelper
+ * @param OrderHelper $orderHelper
* @param OrderRepositoryContract $orderRepository
*/
- public function __construct(WalleeSdkService $sdkService, ConfigRepository $config, ItemRepositoryContract $itemRepository, FrontendSessionStorageFactoryContract $session, AddressRepositoryContract $addressRepository, CountryRepositoryContract $countryRepository, WebstoreHelper $webstoreHelper, PaymentHelper $paymentHelper, OrderRepositoryContract $orderRepository)
+ public function __construct(WalleeSdkService $sdkService, ConfigRepository $config, ItemRepositoryContract $itemRepository, VariationRepositoryContract $variationRepository, FrontendSessionStorageFactoryContract $session, AddressRepositoryContract $addressRepository, CountryRepositoryContract $countryRepository, WebstoreHelper $webstoreHelper, PaymentHelper $paymentHelper, OrderHelper $orderHelper, OrderRepositoryContract $orderRepository)
{
$this->sdkService = $sdkService;
$this->config = $config;
$this->itemRepository = $itemRepository;
+ $this->variationRepository = $variationRepository;
$this->session = $session;
$this->addressRepository = $addressRepository;
$this->countryRepository = $countryRepository;
$this->webstoreHelper = $webstoreHelper;
$this->paymentHelper = $paymentHelper;
+ $this->orderHelper = $orderHelper;
$this->orderRepository = $orderRepository;
}
@@ -126,20 +145,20 @@ public function getPaymentContent(Basket $basket, array $basketForTemplate, Paym
];
$this->getLogger(__METHOD__)->error('wallee::TransactionParameters', $parameters);
- $transaction = $this->sdkService->call('createTransaction', $parameters);
+ // $transaction = $this->sdkService->call('createTransactionFromBasket', $parameters);
$this->createWebhook();
- if (is_array($transaction) && isset($transaction['error'])) {
- return [
- 'type' => GetPaymentMethodContent::RETURN_TYPE_ERROR,
- 'content' => $transaction['error_msg']
- ];
- }
+ // if (is_array($transaction) && isset($transaction['error'])) {
+ // return [
+ // 'type' => GetPaymentMethodContent::RETURN_TYPE_ERROR,
+ // 'content' => $transaction['error_msg']
+ // ];
+ // }
- $this->getLogger(__METHOD__)->error('wallee::transaction result', $transaction);
+ // $this->getLogger(__METHOD__)->error('wallee::transaction result', $transaction);
- $this->session->getPlugin()->setValue('walleeTransactionId', $transaction['id']);
+ // $this->session->getPlugin()->setValue('walleeTransactionId', $transaction['id']);
return [
'type' => GetPaymentMethodContent::RETURN_TYPE_CONTINUE
@@ -167,27 +186,20 @@ private function createWebhook()
*/
public function executePayment(Order $order, PaymentMethod $paymentMethod): array
{
- $transactionId = $this->session->getPlugin()->getValue('walleeTransactionId');
-
$parameters = [
- 'id' => $transactionId,
'order' => $order,
'paymentMethod' => $paymentMethod,
'billingAddress' => $this->getAddress($order->billingAddress),
'shippingAddress' => $this->getAddress($order->deliveryAddress),
'language' => $this->session->getLocaleSettings()->language,
+ 'customerId' => $this->orderHelper->getOrderRelationId($order, OrderRelationReference::REFERENCE_TYPE_CONTACT),
'successUrl' => $this->getSuccessUrl(),
'failedUrl' => $this->getFailedUrl(),
'checkoutUrl' => $this->getCheckoutUrl()
];
$this->getLogger(__METHOD__)->error('wallee::TransactionParameters', $parameters);
- // $transaction = $this->sdkService->call('updateTransaction', $parameters);
-
- $transaction = $this->sdkService->call('getTransaction', [
- 'id' => $transactionId
- ]);
-
+ $transaction = $this->sdkService->call('createTransactionFromOrder', $parameters);
$this->getLogger(__METHOD__)->error('wallee::ConfirmTransaction', $transaction);
if (is_array($transaction) && $transaction['error']) {
@@ -197,8 +209,6 @@ public function executePayment(Order $order, PaymentMethod $paymentMethod): arra
];
}
- $this->session->getPlugin()->setValue('walleeTransactionId', null);
-
$payment = $this->paymentHelper->createPlentyPayment($transaction);
$this->paymentHelper->assignPlentyPaymentToPlentyOrder($payment, $order->id);
From 697ed85f9f4704692011e44885dbb7e8f5e66a91 Mon Sep 17 00:00:00 2001
From: Simon Schurter
Date: Tue, 19 Mar 2019 16:54:54 +0100
Subject: [PATCH 4/6] Improve payment process.
---
resources/lang/de/Config.properties | 60 +--
resources/lang/de/Template.properties | 7 +
resources/lang/en/Template.properties | 7 +
resources/lib/createTransactionFromBasket.php | 28 +-
resources/lib/createTransactionFromOrder.php | 26 +-
resources/lib/hasPossiblePaymentMethods.php | 17 +
resources/views/Failure.twig | 413 +++++++++++++++++-
resources/views/PaymentInformation.twig | 6 +-
.../PaymentNotificationController.php | 2 +-
src/Controllers/PaymentProcessController.php | 116 ++---
.../PaymentTransactionController.php | 4 -
src/Helper/PaymentHelper.php | 1 -
.../DataProvider/PaymentInformation.php | 10 +-
src/Providers/WalleeRouteServiceProvider.php | 4 +-
src/Services/PaymentService.php | 55 ++-
src/Services/WebhookCronHandler.php | 2 +-
16 files changed, 584 insertions(+), 174 deletions(-)
create mode 100644 resources/lang/de/Template.properties
create mode 100644 resources/lang/en/Template.properties
create mode 100644 resources/lib/hasPossiblePaymentMethods.php
diff --git a/resources/lang/de/Config.properties b/resources/lang/de/Config.properties
index 8a933ac..a84b225 100644
--- a/resources/lang/de/Config.properties
+++ b/resources/lang/de/Config.properties
@@ -1,137 +1,137 @@
GrundeinstellungenTab=Grundeinstellungen
apiUserIdLabel=API Benutzer ID
-apiUserKeyLabel=API Benutzer Schlüssel
+apiUserKeyLabel=API Benutzer Schlüssel
spaceIdLabel=Space Id
resourceVersionLabel=Resource Version
-refundSuccessfulStatusLabel=Status ID für erfolgreiche Gutschrift
-refundFailedStatusLabel=Status ID für fehlgeschlagene Gutschrift
+refundSuccessfulStatusLabel=Status ID für erfolgreiche Gutschrift
+refundFailedStatusLabel=Status ID für fehlgeschlagene Gutschrift
AlipayTab=Alipay
alipayActiveLabel=Aktiv
alipayTitleLabel=Titel
alipayDescriptionLabel=Beschreibung
-alipayFeeLabel=Gebühr
-BankBerweisungTab=Bank Überweisung
+alipayFeeLabel=Gebühr
+BankBerweisungTab=Bank Ãœberweisung
banktransferActiveLabel=Aktiv
banktransferTitleLabel=Titel
banktransferDescriptionLabel=Beschreibung
-banktransferFeeLabel=Gebühr
+banktransferFeeLabel=Gebühr
CASHUTab=CASHU
cashuActiveLabel=Aktiv
cashuTitleLabel=Titel
cashuDescriptionLabel=Beschreibung
-cashuFeeLabel=Gebühr
+cashuFeeLabel=Gebühr
KreditDebitkarteTab=Kredit- / Debitkarte
creditcardActiveLabel=Aktiv
creditcardTitleLabel=Titel
creditcardDescriptionLabel=Beschreibung
-creditcardFeeLabel=Gebühr
+creditcardFeeLabel=Gebühr
DaoPayTab=DaoPay
daopayActiveLabel=Aktiv
daopayTitleLabel=Titel
daopayDescriptionLabel=Beschreibung
-daopayFeeLabel=Gebühr
+daopayFeeLabel=Gebühr
LastschriftSEPATab=Lastschrift (SEPA)
directdebitsepaActiveLabel=Aktiv
directdebitsepaTitleLabel=Titel
directdebitsepaDescriptionLabel=Beschreibung
-directdebitsepaFeeLabel=Gebühr
+directdebitsepaFeeLabel=Gebühr
LastschriftUKTab=Lastschrift (UK)
directdebitukActiveLabel=Aktiv
directdebitukTitleLabel=Titel
directdebitukDescriptionLabel=Beschreibung
-directdebitukFeeLabel=Gebühr
+directdebitukFeeLabel=Gebühr
EPSTab=EPS
epsActiveLabel=Aktiv
epsTitleLabel=Titel
epsDescriptionLabel=Beschreibung
-epsFeeLabel=Gebühr
+epsFeeLabel=Gebühr
GiropayTab=Giropay
giropayActiveLabel=Aktiv
giropayTitleLabel=Titel
giropayDescriptionLabel=Beschreibung
-giropayFeeLabel=Gebühr
+giropayFeeLabel=Gebühr
iDealTab=iDeal
idealActiveLabel=Aktiv
idealTitleLabel=Titel
idealDescriptionLabel=Beschreibung
-idealFeeLabel=Gebühr
+idealFeeLabel=Gebühr
RechnungTab=Rechnung
invoiceActiveLabel=Aktiv
invoiceTitleLabel=Titel
invoiceDescriptionLabel=Beschreibung
-invoiceFeeLabel=Gebühr
+invoiceFeeLabel=Gebühr
MasterPassTab=MasterPass
masterpassActiveLabel=Aktiv
masterpassTitleLabel=Titel
masterpassDescriptionLabel=Beschreibung
-masterpassFeeLabel=Gebühr
+masterpassFeeLabel=Gebühr
OnlineBankingTab=Online Banking
onlinebankingActiveLabel=Aktiv
onlinebankingTitleLabel=Titel
onlinebankingDescriptionLabel=Beschreibung
-onlinebankingFeeLabel=Gebühr
+onlinebankingFeeLabel=Gebühr
payboxTab=paybox
payboxActiveLabel=Aktiv
payboxTitleLabel=Titel
payboxDescriptionLabel=Beschreibung
-payboxFeeLabel=Gebühr
+payboxFeeLabel=Gebühr
PaydirektTab=Paydirekt
paydirektActiveLabel=Aktiv
paydirektTitleLabel=Titel
paydirektDescriptionLabel=Beschreibung
-paydirektFeeLabel=Gebühr
+paydirektFeeLabel=Gebühr
PaylibTab=Paylib
paylibActiveLabel=Aktiv
paylibTitleLabel=Titel
paylibDescriptionLabel=Beschreibung
-paylibFeeLabel=Gebühr
+paylibFeeLabel=Gebühr
PayPalTab=PayPal
paypalActiveLabel=Aktiv
paypalTitleLabel=Titel
paypalDescriptionLabel=Beschreibung
-paypalFeeLabel=Gebühr
+paypalFeeLabel=Gebühr
paysafecardTab=paysafecard
paysafecardActiveLabel=Aktiv
paysafecardTitleLabel=Titel
paysafecardDescriptionLabel=Beschreibung
-paysafecardFeeLabel=Gebühr
+paysafecardFeeLabel=Gebühr
POLiTab=POLi
poliActiveLabel=Aktiv
poliTitleLabel=Titel
poliDescriptionLabel=Beschreibung
-poliFeeLabel=Gebühr
+poliFeeLabel=Gebühr
Przelewy24Tab=Przelewy24
przelewy24ActiveLabel=Aktiv
przelewy24TitleLabel=Titel
przelewy24DescriptionLabel=Beschreibung
-przelewy24FeeLabel=Gebühr
+przelewy24FeeLabel=Gebühr
QIWITab=QIWI
qiwiActiveLabel=Aktiv
qiwiTitleLabel=Titel
qiwiDescriptionLabel=Beschreibung
-qiwiFeeLabel=Gebühr
+qiwiFeeLabel=Gebühr
SkrillTab=Skrill
skrillActiveLabel=Aktiv
skrillTitleLabel=Titel
skrillDescriptionLabel=Beschreibung
-skrillFeeLabel=Gebühr
+skrillFeeLabel=Gebühr
SOFORTBankingTab=SOFORT Banking
sofortbankingActiveLabel=Aktiv
sofortbankingTitleLabel=Titel
sofortbankingDescriptionLabel=Beschreibung
-sofortbankingFeeLabel=Gebühr
+sofortbankingFeeLabel=Gebühr
TenpayTab=Tenpay
tenpayActiveLabel=Aktiv
tenpayTitleLabel=Titel
tenpayDescriptionLabel=Beschreibung
-tenpayFeeLabel=Gebühr
+tenpayFeeLabel=Gebühr
TrustlyTab=Trustly
trustlyActiveLabel=Aktiv
trustlyTitleLabel=Titel
trustlyDescriptionLabel=Beschreibung
-trustlyFeeLabel=Gebühr
+trustlyFeeLabel=Gebühr
TWINTTab=TWINT
twintActiveLabel=Aktiv
twintTitleLabel=Titel
twintDescriptionLabel=Beschreibung
-twintFeeLabel=Gebühr
\ No newline at end of file
+twintFeeLabel=Gebühr
\ No newline at end of file
diff --git a/resources/lang/de/Template.properties b/resources/lang/de/Template.properties
new file mode 100644
index 0000000..19acd2d
--- /dev/null
+++ b/resources/lang/de/Template.properties
@@ -0,0 +1,7 @@
+paymentFailureTitle = "Zahlung abgebrochen"
+paymentFailureDescription = "Die Bestellung wurde übermittelt, aber die Zahlung ist abgebrochen worden. Bitte versuchen Sie es erneut."
+paymentFailureSubmit = "Zahlen"
+
+paymentInformationLabel = "Ihre Zahlung wurde erhalten. Der Bestellstatus wird in Kürze aktualisiert."
+paymentInformationDownloadInvoice = "Rechnung herunterladen"
+paymentInformationDownloadPackingSlip = "Lieferschein herunterladen"
\ No newline at end of file
diff --git a/resources/lang/en/Template.properties b/resources/lang/en/Template.properties
new file mode 100644
index 0000000..007300f
--- /dev/null
+++ b/resources/lang/en/Template.properties
@@ -0,0 +1,7 @@
+paymentFailureTitle = "Payment cancelled"
+paymentFailureDescription = "The order has been submitted but the payment was cancelled. Please try again."
+paymentFailureSubmit = "Pay"
+
+paymentInformationLabel = "Your payment has been received. The order's status will be updated shortly."
+paymentInformationDownloadInvoice = "Download Invoice"
+paymentInformationDownloadPackingSlip = "Download Packing Slip"
\ No newline at end of file
diff --git a/resources/lib/createTransactionFromBasket.php b/resources/lib/createTransactionFromBasket.php
index 01ab476..e3c9d08 100644
--- a/resources/lib/createTransactionFromBasket.php
+++ b/resources/lib/createTransactionFromBasket.php
@@ -210,15 +210,18 @@ function collectTransactionData($transactionRequest, $client)
$transactionRequest->setAllowedPaymentMethodConfigurations($allowedPaymentMethodConfigurations);
}
-$spaceId = SdkRestApi::getParam('spaceId');
-
-$transactionRequest = new TransactionCreate();
-collectTransactionData($transactionRequest, $client);
-$transactionRequest->setAutoConfirmationEnabled(true);
-$transactionRequest->setCustomersPresence(\Wallee\Sdk\Model\CustomersPresence::VIRTUAL_PRESENT);
-
$service = new TransactionService($client);
-$createdTransaction = $service->create($spaceId, $transactionRequest);
+$spaceId = SdkRestApi::getParam('spaceId');
+$transactionId = SdkRestApi::getParam('transactionId');
+if (! empty($transactionId)) {
+ $createdTransaction = $service->read($spaceId, $transactionId);
+} else {
+ $transactionRequest = new TransactionCreate();
+ collectTransactionData($transactionRequest, $client);
+ $transactionRequest->setAutoConfirmationEnabled(true);
+ $transactionRequest->setCustomersPresence(\Wallee\Sdk\Model\CustomersPresence::VIRTUAL_PRESENT);
+ $createdTransaction = $service->create($spaceId, $transactionRequest);
+}
$pendingTransaction = new TransactionPending();
$pendingTransaction->setId($createdTransaction->getId());
@@ -227,11 +230,4 @@ function collectTransactionData($transactionRequest, $client)
$pendingTransaction->setFailedUrl(SdkRestApi::getParam('failedUrl') . '/' . $createdTransaction->getId());
$transactionResponse = $service->update($spaceId, $pendingTransaction);
-$possiblePaymentMethods = $service->fetchPossiblePaymentMethods($spaceId, $transactionResponse->getId());
-if ($possiblePaymentMethods != null && ! empty($possiblePaymentMethods)) {
- return [
- 'id' => $transactionResponse->getId()
- ];
-} else {
- throw new \Exception('The selected payment method is not available.');
-}
\ No newline at end of file
+return WalleeSdkHelper::convertData($transactionResponse);
\ No newline at end of file
diff --git a/resources/lib/createTransactionFromOrder.php b/resources/lib/createTransactionFromOrder.php
index 79c8c3d..91501d1 100644
--- a/resources/lib/createTransactionFromOrder.php
+++ b/resources/lib/createTransactionFromOrder.php
@@ -189,15 +189,18 @@ function collectTransactionData($transactionRequest, $client)
$transactionRequest->setAllowedPaymentMethodConfigurations($allowedPaymentMethodConfigurations);
}
-$spaceId = SdkRestApi::getParam('spaceId');
-
-$transactionRequest = new TransactionCreate();
-collectTransactionData($transactionRequest, $client);
-$transactionRequest->setAutoConfirmationEnabled(false);
-$transactionRequest->setCustomersPresence(\Wallee\Sdk\Model\CustomersPresence::VIRTUAL_PRESENT);
-
$service = new TransactionService($client);
-$createdTransaction = $service->create($spaceId, $transactionRequest);
+$spaceId = SdkRestApi::getParam('spaceId');
+$transactionId = SdkRestApi::getParam('transactionId');
+if (! empty($transactionId)) {
+ $createdTransaction = $service->read($spaceId, $transactionId);
+} else {
+ $transactionRequest = new TransactionCreate();
+ collectTransactionData($transactionRequest, $client);
+ $transactionRequest->setAutoConfirmationEnabled(false);
+ $transactionRequest->setCustomersPresence(\Wallee\Sdk\Model\CustomersPresence::VIRTUAL_PRESENT);
+ $createdTransaction = $service->create($spaceId, $transactionRequest);
+}
$pendingTransaction = new TransactionPending();
$pendingTransaction->setId($createdTransaction->getId());
@@ -206,9 +209,4 @@ function collectTransactionData($transactionRequest, $client)
$pendingTransaction->setFailedUrl(SdkRestApi::getParam('failedUrl') . '/' . $createdTransaction->getId());
$transactionResponse = $service->confirm($spaceId, $pendingTransaction);
-$possiblePaymentMethods = $service->fetchPossiblePaymentMethods($spaceId, $transactionResponse->getId());
-if ($possiblePaymentMethods != null && ! empty($possiblePaymentMethods)) {
- return WalleeSdkHelper::convertData($transactionResponse);
-} else {
- throw new \Exception('The selected payment method is not available.');
-}
\ No newline at end of file
+return WalleeSdkHelper::convertData($transactionResponse);
\ No newline at end of file
diff --git a/resources/lib/hasPossiblePaymentMethods.php b/resources/lib/hasPossiblePaymentMethods.php
new file mode 100644
index 0000000..21ff672
--- /dev/null
+++ b/resources/lib/hasPossiblePaymentMethods.php
@@ -0,0 +1,17 @@
+fetchPossiblePaymentMethods($spaceId, $transactionId);
+if ($possiblePaymentMethods != null && ! empty($possiblePaymentMethods)) {
+ return true;
+} else {
+ return false;
+}
\ No newline at end of file
diff --git a/resources/views/Failure.twig b/resources/views/Failure.twig
index abdb7ba..81b592c 100644
--- a/resources/views/Failure.twig
+++ b/resources/views/Failure.twig
@@ -1,27 +1,394 @@
{% extends getPartial('page-design') %}
+{% block PartialHead %}
+
+ {{ trans("Ceres::Template.orderConfirmation") }} | {{ trans("Ceres::Template.headerCompanyName") }}
+{% endblock %}
+
{% block PageBody %}
- {{ transaction.userFailureMessage }}
-
- Transaction Id: {{ transaction.id }}
-
- Order Id: {{ order.id }}
-
- Payment State: {{ payment.status }}
-
- Current Payment Method: {{ currentPaymentMethodId }}
-
- {% if allowSwitchPaymentMethod %}
-
-
Switch payment method:
-
- {% for method in paymentMethodListForSwitch %}
- -
- {{ method | json_encode() }} {% if method.id == currentPaymentMethodId %}[current]{% endif %}
- Pay
-
- {% endfor %}
-
-
- {% endif %}
+ {% import "Ceres::PageDesign.Macros.ItemName" as ItemName %}
+
+ {{ component( "Ceres::Item.Components.ItemBundle" ) }}
+
+ {% set basketTotalsCurrency = totals.currency %}
+
+
+
+
+
{{ trans("wallee::Template.paymentFailureTitle") }}
+
{{ trans("wallee::Template.paymentFailureDescription") }}
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ trans("Ceres::Template.orderConfirmationDate") }}
+ {{ orderData.order.createdAt | formatDateTime | date(trans("Ceres::Template.devDateTimeFormat")) }}
+
+
+
+
+
+
+
+
{{ trans("Ceres::Template.orderConfirmationInvoiceAddress") }}
+
+ {{ orderData.order.billingAddress.name1 }}
+ {{ orderData.order.billingAddress.name2 }} {{ orderData.order.billingAddress.name3 }}
+ {{ orderData.order.billingAddress.name4 }}
+ {{ orderData.order.billingAddress.address1 }} {{ orderData.order.billingAddress.address2 }}
+ {{ orderData.order.billingAddress.postalCode }} {{ orderData.order.billingAddress.town }}
+ {{ services.country.getCountryName(orderData.order.billingAddress.countryId) }}
+
+
+
+
+
{{ trans("Ceres::Template.orderConfirmationShippingAddress") }}
+
+ {% if orderData.order.billingAddress.id == orderData.order.deliveryAddress.id %}
+
+ {{ trans("Ceres::Template.orderConfirmationSameAsInvoice") }}
+
+ {% else %}
+
+ {{ orderData.order.deliveryAddress.name1 }}
+ {{ orderData.order.deliveryAddress.name2 }} {{ orderData.order.deliveryAddress.name3 }}
+ {{ orderData.order.deliveryAddress.name4 }}
+ {{ orderData.order.deliveryAddress.address1 }} {{ orderData.order.deliveryAddress.address2 }}
+
+ {% if orderData.order.deliveryAddress.address1 == 'PACKSTATION' or orderData.order.deliveryAddress.address1 == 'POSTFILIALE' %}
+ {{ trans("Ceres::Template.addressPostNummer") }}
+ {% endif %}
+
+ {{ orderData.order.deliveryAddress.address3 }}
+
+ {{ orderData.order.deliveryAddress.postalCode }} {{ orderData.order.deliveryAddress.town }}
+ {{ services.country.getCountryName(orderData.order.deliveryAddress.countryId) }}
+
+ {% endif %}
+
+
+
+
+
+
+
+
+ {{ trans("Ceres::Template.orderConfirmationPaymentMethod") }}
+ {{ orderData.paymentMethodName }}
+
+
+ {{ trans("Ceres::Template.orderConfirmationPaymentStatus") }}
+ {% for propertyKey in orderData.order.properties %}
+ {% if orderData.order.properties[loop.index0].typeId == 4 %}
+ {% set paymentStatus = entry.order.properties[loop.index0].value %}
+ {{ trans("Ceres::Template.orderConfirmationPaymentStatus_" ~ orderData.order.properties[loop.index0].value) }}
+ {% endif %}
+ {% endfor %}
+
+
+
+
+
+
+
+ {{ trans("Ceres::Template.orderConfirmationShippingProfile") }}
+ {{ orderData.shippingProvider }} - {{ orderData.shippingProfileName }}
+
+
+ {% set shippingDate = "" %}
+ {% for date in orderData.order.dates %}
+ {% if date.typeId == 8 %}
+ {% set shippingDate = date.date %}
+ {% endif %}
+ {% endfor %}
+
+ {% if shippingDate %}
+
+ {{ trans("Ceres::Template.orderConfirmationEstimatedShippingDate") }}
+ {{ shippingDate | date(trans("Ceres::Template.devDateFormat")) }}
+
+ {% endif %}
+
+
+
+
+
+ {% if allowSwitchPaymentMethod %}
+
+ {% endif %}
+
+
+
+
+
+ {% set rebatedAmountTotalGross = 0 %}
+ {% set rebatedAmountTotalNet = 0 %}
+ {% set rebatedAmountTotal = 0 %}
+
+ {% for item in orderData.order.orderItems %}
+ {% if item.itemVariationId > 0 and not ('[-]' in item.orderItemName) %}
+ {% set currentVariationId = item.itemVariationId | trimNewlines %}
+
+
+
+
+
+
+
+ {{ ItemName.get(item.orderItemName, item.bundleType) }}
+
+
+
+ {% if splitItemBundle != "1" and item.bundleType == "bundle" %}
+
+ {% for bundleComponent in item.bundleComponents %}
+
+ {% endfor %}
+
+ {% endif %}
+
+ {% if item.amounts[0].discount > 0 %}
+ {% if item.amounts[0].isPercentage == "1" %}
+ {% set rebatedAmountItemGross = (item.quantity * (((item.amounts[0].priceGross / (100 - item.amounts[0].discount)) * 100) - item.amounts[0].priceGross)) %}
+ {% set rebatedAmountItemNet = (item.quantity * (((item.amounts[0].priceNet / (100 - item.amounts[0].discount)) * 100) - item.amounts[0].priceNet)) %}
+ {% else %}
+ {% set rebatedAmountItemGross = (item.quantity * item.amounts[0].discount) %}
+ {% endif %}
+ {% set rebatedAmountTotalGross = rebatedAmountTotalGross + rebatedAmountItemGross %}
+ {% set rebatedAmountTotalNet = rebatedAmountTotalNet + rebatedAmountItemNet %}
+ {% endif %}
+
+ {% set itemPrice = 0 %}
+ {% set rebatedAmount = 0 %}
+
+ {% if orderData.highlightNetPrices %}
+ {% set itemPrice = item.amounts[0].priceNet %}
+ {% set rebatedAmount = rebatedAmountItemNet %}
+ {% set rebatedAmountTotal = rebatedAmountTotalNet %}
+ {% else %}
+ {% set itemPrice = item.amounts[0].priceGross %}
+ {% set rebatedAmount = rebatedAmountItemGross %}
+ {% set rebatedAmountTotal = rebatedAmountTotalGross %}
+ {% endif %}
+
+
+ {{ trans("Ceres::Template.orderConfirmationPricePerPiece") }}
+ {{ (itemPrice + rebatedAmount) | formatMonetary( item.amounts[0].currency ) }}
+
+
+ {{ trans("Ceres::Template.orderConfirmationPeace") }}
+ {{ item.quantity }}
+
+
+ {{ trans("Ceres::Template.orderConfirmationTotal") }}
+ {{ (item.quantity * (itemPrice + rebatedAmount)) | formatMonetary( item.amounts[0].currency ) }}
+
+ {% if item.orderProperties %}
+ {% for property in item.orderProperties %}
+
+
{{ property.name }}
+ {% if property.type == 'file' %}
+
+ {% set splitPath = property.value |split('/') %}
+ {% set filename = '' %}
+ {% set path = '' %}
+
+ {% for temp in splitPath %}
+ {% if loop.first %}
+ {% set path = temp %}
+ {% elseif loop.last %}
+ {% set filename = temp %}
+ {% else %}
+ {% set path = path ~ '/' ~ temp %}
+ {% endif %}
+ {% endfor %}
+
+
+
+
+ {{ splitPath | last }}
+
+
+ {% elseif property.type | length > 0 %}
+
{{ property.value }}
+ {% endif %}
+
+ {% endfor %}
+ {% endif %}
+
+
+ {% endif %}
+ {% endfor %}
+
+
+
+
+
+
{{ trans("Ceres::Template.checkoutSum") }}
+
+
+ -
+ {{ trans("Ceres::Template.checkoutValue") }} ({{ trans("Ceres::Template.checkoutNet") }})
+
-
+ {{ (totals.itemSumNet + rebatedAmountTotalNet) | formatMonetary( basketTotalsCurrency ) }}
+
+
+ -
+ {{ trans("Ceres::Template.checkoutValue") }} ({{ trans("Ceres::Template.checkoutGross") }})
+
-
+ {% if orderData.order.amounts[0].isNet %}
+ {{ (totals.itemSumGross + rebatedAmountTotalNet) | formatMonetary( basketTotalsCurrency ) }}
+ {% else %}
+ {{ (totals.itemSumGross + rebatedAmountTotalGross) | formatMonetary( basketTotalsCurrency ) }}
+ {% endif %}
+
+ {% if rebatedAmountTotal > 0 %}
+ -
+ {{ trans("Ceres::Template.orderConfirmationRebate") }}
+
-
+ {{ rebatedAmountTotal| formatMonetary( basketTotalsCurrency ) }}
+
+ -
+ {{ trans("Ceres::Template.orderConfirmationSubTotal") }} ({{ trans("Ceres::Template.checkoutNet") }})
+
-
+ {{ totals.itemSumNet | formatMonetary( basketTotalsCurrency ) }}
+
+ -
+ {{ trans("Ceres::Template.orderConfirmationSubTotal") }} ({{ trans("Ceres::Template.checkoutGross") }})
+
-
+ {{ totals.itemSumGross | formatMonetary( basketTotalsCurrency ) }}
+
+ {% endif %}
+ -
+ {{ trans("Ceres::Template.orderConfirmationShippingCosts") }} ({{ trans("Ceres::Template.checkoutNet") }})
+
-
+ {{ totals.shippingNet | formatMonetary( basketTotalsCurrency ) }}
+
+ -
+ {{ trans("Ceres::Template.orderConfirmationShippingCosts") }} ({{ trans("Ceres::Template.checkoutGross") }})
+
-
+ {{ totals.shippingGross | formatMonetary( basketTotalsCurrency ) }}
+
+
+
+ -
+ {{ trans("Ceres::Template.checkoutTotalSum") }} ({{ trans("Ceres::Template.checkoutNet") }})
+
-
+ {{ totals.totalNet | formatMonetary( basketTotalsCurrency ) }}
+
+
+ {% if totals.couponType == 'promotional' and (totals.couponValue | trimNewlines) != 0 %}
+ -
+ {{ trans("Ceres::Template.checkoutCoupon") }}
+
-
+ {{ totals.couponValue | formatMonetary( basketTotalsCurrency ) }}
+
+ {% endif %}
+
+ {% if not orderData.order.amounts[0].isNet %}
+
+ {% for vat in totals.vats %}
+
-
+ {{ trans("Ceres::Template.orderConfirmationVAT") }} {{ vat.rate }}%
+
-
+ {{ vat.value | formatMonetary( basketTotalsCurrency ) }}
+
+ {% endfor %}
+
+ {% endif %}
+
+
+
+ -
+ {{ trans("Ceres::Template.checkoutTotalSum") }} ({{ trans("Ceres::Template.checkoutGross") }})
+
-
+ {{ totals.totalGross | formatMonetary( basketTotalsCurrency ) }}
+
+
+ {% if totals.couponType == 'sales' and (totals.couponValue | trimNewlines) != 0 %}
+ -
+ {{ trans("Ceres::Template.checkoutCoupon") }}
+
-
+ {{ totals.couponValue | formatMonetary( basketTotalsCurrency ) }}
+
+ -
+ {{ trans("Ceres::Template.checkoutOpenAmount") }}
+
-
+ {{ totals.openAmount | formatMonetary( basketTotalsCurrency ) }}
+
+ {% endif %}
+
+
+
+
+
+
+
+
{% endblock %}
\ No newline at end of file
diff --git a/resources/views/PaymentInformation.twig b/resources/views/PaymentInformation.twig
index 6f81d97..af41cac 100644
--- a/resources/views/PaymentInformation.twig
+++ b/resources/views/PaymentInformation.twig
@@ -1,11 +1,11 @@
\ No newline at end of file
diff --git a/src/Controllers/PaymentNotificationController.php b/src/Controllers/PaymentNotificationController.php
index 6b5697d..3699a84 100644
--- a/src/Controllers/PaymentNotificationController.php
+++ b/src/Controllers/PaymentNotificationController.php
@@ -83,7 +83,7 @@ public function __construct(Request $request, Response $response, ConfigReposito
public function updateTransaction()
{
$webhookRequest = json_decode($this->request->getContent());
- $this->getLogger(__METHOD__)->debug('webhookRequest', $webhookRequest);
+ $this->getLogger(__METHOD__)->info('webhookRequest', $webhookRequest);
if (in_array(strtolower($webhookRequest->listenerEntityTechnicalName), [
'transaction',
diff --git a/src/Controllers/PaymentProcessController.php b/src/Controllers/PaymentProcessController.php
index 90b25ea..fbfcbae 100644
--- a/src/Controllers/PaymentProcessController.php
+++ b/src/Controllers/PaymentProcessController.php
@@ -17,24 +17,22 @@
use Plenty\Modules\Authorization\Services\AuthHelper;
use IO\Constants\OrderPaymentStatus;
use Plenty\Modules\Order\Models\Order;
-use Plenty\Modules\Order\Property\Models\OrderProperty;
use Plenty\Modules\Frontend\PaymentMethod\Contracts\FrontendPaymentMethodRepositoryContract;
use Plenty\Modules\Order\Property\Models\OrderPropertyType;
use Plenty\Modules\Payment\Method\Contracts\PaymentMethodRepositoryContract;
use Wallee\Services\PaymentService;
use Plenty\Modules\Payment\Events\Checkout\GetPaymentMethodContent;
+use IO\Services\OrderTotalsService;
+use IO\Models\LocalizedOrder;
+use IO\Services\SessionStorageService;
+use Wallee\Helper\OrderHelper;
+use Plenty\Modules\Frontend\Session\Storage\Contracts\FrontendSessionStorageFactoryContract;
class PaymentProcessController extends Controller
{
use Loggable;
- /**
- *
- * @var Request
- */
- private $request;
-
/**
*
* @var Response
@@ -83,6 +81,12 @@ class PaymentProcessController extends Controller
*/
private $paymentOrderRelationRepository;
+ /**
+ *
+ * @var OrderHelper
+ */
+ private $orderHelper;
+
/**
*
* @var OrderService
@@ -101,10 +105,21 @@ class PaymentProcessController extends Controller
*/
private $paymentMethodService;
+ /**
+ *
+ * @var SessionStorageService
+ */
+ private $sessionStorage;
+
+ /**
+ *
+ * @var FrontendSessionStorageFactoryContract
+ */
+ private $frontendSession;
+
/**
* Constructor.
*
- * @param Request $request
* @param Response $response
* @param WalleeSdkService $sdkService
* @param NotificationService $notificationService
@@ -113,14 +128,16 @@ class PaymentProcessController extends Controller
* @param PaymentRepositoryContract $paymentRepository
* @param OrderRepositoryContract $orderRepository
* @param PaymentOrderRelationRepositoryContract $paymentOrderRelationRepository
+ * @param OrderHelper $orderHelper
* @param OrderService $orderService
* @param FrontendPaymentMethodRepositoryContract $frontendPaymentMethodRepository
* @param PaymentMethodRepositoryContract $paymentMethodService
+ * @param SessionStorageService $sessionStorage
+ * @param FrontendSessionStorageFactoryContract $frontendSession
*/
- public function __construct(Request $request, Response $response, WalleeSdkService $sdkService, NotificationService $notificationService, PaymentService $paymentService, PaymentHelper $paymentHelper, PaymentRepositoryContract $paymentRepository, OrderRepositoryContract $orderRepository, PaymentOrderRelationRepositoryContract $paymentOrderRelationRepository, OrderService $orderService, FrontendPaymentMethodRepositoryContract $frontendPaymentMethodRepository, PaymentMethodRepositoryContract $paymentMethodService)
+ public function __construct(Response $response, WalleeSdkService $sdkService, NotificationService $notificationService, PaymentService $paymentService, PaymentHelper $paymentHelper, PaymentRepositoryContract $paymentRepository, OrderRepositoryContract $orderRepository, PaymentOrderRelationRepositoryContract $paymentOrderRelationRepository, OrderHelper $orderHelper, OrderService $orderService, FrontendPaymentMethodRepositoryContract $frontendPaymentMethodRepository, PaymentMethodRepositoryContract $paymentMethodService, SessionStorageService $sessionStorage, FrontendSessionStorageFactoryContract $frontendSession)
{
parent::__construct();
- $this->request = $request;
$this->response = $response;
$this->sdkService = $sdkService;
$this->notificationService = $notificationService;
@@ -129,9 +146,12 @@ public function __construct(Request $request, Response $response, WalleeSdkServi
$this->paymentRepository = $paymentRepository;
$this->orderRepository = $orderRepository;
$this->paymentOrderRelationRepository = $paymentOrderRelationRepository;
+ $this->orderHelper = $orderHelper;
$this->orderService = $orderService;
$this->frontendPaymentMethodRepository = $frontendPaymentMethodRepository;
$this->paymentMethodService = $paymentMethodService;
+ $this->sessionStorage = $sessionStorage;
+ $this->frontendSession = $frontendSession;
}
/**
@@ -144,50 +164,51 @@ public function failTransaction(Twig $twig, int $id)
'id' => $id
]);
if (is_array($transaction) && isset($transaction['error'])) {
- // TODO: Handle transaction fetching error.
+ return $this->response->redirectTo('confirmation');
}
- $this->getLogger(__METHOD__)->debug('wallee:failTransaction', $transaction);
$payments = $this->paymentRepository->getPaymentsByPropertyTypeAndValue(PaymentProperty::TYPE_TRANSACTION_ID, $transaction['id']);
$payment = $payments[0];
- $this->getLogger(__METHOD__)->error('wallee:failTransaction', $payment);
$orderRelation = $this->paymentOrderRelationRepository->findOrderRelation($payment);
$order = $this->orderRepository->findOrderById($orderRelation->orderId);
- $this->getLogger(__METHOD__)->error('wallee:failTransaction', $order);
- $paymentMethodId = $this->getOrderPropertyValue($order, OrderPropertyType::PAYMENT_METHOD);
+ $paymentMethodId = $this->orderHelper->getOrderPropertyValue($order, OrderPropertyType::PAYMENT_METHOD);
- if (isset($transaction['userFailureMessage']) && ! empty($transaction['userFailureMessage'])) {
+ $errorMessage = $this->frontendSession->getPlugin()->getValue('walleePayErrorMessage');
+ if ($errorMessage) {
+ $this->notificationService->error($errorMessage);
+ $this->frontendSession->getPlugin()->unsetKey('walleePayErrorMessage');
+ } elseif (isset($transaction['userFailureMessage']) && ! empty($transaction['userFailureMessage'])) {
$this->notificationService->error($transaction['userFailureMessage']);
$this->paymentHelper->updatePlentyPayment($transaction);
}
- // return $this->response->redirectTo('confirmation');
+ if (! is_null($order) && ! ($order instanceof LocalizedOrder)) {
+ $order = LocalizedOrder::wrap($order, $this->sessionStorage->getLang());
+ }
+
return $twig->render('wallee::Failure', [
'transaction' => $transaction,
'payment' => $payment,
- 'order' => $order,
+ 'orderData' => $order,
+ 'totals' => pluginApp(OrderTotalsService::class)->getAllTotals($order->order),
'currentPaymentMethodId' => $paymentMethodId,
- 'allowSwitchPaymentMethod' => $this->allowSwitchPaymentMethod($order->id),
- 'paymentMethodListForSwitch' => $this->getPaymentMethodListForSwitch($paymentMethodId, $order->id)
+ 'allowSwitchPaymentMethod' => $this->allowSwitchPaymentMethod($order->order->id),
+ 'paymentMethodListForSwitch' => $this->getPaymentMethodListForSwitch($paymentMethodId, $order->order->id)
]);
}
- /**
- *
- * @param int $id
- * @param int $paymentMethodId
- */
- public function payOrder(int $id, int $paymentMethodId)
+ public function payOrder(Request $request)
{
- $this->getLogger(__METHOD__)->error('wallee:retryPayment', $paymentMethodId);
+ $orderId = $request->get('orderId', '');
+ $paymentMethodId = $request->get('paymentMethod', '');
/** @var AuthHelper $authHelper */
$authHelper = pluginApp(AuthHelper::class);
$orderRepo = $this->orderRepository;
- $order = $order = $authHelper->processUnguarded(function () use ($id, $orderRepo) {
- return $orderRepo->findOrderById($id);
+ $order = $order = $authHelper->processUnguarded(function () use ($orderId, $orderRepo) {
+ return $orderRepo->findOrderById($orderId);
});
$this->switchPaymentMethodForOrder($order, $paymentMethodId);
@@ -195,8 +216,13 @@ public function payOrder(int $id, int $paymentMethodId)
if ($result['type'] == GetPaymentMethodContent::RETURN_TYPE_REDIRECT_URL) {
return $this->response->redirectTo($result['content']);
+ } elseif (isset($result['transactionId'])) {
+ if (isset($result['content'])) {
+ $this->frontendSession->getPlugin()->setValue('walleePayErrorMessage', $result['content']);
+ }
+ return $this->response->redirectTo('wallee/fail-transaction/' . $result['transactionId']);
} else {
- // TODO
+ return $this->response->redirectTo('confirmation');
}
}
@@ -240,11 +266,17 @@ private function switchPaymentMethodForOrder(Order $order, $paymentMethodId)
private function getPaymentMethodListForSwitch($paymentMethodId, $orderId)
{
+ $lang = $this->sessionStorage->getLang();
$paymentMethods = $this->frontendPaymentMethodRepository->getCurrentPaymentMethodsList();
$paymentMethodsForSwitch = [];
foreach ($paymentMethods as $paymentMethod) {
if ($paymentMethod->pluginKey == 'wallee') {
- $paymentMethodsForSwitch[] = $paymentMethod;
+ $paymentMethodsForSwitch[] = [
+ 'id' => $paymentMethod->id,
+ 'name' => $this->frontendPaymentMethodRepository->getPaymentMethodName($paymentMethod, $lang),
+ 'icon' => $this->frontendPaymentMethodRepository->getPaymentMethodIcon($paymentMethod, $lang),
+ 'description' => $this->frontendPaymentMethodRepository->getPaymentMethodDescription($paymentMethod, $lang)
+ ];
}
}
return $paymentMethodsForSwitch;
@@ -274,26 +306,4 @@ private function allowSwitchPaymentMethod($orderId)
return true;
}
-
- /**
- *
- * @param Order $order
- * @param int $propertyType
- * @return null|string
- */
- public function getOrderPropertyValue($order, $propertyType)
- {
- $properties = $order->properties;
- if (($properties->count() > 0) || (is_array($properties) && count($properties) > 0)) {
- /** @var OrderProperty $property */
- foreach ($properties as $property) {
- if ($property instanceof OrderProperty) {
- if ($property->typeId == $propertyType) {
- return $property->value;
- }
- }
- }
- }
- return null;
- }
}
\ No newline at end of file
diff --git a/src/Controllers/PaymentTransactionController.php b/src/Controllers/PaymentTransactionController.php
index 1d23f38..5c4361a 100644
--- a/src/Controllers/PaymentTransactionController.php
+++ b/src/Controllers/PaymentTransactionController.php
@@ -49,12 +49,10 @@ public function downloadInvoice(int $id)
$transaction = $this->sdkService->call('getTransaction', [
'id' => $id
]);
- $this->getLogger(__METHOD__)->error('wallee::transaction', $transaction);
if (is_array($transaction) && ! isset($transaction['error'])) {
$invoiceDocument = $this->sdkService->call('getInvoiceDocument', [
'id' => $id
]);
- $this->getLogger(__METHOD__)->error('wallee::invoice document', $invoiceDocument);
if (is_array($invoiceDocument) && ! isset($invoiceDocument['error'])) {
return $this->download($invoiceDocument);
}
@@ -66,12 +64,10 @@ public function downloadPackingSlip(int $id)
$transaction = $this->sdkService->call('getTransaction', [
'id' => $id
]);
- $this->getLogger(__METHOD__)->error('wallee::transaction', $transaction);
if (is_array($transaction) && ! isset($transaction['error'])) {
$packingSlip = $this->sdkService->call('getPackingSlip', [
'id' => $id
]);
- $this->getLogger(__METHOD__)->error('wallee::packing slip', $packingSlip);
if (is_array($packingSlip) && ! isset($packingSlip['error'])) {
return $this->download($packingSlip);
}
diff --git a/src/Helper/PaymentHelper.php b/src/Helper/PaymentHelper.php
index d5188d7..fe7efdd 100644
--- a/src/Helper/PaymentHelper.php
+++ b/src/Helper/PaymentHelper.php
@@ -169,7 +169,6 @@ public function updatePlentyPayment($transaction)
$payment->updateOrderPaymentStatus = true;
}
$this->paymentRepository->updatePayment($payment);
- $this->getLogger(__METHOD__)->debug('updateOrderPayment', $payment);
}
}
}
diff --git a/src/Providers/DataProvider/PaymentInformation.php b/src/Providers/DataProvider/PaymentInformation.php
index 8904076..7eeba9f 100644
--- a/src/Providers/DataProvider/PaymentInformation.php
+++ b/src/Providers/DataProvider/PaymentInformation.php
@@ -6,21 +6,15 @@
use Plenty\Modules\Payment\Models\Payment;
use Plenty\Modules\Payment\Models\PaymentProperty;
use Wallee\Services\WalleeSdkService;
-use Plenty\Plugin\Log\LoggerFactory;
class PaymentInformation
{
public function call(Twig $twig, $arg): string
{
- $logger = pluginApp(LoggerFactory::class)->getLogger('Wallee', __METHOD__);
-
$order = $arg[0];
- $logger->error('wallee::payment information order', $order);
-
$payments = pluginApp(PaymentRepositoryContract::class)->getPaymentsByOrderId($order['id']);
- foreach ($payments as $payment) {
- $logger->error('wallee::payment information payment', $payment);
+ foreach (array_reverse($payments) as $payment) {
if ($payment->status != Payment::STATUS_CANCELED) {
$transactionId = null;
foreach ($payment->properties as $property) {
@@ -28,7 +22,6 @@ public function call(Twig $twig, $arg): string
$transactionId = $property->value;
}
}
- $logger->error('wallee::payment information transaction id', $transactionId);
if (! empty($transactionId)) {
$transaction = pluginApp(WalleeSdkService::class)->call('getTransaction', [
'id' => $transactionId
@@ -36,7 +29,6 @@ public function call(Twig $twig, $arg): string
if (is_array($transaction) && isset($transaction['error'])) {
return "";
} else {
- $logger->error('wallee::payment information transaction', $transaction);
return $twig->render('wallee::PaymentInformation', [
'order' => $order,
'transaction' => $transaction,
diff --git a/src/Providers/WalleeRouteServiceProvider.php b/src/Providers/WalleeRouteServiceProvider.php
index 42bda63..5679d71 100644
--- a/src/Providers/WalleeRouteServiceProvider.php
+++ b/src/Providers/WalleeRouteServiceProvider.php
@@ -15,9 +15,7 @@ public function map(Router $router)
{
$router->post('wallee/update-transaction', 'Wallee\Controllers\PaymentNotificationController@updateTransaction');
$router->get('wallee/fail-transaction/{id}', 'Wallee\Controllers\PaymentProcessController@failTransaction')->where('id', '\d+');
- $router->get('wallee/pay-order/{id}/{paymentMethodId}', 'Wallee\Controllers\PaymentProcessController@payOrder')
- ->where('id', '\d+')
- ->where('paymentMethodId', '\d+');
+ $router->post('wallee/pay-order', 'Wallee\Controllers\PaymentProcessController@payOrder');
$router->get('wallee/download-invoice/{id}', 'Wallee\Controllers\PaymentTransactionController@downloadInvoice')->where('id', '\d+');
$router->get('wallee/download-packing-slip/{id}', 'Wallee\Controllers\PaymentTransactionController@downloadPackingSlip')->where('id', '\d+');
}
diff --git a/src/Services/PaymentService.php b/src/Services/PaymentService.php
index 60010fb..2e8ca37 100644
--- a/src/Services/PaymentService.php
+++ b/src/Services/PaymentService.php
@@ -131,7 +131,10 @@ public function __construct(WalleeSdkService $sdkService, ConfigRepository $conf
*/
public function getPaymentContent(Basket $basket, array $basketForTemplate, PaymentMethod $paymentMethod): array
{
+ $this->createWebhook();
+
$parameters = [
+ 'transactionId' => $this->session->getPlugin()->getValue('walleeTransactionId'),
'basket' => $basket,
'basketForTemplate' => $basketForTemplate,
'paymentMethod' => $paymentMethod,
@@ -145,20 +148,25 @@ public function getPaymentContent(Basket $basket, array $basketForTemplate, Paym
];
$this->getLogger(__METHOD__)->error('wallee::TransactionParameters', $parameters);
- // $transaction = $this->sdkService->call('createTransactionFromBasket', $parameters);
-
- $this->createWebhook();
-
- // if (is_array($transaction) && isset($transaction['error'])) {
- // return [
- // 'type' => GetPaymentMethodContent::RETURN_TYPE_ERROR,
- // 'content' => $transaction['error_msg']
- // ];
- // }
+ $transaction = $this->sdkService->call('createTransactionFromBasket', $parameters);
+ if (is_array($transaction) && isset($transaction['error'])) {
+ return [
+ 'type' => GetPaymentMethodContent::RETURN_TYPE_ERROR,
+ 'content' => $transaction['error_msg']
+ ];
+ }
- // $this->getLogger(__METHOD__)->error('wallee::transaction result', $transaction);
+ $this->session->getPlugin()->setValue('walleeTransactionId', $transaction['id']);
- // $this->session->getPlugin()->setValue('walleeTransactionId', $transaction['id']);
+ $hasPossiblePaymentMethods = $this->sdkService->call('hasPossiblePaymentMethods', [
+ 'transactionId' => $transaction['id']
+ ]);
+ if (! $hasPossiblePaymentMethods) {
+ return [
+ 'type' => GetPaymentMethodContent::RETURN_TYPE_ERROR,
+ 'content' => 'The selected payment method is not available.'
+ ];
+ }
return [
'type' => GetPaymentMethodContent::RETURN_TYPE_CONTINUE
@@ -186,7 +194,10 @@ private function createWebhook()
*/
public function executePayment(Order $order, PaymentMethod $paymentMethod): array
{
+ $transactionId = $this->session->getPlugin()->getValue('walleeTransactionId');
+
$parameters = [
+ 'transactionId' => $transactionId,
'order' => $order,
'paymentMethod' => $paymentMethod,
'billingAddress' => $this->getAddress($order->billingAddress),
@@ -199,12 +210,13 @@ public function executePayment(Order $order, PaymentMethod $paymentMethod): arra
];
$this->getLogger(__METHOD__)->error('wallee::TransactionParameters', $parameters);
- $transaction = $this->sdkService->call('createTransactionFromOrder', $parameters);
- $this->getLogger(__METHOD__)->error('wallee::ConfirmTransaction', $transaction);
+ $this->session->getPlugin()->unsetKey('walleeTransactionId');
+ $transaction = $this->sdkService->call('createTransactionFromOrder', $parameters);
if (is_array($transaction) && $transaction['error']) {
return [
- 'type' => 'error',
+ 'transactionId' => $transactionId,
+ 'type' => GetPaymentMethodContent::RETURN_TYPE_ERROR,
'content' => $transaction['error_msg']
];
}
@@ -212,16 +224,27 @@ public function executePayment(Order $order, PaymentMethod $paymentMethod): arra
$payment = $this->paymentHelper->createPlentyPayment($transaction);
$this->paymentHelper->assignPlentyPaymentToPlentyOrder($payment, $order->id);
+ $hasPossiblePaymentMethods = $this->sdkService->call('hasPossiblePaymentMethods', [
+ 'transactionId' => $transaction['id']
+ ]);
+ if (! $hasPossiblePaymentMethods) {
+ return [
+ 'transactionId' => $transaction['id'],
+ 'type' => GetPaymentMethodContent::RETURN_TYPE_ERROR,
+ 'content' => 'The selected payment method is not available.'
+ ];
+ }
+
$paymentPageUrl = $this->sdkService->call('buildPaymentPageUrl', [
'id' => $transaction['id']
]);
if (is_array($paymentPageUrl) && isset($paymentPageUrl['error'])) {
return [
+ 'transactionId' => $transaction['id'],
'type' => GetPaymentMethodContent::RETURN_TYPE_ERROR,
'content' => $paymentPageUrl['error_msg']
];
}
- $this->getLogger(__METHOD__)->error('wallee::before redirect', $paymentPageUrl);
return [
'type' => GetPaymentMethodContent::RETURN_TYPE_REDIRECT_URL,
diff --git a/src/Services/WebhookCronHandler.php b/src/Services/WebhookCronHandler.php
index 50217e4..40b0bc6 100644
--- a/src/Services/WebhookCronHandler.php
+++ b/src/Services/WebhookCronHandler.php
@@ -64,7 +64,7 @@ public function __construct(ConfigRepository $config, PaymentHelper $paymentHelp
public function handle()
{
foreach ($this->webhookRepository->getWebhookList() as $webhook) {
- $this->getLogger(__METHOD__)->debug('processWebhook', $webhook);
+ $this->getLogger(__METHOD__)->info('processWebhook', $webhook);
$this->processWebhook($webhook);
$this->webhookRepository->deleteWebhook($webhook->id);
}
From 1c9bc56e3aa0d55bfa42d54754027bccd0bec66e Mon Sep 17 00:00:00 2001
From: Simon Schurter
Date: Wed, 20 Mar 2019 16:45:07 +0100
Subject: [PATCH 5/6] Fix discount line item.
---
resources/lib/createTransactionFromOrder.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/resources/lib/createTransactionFromOrder.php b/resources/lib/createTransactionFromOrder.php
index 91501d1..6c3d0b5 100644
--- a/resources/lib/createTransactionFromOrder.php
+++ b/resources/lib/createTransactionFromOrder.php
@@ -83,7 +83,7 @@ function collectTransactionData($transactionRequest, $client)
$lineItems[] = $lineItem;
} elseif ($orderItem['typeId'] == 4 || $orderItem['typeId'] == 5) {
// GIFT_CARD
- $lineItem = buildLineItem($orderItem, $orderItem['itemVariationId'], $orderItem['itemVariationId'], LineItemType::DISCOUNT, $netPrices, $currencyDecimalPlaces);
+ $lineItem = buildLineItem($orderItem, 'coupon-discount', 'coupon-discount', LineItemType::DISCOUNT, $netPrices, $currencyDecimalPlaces);
$lineItems[] = $lineItem;
} elseif ($orderItem['typeId'] == 6) {
// SHIPPING
From 82c70982a43f504b2d761d9dcd433e9fccc6473d Mon Sep 17 00:00:00 2001
From: Simon Schurter
Date: Thu, 21 Mar 2019 10:45:45 +0100
Subject: [PATCH 6/6] Update version number.
---
config.json | 16 +++++++++++++++
meta/documents/changelog_de.md | 9 +++++++++
meta/documents/changelog_en.md | 9 +++++++++
plugin.json | 4 ++--
resources/lang/de/Config.properties | 2 ++
resources/lang/en/Config.properties | 2 ++
resources/lib/WalleeSdkHelper.php | 20 +++++++++++++------
resources/lib/createTransactionFromBasket.php | 5 +----
resources/lib/createTransactionFromOrder.php | 3 ---
resources/views/PaymentInformation.twig | 4 ++--
src/Methods/AbstractPaymentMethod.php | 1 -
.../DataProvider/PaymentInformation.php | 5 ++++-
src/Services/PaymentService.php | 4 ++--
13 files changed, 63 insertions(+), 21 deletions(-)
diff --git a/config.json b/config.json
index cae51a2..062da49 100644
--- a/config.json
+++ b/config.json
@@ -45,6 +45,22 @@
"options": {
"defaultValue": "11.3"
}
+ },
+ "confirmation_invoice": {
+ "type": "checkBox",
+ "required": false,
+ "label": "Config.confirmationInvoiceLabel",
+ "options": {
+ "defaultValue": true
+ }
+ },
+ "confirmation_packing_slip": {
+ "type": "checkBox",
+ "required": false,
+ "label": "Config.confirmationPackingSlipLabel",
+ "options": {
+ "defaultValue": true
+ }
}
}
},
diff --git a/meta/documents/changelog_de.md b/meta/documents/changelog_de.md
index 512691e..ef9f321 100644
--- a/meta/documents/changelog_de.md
+++ b/meta/documents/changelog_de.md
@@ -1,5 +1,14 @@
# Release Notes for wallee
+## v2.0.0 (2019-03-21)
+
+### Added
+- Allow customers to change payment method if a payment fails.
+- Allow customers to download invoice document and packing slip from order confirmation page.
+
+### Fixed
+- Create order before redirecting customer to payment page.
+
## v1.0.23 (2019-03-01)
### Fixed
diff --git a/meta/documents/changelog_en.md b/meta/documents/changelog_en.md
index 512691e..ef9f321 100644
--- a/meta/documents/changelog_en.md
+++ b/meta/documents/changelog_en.md
@@ -1,5 +1,14 @@
# Release Notes for wallee
+## v2.0.0 (2019-03-21)
+
+### Added
+- Allow customers to change payment method if a payment fails.
+- Allow customers to download invoice document and packing slip from order confirmation page.
+
+### Fixed
+- Create order before redirecting customer to payment page.
+
## v1.0.23 (2019-03-01)
### Fixed
diff --git a/plugin.json b/plugin.json
index 1d71abf..164ad5c 100644
--- a/plugin.json
+++ b/plugin.json
@@ -6,7 +6,7 @@
},
"namespace": "Wallee",
"type": "payment",
- "version": "1.0.23",
+ "version": "2.0.0",
"license": " Apache License Version 2",
"isClosedSource" : false,
"pluginIcon" : "icon_plugin_md.png",
@@ -33,7 +33,7 @@
"containers": [],
"require": ["IO"],
"dependencies":{
- "wallee/sdk":"1.1.1"
+ "wallee/sdk":"1.1.14"
},
"runOnBuild": [
"Wallee\\Migrations\\CreatePaymentMethods",
diff --git a/resources/lang/de/Config.properties b/resources/lang/de/Config.properties
index a84b225..48eaac4 100644
--- a/resources/lang/de/Config.properties
+++ b/resources/lang/de/Config.properties
@@ -5,6 +5,8 @@ spaceIdLabel=Space Id
resourceVersionLabel=Resource Version
refundSuccessfulStatusLabel=Status ID für erfolgreiche Gutschrift
refundFailedStatusLabel=Status ID für fehlgeschlagene Gutschrift
+confirmationInvoiceLabel=Kunden erlauben, Rechnungsdokument herunterzuladen
+confirmationPackingSlipLabel=Kunden erlauben, Lieferschein herunterzuladen
AlipayTab=Alipay
alipayActiveLabel=Aktiv
alipayTitleLabel=Titel
diff --git a/resources/lang/en/Config.properties b/resources/lang/en/Config.properties
index 8994277..524333d 100644
--- a/resources/lang/en/Config.properties
+++ b/resources/lang/en/Config.properties
@@ -5,6 +5,8 @@ spaceIdLabel=Space Id
resourceVersionLabel=Resource Version
refundSuccessfulStatusLabel=Status ID for successful refunds
refundFailedStatusLabel=Status ID for failed refunds
+confirmationInvoiceLabel=Allow customers to download invoice document
+confirmationPackingSlipLabel=Allow customers to download packing slip
AlipayTab=Alipay
alipayActiveLabel=Enabled
alipayTitleLabel=Title
diff --git a/resources/lib/WalleeSdkHelper.php b/resources/lib/WalleeSdkHelper.php
index 1f472ce..d015e75 100644
--- a/resources/lib/WalleeSdkHelper.php
+++ b/resources/lib/WalleeSdkHelper.php
@@ -89,14 +89,22 @@ public static function convertData($data)
}
return $data;
} elseif (is_object($data)) {
- $values = [];
- foreach (array_keys($data::swaggerTypes()) as $property) {
- $getter = 'get' . ucfirst($property);
- if ($data->$getter() !== null) {
- $values[$property] = self::convertData($data->$getter());
+ if ($data instanceof stdClass) {
+ $values = [];
+ foreach ($data as $property => $value) {
+ $values[$property] = self::convertData($value);
}
+ return $values;
+ } else {
+ $values = [];
+ foreach (array_keys($data::swaggerTypes()) as $property) {
+ $getter = 'get' . ucfirst($property);
+ if ($data->$getter() !== null) {
+ $values[$property] = self::convertData($data->$getter());
+ }
+ }
+ return $values;
}
- return $values;
} else {
return (string) $data;
}
diff --git a/resources/lib/createTransactionFromBasket.php b/resources/lib/createTransactionFromBasket.php
index e3c9d08..b83ceaf 100644
--- a/resources/lib/createTransactionFromBasket.php
+++ b/resources/lib/createTransactionFromBasket.php
@@ -1,19 +1,16 @@
{{ trans("wallee::Template.paymentInformationDownloadInvoice") }}
- {{ trans("wallee::Template.paymentInformationDownloadPackingSlip") }}
+ {% if downloadInvoice %}{{ trans("wallee::Template.paymentInformationDownloadInvoice") }}
{% endif %}
+ {% if downloadPackingSlip %}{{ trans("wallee::Template.paymentInformationDownloadPackingSlip") }}
{% endif %}
{% endif %}
\ No newline at end of file
diff --git a/src/Methods/AbstractPaymentMethod.php b/src/Methods/AbstractPaymentMethod.php
index 0a5385b..b9cf757 100644
--- a/src/Methods/AbstractPaymentMethod.php
+++ b/src/Methods/AbstractPaymentMethod.php
@@ -5,7 +5,6 @@
use Plenty\Plugin\ConfigRepository;
use Wallee\Services\PaymentService;
use Plenty\Modules\Payment\Contracts\PaymentRepositoryContract;
-use Plenty\Modules\Payment\Models\Payment;
abstract class AbstractPaymentMethod extends PaymentMethodService
{
diff --git a/src/Providers/DataProvider/PaymentInformation.php b/src/Providers/DataProvider/PaymentInformation.php
index 7eeba9f..7d49a6d 100644
--- a/src/Providers/DataProvider/PaymentInformation.php
+++ b/src/Providers/DataProvider/PaymentInformation.php
@@ -6,6 +6,7 @@
use Plenty\Modules\Payment\Models\Payment;
use Plenty\Modules\Payment\Models\PaymentProperty;
use Wallee\Services\WalleeSdkService;
+use Plenty\Plugin\ConfigRepository;
class PaymentInformation
{
@@ -32,7 +33,9 @@ public function call(Twig $twig, $arg): string
return $twig->render('wallee::PaymentInformation', [
'order' => $order,
'transaction' => $transaction,
- 'payment' => $payment
+ 'payment' => $payment,
+ 'downloadInvoice' => pluginApp(ConfigRepository::class)->get('wallee.confirmation_invoice') === "true",
+ 'downloadPackingSlip' => pluginApp(ConfigRepository::class)->get('wallee.confirmation_packing_slip') === "true"
]);
}
} else {
diff --git a/src/Services/PaymentService.php b/src/Services/PaymentService.php
index 2e8ca37..721ccd9 100644
--- a/src/Services/PaymentService.php
+++ b/src/Services/PaymentService.php
@@ -146,7 +146,7 @@ public function getPaymentContent(Basket $basket, array $basketForTemplate, Paym
'failedUrl' => $this->getFailedUrl(),
'checkoutUrl' => $this->getCheckoutUrl()
];
- $this->getLogger(__METHOD__)->error('wallee::TransactionParameters', $parameters);
+ $this->getLogger(__METHOD__)->debug('wallee::TransactionParameters', $parameters);
$transaction = $this->sdkService->call('createTransactionFromBasket', $parameters);
if (is_array($transaction) && isset($transaction['error'])) {
@@ -208,7 +208,7 @@ public function executePayment(Order $order, PaymentMethod $paymentMethod): arra
'failedUrl' => $this->getFailedUrl(),
'checkoutUrl' => $this->getCheckoutUrl()
];
- $this->getLogger(__METHOD__)->error('wallee::TransactionParameters', $parameters);
+ $this->getLogger(__METHOD__)->debug('wallee::TransactionParameters', $parameters);
$this->session->getPlugin()->unsetKey('walleeTransactionId');