Skip to content
Open
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
10 changes: 9 additions & 1 deletion Block/Adminhtml/Config/Field/LegacyAuthInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,15 @@ protected function _getElementHtml(AbstractElement $element): string
if ($isLegacyConnected) {
$message = __('Connected with <strong>%1</strong>', $this->helper->getConfigValue('email'));
} elseif ($isOauthConnected) {
$message = __('Connected with OAuth2 Authentication');
$companyName = $this->helper->getConfigValue(
Config::OAUTH_COMPANY_NAME,
ScopeInterface::SCOPE_WEBSITE,
(int)$this->_request->getParam('website'),
Config::OAUTH_CONFIG_PATH
);

$message = $companyName ? __('Connected with OAuth2 Authentication (<strong>%1</strong>)', $companyName)
: __('Connected with OAuth2 Authentication');
} elseif ($isDefaultLegacyConnected) {
$message = __(
'Connected with <strong>%1</strong> in default scope',
Expand Down
30 changes: 25 additions & 5 deletions Block/Adminhtml/Config/Field/Oauth2Logout.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,15 @@ protected function _getElementHtml(AbstractElement $element): string
'onclick' => "setLocation('$url')"
];

$statusLabel = __(
'You are currently authenticated with email <strong>%1</strong> (%2)',
$this->getEmailValue(),
$websiteId && $this->isEmailSetForCurrentScope() ? __('Website') : __('Default')
);
$statusLabel = __('You are currently authenticated with email <strong>%1</strong>', $this->getEmailValue());
$companyName = $this->getCompanyNameValue();

if ($companyName) {
$statusLabel .= ' (<strong>' . $this->escapeHtml($companyName) . '</strong>)';
}

$statusLabel .= '<br>'
. ($websiteId && $this->isEmailSetForCurrentScope() ? __('Scope: website') : __('Scope: default'));

$info = <<<HTML
<div class="message message-success">$statusLabel</div>
Expand Down Expand Up @@ -148,6 +152,22 @@ private function getEmailValue(): ?string
);
}

/**
* Get the company name the account is attached to
*
* @return string|null
*/
private function getCompanyNameValue(): ?string
{
$websiteId = $this->getCurrentWebsite();

return $this->scopeConfig->getValue(
Config::OAUTH_CONFIG_PATH . Config::OAUTH_COMPANY_NAME,
$websiteId ? StoreScopeInterface::SCOPE_WEBSITES : ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
$websiteId ?: 0
);
}

/**
* Get access token data
*
Expand Down
16 changes: 15 additions & 1 deletion Controller/Adminhtml/Config/Oauth2FetchClientData.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
use Payplug\Payments\Helper\Config as ConfigHelper;
use Payplug\Payments\Logger\Logger;
use Payplug\Payments\Service\GetOauth2AccessTokenData;
use Payplug\Payments\Service\GetOauth2CompanyName;
use Payplug\Payplug;

class Oauth2FetchClientData extends Action implements HttpGetActionInterface
Expand All @@ -49,6 +50,7 @@ class Oauth2FetchClientData extends Action implements HttpGetActionInterface
* @param SerializerInterface $serializer
* @param ReinitableConfigInterface $scopeConfig
* @param GetOauth2AccessTokenData $getOauth2AccessTokenData
* @param GetOauth2CompanyName $getOauth2CompanyName
* @param ConfigHelper $configHelper
* @param EventManager $eventManager
* @param TypeListInterface $typeList
Expand All @@ -65,6 +67,7 @@ public function __construct(
private readonly SerializerInterface $serializer,
private readonly ReinitableConfigInterface $scopeConfig,
private readonly GetOauth2AccessTokenData $getOauth2AccessTokenData,
private readonly GetOauth2CompanyName $getOauth2CompanyName,
private readonly ConfigHelper $configHelper,
private readonly EventManager $eventManager,
private readonly TypeListInterface $typeList,
Expand Down Expand Up @@ -161,13 +164,24 @@ public function execute(): Redirect
* Create first JWT for selected env mode
*/
$websiteId = $this->getWebsiteId();
$this->getOauth2AccessTokenData->execute($this->getWebsiteId(), true);
$accessTokenData = $this->getOauth2AccessTokenData->execute($websiteId, true);

/**
* Store merchant email into config
*/
$this->saveConfig(ConfigHelper::OAUTH_CONFIG_PATH . ConfigHelper::OAUTH_EMAIL, $payloadDecode['email']);

