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
59 changes: 58 additions & 1 deletion controllers/admin/AdminSaferPayOfficialSettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use Invertus\SaferPay\Repository\SaferPaySavedCreditCardRepository;
use Invertus\SaferPay\Adapter\Configuration as SaferPayConfiguration;
use Invertus\SaferPay\Service\SaferPayFieldCreator;
use Invertus\SaferPay\Service\SaferPayGenerateFieldAccessToken;
use Invertus\SaferPay\Service\SaferPayGetLicense;
use Invertus\SaferPay\Service\SaferPayGetTerminals;
use Invertus\SaferPay\Service\SaferPayLogoCreator;
Expand Down Expand Up @@ -58,6 +59,7 @@ class AdminSaferPayOfficialSettingsController extends ModuleAdminController
'saveGeneralSettings',
'savePaymentMethods',
'getTerminals',
'generateFieldAccessToken',
'refreshData',
];

Expand Down Expand Up @@ -225,6 +227,7 @@ public function ajaxProcessSaveCredentials()
$configuration->set(SaferPayConfig::BUSINESS_LICENSE . $suffix, $hasBusinessLicense ? 1 : 0);
} catch (\Exception $e) {
$configuration->set(SaferPayConfig::BUSINESS_LICENSE . $suffix, 0);

$licenseMessage = ' ' . $this->module->l('Could not retrieve license information. Please verify your credentials.', self::FILE_NAME);
}
} else {
Expand All @@ -233,7 +236,7 @@ public function ajaxProcessSaveCredentials()

$this->ajaxResponse(
true,
$this->module->l('API Credentials saved successfully', self::FILE_NAME) . $licenseMessage,
$this->module->l('Settings saved successfully.', self::FILE_NAME) . $licenseMessage,
[
'hasBusinessLicense' => $hasBusinessLicense,
]
Expand Down Expand Up @@ -425,6 +428,60 @@ public function ajaxProcessGetTerminals()
}
}

/**
* AJAX: Generate Saferpay Fields access token
*/
public function ajaxProcessGenerateFieldAccessToken()
{
$data = $this->getJsonInput();
$isTestMode = isset($data['env']) && $data['env'] === 'test';
$suffix = $isTestMode ? SaferPayConfig::TEST_SUFFIX : '';

$username = isset($data['username']) ? trim($data['username']) : '';
$password = isset($data['password']) ? $data['password'] : '';
$terminalId = isset($data['terminalId']) ? trim($data['terminalId']) : '';
$customerId = $this->parseCustomerIdFromUsername($username);

if ($password === self::PASSWORD_PLACEHOLDER) {
/** @var SaferPayConfiguration $configuration */
$configuration = $this->module->getService(SaferPayConfiguration::class);
$password = (string) $configuration->get(SaferPayConfig::PASSWORD . $suffix);
}

if (empty($username) || empty($password) || empty($customerId) || empty($terminalId)) {
$this->ajaxResponse(false, $this->module->l('Please enter valid credentials and select a terminal first.', self::FILE_NAME));
return;
}

try {
/** @var SaferPayGenerateFieldAccessToken $tokenGenerator */
$tokenGenerator = $this->module->getService(SaferPayGenerateFieldAccessToken::class);
$shopUrl = $this->context->link->getBaseLink();
$token = $tokenGenerator->generateWithCredentials($username, $password, $customerId, $terminalId, $isTestMode, $shopUrl);

/** @var SaferPayConfiguration $configuration */
$configuration = $this->module->getService(SaferPayConfiguration::class);
$configuration->set(SaferPayConfig::FIELDS_ACCESS_TOKEN . $suffix, $token);

$this->sendJsonResponse([
'success' => true,
'message' => $this->module->l('Access token generated successfully.', self::FILE_NAME),
'token' => $token,
]);
} catch (\Exception $e) {
\PrestaShopLogger::addLog(
'SaferPay: Failed to generate field access token - ' . $e->getMessage(),
3,
null,
null,
null,
true
);

$this->ajaxResponse(false, $this->module->l('Failed to generate access token.', self::FILE_NAME));
}
}

/**
* AJAX: Refresh all data
*/
Expand Down
56 changes: 56 additions & 0 deletions src/Api/ApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,62 @@ public function getWithCredentials($url, $username, $password, $baseUrl, $params
}
}

/**
* API Request Post Method with explicit credentials.
*
* @param string $url
* @param string $username
* @param string $password
* @param string $baseUrl
* @param array|null $params
* @return mixed
* @throws Exception
*/
public function postWithCredentials($url, $username, $password, $baseUrl, $params = null)
{
$response = null;

try {
$credentials = base64_encode("$username:$password");
$headers = [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Saferpay-ApiVersion' => SaferPayConfig::API_VERSION,
'Saferpay-RequestId' => 'false',
'Authorization' => "Basic $credentials",
];

$body = $params !== null ? json_encode($params) : '{}';

$response = Request::post(
$baseUrl . $url,
$headers,
$body
);

$this->logger->debug(sprintf('%s - POST (credentials) response: %d', self::FILE_NAME, $response->code), [
'context' => [
'uri' => $baseUrl . $url,
],
'request' => $params,
'response' => $response->body,
]);

$this->isValidResponse($response);

return json_decode($response->raw_body);
} catch (Exception $exception) {
$this->logger->error($exception->getMessage(), [
'context' => [],
'request' => $params,
'response' => $response ? json_decode($response->raw_body) : null,
'exceptions' => ExceptionUtility::getExceptions($exception),
]);

throw $exception;
}
}

