Skip to content

Commit

Permalink
preliminary completion of auto-setting
Browse files Browse the repository at this point in the history
  • Loading branch information
leon-zhang-awx committed Oct 25, 2024
1 parent 87172c2 commit 5898926
Show file tree
Hide file tree
Showing 7 changed files with 151 additions and 18 deletions.
55 changes: 55 additions & 0 deletions Controller/Adminhtml/Configuration/SetUpdateSettingsMessage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

namespace Airwallex\Payments\Controller\Adminhtml\Configuration;

use Magento\Framework\Math\Random;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\StoreManager;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\App\RequestInterface;

class SetUpdateSettingsMessage extends Action
{
public const CACHE_NAME = 'airwallex_set_update_settings_message';

protected JsonFactory $resultJsonFactory;
protected Context $context;
protected StoreManager $storeManager;
protected Random $random;
protected CacheInterface $cache;
protected RequestInterface $request;

public function __construct(
Context $context,
JsonFactory $resultJsonFactory,
StoreManager $storeManager,
Random $random,
CacheInterface $cache,
RequestInterface $request
)
{
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->context = $context;
$this->storeManager = $storeManager;
$this->random = $random;
$this->cache = $cache;
$this->request = $request;
}

/**
* @return Json
*/
public function execute(): Json
{
$resultJson = $this->resultJsonFactory->create();
$this->context->getMessageManager()->addSuccessMessage('Your Airwallex plug-in is activated.
You can also manage which account is connected to your Magento store.');
header('Location: ' . base64_decode($this->request->getParam('target_url')));
return $resultJson;
}
}
10 changes: 10 additions & 0 deletions Helper/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,16 @@ public function getMode(): string
return $this->scopeConfig->getValue('airwallex/general/mode');
}

/**
* Account
*
* @return string
*/
public function getAccount(): string
{
return $this->scopeConfig->getValue('airwallex/general/account') ?? '';
}