/**
* Store merchant company name into config
*/
$this->saveConfig(
ConfigHelper::OAUTH_CONFIG_PATH . ConfigHelper::OAUTH_COMPANY_NAME,
$this->getOauth2CompanyName->execute(
(string)($accessTokenData['access_token'] ?? ''),
(string)($oauth2Params['company_id'] ?? '')
)
);

/**
* Cleanup legacy auth config
*/
Expand Down
2 changes: 2 additions & 0 deletions Helper/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class Config
public const OAUTH_ENVIRONMENT_MODE = 'environmentmode';
public const OAUTH_CLIENT_DATA = 'client_data';
public const OAUTH_EMAIL = 'email';
public const OAUTH_COMPANY_NAME = 'company_name';
public const APM_FILTERING_MODE_SHIPPING_ADDRESS = 'shipping_address';
public const APM_FILTERING_MODE_BILLING_ADDRESS = 'billing_address';
public const MODULE_VERSION = '4.8.1';
Expand Down Expand Up @@ -549,6 +550,7 @@ public function clearConfig(): void
'payplug_payments/general/can_use_integrated_payments',
// OAUTH 2 configuration
'payplug_payments/oauth2/email',
'payplug_payments/oauth2/company_name',
'payplug_payments/oauth2/client_data',
'payplug_payments/oauth2/access_token_data',
// Payplug payment Standard configuration
Expand Down
109 changes: 109 additions & 0 deletions Service/GetOauth2CompanyName.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
<?php
/**
* Payplug - https://www.payplug.com/
* Copyright © Payplug. All rights reserved.
* See LICENSE for license details.
*/

declare(strict_types=1);

namespace Payplug\Payments\Service;

use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\Url\Decoder as UrlDecoder;
use Payplug\Core\APIRoutes;
use Payplug\Core\HttpClient;
use Payplug\Exception\ConnectionException;
use Payplug\Exception\HttpException;
use Payplug\Exception\UnexpectedAPIResponseException;
use Payplug\Payments\Logger\Logger;
use Payplug\Payplug;
use Throwable;

