Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Ab testing with widget and chosted checkout #91

Merged
merged 7 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion Controller/Payment/Checkout/AbstractPaymentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Message\ManagerInterface as MessageManagerInterface;
use Mondu\Mondu\Helpers\ABTesting\ABTesting;
use Mondu\Mondu\Helpers\Logger\Logger as MonduFileLogger;
use Mondu\Mondu\Model\Request\Factory as RequestFactory;

Expand Down Expand Up @@ -52,6 +53,10 @@ abstract class AbstractPaymentController implements ActionInterface
*/
protected $jsonResultFactory;

/**
* @var ABTesting
*/
protected $aBTesting;
/**
* Execute
*
Expand All @@ -77,7 +82,8 @@ public function __construct(
MessageManagerInterface $messageManager,
MonduFileLogger $monduFileLogger,
RequestFactory $requestFactory,
JsonFactory $jsonResultFactory
JsonFactory $jsonResultFactory,
ABTesting $aBTesting
) {
$this->request = $request;
$this->response = $response;
Expand All @@ -87,6 +93,7 @@ public function __construct(
$this->monduFileLogger = $monduFileLogger;
$this->requestFactory = $requestFactory;
$this->jsonResultFactory = $jsonResultFactory;
$this->aBTesting = $aBTesting;
}


Expand Down
5 changes: 4 additions & 1 deletion Controller/Payment/Checkout/AbstractSuccessController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Magento\Sales\Model\Order\Email\Sender\OrderSender;
use Magento\Checkout\Helper\Data as CheckoutData;
use Magento\Quote\Api\CartManagementInterface;
use Mondu\Mondu\Helpers\ABTesting\ABTesting;
use Mondu\Mondu\Helpers\Logger\Logger as MonduFileLogger;
use Mondu\Mondu\Model\Request\Factory as RequestFactory;

Expand Down Expand Up @@ -64,7 +65,8 @@ public function __construct(
\Magento\Customer\Model\Session $customerSession,
OrderSender $orderSender,
CheckoutData $checkoutData,
CartManagementInterface $quoteManagement
CartManagementInterface $quoteManagement,
ABTesting $aBTesting
) {
parent::__construct(
$request,
Expand All @@ -75,6 +77,7 @@ public function __construct(
$monduFileLogger,
$requestFactory,
$jsonResultFactory,
$aBTesting
);
$this->customerSession = $customerSession;
$this->orderSender = $orderSender;
Expand Down
8 changes: 2 additions & 6 deletions Controller/Payment/Checkout/Token.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Mondu\Mondu\Controller\Payment\Checkout;

use Magento\Framework\Webapi\Response;
use Mondu\Mondu\Helpers\ABTesting\ABTesting;
use Mondu\Mondu\Model\Request\Factory as RequestFactory;

class Token extends AbstractPaymentController
Expand All @@ -22,12 +23,7 @@ public function execute()
'payment_method' => $paymentMethod
]);

$response = [
'error' => $result['error'],
'message' => $result['message'],
'token' => $result['body']['order']['token'] ?? null,
'hosted_checkout_url' => $result['body']['order']['hosted_checkout_url'] ?? null
];
$response = $this->aBTesting->formatApiResult($result);

$this->monduFileLogger->info('Token controller got a result ', $response);
if (!$response['error']) {
Expand Down
45 changes: 45 additions & 0 deletions Helpers/ABTesting/ABTesting.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php
namespace Mondu\Mondu\Helpers\ABTesting;

class ABTesting
{
protected const HOSTED_SOURCE = 'hosted';
protected const WIDGET_SOURCE = 'widget';

/**
* FormatApiResult
*
* @param array $result
* @return array
*/
public function formatApiResult($result)
{
$body = $result['body'];

$response = [
'error' => $result['error'],
'message' => $result['message'],
'token' => $result['body']['order']['token'] ?? null,
'hosted_checkout_url' => $result['body']['order']['hosted_checkout_url'] ?? null
];

if ($this->isHostedCheckout($body['order'])) {
$response['source'] = self::HOSTED_SOURCE;
} else {
$response['source'] = self::WIDGET_SOURCE;
}

return $response;
}

