Skip to content

Commit

Permalink
Merge pull request #59 from airwallex/bugfix
Browse files Browse the repository at this point in the history
Bugfix
  • Loading branch information
leon-zhang-awx authored Dec 23, 2024
2 parents 2180278 + 45d977a commit 32d9a8d
Show file tree
Hide file tree
Showing 13 changed files with 290 additions and 41 deletions.
Binary file added .DS_Store
Binary file not shown.
14 changes: 0 additions & 14 deletions Api/Data/PlaceOrderResponseInterface.php
Original file line number Diff line number Diff line change
@@ -1,18 +1,4 @@
<?php
/**
* This file is part of the Airwallex Payments module.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade
* to newer versions in the future.
*
* @copyright Copyright (c) 2021 Magebit, Ltd. (https://magebit.com/)
* @license GNU General Public License ("GPL") v3.0
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Airwallex\Payments\Api\Data;

Expand Down
Binary file added Controller/.DS_Store
Binary file not shown.
154 changes: 154 additions & 0 deletions Controller/Adminhtml/Configuration/SetUpdateSettingsMessage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
<?php

namespace Airwallex\Payments\Controller\Adminhtml\Configuration;

use Airwallex\Payments\Helper\Configuration;
use Magento\Framework\DataObject\IdentityService;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
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\UrlInterface;
use Magento\Store\Model\StoreManager;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\App\RequestInterface;

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

protected JsonFactory $resultJsonFactory;
protected Context $context;
protected StoreManager $storeManager;
protected Random $random;
protected CacheInterface $cache;
protected RequestInterface $request;
protected Configuration $configuration;
protected IdentityService $identityService;

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

public function getOriginFromUrl($url): string
{
$parsedUrl = parse_url($url);
$origin = $parsedUrl['scheme'] . '://' . $parsedUrl['host'];
if (isset($parsedUrl['port'])) {
$origin .= ':' . $parsedUrl['port'];
}
return $origin;
}

/**
* @return Json
* @throws NoSuchEntityException|LocalizedException
*/
public function execute(): Json
{
$resultJson = $this->resultJsonFactory->create();
if (empty($this->request->getParam('code'))) {
header('Location: ' . base64_decode($this->request->getParam('target_url')));
return $resultJson;
}
$environment = 'demo';
if ($this->request->getParam('env') !== 'demo') {
$environment = 'www';
}
$platform = 'magento';
$storeUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_WEB);
$baseUrl = trim($storeUrl, '/');
$webhookNotificationUrl = $baseUrl . '/airwallex/webhooks';
if (!function_exists('gzdecode')) {
return $this->error('Error: The gzdecode function is not available. Please make sure the zlib extension is enabled.', $resultJson);
}

$accessToken = gzdecode(base64_decode($this->request->getParam('code')));
$requestId = $this->identityService->generateId();

$url = "https://$environment.airwallex.com/payment_app/plugin/api/v1/connection/finalize";
$data = [
'platform' => $platform,
'origin' => $this->getOriginFromUrl($baseUrl),
'baseUrl' => $baseUrl,
'webhookNotificationUrl' => $webhookNotificationUrl,
'token' => $this->token($environment),
'requestId' => $requestId
];

if (!function_exists('curl_init')) {
return $this->error('Error: Please make sure the curl extension is enabled.', $resultJson);
}

$options = [
'http' => [
'method' => 'POST',
'header' => [
'Content-Type: application/json',
'Authorization: Bearer ' . $accessToken,
],
'content' => json_encode($data),
'ignore_errors' => true
],
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
if ($response === false) {
return $this->error('Error: Unable to fetch the URL. Please try again.', $resultJson);
}
$responseData = json_decode($response, true);

if (!empty($responseData['message']) && $responseData['message'] == 'OK') {
return $this->success('Your Airwallex plug-in is activated.
You can also manage which account is connected to your Magento store.', $resultJson);
}

return $this->error($responseData['error'], $resultJson);
}

public function error($message, $resultJson): Json
{
$this->context->getMessageManager()->addErrorMessage($message);
header('Location: ' . base64_decode($this->request->getParam('target_url')));
return $resultJson;
}

public function success($message, $resultJson): Json
{
$this->context->getMessageManager()->addSuccessMessage($message);
header('Location: ' . base64_decode($this->request->getParam('target_url')));
return $resultJson;
}

/**
* @throws LocalizedException
*/
public function token($environment): string
{
$token = $environment . '-' . $this->random->getRandomString(32);
$this->cache->save($token, self::CACHE_NAME, [], 60 * 60 * 24);
return $token;
}
}
3 changes: 2 additions & 1 deletion Controller/Webhooks/Index.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ public function execute(): ResponseHttp
}
} catch (Exception $e) {
$id = $data->sourceId ?? '';
$this->requestLog->setMessage($data->name . " $id webhook: " . $e->getMessage(), $e->getTraceAsString())->send();
$name = $data->name ?? '';
$this->requestLog->setMessage("$name $id webhook: " . $e->getMessage(), $e->getTraceAsString())->send();
$this->logger->error($e->getMessage());
throw $e;
}
Expand Down
43 changes: 43 additions & 0 deletions Model/Config/Adminhtml/UpdateSettings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Airwallex\Payments\Model\Config\Adminhtml;

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