/**
* Api url
*
Expand Down
8 changes: 7 additions & 1 deletion Model/Config/Adminhtml/UpdateSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Airwallex\Payments\Model\Config\Adminhtml;

use Airwallex\Payments\Helper\Configuration;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;

Expand All @@ -20,11 +21,16 @@ public function render(AbstractElement $element): string
return parent::render($element);
}

public function getAccount()
{
return \Magento\Framework\App\ObjectManager::getInstance()->get(Configuration::class)->getAccount();
}

public function getButtonHtml()
{
$data = [
'id' => 'airwallex_update_settings',
'label' => __('Connecting'),
'label' => __('Connect account'),
];

return $this->getLayout()->createBlock('Magento\Backend\Block\Widget\Button')->setData($data)->toHtml();
Expand Down
27 changes: 24 additions & 3 deletions Model/Service.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,8 @@ public function __construct(
CacheInterface $cache,
Manager $cacheManager,
Writer $configWriter
) {
)
{
$this->configuration = $configuration;
$this->checkoutHelper = $checkoutHelper;
$this->quoteIdToMaskedQuoteId = $quoteIdToMaskedQuoteId;
Expand Down Expand Up @@ -600,10 +601,18 @@ public function updateSettings(): string
return $this->error('Token is not valid.');
}
$this->cache->remove(UpdateSettingsToken::CACHE_NAME);

$redirectUrl = $this->request->getParam('redirect_url');
$arrayRedirectUrl = parse_url($redirectUrl);
parse_str($arrayRedirectUrl['query'], $queryParams);
json_encode($queryParams);
$targetUrl = json_encode($queryParams['target_url']);
$mode = $queryParams['env'];
$clientId = $this->request->getParam('client_id');
$apiKey = $this->request->getParam('api_key');
$webhookKey = $this->request->getParam('webhook_key');
$mode = $this->request->getParam('mode');
$webhookKey = $this->request->getParam('webhook_secret_key');
$accountId = $this->request->getParam('account_id');
$accountName = $this->request->getParam('account_name');
if (empty($clientId)) {
return $this->error('Client ID is required.');
}
Expand All @@ -616,8 +625,20 @@ public function updateSettings(): string
if (empty($mode)) {
return $this->error('Mode is required.');
}
if (empty($accountId)) {
return $this->error('Account id is required.');
}
if (empty($accountName)) {
return $this->error('Account name is required.');
}
$encryptor = ObjectManager::getInstance()->get(EncryptorInterface::class);
$mode = $mode === 'demo' ? 'demo' : 'prod';
$account = $this->configuration->getAccount();
$arrAccount = $account ? json_decode($account, true) : [];
$arrAccount[$mode . '_account_id'] = $accountId;
$arrAccount[$mode . '_account_name'] = $accountName;
$this->configWriter->save('airwallex/general/' . 'account', json_encode($arrAccount));
$this->configWriter->save('airwallex/general/' . $mode . '_account_name', $accountName);
$this->configWriter->save('airwallex/general/' . $mode . '_client_id', $clientId);
$this->configWriter->save('airwallex/general/' . $mode . '_api_key', $encryptor->encrypt($apiKey));
$this->configWriter->save('airwallex/general/webhook_' . $mode . '_secret_key', $encryptor->encrypt($webhookKey));
Expand Down
6 changes: 3 additions & 3 deletions etc/adminhtml/system/basic.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
<source_model>Airwallex\Payments\Model\Config\Source\Mode</source_model>
<config_path>airwallex/general/mode</config_path>
</field>
<!-- <field id="update_settings" translate="label" type="button" sortOrder="15" showInDefault="1" showInWebsite="1" showInStore="1">-->
<!-- <frontend_model>Airwallex\Payments\Model\Config\Adminhtml\UpdateSettings</frontend_model>-->
<!-- </field>-->
<field id="update_settings" translate="label" type="button" sortOrder="15" showInDefault="1" showInWebsite="1" showInStore="1">
<frontend_model>Airwallex\Payments\Model\Config\Adminhtml\UpdateSettings</frontend_model>
</field>
<field id="demo_client_id" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Demo Client ID</label>
<config_path>airwallex/general/demo_client_id</config_path>
Expand Down
1 change: 0 additions & 1 deletion etc/adminhtml/system/card.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
<label>Credit Card</label>
<field id="active" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1">
<label>Enable Credit Card</label>
<!-- <comment>Enable Credit Card</comment> -->
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<config_path>payment/airwallex_payments_card/active</config_path>
</field>
Expand Down
62 changes: 52 additions & 10 deletions view/adminhtml/templates/config/update_settings.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,67 @@
'jquery'
],
function(jQuery) {
let accountStr = '<?= $this->getAccount() ?>';
let account = accountStr ? JSON.parse(accountStr) : {};
let typeSelector = '[name="groups[airwallex_payments][groups][basic][fields][mode][value]"]';
let env = document.querySelector(typeSelector).value;

jQuery(document).ready(function() {
if (account[env + "_account_id"]) {
jQuery("#awx-connected").hide();
}
});

jQuery(typeSelector).on('change', () => {
let env = document.querySelector(typeSelector).value;
if (account[env + "_account_id"]) {
jQuery("#awx-connected").hide();
} else {
jQuery("#awx-connected").show();
}
});

// todo: when change the mode configuration, then we click configuration, it will show the original mode configuration when redirect back
jQuery('#airwallex_update_settings').click(function() {
let env = document.querySelector(typeSelector).value;
let redirectUrl = '<?= $block->escapeJs($block->getUrl('airwallex/configuration/setUpdateSettingsMessage')) ?>';
redirectUrl += "?target_url=" + btoa(location.href) + '&env=' + env;
new Ajax.Request('<?= $block->escapeJs($block->getUrl('airwallex/configuration/updateSettingsToken')) ?>', {
type: "GET",
asynchronous: true,
onSuccess: function(response) {
let domain = 'https://demo.airwallex.com/';
if (document.querySelector('[name="groups[airwallex_payments][groups][basic][fields][mode][value]"]').value === 'prod') {
domain = domain.replace('demo.airwallex', 'www.airwallex');
let awxUrl = 'https://demo.airwallex.com/';
if (env === 'prod') {
awxUrl = awxUrl.replace('demo.airwallex', 'www.airwallex');
}
location.href = domain + "/index.html?" +
"domain=" + encodeURIComponent(location.href) +
"&token=" + response.responseJSON.token
},
onFailure: function(response) {},
onComplete: function() {}
let connectedAccountId = account[env + "_account_id"] || '';
awxUrl = "https://mg.qianjinyike.com/test2.html";
location.href = awxUrl.trim() + "?" +
"redirect_url=" + encodeURIComponent(redirectUrl) +
"&token=" + response.responseJSON.token +
"&connected_account_id=" + connectedAccountId
}
});
});


});
</script>

<?php echo $block->getButtonHtml() ?>
<?php echo $block->getButtonHtml() ?>

<div id="awx-connected" class="awx-connect-tip">
<div class="title">Your Airwallex plug-in is activated</div>
<div class="content">You can also manage which account is connected to your WooCommerce store.</div>
</div>

<style>
.awx-connect-tip {
margin: 10px 0;
}

.awx-connect-tip .title {
font-weight: bold;
margin-bottom: 5px;
}
</style>

0 comments on commit 5898926

Please sign in to comment.