private function getHeaders()
{
$username = Configuration::get(SaferPayConfig::USERNAME . SaferPayConfig::getConfigSuffix());
Expand Down
61 changes: 61 additions & 0 deletions src/Api/Request/GenerateFieldAccessTokenService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php
/**
*NOTICE OF LICENSE
*
*This source file is subject to the Open Software License (OSL 3.0)
*that is bundled with this package in the file LICENSE.txt.
*It is also available through the world-wide-web at this URL:
*http://opensource.org/licenses/osl-3.0.php
*If you did not receive a copy of the license and are unable to
*obtain it through the world-wide-web, please send an email
*to license@prestashop.com so we can send you a copy immediately.
*
*DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
*versions in the future. If you wish to customize PrestaShop for your
*needs please refer to http://www.prestashop.com for more information.
*
*@author INVERTUS UAB www.invertus.eu <support@invertus.eu>
*@copyright SIX Payment Services
*@license SIX Payment Services
*/

namespace Invertus\SaferPay\Api\Request;

use Invertus\SaferPay\Api\ApiRequest;
use Invertus\SaferPay\DTO\Request\GenerateFieldAccessToken\GenerateFieldAccessTokenRequest;

if (!defined('_PS_VERSION_')) {
exit;
}

class GenerateFieldAccessTokenService
{
/** @var ApiRequest */
private $apiRequest;

public function __construct(ApiRequest $apiRequest)
{
$this->apiRequest = $apiRequest;
}

/**
* @param GenerateFieldAccessTokenRequest $request
* @param string $username
* @param string $password
* @param string $baseUrl
* @param array|null $params
* @return mixed
*/
public function generateToken(GenerateFieldAccessTokenRequest $request, $username, $password, $baseUrl, $params = null)
{
return $this->apiRequest->postWithCredentials(
$request->generateRequestUrl(),
$username,
$password,
$baseUrl,
$params
);
}
}
76 changes: 76 additions & 0 deletions src/Api/Request/GetLicenseService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php
/**
*NOTICE OF LICENSE
*
*This source file is subject to the Open Software License (OSL 3.0)
*that is bundled with this package in the file LICENSE.txt.
*It is also available through the world-wide-web at this URL:
*http://opensource.org/licenses/osl-3.0.php
*If you did not receive a copy of the license and are unable to
*obtain it through the world-wide-web, please send an email
*to license@prestashop.com so we can send you a copy immediately.
*
*DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
*versions in the future. If you wish to customize PrestaShop for your
*needs please refer to http://www.prestashop.com for more information.
*
*@author INVERTUS UAB www.invertus.eu <support@invertus.eu>
*@copyright SIX Payment Services
*@license SIX Payment Services
*/

namespace Invertus\SaferPay\Api\Request;

use Invertus\SaferPay\Api\ApiRequest;
use Invertus\SaferPay\DTO\Request\GetLicense\GetLicenseRequest;

if (!defined('_PS_VERSION_')) {
exit;
}

class GetLicenseService
{
/** @var ApiRequest */
private $apiRequest;

public function __construct(ApiRequest $apiRequest)
{
$this->apiRequest = $apiRequest;
}

/**
* @param GetLicenseRequest $request
* @param string $username
* @param string $password
* @param string $baseUrl
* @return mixed
*/
public function getLicense(GetLicenseRequest $request, $username, $password, $baseUrl)
{
return $this->apiRequest->getWithCredentials(
$request->generateRequestUrl(),
$username,
$password,
$baseUrl
);
}

/**
* @param GetLicenseRequest $request
* @param string $username
* @param string $password
* @param string $baseUrl
* @return mixed
*/
public function getLicenseFallback(GetLicenseRequest $request, $username, $password, $baseUrl)
{
return $this->apiRequest->getWithCredentials(
$request->generateFallbackRequestUrl(),
$username,
$password,
$baseUrl
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php
/**
*NOTICE OF LICENSE
*
*This source file is subject to the Open Software License (OSL 3.0)
*that is bundled with this package in the file LICENSE.txt.
*It is also available through the world-wide-web at this URL:
*http://opensource.org/licenses/osl-3.0.php
*If you did not receive a copy of the license and are unable to
*obtain it through the world-wide-web, please send an email
*to license@prestashop.com so we can send you a copy immediately.
*
*DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
*versions in the future. If you wish to customize PrestaShop for your
*needs please refer to http://www.prestashop.com for more information.
*
*@author INVERTUS UAB www.invertus.eu <support@invertus.eu>
*@copyright SIX Payment Services
*@license SIX Payment Services
*/

namespace Invertus\SaferPay\DTO\Request\GenerateFieldAccessToken;

if (!defined('_PS_VERSION_')) {
exit;
}

class GenerateFieldAccessTokenRequest
{
/** @var string */
private $customerId;

/** @var string */
private $terminalId;

/**
* @param string $customerId
* @param string $terminalId
*/
public function __construct($customerId, $terminalId)
{
if (!preg_match('/^[a-zA-Z0-9\-_]+$/', $customerId)) {
throw new \InvalidArgumentException('Invalid customer ID format');
}

if (!preg_match('/^[a-zA-Z0-9\-_]+$/', $terminalId)) {
throw new \InvalidArgumentException('Invalid terminal ID format');
}

$this->customerId = $customerId;
$this->terminalId = $terminalId;
}

/**
* @return string
*/
public function generateRequestUrl()
{
return sprintf(
'rest/customers/%s/terminals/%s/fields-access-tokens',
$this->customerId,
$this->terminalId
);
}
}
Loading
Loading