/**
* IsHostedCheckout
*
* @param array $monduOrder
* @return bool
*/
protected function isHostedCheckout($monduOrder): bool
{
return isset($monduOrder['hosted_checkout_url']);
}
}
2 changes: 1 addition & 1 deletion Model/Request/Confirm.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

class Confirm extends CommonRequest
{
public const ORDER_STATE = ['pending', 'confirmed'];
public const ORDER_STATE = ['pending', 'confirmed', 'authorized'];

/**
* @var Curl
Expand Down
25 changes: 23 additions & 2 deletions Model/Ui/ConfigProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,17 @@
class ConfigProvider implements ConfigProviderInterface
{
public const CODE = 'mondu';
public const SEPA_CODE = 'mondusepa';
public const INSTALLMENT_CODE = 'monduinstallment';

public const API_URL = 'https://api.mondu.ai/api/v1';
public const SANDBOX_API_URL = 'https://api.demo.mondu.ai/api/v1';

public const AUTHORIZATION_STATE_FLOW = 'authorization_flow';

public const SDK_URL = 'https://checkout.mondu.ai/widget.js';
public const SANDBOX_SDK_URL = 'https://checkout.demo.mondu.ai/widget.js';

/**
* @var UrlInterface
*/
Expand Down Expand Up @@ -96,6 +101,19 @@ public function getApiUrl($path = null): string
return $baseUrl . ($path ? '/'.$path : '');
}

/**
* Returns mondu.js url
*
* @return string
*/
public function getSdkUrl(): string
{
if ($this->scopeConfig->getValue('payment/mondu/sandbox', ScopeInterface::SCOPE_STORE, $this->contextCode)) {
return self::SANDBOX_SDK_URL;
}
return self::SDK_URL;
}

/**
* Get mode (sandbox or live)
*
Expand Down Expand Up @@ -206,16 +224,19 @@ public function getConfig()
return [
'payment' => [
self::CODE => [
'sdkUrl' => $this->getSdkUrl(),
'monduCheckoutTokenUrl' => $this->urlBuilder->getUrl('mondu/payment_checkout/token'),
'description' => $descriptionMondu,
'title' => __($this->scopeConfig->getValue('payment/mondu/title', ScopeInterface::SCOPE_STORE))
],
'mondusepa' => [
self::SEPA_CODE => [
'sdkUrl' => $this->getSdkUrl(),
'monduCheckoutTokenUrl' => $this->urlBuilder->getUrl('mondu/payment_checkout/token'),
'description' => $descriptionMondusepa,
'title' => __($this->scopeConfig->getValue('payment/mondusepa/title', ScopeInterface::SCOPE_STORE))
],
'monduinstallment' => [
self::INSTALLMENT_CODE => [
'sdkUrl' => $this->getSdkUrl(),
'monduCheckoutTokenUrl' => $this->urlBuilder->getUrl('mondu/payment_checkout/token'),
'description' => $descriptionMonduinstallment,
'title' => __($this->scopeConfig
Expand Down
21 changes: 21 additions & 0 deletions Observer/CreateOrder.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,12 +139,17 @@ public function _execute(Observer $observer)
try {
$this->monduFileLogger
->info('Validating order status in Mondu. ', ['orderNumber' => $order->getIncrementId()]);

$orderData = $this->_requestFactory->create(RequestFactory::TRANSACTION_CONFIRM_METHOD)
->setValidate(true)
->process(['orderUid' => $orderUid]);

$orderData = $orderData['order'];
$authorizationData = $this->confirmAuthorizedOrder($orderData, $order->getIncrementId());
$orderData['state'] = $authorizationData['state'];

$order->setData('mondu_reference_id', $orderUid);
$order->addStatusHistoryComment(__('Mondu: order id %1', $orderData['uuid']));

$order->save();
$this->monduFileLogger->info('Saved the order in Magento ', ['orderNumber' => $order->getIncrementId()]);
Expand All @@ -163,4 +168,20 @@ public function _execute(Observer $observer)
throw new LocalizedException(__($e->getMessage()));
}
}

/**
* Confirm Authorized Order
*
* @param array $orderData
* @param string $orderNumber
*/
protected function confirmAuthorizedOrder($orderData, $orderNumber)
{
if ($orderData['state'] === 'authorized') {
$authorizationData = $this->_requestFactory->create(RequestFactory::CONFIRM_ORDER)
->process(['orderUid' => $orderData['uuid'], 'referenceId' => $orderNumber]);
return $authorizationData['order'];
}
return $orderData;
}
}
1 change: 1 addition & 0 deletions Observer/ShipOrder.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ public function _execute(Observer $observer)
}