class UpdateSettings extends Field
{
protected $_template = 'Airwallex_Payments::config/update_settings.phtml';

protected function _getElementHtml(AbstractElement $element): string
{
return $this->_toHtml();
}

public function render(AbstractElement $element): string
{
$element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
return parent::render($element);
}

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

/**
* @throws LocalizedException
*/
public function getButtonHtml()
{
$data = [
'id' => 'airwallex_update_settings',
'label' => __('Connect account'),
];

return $this->getLayout()->createBlock('Magento\Backend\Block\Widget\Button')->setData($data)->toHtml();
}
}
14 changes: 0 additions & 14 deletions Setup/Patch/Data/AddAirwallexCustomerIdAttribute.php
Original file line number Diff line number Diff line change
@@ -1,18 +1,4 @@
<?php
/**
* This file is part of the Airwallex Payments module.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade
* to newer versions in the future.
*
* @copyright Copyright (c) 2021 Magebit, Ltd. (https://magebit.com/)
* @license GNU General Public License ("GPL") v3.0
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Airwallex\Payments\Setup\Patch\Data;

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": "airwallex/payments-plugin-magento",
"type": "magento2-module",
"description": "",
"version": "1.10.0",
"version": "1.10.1",
"require": {
"ext-json": "*",
"php": "^7.4|^8.0",
Expand Down
3 changes: 3 additions & 0 deletions etc/adminhtml/system/basic.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +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="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
14 changes: 7 additions & 7 deletions etc/adminhtml/system/card.xml
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,14 @@
<![CDATA[This determines how large or small the text will appear within the input field. Set a font size between 12 to 20px.]]>
</comment>
</field>
<field id="preverification" translate="label" type="select" sortOrder="63" showInDefault="1" showInWebsite="1">
<label>Pre Verfication</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<config_path>payment/airwallex_payments_card/preverification</config_path>
<comment>
<!-- <field id="preverification" translate="label" type="select" sortOrder="63" showInDefault="1" showInWebsite="1">-->
<!-- <label>Pre Verfication</label>-->
<!-- <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>-->
<!-- <config_path>payment/airwallex_payments_card/preverification</config_path>-->
<!-- <comment>-->
<!-- <![CDATA[If you enable this option, we will provide the necessary card information before payment, allowing you to integrate with third-party risk control systems. For more details, please refer to this <a href='https://baidu.com'>document</a>.]]>-->
</comment>
</field>
<!-- </comment>-->
<!-- </field>-->
<field id="sort_order" translate="label" type="text" sortOrder="210" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Sort Order</label>
<comment>Adjust this to move the payment method above or below other payment methods</comment>
Expand Down
2 changes: 1 addition & 1 deletion etc/module.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?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="Airwallex_Payments" setup_version="1.10.0">
<module name="Airwallex_Payments" setup_version="1.10.1">
<sequence>
<module name="Magento_Sales"/>
<module name="Magento_Payment"/>
Expand Down
73 changes: 73 additions & 0 deletions view/adminhtml/templates/config/update_settings.phtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php /** @var \Airwallex\Payments\Model\Config\Adminhtml\UpdateSettings $block */ ?>
<script>
require([
'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;

let setting = function () {
let env = document.querySelector(typeSelector).value;
let connectedSelector = "#awx-connected";
if (!account[env + "_account_id"]) {
jQuery(connectedSelector).hide();
jQuery("#airwallex_update_settings").html('Connect account');
} else {
jQuery(connectedSelector).show();
jQuery(connectedSelector).html(account[env + "_account_name"]);
jQuery("#airwallex_update_settings").html('Manage');
}
};

jQuery(document).ready(setting);
jQuery(typeSelector).on('change', setting);

function uuid() {
let S4 = function () {
return ((1 + Math.random()) * 0X10000 | 0).toString(16).substring(1);
};
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

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;
let awxUrl = 'https://demo.airwallex.com/';
if (env === 'prod') {
awxUrl = awxUrl.replace('demo.airwallex', 'www.airwallex');
}
const connectedAccountId = account[`${env}_account_id`] || '';
const params = new URLSearchParams({
platform: 'magento',
origin: location.href,
returnUrl: redirectUrl,
requestId: uuid(),
connectedAccountId: connectedAccountId,
});

location.href = `${awxUrl.trim()}payment_app/plugin/api/v1/connection/start?${params.toString()}`;
});
});
</script>


<div style="display: flex">
<div id="awx-connected" class="awx-connect-tip">
</div>
<?php echo $block->getButtonHtml() ?>
</div>

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

.awx-connect-tip .title {
font-weight: bold;
margin-bottom: 5px;
}
</style>
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,13 @@ define([
},

city(addr, type) {
if (type === 'google') {
return addr.locality || addr.administrativeArea || addr.countryCode;
if (addr.locality) return addr.locality;
if (['sg', 'singapore'].indexOf(addr.countryCode.toLowerCase()) !== -1) {
return 'Singapore';
}
return addr.locality;
if (addr.administrativeArea) return addr.administrativeArea;
if (addr.country) return addr.country;
return addr.countryCode;
},

postcode(addr, type) {
Expand Down

0 comments on commit 32d9a8d

Please sign in to comment.