class GetOauth2CompanyName
{
private const SESSION_RESOURCE = '/users/api/v1/sessions/current';
private const COMPANY_RESOURCE = '/users/api/v1/companies/';
private const COMPANY_NAME_FIELDS = ['company_display_name', 'company_name'];

/**
* @param UrlDecoder $urlDecoder
* @param Json $json
* @param Logger $logger
*/
public function __construct(
private readonly UrlDecoder $urlDecoder,
private readonly Json $json,
private readonly Logger $logger
) {
}

/**
* Retrieve the merchant company name from the Payplug users API
*
* @param string $accessToken
* @param string $companyId
* @return string
*/
public function execute(string $accessToken, string $companyId): string
{
if ($accessToken === '' || $companyId === '') {
return '';
}

try {
$httpClient = new HttpClient(new Payplug($accessToken));
$realmId = $this->getRealmId($httpClient, $accessToken);

if ($realmId === '') {
return '';
}

$response = $httpClient->get(
APIRoutes::getServiceRoute(self::COMPANY_RESOURCE, ['realm_id' => $realmId])
);
$companies = is_array($response['httpResponse'] ?? null) ? $response['httpResponse'] : [];

foreach ($companies as $company) {
if (!is_array($company) || ($company['company_ref'] ?? null) !== $companyId) {
continue;
}

foreach (self::COMPANY_NAME_FIELDS as $field) {
$name = is_string($company[$field] ?? null) ? trim($company[$field]) : '';

if ($name !== '') {
return $name;
}
}
}
} catch (Throwable $e) {
$this->logger->info(sprintf('Could not retrieve the Oauth2 company name: %s', $e->getMessage()));
}

return '';
}

/**
* Get the realm id from the JWT payload, or from the current session as a fallback
*
* @param HttpClient $httpClient
* @param string $accessToken
* @return string
* @throws ConnectionException
* @throws HttpException
* @throws UnexpectedAPIResponseException
*/
private function getRealmId(HttpClient $httpClient, string $accessToken): string
{
$payload = $this->json->unserialize($this->urlDecoder->decode(explode('.', $accessToken)[1] ?? ''));
$realmId = $payload['realm_id'] ?? $payload['ext']['realm_id'] ?? null;

if (!is_string($realmId) || $realmId === '') {
$session = $httpClient->get(APIRoutes::getServiceRoute(self::SESSION_RESOURCE));
$realmId = $session['httpResponse']['realmId'] ?? $session['httpResponse']['realm_ref'] ?? null;
}

return is_string($realmId) ? $realmId : '';
}
}
1 change: 1 addition & 0 deletions etc/adminhtml/system.xml
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@
<comment>Need to use old login / password authentication mode ? Please disconnect Oauth2 connection</comment>
</field>
<field id="email"/>
<field id="company_name"/>
<field id="client_data"/>
<field id="access_token_data"/>
</group>
Expand Down
25 changes: 25 additions & 0 deletions i18n/en_US.csv
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@
"Abort","Abort"
"Aborted payment","Cancelled payment"
"Aborted","Aborted"
"Access token data is not valid.","Access token data is not valid."
"Access token is not on the proper scope.","Access token is not on the proper scope."
"Account Key","Account Key"
"All fields must be defined when trying to connect at website level.","All fields must be defined."
"Allow customers to spread out payments over 2, 3 or 4 installments.","Allow your customers to spread out their payments over 2, 3 or 4 installments."
"Allowed languages are: %1","Accepted languages are: %1"
"Already activated our new secure authentication? Simply connect your Payplug account above to continue.","Already activated our new secure authentication? Simply connect your Payplug account above to continue."
"Amex is unavailable in TEST mode. Please switch your Payplug plugin to LIVE mode to activate it.","Amex is unavailable in TEST mode. Please switch your Payplug plugin to LIVE mode to activate it."
"Amount remaining in payplug is inferior to amount to refund","The amount remaining in Payplug is inferior to the amount to refund."
"Amount","Amount"
Expand Down Expand Up @@ -43,16 +46,25 @@
"Capture online","Capture online"
"Card #","Card number"
"Card mask","The last 4 digits of the card"
"Client data is not valid.","Client data is not valid."
"Close","Close"
"Complete","Paid"
"Configure the following IPN URL in your Dalenys Merchant Console.","Configure the following IPN URL in your Dalenys Merchant Console."
"Connect to Payplug for this website","Connect to Payplug for this website"
"Connect to Payplug","Connect to Payplug"
"Connected with <strong>%1</strong>","Connected with <strong>%1</strong>"
"Connected with <strong>%1</strong> in default scope","Connected with <strong>%1</strong> in default scope"
"Connected with OAuth2 Authentication","Connected with OAuth2 Authentication"
"Connected with OAuth2 Authentication (<strong>%1</strong>)","Connected with OAuth2 Authentication (<strong>%1</strong>)"
"Connection state","Connection state"
"Contribution:","Contribution:"
"Could not fetch credentials from Payplug Portal","Could not fetch credentials from Payplug Portal"
"Could not find valid payplug order payment. Please try refunding offline.","Could not find valid Payplug order payment. Please try refunding offline."
"Could not retrieve Auth Code from Payplug Portal","Could not retrieve Auth Code from Payplug Portal"
"Could not retrieve TEST credentials from Payplug Portal","Could not retrieve TEST credentials from Payplug Portal"
"Credit Card Payment Mode","Credit Card Payment Mode"
"Credit card","Credit card"
"Current access token expiration date","Current access token expiration date"
"Custom Payplug Payments status","Payplug custom payment status"
"Date","Date"
"Default Country","Default Country"
Expand All @@ -61,6 +73,7 @@
"Description","Description"
"Details","Details"
"Disconnect","Disconnect"
"Don't have a Payplug account? Create one.","Don't have a Payplug account? Create one."
"Email","Email"
"Email","Email"
"Enable Hosted Fields Advanced","Enable Hosted Fields Advanced"
Expand Down Expand Up @@ -102,29 +115,39 @@
"Invoice is created","Invoice is created"
"Invoice on payment validation","Invoice after payment"
"Italian","Italian"
"LIVE client credentials available","LIVE client credentials available"
"Language","Language"
"Last payment %1 has already been paid. Please wait for the automatic notification or update the payment manually.","The last payment %1 has already been paid. You should receive an automatic notification shortly. If not, please update the payment manually."
"Logout","Logout"
"Mandatory field.","Mandatory field."
"Mobile / Email","Mobile number or Email"
"Mobile","Mobile number"
"Mode","Mode"
"More info","More info"
"My Saved Cards","My Saved Cards"
"MyBank is unavailable in TEST mode. Please switch your Payplug plugin to LIVE mode to activate it.","MyBank is unavailable in TEST mode. Please switch your Payplug plugin to LIVE mode to activate it."
"N/A","N/A"
"Need to use old login / password authentication mode ? Please disconnect Oauth2 connection","Need to use old login / password authentication mode ? Please disconnect Oauth2 connection"
"New payment link for order %1","New payment link for order %1"
"New payment link was successfully sent.","New payment link was successfully sent."
"New payment reference %1","New payment reference %1"
"New","New"
"No","No"
"Not Paid","Not Paid"
"Not connected","Not connected"
"Number of installments","Number of installments"
"Oauth2 authentication successful","Oauth2 authentication successful"
"Object with id ""%1"" does not exist.","The object with id ""%1"" does not exist."
"Offre de financement sans assurance avec apport obligatoire, réservée aux particuliers et valable pour tout achat de %1 à %2. Sous réserve d'acceptation par Oney Bank. Vous disposez d'un délai de 14 jours pour renoncer à votre crédit. Oney Bank - SA au capital de 51 286 585€ - 34 Avenue de Flandre 59170 Croix - 546 380 197 RCS Lille Métropole - n° Orias 07 023 261 www.orias.fr Correspondance : CS 60 006 - 59895 Lille Cedex - <a href=""http://www.oney.fr"" target=""_blank"">www.oney.fr</a>","Offre de financement sans assurance avec apport obligatoire, réservée aux particuliers et valable pour tout achat de %1 à %2. Sous réserve d'acceptation par Oney Bank. Vous disposez d'un délai de 14 jours pour renoncer à votre crédit. Oney Bank - SA au capital de 51 286 585€ - 34 Avenue de Flandre 59170 Croix - 546 380 197 RCS Lille Métropole - n° Orias 07 023 261 www.orias.fr Correspondance : CS 60 006 - 59895 Lille Cedex - <a href=""http://www.oney.fr"" target=""_blank"">www.oney.fr</a>"
"One-click payment","One-click payment"
"Oney option","Oney option"
"Ongoing","Ongoing"
"Only Premium accounts can use installment plan in LIVE mode.","Only Premium accounts can use the installment plan in LIVE mode."
"Only Premium accounts can use one click in LIVE mode.","Only Premium accounts have access to this feature."
"Scope: default","Scope: default"
"Scope: website","Scope: website"
"TEST client credentials available","TEST client credentials available"
"The JWT is invalid.","The JWT is invalid."
"The delay must be between 1 and 6 days.","The delay must be between 1 and 6 days."
"Or pay in","Or pay in"
"Order Store (Automatic)","Order Store (Automatic)"
Expand Down Expand Up @@ -253,6 +276,7 @@
"We are not able to retrieve your account information. Please go to section Sales > Payplug Payments to log in again.","We are not able to retrieve your account information. Please go to section Sales > Payplug Payments to log in again."
"Yes","Yes"
"You are able to perform only TEST transactions.","You must activate your account to accept payments in LIVE mode."
"You are currently authenticated with email <strong>%1</strong>","You are currently authenticated with email <strong>%1</strong>"
"You are not connected to a payplug account. Please go to section Sales > Payplug Payments to log in.","You are not connected to a Payplug account. Please go to the section Sales > Payplug Payments to log in."
"You do not have access to this feature yet. To activate Bancontact, please fill in the following form: %1 (%2)","You do not have access to this feature yet. To activate Bancontact, please fill in the following form: %1"
"You do not have access to this feature yet. To activate it, please fill in the following form: https://support.payplug.com/hc/en-gb/requests/new?ticket_form_id=8138934372636","You do not have access to this feature yet. To activate it, please fill in the following form: https://support.payplug.com/hc/en-gb/requests/new?ticket_form_id=8138934372636"
Expand All @@ -264,6 +288,7 @@
"You don't have access to this feature yet. To activate iDEAL, please fill in the following form: https://support.payplug.com/hc/en-gb/requests/new?ticket_form_id=8248663314844","You don't have access to this feature yet. To activate iDEAL, please fill in the following form: https://support.payplug.com/hc/en-gb/requests/new?ticket_form_id=8248663314844"
"You don't have access to this feature yet. To activate the Oney guaranteed split payment, go to your PayPlug portal: %1.","You don't have access to this feature yet. To activate the Oney guaranteed split payment, go to your Payplug portal: %1."
"You have aborted the transaction.","You have cancelled the transaction."
"You have been logged out successfully","You have been logged out successfully"
"You have no saved cards.","You have no saved cards."
"You need to connect to Payplug, with standard or Oauth2 authentication before configure Hosted Fields Advanced","You need to connect to Payplug, with standard or Oauth2 authentication before configure Hosted Fields Advanced"
"Your account is not configured for Oney. Please contact us.","Your account is not configured for Oney. Please contact us for more information."
Expand Down
Loading
Loading