$monduId = $order->getData('mondu_reference_id');
$this->monduLogger->syncOrder($monduId);

if (!$this->monduLogger->canShipOrder($monduId)) {
throw new LocalizedException(
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "mondu_gmbh/magento2-payment",
"description": "Mondu payment method for magento 2",
"type": "magento2-module",
"version": "2.1.3",
"version": "2.2.0",
"license": [
"MIT"
],
Expand Down
19 changes: 19 additions & 0 deletions etc/csp_whitelist.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?xml version="1.0"?>
<csp_whitelist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Csp/etc/csp_whitelist.xsd">
<policies>
<policy id="script-src">
<values>
<value id="mondu_io_wildcard" type="host">*.mondu.ai/widget.js</value>
<value id="mondu_io_wildcard_local" type="host">*.mondu.local/widget.js</value>
<value id="mondu_io_wildcard_localhost" type="host">localhost:*/dist/widget.js</value>
</values>
</policy>
<policy id="frame-src">
<values>
<value id="mondu_io_wildcard" type="host">*.mondu.ai/</value>
<value id="mondu_io_wildcard_local" type="host">*.mondu.local</value>
<value id="mondu_io_wildcard_localhost" type="host">localhost:*/</value>
</values>
</policy>
</policies>
</csp_whitelist>
2 changes: 1 addition & 1 deletion etc/module.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Mondu_Mondu" setup_version="2.1.3">
<module name="Mondu_Mondu" setup_version="2.2.0">
<sequence>
<module name="Magento_Sales"/>
<module name="Magento_Payment"/>
Expand Down
63 changes: 60 additions & 3 deletions view/frontend/web/js/view/payment/method-renderer/mondu.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ define([
initObservable: function () {
var self = this;

if (!window.monduLoading) {
window.monduLoading = true;
var monduSkd = document.createElement("script");
monduSkd.onload = function () {
self.monduSdkLoaded = true;
};
monduSkd.src = self.getMonduSdkUrl();
document.head.appendChild(monduSkd);
}

this.messageContainer = new Messages();

return self;
Expand All @@ -44,6 +54,11 @@ define([
.monduCheckoutTokenUrl;
},

getMonduSdkUrl: function () {
var self = this;
return window.checkoutConfig.payment[self.getCode()].sdkUrl;
},

getCustomerEmail: function () {
if (quote.guestEmail) {
return quote.guestEmail;
Expand Down Expand Up @@ -89,9 +104,7 @@ define([
},
}).always(function (res) {
if (res && res.token && !res.error) {
customerData.invalidate(['cart', 'checkout-data']);

$.mage.redirect(res.hosted_checkout_url);
self.handlePayment(res.source, res);
return;
} else {
self.isPlaceOrderActionAllowed(true);
Expand All @@ -113,5 +126,49 @@ define([
$("body").trigger("processStop");
})
},

handlePayment: function (source, res) {
var self = this;
if (source === 'hosted') {
customerData.invalidate(['cart', 'checkout-data']);
$.mage.redirect(res.hosted_checkout_url);
return;
}

if (source === 'widget') {
self.openWidget(res.token);
}
},

openWidget: function (token) {
var self = this;
$(
'<div id="mondu-checkout-widget" style="position: fixed; top: 0;right: 0;left: 0;bottom: 0; z-index: 99999999;"/>'
).appendTo("body");
window.monduCheckout.render({
token,
onCancel: () => {
$("#mondu-checkout-widget").remove();
self.isPlaceOrderActionAllowed(true);
$("body").trigger("processStop");
},
onSuccess: () => {
self.getPlaceOrderDeferredObject()
.fail(function () {
self.isPlaceOrderActionAllowed(true);
$("body").trigger("processStop");
})
.done(function () {
self.afterPlaceOrder();
if (self.redirectAfterPlaceOrder) {
redirectOnSuccessAction.execute();
}
});
$("#mondu-checkout-widget").remove();
$("body").trigger("processStop");
},
onClose: () => {},
});
},
});
});