first commit

This commit is contained in:
2025-01-06 20:47:25 +01:00
commit 3bdbd78c2f
25591 changed files with 3586440 additions and 0 deletions

View File

@@ -0,0 +1,206 @@
<?php
/**
* Class Przelewy24BlikErrorEnum
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24BlikErrorEnum
*/
class Przelewy24BlikErrorEnum
{
const ERR_BLIKCODE_REJECTED = 6;
const ERR_BLIK_DISABLED = 8;
const ERR_ALIAS_NOT_CONFIRMED = 11;
const ERR_ALIAS_UNREGISTERED = 12;
const ERR_ALIAS_EXPIRED = 13;
const ERR_ALIAS_NOT_FOUND = 15;
const ERR_ALIAS_INCORRECT = 20;
const ERR_TRANSACTION_ALIAS_INCORRECT = 21;
const ERR_TICKET_INCORRECT = 28;
const ERR_TICKET_FORMAT = 29;
const ERR_TICKET_EXPIRED = 30;
const ERR_TICKET_USED = 35;
const ERR_ALIAS_NOT_SUPPORTED = 49;
const ERR_ALIAS_IDENTIFICATION = 51;
const ERR_TRANSACTION_NOT_CONFIRMED = 55;
const ERR_LIMIT_EXCEEDED = 60;
const ERR_INSUFFICIENT_FUNDS = 61;
const ERR_PIN_DECLINED = 65;
const ERR_BAD_PIN = 66;
const ERR_ALIAS_DECLINED = 68;
const ERR_TIMEOUT = 69;
const ERR_USER_TIMEOUT = 70;
/**
* Controller.
*
* @var ModuleFrontController
*/
private $controller;
/**
* Main Przelewy24 module class. Will be used to provide translations.
*
* @var Przelewy24
*/
private $przelewy24;
/**
* Przelewy24BlikErrorEnum constructor.
*
* @param ModuleFrontController $controller
*/
public function __construct(ModuleFrontController $controller)
{
$this->controller = $controller;
$this->przelewy24 = new Przelewy24();
}
/**
* 'type' parameter indicates which action should be executed to handle this error.
* - success - there is no error, no additional action required
* - blikcode - error message will be displayed as error of input "blikCode"
* - alias - error message will be handled as alias error (user will be asked to provide blikCode)
* - wait - shows no additional information, user will have to wait for
* GetTransactionStatus to return proper status (or timeout)
* - fatal - transaction error screen will be displayed, transaction status will be changed to "Payment error"
*
* @param int $errorCode
*
* @return Przelewy24ErrorResult
*/
public function getErrorMessage($errorCode)
{
switch ($errorCode) {
case 0:
$type = 'success';
$message = $this->przelewy24
->getLangString('Success, no error');
break;
case Przelewy24BlikErrorEnum::ERR_ALIAS_DECLINED:
$type = 'alias';
$message = $this->przelewy24->getLangString('Your Blik alias was declined, please provide BlikCode');
break;
case Przelewy24BlikErrorEnum::ERR_ALIAS_EXPIRED:
$type = 'alias';
$message = $this->przelewy24
->getLangString('Your Blik alias was declined, please provide BlikCode');
break;
case Przelewy24BlikErrorEnum::ERR_ALIAS_IDENTIFICATION:
$type = 'fatal';
$message = $this->przelewy24->getLangString('Identification not possible by given alias');
break;
case Przelewy24BlikErrorEnum::ERR_ALIAS_INCORRECT:
$type = 'alias';
$message = $this->przelewy24->getLangString('Your Blik alias is incorrect, please provide BlikCode');
break;
case Przelewy24BlikErrorEnum::ERR_ALIAS_NOT_CONFIRMED:
$type = 'alias';
$message = $this->przelewy24
->getLangString('Your Blik alias is not confirmed, please provide BlikCode');
break;
case Przelewy24BlikErrorEnum::ERR_ALIAS_NOT_FOUND:
$type = 'alias';
$message = $this->przelewy24->getLangString('Your Blik alias was not found, please provide BlikCode');
break;
case Przelewy24BlikErrorEnum::ERR_ALIAS_NOT_SUPPORTED:
$type = 'alias';
$message = $this->przelewy24->getLangString(
'Alias payments are currently not supported, please provide BlikCode'
);
break;
case Przelewy24BlikErrorEnum::ERR_ALIAS_UNREGISTERED:
$type = 'alias';
$message = $this->przelewy24
->getLangString('Your Blik alias was unregistered, please provide BlikCode');
break;
case Przelewy24BlikErrorEnum::ERR_BAD_PIN:
$type = 'blikcode';
$message = $this->przelewy24->getLangString('Bad PIN provided, please generate new BlikCode');
break;
case Przelewy24BlikErrorEnum::ERR_BLIK_DISABLED:
$type = 'fatal';
$message = $this->przelewy24->getLangString('Blik service unavailable');
break;
case Przelewy24BlikErrorEnum::ERR_BLIKCODE_REJECTED:
$type = 'blikcode';
$message = $this->przelewy24
->getLangString('Your BlikCode was rejected, please generate new BlikCode');
break;
case Przelewy24BlikErrorEnum::ERR_INSUFFICIENT_FUNDS:
$type = 'fatal';
$message = $this->przelewy24->getLangString('Insufficient funds');
break;
case Przelewy24BlikErrorEnum::ERR_LIMIT_EXCEEDED:
$type = 'fatal';
$message = $this->przelewy24->getLangString('Limit exceeded');
break;
case Przelewy24BlikErrorEnum::ERR_PIN_DECLINED:
$type = 'blikcode';
$message = $this->przelewy24->getLangString('Your PIN was rejected');
break;
case Przelewy24BlikErrorEnum::ERR_TIMEOUT:
case Przelewy24BlikErrorEnum::ERR_USER_TIMEOUT:
$type = 'fatal';
$message = $this->przelewy24->getLangString('Transaction timeout');
break;
case Przelewy24BlikErrorEnum::ERR_TICKET_EXPIRED:
$type = 'blikcode';
$message = $this->przelewy24->getLangString('Your BlikCode has expired, please generate another');
break;
case Przelewy24BlikErrorEnum::ERR_TICKET_FORMAT:
$type = 'blikcode';
$message = $this->przelewy24->getLangString('Incorrect BlikCode format, please generate another');
break;
case Przelewy24BlikErrorEnum::ERR_TICKET_INCORRECT:
$type = 'blikcode';
$message = $this->przelewy24->getLangString('Your BlikCode is incorrect, please generate another');
break;
case Przelewy24BlikErrorEnum::ERR_TICKET_USED:
$type = 'blikcode';
$message = $this->przelewy24->getLangString('Your BlikCode was already used, please generate another');
break;
case Przelewy24BlikErrorEnum::ERR_TRANSACTION_ALIAS_INCORRECT:
$type = 'fatal';
$message = $this->przelewy24->getLangString('Transaction failed, incorrect alias');
break;
case Przelewy24BlikErrorEnum::ERR_TRANSACTION_NOT_CONFIRMED:
$type = 'wait';
$message = '';
break;
default:
$type = 'fatal';
$message = $this->przelewy24->getLangString('Blik payment error');
break;
}
return new Przelewy24ErrorResult($errorCode, $message, $type);
}
}

View File

@@ -0,0 +1,83 @@
<?php
/**
* Class Przelewy24BlikHelper
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24BlikHelper
*/
class Przelewy24BlikHelper
{
/**
* Retrieve existing customer alias, or try getting it from SOAP
*
* @param Customer $customer
*
* @return bool|string
* @throws Exception
*/
public static function getSavedAlias(Customer $customer)
{
$blikAlias = new Przelewy24BlikAlias($customer->id);
if (Validate::isLoadedObject($blikAlias)) {
if (!$blikAlias->alias) {
$p24BlikSoap = Przelewy24BlikSoapInterfaceFactory::getDefault();
if ($blikAlias->alias = $p24BlikSoap->getAlias($blikAlias->last_order_id)) {
$blikAlias->save();
}
}
if (Przelewy24BlikHelper::checkIfAliasIsRegisteredForEmail($customer->email, $blikAlias->alias)) {
return $blikAlias->alias;
}
}
return false;
}
/**
* Method checks (using Przelewy24 api) if alias is assigned to email address
*
* @param string $email
* @param string $aliasFromShop
*
* @return bool
* @throws Exception
*/
public static function checkIfAliasIsRegisteredForEmail($email, $aliasFromShop)
{
$blikSoap = Przelewy24BlikSoapInterfaceFactory::getDefault();
$aliases = $blikSoap->getAliasesByEmail($email);
if (!$aliases || !sizeof($aliases)) {
return false;
}
foreach ($aliases as $alias) {
if ($alias['value'] === $aliasFromShop && 'REGISTERED' === $alias['status']) {
return true;
}
}
return false;
}
/**
* Returns websocket address
*
* @param bool $testMode
*
* @return string
*/
public static function getWebsocketHost($testMode = false)
{
if ($testMode) {
return 'wss://sandbox.przelewy24.pl/wss/blik/';
}
return 'wss://sandbox.przelewy24.pl/wss/blik/';
}
}

View File

@@ -0,0 +1,391 @@
<?php
/**
* Class Przelewy24BlikSoap
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24BlikSoap
*/
class Przelewy24BlikSoap extends Przelewy24SoapAbstract implements Przelewy24BlikSoapInterface
{
/**
* Wsdl service of blik api.
*
* @var string
*/
protected $wsdlService = 'external/wsdl/charge_blik_service.php?wsdl';
/**
* Api key to blik.
*
* @var string
*/
protected $apiKey;
/**
* Przelewy24BlikSoap constructor.
*
* @param string $apiKey
* @param Przelewy24ClassInterface $p24Class
* @param int $merchantId
* @param int $posId
* @param string $salt
* @param bool $testMode
* @throws SoapFault
*/
public function __construct($apiKey, Przelewy24ClassInterface $p24Class, $merchantId, $posId, $salt, $testMode)
{
$this->apiKey = $apiKey;
parent::__construct($p24Class, $merchantId, $posId, $salt, $testMode);
}
/**
* Executes payment and creates uid.
*
* @param string $blikCode
* @param string $token
*
* @return array|bool
*/
public function executePaymentAndCreateUid($blikCode, $token)
{
if (!$this->soap) {
return false;
}
try {
$response = $this->soap->ExecutePaymentAndCreateUid(
$this->posId,
$this->apiKey,
$token,
$blikCode
);
if (!$response->error->errorCode) {
return array('success' => true, 'orderId' => $response->result->orderId);
} else {
Przelewy24Logger::addApiErrorLog($response, 'ExecutePaymentAndCreateUid');
}
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
return array('success' => false, 'error' => 500); //unknown error
}
return array('success' => false, 'error' => $response->error->errorCode);
}
/**
* Get alias.
*
* @param int $orderId
*
* @return bool
*/
public function getAlias($orderId)
{
if (!$this->soap) {
return false;
}
$alias = false;
try {
$res = $this->soap->GetAlias($this->posId, $this->apiKey, $orderId);
if (!$res->error->errorCode && 'UID' === $res->result->aliasType) {
$alias = $res->result->aliasValue;
} else {
Przelewy24Logger::addApiErrorLog($res, 'GetAlias');
return false;
}
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
}
return $alias;
}
/**
* Get aliases by email
*
* @param string $email
*
* @return array|bool
*/
public function getAliasesByEmail($email)
{
if (!$this->soap || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
$result = array();
try {
$res = $this->soap->GetAliasesByEmail($this->posId, $this->apiKey, $email);
if ($res->error->errorCode) {
Przelewy24Logger::addApiErrorLog($res, 'GetAliasesByEmail');
return false;
}
$aliases = $res->aliases;
if (sizeof($aliases)) {
foreach ($aliases as $alias) {
$result[] = array(
'value' => filter_var($alias->value, FILTER_SANITIZE_STRING),
'type' => filter_var($alias->type, FILTER_SANITIZE_STRING),
'status' => filter_var($alias->status, FILTER_SANITIZE_STRING),
);
}
}
return $result;
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
}
return false;
}
/**
* Executes payment by uid with blik code.
*
* @param string $alias
* @param string $amount
* @param string $currency
* @param string $email
* @param string $sessionId
* @param string $client
* @param string $description
* @param string $blikCode
* @param string $additional
*
* @return array|bool
*/
public function executePaymentByUidWithBlikCode(
$alias,
$amount,
$currency,
$email,
$sessionId,
$client,
$description,
$blikCode,
$additional
) {
if (!$this->soap) {
return false;
}
try {
$response = $this->soap->ExecutePaymentByUidWithBlikCode(
$this->posId,
$this->apiKey,
$alias,
$amount,
$currency,
$email,
$sessionId,
$client,
$description,
$blikCode,
$additional
);
if (!$response->error->errorCode) {
return array('success' => true, 'orderId' => $response->result->orderId);
} else {
Przelewy24Logger::addApiErrorLog($response, 'ExecutePaymentByUidWithBlikCode');
}
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
return array('success' => false, 'error' => 500); //unknown error
}
return array('success' => false, 'error' => $response->error->errorCode);
}
/**
* Execute payment by uid with alternative key.
*
* @param string $alias
* @param string $amount
* @param string $currency
* @param string $email
* @param string $sessionId
* @param string $client
* @param string $description
* @param string $alternativeKey
* @param string $additional
*
* @return array|bool
*/
public function executePaymentByUIdWithAlternativeKey(
$alias,
$amount,
$currency,
$email,
$sessionId,
$client,
$description,
$alternativeKey,
$additional
) {
if (!$this->soap) {
return false;
}
try {
$response = $this->soap->ExecutePaymentByUIdWithAlternativeKey(
$this->posId,
$this->apiKey,
$alias,
$amount,
$currency,
$email,
$sessionId,
$client,
$description,
$alternativeKey,
$additional
);
if (!$response->error->errorCode) {
return array('success' => true, 'orderId' => $response->result->orderId);
} else {
Przelewy24Logger::addApiErrorLog($response, 'ExecutePaymentByUIdWithAlternativeKey');
}
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
return array('success' => false, 'error' => 500); //unknown error
}
return array('success' => false, 'error' => $response->error->errorCode);
}
/**
* Execute payment by uid.
*
* @param string $alias
* @param string $amount
* @param string $currency
* @param string $email
* @param string $sessionId
* @param string $client
* @param string $description
* @param string $additional
*
* @return array|bool
*/
public function executePaymentByUid(
$alias,
$amount,
$currency,
$email,
$sessionId,
$client,
$description,
$additional
) {
if (!$this->soap) {
return false;
}
try {
$response = $this->soap->ExecutePaymentByUid(
$this->posId,
$this->apiKey,
$alias,
$amount,
$currency,
$email,
$sessionId,
$client,
$description,
$additional
);
if (!$response->error->errorCode) {
return array('success' => true, 'orderId' => $response->result->orderId);
} else {
Przelewy24Logger::addApiErrorLog($response, 'ExecutePaymentByUid');
}
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
return array('success' => false, 'error' => 500); //unknown error
}
return array(
'success' => false,
'error' => $response->error->errorCode,
'aliasAlternatives' => $response->result->aliasAlternatives,
);
}
/**
* Test access
*
* @return array|bool
*/
public function testAccess()
{
$access = false;
if (!$this->soap) {
return false;
}
try {
$res = $this->soap->TestAccess($this->posId, $this->apiKey);
if (!$res->error->errorCode) {
$access = true;
} else {
Przelewy24Logger::addApiErrorLog($res, 'TestAccess');
}
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
return array('success' => false, 'error' => 500); //unknown error
}
return $access;
}
/**
* Get transaction status.
*
* @param int $orderId
*
* @return array|bool
*/
public function getTransactionStatus($orderId)
{
if (!$this->soap) {
return false;
}
try {
$res = $this->soap->GetTransactionStatus($this->posId, $this->apiKey, $orderId, null);
if ('AUTHORIZED' !== $res->result->status) {
PrestaShopLogger::addLog(print_r($res, true), 1);
}
return array(
'success' => true,
'status' => $res->result->status,
'reasonCode' => $res->result->reasonCode,
'error' => $res->error->errorCode,
);
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
}
return array('success' => false, 'error' => 500); //unknown error
}
}

View File

@@ -0,0 +1,681 @@
<?php
/**
* Przelewy24 comunication class
* Communication protol version
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*/
define('P24_VERSION', '3.2');
if (!class_exists('Przelewy24Class', false)) {
class Przelewy24Class implements
Przelewy24ClassInterface,
Przelewy24ClassBlikInterface,
Przelewy24ClassStaticInterface
{
/**
* Live system URL address.
*
* @var string
*/
private static $hostLive = 'https://secure.przelewy24.pl/';
/**
* Sandbox system URL address.
*
* @var string
*/
private static $hostSandbox = 'https://sandbox.przelewy24.pl/';
/**
* Use Live (false) or Sandbox (true) environment.
*
* @var bool
*/
private $testMode = false;
/**
* Merchant Id.
*
* @var int
*/
private $merchantId = 0;
/**
* Merchant posId.
*
* @var int
*/
private $posId = 0;
/**
* Salt to create a control sum (from P24 panel).
*
* @var string
*/
private $salt = '';
/**
* Array of POST data.
*
* @var array
*/
private $postData = array();
/**
* Minimal amount for single installment.
*
* @var int
*/
private static $minInstallmentValue = 300;
/**
* Obcject constructor. Set initial parameters.
*
* @param int $merchantId
* @param int $posId
* @param string $salt
* @param bool $testMode
*/
public function __construct($merchantId, $posId, $salt, $testMode = false)
{
$this->posId = (int)trim($posId);
$this->merchantId = (int)trim($merchantId);
if (0 === $this->merchantId) {
$this->merchantId = $this->posId;
}
$this->salt = trim($salt);
$this->testMode = $testMode;
$this->addValue('p24_merchant_id', $this->merchantId);
$this->addValue('p24_pos_id', $this->posId);
$this->addValue('p24_api_version', P24_VERSION);
}
/**
* Returns host URL.
*
* @return string
*/
public function getHost()
{
return self::getHostForEnvironment($this->testMode);
}
/**
* Returns host URL For Environmen
*
* @param bool $isTestMode
* @return string
*/
public static function getHostForEnvironment($isTestMode = false)
{
return $isTestMode ? self::$hostSandbox : self::$hostLive;
}
/**
* Get min installment value
*
* @return int
*/
public static function getMinInstallmentValue()
{
return self::$minInstallmentValue;
}
/**
* Returns URL for direct request (trnDirect).
*
* @return string
*/
public function trnDirectUrl()
{
return $this->getHost() . 'trnDirect';
}
/**
* Adds value do post request.
*
* @param string $name Argument name.
* @param int|string|bool $value Argument value.
*/
public function addValue($name, $value)
{
if ($this->validateField($name, $value)) {
$this->postData[$name] = $value;
}
}
/**
* Method is testing a connection with P24 server.
*
* @return array Array(INT Error, Array Data), where data.
*
* @throws Exception
*/
public function testConnection()
{
$arg = array();
$crc = md5($this->posId . "|" . $this->salt);
$arg["p24_pos_id"] = $this->posId;
$arg["p24_sign"] = $crc;
$arg["p24_merchant_id"] = $this->merchantId;
$res = $this->callUrl("testConnection", $arg);
return $res;
}
/**
* Prepare a transaction request.
*
* @param bool $redirect Set true to redirect to Przelewy24 after transaction registration.
*
* @return array array(INT Error code, STRING Token).
*
* @throws Exception
*/
public function trnRegister($redirect = false)
{
$crc = md5(
$this->postData["p24_session_id"] . "|"
. $this->posId . "|" . $this->postData["p24_amount"] . "|"
. $this->postData["p24_currency"] . "|"
. $this->salt
);
$this->addValue("p24_sign", $crc);
$res = $this->callUrl("trnRegister", $this->postData);
if ('0' === (string)$res["error"]) {
$token = $res["token"];
} else {
return $res;
}
if ($redirect) {
$this->trnRequest($token);
}
return array("error" => 0, "token" => $token);
}
/**
* Redirects or returns URL to a P24 payment screen.
*
* @param string $token Token
* @param bool $redirect If set to true redirects to P24 payment screen.
* If set to false function returns URL to redirect to P24 payment screen.
*
* @return string URL to P24 payment screen
*/
public function trnRequest($token, $redirect = true)
{
$token = Tools::substr($token, 0, 100);
$url = $this->getHost() . 'trnRequest/' . $token;
if ($redirect) {
Tools::redirect($url);
return '';
}
return $url;
}
/**
* Function verify received from P24 system transaction's result.
*
* @return array
*
* @throws Exception
*/
public function trnVerify()
{
$crc = md5(
$this->postData["p24_session_id"] . "|"
. $this->postData["p24_order_id"] . "|"
. $this->postData["p24_amount"] . "|"
. $this->postData["p24_currency"] . "|"
. $this->salt
);
$this->addValue('p24_sign', $crc);
$res = $this->callUrl('trnVerify', $this->postData);
return $res;
}
/**
* Method is used to communicate with P24 system.
*
* @param string $function Method name.
* @param array $ARG POST parameters.
*
* @return array array(INT Error code, ARRAY Result).
*
* @throws Exception
*/
private function callUrl($function, $ARG)
{
if (!in_array($function, array('trnRegister', 'trnRequest', 'trnVerify', 'testConnection'))) {
return array('error' => 201, 'errorMessage' => 'class:Method not exists');
}
if ('testConnection' !== $function) {
$this->checkMandatoryFieldsForAction($ARG, $function);
}
$REQ = array();
foreach ($ARG as $k => $v) {
$REQ[] = $k . "=" . urlencode($v);
}
$url = $this->getHost() . $function;
$user_agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';
if (($ch = curl_init())) {
if (count($REQ)) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, join("&", $REQ));
}
curl_setopt($ch, CURLOPT_URL, $url);
if ($this->testMode) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
} else {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
}
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if (($result = curl_exec($ch))) {
$info = curl_getinfo($ch);
curl_close($ch);
if (200 !== (int)$info['http_code']) {
return array(
'error' => 200,
'errorMessage' => 'call:Page load error (' . $info['http_code'] . ')',
);
} else {
$res = array();
$X = explode('&', $result);
foreach ($X as $val) {
$Y = explode('=', $val);
$res[trim($Y[0])] = urldecode(trim($Y[1]));
}
return $res;
}
} else {
curl_close($ch);
return array('error' => 203, 'errorMessage' => 'call:Curl exec error');
}
} else {
return array('error' => 202, 'errorMessage' => 'call:Curl init error');
}
}
/**
* Validate api version.
*
* @param string $version
*
* @return bool
*/
private function validateVersion(&$version)
{
if (preg_match('/^[0-9]+(?:\.[0-9]+)*(?:[\.\-][0-9a-z]+)?$/', $version)) {
return true;
}
$version = '';
return false;
}
/**
* Validate email.
*
* @param string $email
* @return bool
*/
private function validateEmail(&$email)
{
if (($email = filter_var($email, FILTER_VALIDATE_EMAIL))) {
return true;
}
$email = '';
return false;
}
/**
* Validate number.
*
* @param string|float|int $value
* @param bool $min
* @param bool $max
*
* @return bool
*/
private function validateNumber(&$value, $min = false, $max = false)
{
if (is_numeric($value)) {
$value = (int)$value;
if ((false !== $min && $value < $min) || (false !== $max && $value > $max)) {
return false;
}
return true;
}
$value = (false !== $min ? $min : 0);
return false;
}
/**
* Validate string.
*
* @param string $value
* @param int $len
*
* @return bool
*/
private function validateString(&$value, $len = 0)
{
$len = (int)$len;
if (preg_match("/<[^<]+>/", $value, $m) > 0) {
return false;
}
if (0 === $len ^ Tools::strlen($value) <= $len) {
return true;
}
$value = '';
return false;
}
private function validateUrl(&$url, $len = 0)
{
$len = (int)$len;
if (0 === $len ^ Tools::strlen($url) <= $len) {
if (preg_match('@^https?://[^\s/$.?#].[^\s]*$@iS', $url)) {
return true;
}
}
$url = '';
return false;
}
/**
* Validate enum.
*
* @param string $value Provided value.
* @param string[] $haystack Array of valid values.
*
* @return bool
*/
private function validateEnum(&$value, $haystack)
{
if (in_array(Tools::strtolower($value), $haystack)) {
return true;
}
$value = $haystack[0];
return false;
}
/**
* Validate field.
*
* @param string $field
* @param mixed &$value
*
* @return boolean
*/
public function validateField($field, &$value)
{
$ret = false;
switch ($field) {
case 'p24_session_id':
$ret = $this->validateString($value, 100);
break;
case 'p24_description':
$ret = $this->validateString($value, 1024);
break;
case 'p24_address':
$ret = $this->validateString($value, 80);
break;
case 'p24_country':
case 'p24_language':
$ret = $this->validateString($value, 2);
break;
case 'p24_client':
case 'p24_city':
$ret = $this->validateString($value, 50);
break;
case 'p24_merchant_id':
case 'p24_pos_id':
case 'p24_order_id':
case 'p24_amount':
case 'p24_method':
case 'p24_time_limit':
case 'p24_channel':
case 'p24_shipping':
$ret = $this->validateNumber($value);
break;
case 'p24_wait_for_result':
$ret = $this->validateNumber($value, 0, 1);
break;
case 'p24_api_version':
$ret = $this->validateVersion($value);
break;
case 'p24_sign':
if ((32 === Tools::strlen($value)) && ctype_xdigit($value)) {
$ret = true;
} else {
$value = '';
}
break;
case 'p24_url_return':
case 'p24_url_status':
$ret = $this->validateUrl($value, 250);
break;
case 'p24_currency':
$ret = preg_match('/^[A-Z]{3}$/', $value);
if (!$ret) {
$value = '';
}
break;
case 'p24_email':
$ret = $this->validateEmail($value);
break;
case 'p24_encoding':
$ret = $this->validateEnum($value, array('iso-8859-2', 'windows-1250', 'urf-8', 'utf8'));
break;
case 'p24_transfer_label':
$ret = $this->validateString($value, 20);
break;
case 'p24_phone':
$ret = $this->validateString($value, 12);
break;
case 'p24_zip':
$ret = $this->validateString($value, 10);
break;
default:
if ((0 === strpos($field, 'p24_quantity_')) ||
(0 === strpos($field, 'p24_price_')) ||
(0 === strpos($field, 'p24_number_'))
) {
$ret = $this->validateNumber($value);
} elseif ((0 === strpos($field, 'p24_name_'))
|| (0 === strpos($field, 'p24_description_'))) {
$ret = $this->validateString($value, 127);
} else {
$value = '';
}
break;
}
return $ret;
}
/**
* Filter value.
*
* @param string $field
* @param string $value
*
* @return bool|string
*/
private function filterValue($field, $value)
{
return $this->validateField($field, $value) ? addslashes($value) : false;
}
/**
* Check mandatory fields for action.
*
* @param array $fieldsArray
* @param string $action
*
* @return bool
*
* @throws Exception
*/
public function checkMandatoryFieldsForAction($fieldsArray, $action)
{
$keys = array_keys($fieldsArray);
$verification = ('trnVerify' === $action);
static $mandatory = array(
'p24_order_id',//verify
'p24_sign',
'p24_merchant_id',
'p24_pos_id',
'p24_api_version',
'p24_session_id',
'p24_amount',//all
'p24_currency',
'p24_description',
'p24_country',
'p24_url_return',
'p24_currency',
'p24_email',
);
for ($i = ($verification ? 0 : 1); $i < ($verification ? 4 : count($mandatory)); $i++) {
if (!in_array($mandatory[$i], $keys)) {
throw new Exception('Field ' . $mandatory[$i] . ' is required for ' . $action . ' request!');
}
}
return true;
}
/**
* Parse and validate POST response data from Przelewy24.
*
* @return array - valid response | false - invalid crc | null - not a Przelewy24 response
*/
public function parseStatusResponse()
{
if (Tools::getIsset(
'p24_session_id',
'p24_order_id',
'p24_merchant_id',
'p24_pos_id',
'p24_amount',
'p24_currency',
'p24_method',
'p24_sign'
)) {
$session_id = $this->filterValue('p24_session_id', Tools::getValue('p24_session_id'));
$merchant_id = $this->filterValue('p24_merchant_id', Tools::getValue('p24_merchant_id'));
$pos_id = $this->filterValue('p24_pos_id', Tools::getValue('p24_pos_id'));
$order_id = $this->filterValue('p24_order_id', Tools::getValue('p24_order_id'));
$amount = $this->filterValue('p24_amount', Tools::getValue('p24_amount'));
$currency = $this->filterValue('p24_currency', Tools::getValue('p24_currency'));
$method = $this->filterValue('p24_method', Tools::getValue('p24_method'));
$sign = $this->filterValue('p24_sign', Tools::getValue('p24_sign'));
if (((int)$merchant_id !== (int)$this->merchantId) ||
((int)$pos_id !== (int)$this->posId) ||
(md5(
$session_id .
'|' .
$order_id .
'|' .
$amount .
'|' .
$currency .
'|' .
$this->salt
) !== $sign)) {
return false;
}
return array(
'p24_session_id' => $session_id,
'p24_order_id' => $order_id,
'p24_amount' => $amount,
'p24_currency' => $currency,
'p24_method' => $method,
);
}
return null;
}
/**
* Verifies data received in ping from P24.
*
* @param array|null $data
*
* @return bool|null null - status could not be parsed, true - data valid, false - data invalid.
*
* @throws Exception
*/
public function trnVerifyEx($data = null)
{
$response = $this->parseStatusResponse();
if (null === $response) {
return null;
} elseif ($response) {
if (is_array($data)) {
foreach ($data as $field => $value) {
if ((string)$response[$field] !== (string)$value) {
return false;
}
}
}
$this->postData = array_merge($this->postData, $response);
$result = $this->trnVerify();
return ('0' === (string)$result['error']);
}
return false;
}
/**
* Return direct sign.
*
* @param array $data
*
* @return string
*/
public function trnDirectSign($data)
{
return md5(
$data['p24_session_id'] . '|'
. $this->posId . '|'
. $data['p24_amount'] . '|'
. $data['p24_currency'] . '|'
. $this->salt
);
}
}
}

View File

@@ -0,0 +1,94 @@
<?php
/**
* Class Przelewy24ErrorResult
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24ErrorResult
*/
class Przelewy24ErrorResult
{
/**
* Error code.
*
* @var int
*/
private $errorCode;
/**
* Error message.
*
* @var string
*/
private $errorMessage;
/**
* Error type.
*
* @var string
*/
private $errorType;
/**
* Przelewy24ErrorResult constructor.
*
* @param int $errorCode
* @param string $errorMessage
* @param string $errorType
*/
public function __construct($errorCode = 0, $errorMessage = '', $errorType = 'general')
{
$this->errorCode = (int)$errorCode;
$this->errorMessage = $errorMessage;
$this->errorType = $errorType;
}
/**
* Get error code.
*
* @return int
*/
public function getErrorCode()
{
return $this->errorCode;
}
/**
* Get error message.
*
* @return string
*/
public function getErrorMessage()
{
return $this->errorMessage;
}
/**
* Get error type.
*
* @return string
*/
public function getErrorType()
{
return $this->errorType;
}
/**
* To array.
*
* @return array
*/
public function toArray()
{
return array(
'errorCode' => $this->getErrorCode(),
'errorMessage' => $this->getErrorMessage(),
'errorType' => $this->getErrorType(),
);
}
}

View File

@@ -0,0 +1,221 @@
<?php
/**
* Class Przelewy24Helper
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24Helper
*/
class Przelewy24Helper
{
/**
* Available status colors.
*
* @var array
*/
private static $statusColor = array(
0 => 'Lightblue',
1 => 'Limegreen',
);
/**
* Available statuses template.
*
* @var array
*/
private static $statusTemplate = array(
0 => '',
1 => 'payment',
);
/**
* Statuses translations.
*
* @var array
*/
private static $lang = array(
'pl' => array(
0 => 'Oczekiwanie na płatność Przelewy24',
1 => 'Płatność Przelewy24 przyjęta',
),
'en' => array(
0 => 'Waiting for payment Przelewy24',
1 => 'The payment Przelewy24 has been accepted',
),
);
/**
* These statuses will be inserted into database.
*
* @var array
*/
private static $status = array(
0 => array('statusKey' => 0, 'number' => 1, 'colorKey' => 0, 'paid' => 0, 'invoice' => 0, 'templateKey' => 0),
1 => array('statusKey' => 1, 'number' => 2, 'colorKey' => 1, 'paid' => 1, 'invoice' => 1, 'templateKey' => 1),
);
/**
* Add new order state to DB.
*/
public static function addOrderState()
{
foreach (self::$status as $statusKey) {
$title = self::getArrayLangByStatusKey((int)$statusKey['statusKey']);
$template = self::getArrayTemplateByStatusKey((int)$statusKey['statusKey']);
$number = (int)$statusKey['number'];
$color = self::$statusColor[(int)$statusKey['colorKey']];
$paid = (int)$statusKey['paid'];
$invoice = (int)$statusKey['invoice'];
$sql = new DbQuery();
$sql->select('id_order_state');
$sql->from('order_state');
$sql->where('color = \'' . pSQL($color) . '\' AND module_name = \'przelewy24\'');
$orderStateExists = Db::getInstance()->getRow($sql->build());
$orderState = new OrderState((int)$orderStateExists['id_order_state']);
if (0 === (int)$orderState->id) {
$orderState->name = $title;
$orderState->template = $template;
$orderState->unremovable = 1;
$orderState->color = $color;
$orderState->paid = $paid;
$orderState->invoice = $invoice;
$orderState->module_name = 'przelewy24';
$orderState->add();
}
$stateId = $orderState->id;
Configuration::updateValue('P24_ORDER_STATE_' . $number, $stateId);
}
}
/**
* Get array lang by status key.
*
* @param integer $statusKey
*
* @return array
*/
private static function getArrayLangByStatusKey($statusKey)
{
$return = array();
$langTable = Language::getLanguages(false, false);
$arrayLang = self::$lang;
foreach ($langTable as $langRow) {
if (array_key_exists($langRow['iso_code'], $arrayLang)) {
$return[$langRow['id_lang']] = $arrayLang[$langRow['iso_code']][$statusKey];
} else {
$return[$langRow['id_lang']] = $arrayLang['en'][$statusKey];
}
}
return $return;
}
/**
* Get array template by status key.
*
* @param integer $statusKey
*
* @return array
*/
private static function getArrayTemplateByStatusKey($statusKey)
{
$return = array();
$langTable = Language::getLanguages(false, false);
$arrayStatusTemplate = self::$statusTemplate;
foreach ($langTable as $langRow) {
$return[$langRow['id_lang']] = $arrayStatusTemplate[$statusKey];
}
return $return;
}
/**
* Format amount.
*
* @param float $amount
*
* @return string
*/
public static function p24AmountFormat($amount)
{
return number_format($amount * 100, 0, '', '');
}
/**
* Render json.
*
* @param array $data
*/
public static function renderJson($data)
{
header("Content-Type: application/json;charset=utf-8");
print json_encode($data);
exit;
}
/**
* Get suffix.
*
* @param string $currency
*
* @return string
*/
public static function getSuffix($currency)
{
if ('PLN' === $currency) {
return "";
} else {
return "_" . $currency;
}
}
/**
* Is soap extension installed.
*
* @return bool
*/
public static function isSoapExtensionInstalled()
{
return extension_loaded('soap');
}
/**
* Gets content of requested url.
*
* @param string $url
*
* @return string
*/
public static function requestGet($url)
{
$isCurl = function_exists('curl_init')
&& function_exists('curl_setopt')
&& function_exists('curl_exec')
&& function_exists('curl_close');
if ($isCurl) {
$userAgent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';
$curlConnection = curl_init();
curl_setopt($curlConnection, CURLOPT_URL, $url);
curl_setopt($curlConnection, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curlConnection, CURLOPT_USERAGENT, $userAgent);
curl_setopt($curlConnection, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlConnection, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curlConnection);
curl_close($curlConnection);
return $result;
}
return '';
}
}

View File

@@ -0,0 +1,36 @@
<?php
/**
* Class Przelewy24HookHelper
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*/
/**
* Class Przelewy24HookHelper
*
* This class contain methods for hooks.
*/
class Przelewy24HookHelper
{
/**
* Check if store is configured.
*
* Some hooks cannot be run before configuration.
*
* @param string $suffix
*
* @return bool
*/
public static function isStoreConfiguredForSuffix($suffix)
{
return
(int) Configuration::get('P24_MERCHANT_ID'.$suffix) > 0
&&
(int) Configuration::get('P24_SHOP_ID'.$suffix) > 0
&&
!empty(Configuration::get('P24_SALT'.$suffix))
;
}
}

View File

@@ -0,0 +1,17 @@
<?php
/**
* Class Przelewy24HttpException
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class to represent exception to be converted to HTTP responses.
*/
class Przelewy24HttpException extends Exception
{
/* Nothing to add. */
}

View File

@@ -0,0 +1,53 @@
<?php
/**
* Class Przelewy24InstallmentPayment
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
class Przelewy24InstallmentPayment
{
const INSTALLMENT_CALCULATOR_ENDPOINT = 'kalkulator_raty.php';
const QUERY_PARAMETER_AMOUNT_NAME = 'ammount';
const RESULT_TAB_SEPARATOR = '<br>';
const LIVE_URL = 'live_url';
const PART_COUNT = 'part_count';
const PART_COST = 'part_cost';
const PRODUCT_AMOUNT = 'product_amount';
/**
* Get installment payment data.
*
* @param float $amount
* @return array|null
* @throws Exception
*/
public static function getInstallmentPaymentData($amount)
{
$p24c = Przelewy24ClassStaticInterfaceFactory::getDefault();
if ((1 !== (int)Configuration::get('PS_SSL_ENABLED')) ||
(0 === (int)Configuration::get('P24_INSTALLMENT_PAYMENT_METHOD')) ||
($amount < $p24c::getMinInstallmentValue())) {
return null;
}
$amountInt = (int)round($amount * 100);
$liveUrl = $p24c::getHostForEnvironment();
$calculatorAlior = Przelewy24Helper::requestGet(
$liveUrl . self::INSTALLMENT_CALCULATOR_ENDPOINT . '?'
. self::QUERY_PARAMETER_AMOUNT_NAME . '=' . $amountInt
);
$resultTab = explode(self::RESULT_TAB_SEPARATOR, $calculatorAlior);
return array(
self::LIVE_URL => $liveUrl,
self::PART_COUNT => $resultTab[0],
self::PART_COST => $resultTab[1],
self::PRODUCT_AMOUNT => $amount,
);
}
}

View File

@@ -0,0 +1,52 @@
<?php
/**
* Class Przelewy24JsonController
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24JsonController
*
* Common methods for JSON controllers.
*/
class Przelewy24JsonController extends ModuleFrontController
{
/**
* Output to be returned by this controller (response method).
*
* @var array
*/
protected $output = array();
/**
* Initializes common front page content.
*/
public function initContent()
{
parent::initContent();
$this->output = array();
}
/**
* Output response.
*
* @param int $httpCode
* @param string $infoMessage
* @param bool $log
*/
protected function response($httpCode, $infoMessage = '', $log = true)
{
http_response_code($httpCode);
header("Content-Type: application/json;charset=utf-8");
if ($log && $infoMessage) {
Przelewy24Logger::addTruncatedLog($infoMessage);
}
$options = JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT;
echo json_encode($this->output, $options);
exit;
}
}

View File

@@ -0,0 +1,27 @@
<?php
/**
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*/
/**
* Autoloader
*
* @param string $class
*/
function autoloader($class)
{
$directories = array('classes', 'factories', 'interfaces', 'models', 'controllers/front');
foreach ($directories as $directory) {
$fileName = _PS_MODULE_DIR_ . 'przelewy24/' . $directory . '/' . $class . '.php';
if ('index' === $class || !file_exists($fileName)) {
continue;
}
include_once $fileName;
}
include_once _PS_MODULE_DIR_ . 'przelewy24/controllers/front/Przelewy24Controller.php';
}
spl_autoload_register('autoloader');

View File

@@ -0,0 +1,54 @@
<?php
/**
* Class Przelewy24OneClickHelper
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24OneClickHelper
*/
class Przelewy24OneClickHelper
{
/**
* Get card payment ids.
*
* @return array
*/
public static function getCardPaymentIds()
{
return array(140, 142, 145, 218);
}
/**
* Escape string.
*
* @param string $string
*
* @return string
*/
public static function escape($string)
{
$string = trim($string);
return htmlspecialchars($string);
}
/**
* Is one click enabled.
*
* @param string $suffix
*
* @return bool
* @throws Exception
*/
public static function isOneClickEnable($suffix = "")
{
$soap = Przelewy24SoapInterfaceFactory::getForSuffix($suffix);
return ($soap->checkCardRecurrency() && 1 === (int)Configuration::get('P24_ONECLICK_ENABLE' . $suffix));
}
}

View File

@@ -0,0 +1,42 @@
<?php
/**
* Class Przelewy24Service
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24Service
*/
abstract class Przelewy24Service
{
/**
* Main Przelewy24 module class.
*
* @var Przelewy24
*/
private $przelewy24;
/**
* Przelewy24Service constructor.
*
* @param Przelewy24 $przelewy24
*/
public function __construct(Przelewy24 $przelewy24)
{
$this->przelewy24 = $przelewy24;
}
/**
* Get module Przelewy24.
*
* @return Przelewy24
*/
protected function getPrzelewy24()
{
return $this->przelewy24;
}
}

View File

@@ -0,0 +1,794 @@
<?php
/**
* Class Przelewy24ServiceAdminForm
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24ServiceAdminForm
*/
class Przelewy24ServiceAdminForm extends Przelewy24Service
{
const P24_PAYMETHOD_LIST_PROMOTE = 'p24_paymethod_list_promote';
const P24_PAYMETHOD_LIST_PROMOTE_2 = 'p24_paymethod_list_promote_2';
const FORM_TYPE = 'type';
const FORM_LABEL = 'label';
const FORM_NAME = 'name';
const FORM_CLASS = 'class';
const FORM_REQUIRED = 'required';
const FORM_OPTIONS = 'options';
const FORM_DESC = 'desc';
const FORM_VALUES = 'values';
const FORM_VALUE = 'value';
const FORM_ID = 'id';
/**
* Configuration parameters.
*
* @var array
*/
private $parameters = array(
'P24_MERCHANT_ID',
'P24_SHOP_ID',
'P24_SALT',
'P24_TEST_MODE',
'P24_API_KEY',
'P24_VERIFYORDER',
'P24_PAYMENT_METHOD_LIST',
'P24_GRAPHICS_PAYMENT_METHOD_LIST',
'P24_PAYMENTS_ORDER_LIST_FIRST',
'P24_PAYMENTS_ORDER_LIST_SECOND',
'P24_PAYMENTS_PROMOTE_LIST',
'P24_ONECLICK_ENABLE',
'P24_BLIK_UID_ENABLE',
'P24_PAY_CARD_INSIDE_ENABLE',
'P24_EXTRA_CHARGE_ENABLED',
'P24_EXTRA_CHARGE_AMOUNT',
'P24_EXTRA_CHARGE_PERCENT',
'P24_INSTALLMENT_PAYMENT_METHOD',
);
private static function isConfiguredForSuffix($suffix)
{
if ((int)Configuration::get('P24_MERCHANT_ID' . $suffix) <= 0) {
return false;
} elseif ((int)Configuration::get('P24_SHOP_ID' . $suffix) <= 0) {
return false;
} elseif (empty(Configuration::get('P24_SALT' . $suffix))) {
return false;
}
return true;
}
/**
* Display P24 form.
*
* @param string $lang Form language.
*
* @return string
* @throws Exception
*/
public function displayForm($lang)
{
// Get default language
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$output = '';
$fieldsForm = $testApi = array();
foreach (CurrencyCore::getCurrencies() as $currency) {
$currencyCode = $currency['iso_code'];
$suffix = Przelewy24Helper::getSuffix($currencyCode);
if (self::isConfiguredForSuffix($suffix)) {
try {
$soap = Przelewy24SoapInterfaceFactory::getForSuffix($suffix);
$p24BlikSoap = Przelewy24BlikSoapInterfaceFactory::getForSuffix($suffix);
$apiKey = Configuration::get('P24_API_KEY' . $suffix);
$testApiAccess = $soap->apiTestAccess($apiKey);
$blikEnable = $p24BlikSoap->testAccess();
$oneClickEnable = $soap->checkCardRecurrency();
} catch (\Exception $e) {
PrestaShopLogger::addLog('WSDL is configured but not reachable: ' . $e->getMessage(), 1);
$testApiAccess = false;
$blikEnable = false;
$oneClickEnable = false;
}
} else {
$testApiAccess = false;
$blikEnable = false;
$oneClickEnable = false;
}
$testApi[$currencyCode] = [
'testApi' => $testApiAccess,
'P24_BLIK_UID_ENABLE' => $blikEnable,
'P24_ONECLICK_ENABLE' => $oneClickEnable,
];
}
$orderStates = OrderState::getOrderStates(
$this->getPrzelewy24()->getContext()->cookie->id_lang
);
$fieldsForm[1]['form'] = array(
'legend' => array(
'title' => $lang['Select currency for which you want to configure your merchant'],
'image' => $this->getPrzelewy24()->getPath() . 'logo.png',
),
'input' => array(
array(
self::FORM_TYPE => 'radio',
self::FORM_LABEL => $lang['Currency'],
self::FORM_NAME => 'currency',
self::FORM_REQUIRED => true,
self::FORM_VALUES => array(),
),
),
);
$fieldsForm[2]['form'] = array(
'legend' => array(
'title' => $lang['Settings for all currencies'],
'image' => $this->getPrzelewy24()->getPath() . 'logo.png',
),
'input' => array(
array(
self::FORM_TYPE => 'select',
self::FORM_LABEL => $lang['Status before completing payment'],
self::FORM_NAME => 'P24_ORDER_STATE_1',
self::FORM_REQUIRED => true,
self::FORM_OPTIONS => array(
'query' => $orderStates,
self::FORM_ID => 'id_order_state',
self::FORM_NAME => 'name',
),
),
array(
self::FORM_TYPE => 'select',
self::FORM_LABEL => $lang['Status after completing payment'],
self::FORM_NAME => 'P24_ORDER_STATE_2',
self::FORM_REQUIRED => true,
self::FORM_OPTIONS => array(
'query' => $orderStates,
self::FORM_ID => 'id_order_state',
self::FORM_NAME => 'name',
),
),
),
);
foreach (CurrencyCore::getCurrencies() as $currency) {
array_push(
$fieldsForm[1]['form']['input'][0]['values'],
array(
self::FORM_ID => $currency['iso_code'],
self::FORM_VALUE => $currency['iso_code'],
self::FORM_LABEL => $currency['iso_code'],
)
);
}
// Init Fields form array
$fieldsForm[0]['form'] = array(
'legend' => array(
'title' => $lang['Settings'],
'image' => $this->getPrzelewy24()->getPath() . 'logo.png',
),
'input' => array(
array(
self::FORM_TYPE => 'text',
self::FORM_LABEL => $lang['Merchant ID'],
self::FORM_NAME => 'P24_MERCHANT_ID',
self::FORM_REQUIRED => true,
),
array(
self::FORM_TYPE => 'text',
self::FORM_LABEL => $lang['Shop ID'],
self::FORM_NAME => 'P24_SHOP_ID',
self::FORM_REQUIRED => true,
),
array(
self::FORM_TYPE => 'text',
self::FORM_LABEL => $lang['CRC Key'],
self::FORM_NAME => 'P24_SALT',
self::FORM_REQUIRED => true,
),
array(
self::FORM_TYPE => 'radio',
self::FORM_LABEL => $lang['Module mode'],
'desc' => $lang['Choose module mode.'],
self::FORM_NAME => 'P24_TEST_MODE',
self::FORM_REQUIRED => true,
self::FORM_CLASS => 't',
'is_bool' => true,
self::FORM_VALUES => array(
array(
self::FORM_ID => 'active_test',
self::FORM_VALUE => 1,
self::FORM_LABEL => $lang['Test (Sandbox)'],
),
array(
self::FORM_ID => 'active_prod',
self::FORM_VALUE => 0,
self::FORM_LABEL => $lang['Normal/production'],
),
),
),
array(
self::FORM_TYPE => 'text',
self::FORM_LABEL => $lang['API Key'],
self::FORM_NAME => 'P24_API_KEY',
self::FORM_REQUIRED => false,
'desc' => $lang['API key allow access to additional functions, e.g. graphics list of ' .
'payment methods. You can get API key from Przelewy24 dashboard, from my data tab.'],
),
),
'submit' => array(
'title' => $lang['Save'],
self::FORM_CLASS => 'btn btn-default pull-right',
),
);
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'select',
self::FORM_LABEL => $lang['Stage of creating the order:'],
self::FORM_NAME => 'P24_VERIFYORDER',
self::FORM_OPTIONS => array(
'query' => array(
array(
'id_option' => 0,
self::FORM_NAME => $lang['After choosing Przelewy24 as a payment gateway'],
),
array(
'id_option' => 1,
self::FORM_NAME => $lang['After payment'],
),
array(
'id_option' => 2,
self::FORM_NAME => $lang['After click "Confirm" button'],
),
),
self::FORM_ID => 'id_option',
self::FORM_NAME => 'name',
),
);
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'switch',
self::FORM_LABEL => $lang['Oneclick payments'],
'desc' => $lang['Allows you to order products with on-click'],
self::FORM_NAME => 'P24_ONECLICK_ENABLE',
self::FORM_VALUES => array(
array(
self::FORM_ID => 'active_on',
self::FORM_VALUE => 1,
),
array(
self::FORM_ID => 'active_off',
self::FORM_VALUE => 0,
),
),
);
// ajax form
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'switch',
self::FORM_LABEL => $lang['Card payments inside shop'],
'desc' => $lang['Allows to pay by credit/debit card without leaving the store website'],
self::FORM_NAME => 'P24_PAY_CARD_INSIDE_ENABLE',
self::FORM_VALUES => array(
array(
self::FORM_ID => 'active_on',
self::FORM_VALUE => 1,
),
array(
self::FORM_ID => 'active_off',
self::FORM_VALUE => 0,
),
),
);
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'switch',
self::FORM_LABEL => $lang['Show available payment methods in shop'],
'desc' => $lang['Customer can chose payment method on confirmation page.'],
self::FORM_NAME => 'P24_PAYMENT_METHOD_LIST',
self::FORM_VALUES => array(
array(
self::FORM_ID => 'active_on',
self::FORM_VALUE => 1,
),
array(
self::FORM_ID => 'active_off',
self::FORM_VALUE => 0,
),
),
);
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'switch',
self::FORM_LABEL => $lang['Use installment payment methods in shop'],
self::FORM_NAME => 'P24_INSTALLMENT_PAYMENT_METHOD',
self::FORM_VALUES => array(
array(
self::FORM_ID => 'active_on',
self::FORM_VALUE => 1,
),
array(
self::FORM_ID => 'active_off',
self::FORM_VALUE => 0,
),
),
);
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'switch',
self::FORM_LABEL => $lang['Use graphics list of payment methods'],
self::FORM_NAME => 'P24_GRAPHICS_PAYMENT_METHOD_LIST',
self::FORM_VALUES => array(
array(
self::FORM_ID => 'active_on',
self::FORM_VALUE => 1,
),
array(
self::FORM_ID => 'active_off',
self::FORM_VALUE => 0,
),
),
);
// payments method list and order
foreach (CurrencyCore::getCurrencies() as $currency) {
$currencyCode = $currency['iso_code'];
$suffix = Przelewy24Helper::getSuffix($currencyCode);
if (self::isConfiguredForSuffix($suffix)) {
$soap = Przelewy24SoapInterfaceFactory::getForSuffix($suffix);
$paymethodList = $soap->getFirstAndSecondPaymentList(
Configuration::get('P24_API_KEY' . $suffix),
$currencyCode
);
$p24PaymethodDescription = array();
foreach ($soap->availablePaymentMethods(
Configuration::get('P24_API_KEY' . $suffix)
) as $bankId => $bankName) {
if (($value = Configuration::get("P24_PAYMENT_DESCRIPTION_{$bankId}{$suffix}"))) {
Configuration::updateValue("P24_PAYMENT_DESCRIPTION_{$bankId}{$suffix}", $value);
} else {
$value = $bankName;
}
$p24PaymethodDescription[$bankId] = $value;
}
$paymethodList['p24_paymethod_description'] = $p24PaymethodDescription;
} else {
$paymethodList = [
'p24_paymethod_list_first' => [],
'p24_paymethod_list_second' => [],
'p24_paymethod_description' => [],
];
}
$this->getPrzelewy24()->getSmarty()->assign(array('suffix' => $suffix));
$this->getPrzelewy24()->getSmarty()->assign(
array('p24_paymethod_list_first' . $suffix => $paymethodList['p24_paymethod_list_first'])
);
$this->getPrzelewy24()->getSmarty()->assign(
array('p24_paymethod_list_second' . $suffix => $paymethodList['p24_paymethod_list_second'])
);
$this->getPrzelewy24()->getSmarty()->assign(
array('p24_paymethod_description' . $suffix => $paymethodList['p24_paymethod_description'])
);
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'html',
self::FORM_LABEL => $lang['Show available payment methods in confirm'],
self::FORM_NAME => $this->getPrzelewy24()->display(
$this->getPrzelewy24()->getBaseFile(),
'views/templates/admin/sortable_payments.tpl'
),
);
}
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'hidden',
self::FORM_NAME => 'P24_PAYMENTS_ORDER_LIST_FIRST',
);
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'hidden',
self::FORM_NAME => 'P24_PAYMENTS_ORDER_LIST_SECOND',
);
foreach (CurrencyCore::getCurrencies() as $currency) {
$currencyCode = $currency['iso_code'];
$suffix = Przelewy24Helper::getSuffix($currencyCode);
// promote
if (self::isConfiguredForSuffix($suffix)) {
$soap = Przelewy24SoapInterfaceFactory::getForSuffix($suffix);
$promotePaymethodList = $soap->getPromotedPaymentList(
Configuration::get('P24_API_KEY' . $suffix),
$currencyCode
);
} else {
$promotePaymethodList = [
self::P24_PAYMETHOD_LIST_PROMOTE => [],
self::P24_PAYMETHOD_LIST_PROMOTE_2 => [],
];
}
$this->getPrzelewy24()->getSmarty()->assign(array('suffix' => $suffix));
$this->getPrzelewy24()->getSmarty()->assign(
array(
self::P24_PAYMETHOD_LIST_PROMOTE . $suffix =>
$promotePaymethodList[self::P24_PAYMETHOD_LIST_PROMOTE],
)
);
$this->getPrzelewy24()->getSmarty()->assign(
array(
self::P24_PAYMETHOD_LIST_PROMOTE_2 . $suffix =>
$promotePaymethodList[self::P24_PAYMETHOD_LIST_PROMOTE_2],
)
);
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'html',
self::FORM_LABEL => $lang['Promote some payment methods'],
self::FORM_NAME => $this->getPrzelewy24()->display(
$this->getPrzelewy24()->getBaseFile(),
'views/templates/admin/sortable_promote_payments.tpl'
),
);
}
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'hidden',
self::FORM_NAME => 'P24_PAYMENTS_PROMOTE_LIST',
);
foreach (CurrencyCore::getCurrencies() as $currency) {
$currencyCode = $currency['iso_code'];
$suffix = Przelewy24Helper::getSuffix($currencyCode);
// promote
if (self::isConfiguredForSuffix($suffix)) {
$soap = Przelewy24SoapInterfaceFactory::getForSuffix($suffix);
$promotePaymethodList = $soap->getPromotedPaymentList(
Configuration::get('P24_API_KEY' . $suffix),
$currencyCode
);
} else {
$promotePaymethodList = [
self::P24_PAYMETHOD_LIST_PROMOTE => [],
self::P24_PAYMETHOD_LIST_PROMOTE_2 => [],
];
}
$this->getPrzelewy24()->getSmarty()->assign(
array(
'suffix' => $suffix,
self::P24_PAYMETHOD_LIST_PROMOTE . $suffix
=> $promotePaymethodList[self::P24_PAYMETHOD_LIST_PROMOTE],
self::P24_PAYMETHOD_LIST_PROMOTE_2 . $suffix
=> $promotePaymethodList[self::P24_PAYMETHOD_LIST_PROMOTE_2],
)
);
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'html',
self::FORM_LABEL => $lang['Payment descriptions'],
self::FORM_NAME => $this->getPrzelewy24()->display(
$this->getPrzelewy24()->getBaseFile(),
'views/templates/admin/payments_description.tpl'
),
);
}
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'hidden',
self::FORM_NAME => 'P24_PAYMENTS_DESCRIPTION',
);
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'switch',
self::FORM_LABEL => $lang['Enable extra charge'],
self::FORM_NAME => 'P24_EXTRA_CHARGE_ENABLED',
self::FORM_VALUES => array(
array(
self::FORM_ID => 'active_on',
self::FORM_VALUE => 1,
),
array(
self::FORM_ID => 'active_off',
self::FORM_VALUE => 0,
),
),
);
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'text',
self::FORM_LABEL => $lang['Increase payment (amount)'],
self::FORM_NAME => 'P24_EXTRA_CHARGE_AMOUNT',
self::FORM_CLASS => 'input fixed-width-sm',
self::FORM_REQUIRED => false,
);
$fieldsForm[0]['form']['input'][] = array(
self::FORM_TYPE => 'text',
self::FORM_LABEL => $lang['Increase payment (percent)'],
self::FORM_NAME => 'P24_EXTRA_CHARGE_PERCENT',
self::FORM_CLASS => 'input fixed-width-sm',
self::FORM_REQUIRED => false,
);
$this->getPrzelewy24()->getContext()->controller->addCSS(
$this->getPrzelewy24()->getPath() . 'views/css/admin.css',
'all'
);
$helper = new HelperForm();
// Module, token and currentIndex
$helper->module = $this->getPrzelewy24();
$helper->name_controller = $this->getPrzelewy24()->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex . '&configure=' . $this->getPrzelewy24()->name;
// Language
$helper->default_form_language = $default_lang;
$helper->allow_employee_form_lang = $default_lang;
// Title and toolbar
$helper->title = $this->getPrzelewy24()->displayName;
$helper->show_toolbar = true; // false -> remove toolbar
$helper->toolbar_scroll = true; // true - > Toolbar is always visible on the top of the screen.
$helper->submit_action = 'submit' . $this->getPrzelewy24()->name;
$helper->toolbar_btn = array(
'save' =>
array(
'desc' => $lang['Save'],
'href' => AdminController::$currentIndex .
'&configure=' . $this->getPrzelewy24()->name .
'&save' . $this->getPrzelewy24()->name .
'&token=' . Tools::getAdminTokenLite('AdminModules'),
),
'back' => array(
'href' => AdminController::$currentIndex . '&token=' . Tools::getAdminTokenLite('AdminModules'),
'desc' => $lang['Back to list'],
),
);
// Load current value
foreach (CurrencyCore::getCurrencies() as $currency) {
$currencyCode = $currency['iso_code'];
$suffix = Przelewy24Helper::getSuffix($currencyCode);
foreach ($this->parameters as $param) {
$fieldsForm[0]['form']['tabs'][$currencyCode][$param] = Configuration::get($param . $suffix);
}
$fieldsForm[0]['form']['tabs'][$currencyCode]['P24_ADDITIONAL_SETTINGS'] = $testApi[$currencyCode];
}
$defaultCurrency = new CurrencyCore(Configuration::get('PS_CURRENCY_DEFAULT'));
$suffix = Przelewy24Helper::getSuffix($defaultCurrency->iso_code);
foreach ($this->parameters as $param) {
$helper->fields_value[$param] = Configuration::get($param . $suffix);
}
$helper->fields_value["currency"] = $defaultCurrency->iso_code;
$helper->fields_value['P24_ORDER_STATE_1'] = (int)Configuration::get('P24_ORDER_STATE_1');
$helper->fields_value['P24_ORDER_STATE_2'] = (int)Configuration::get('P24_ORDER_STATE_2');
return $output . $helper->generateForm($fieldsForm);
}
/**
* Submit action in admin.
*
* @param string $lang
*
* @return string
* @throws Exception
*/
public function processSubmit($lang)
{
$output = '';
if (Tools::isSubmit('submit' . $this->getPrzelewy24()->name)) {
$isValid = true;
$suffix = Przelewy24Helper::getSuffix(Tools::getValue('currency'));
$merchantId = (string)Tools::getValue('P24_MERCHANT_ID');
if (empty($merchantId) || !Validate::isInt($merchantId) || ($merchantId <= 0)) {
$isValid = false;
$output .= $this->getPrzelewy24()->displayError($lang['Invalid merchant ID']);
}
$shopId = (string)Tools::getValue('P24_SHOP_ID');
if (empty($shopId) || !Validate::isInt($shopId) || ($shopId <= 0)) {
$isValid = false;
$output .= $this->getPrzelewy24()->displayError($lang['Invalid shop ID']);
}
$salt = (string)Tools::getValue('P24_SALT');
if (empty($salt)) {
$isValid = false;
$output .= $this->getPrzelewy24()->displayError($lang['Invalid CRC key']);
}
$apiKey = Tools::getValue('P24_API_KEY');
// Try create object only for valid credentials.
if ($isValid) {
$testMode = (bool)Tools::getValue('P24_TEST_MODE');
try {
$soap = Przelewy24ValidatorSoapInterfaceFactory::getForParams(
$merchantId,
$shopId,
$salt,
$testMode
);
} catch (SoapFault $ex) {
PrestaShopLogger::addLog($ex->getMessage(), 1);
$soap = null;
$output .= $this->getPrzelewy24()->displayError(
$lang['Cannot connect to external service. This could be network error or wrong merchant ID.']
);
$isValid = false;
}
}
// Try these functions only if soap is valid.
if ($isValid) {
$validateCredentials = $soap->validateCredentials();
if (!$validateCredentials) {
$isValid = false;
$output .= $this->getPrzelewy24()->displayError(
$lang['Wrong CRC Key for this Merchant / Shop ID and module mode!']
);
}
if ($apiKey) {
$testApi = $soap->apiTestAccess($apiKey);
if (!$testApi) {
$isValid = false;
$output .= $this->getPrzelewy24()->displayError(
$lang['Wrong API key for this Merchant / Shop ID!']
);
}
}
}
if ($isValid) {
Configuration::updateValue('P24_MERCHANT_ID' . $suffix, $merchantId);
Configuration::updateValue('P24_SHOP_ID' . $suffix, $shopId);
Configuration::updateValue('P24_SALT' . $suffix, $salt);
Configuration::updateValue('P24_API_KEY' . $suffix, $apiKey);
Configuration::updateValue('P24_TEST_MODE' . $suffix, Tools::getValue('P24_TEST_MODE'));
$paymentMehtodList = (int)Tools::getValue('P24_PAYMENT_METHOD_LIST');
Configuration::updateValue(
'P24_PAYMENT_METHOD_LIST' . $suffix,
$paymentMehtodList
);
if ($paymentMehtodList) {
Configuration::updateValue(
'P24_GRAPHICS_PAYMENT_METHOD_LIST' . $suffix,
(int)Tools::getValue('P24_GRAPHICS_PAYMENT_METHOD_LIST')
);
Configuration::updateValue(
'P24_PAYMENTS_ORDER_LIST_FIRST' . $suffix,
Tools::getValue('P24_PAYMENTS_ORDER_LIST_FIRST')
);
Configuration::updateValue(
'P24_PAYMENTS_ORDER_LIST_SECOND' . $suffix,
Tools::getValue('P24_PAYMENTS_ORDER_LIST_SECOND')
);
Configuration::updateValue(
'P24_PAYMENTS_PROMOTE_LIST' . $suffix,
Tools::getValue('P24_PAYMENTS_PROMOTE_LIST')
);
$soap = Przelewy24SoapInterfaceFactory::getForSuffix($suffix);
$p24PaymethodDescription = $soap->availablePaymentMethods(
Configuration::get('P24_API_KEY' . $suffix)
);
foreach ($p24PaymethodDescription as $bankId => $bankName) {
if (($value = Tools::getValue("P24_PAYMENT_DESCRIPTION_{$bankId}{$suffix}")) &&
$value !== $bankName
) {
Configuration::updateValue("P24_PAYMENT_DESCRIPTION_{$bankId}{$suffix}", $value);
} else {
Configuration::updateValue("P24_PAYMENT_DESCRIPTION_{$bankId}{$suffix}", null);
}
}
}
Configuration::updateValue(
'P24_ONECLICK_ENABLE' . $suffix,
Tools::getValue('P24_ONECLICK_ENABLE')
);
Configuration::updateValue(
'P24_BLIK_UID_ENABLE' . $suffix,
Tools::getValue('P24_BLIK_UID_ENABLE')
);
Configuration::updateValue(
'P24_VERIFYORDER' . $suffix,
Tools::getValue('P24_VERIFYORDER')
);
Configuration::updateValue(
'P24_PAY_CARD_INSIDE_ENABLE' . $suffix,
Tools::getValue('P24_PAY_CARD_INSIDE_ENABLE')
);
Configuration::updateValue(
'P24_EXTRA_CHARGE_ENABLED' . $suffix,
Tools::getValue('P24_EXTRA_CHARGE_ENABLED')
);
Configuration::updateValue(
'P24_EXTRA_CHARGE_AMOUNT' . $suffix,
str_replace(',', '.', Tools::getValue('P24_EXTRA_CHARGE_AMOUNT'))
);
Configuration::updateValue(
'P24_EXTRA_CHARGE_PERCENT' . $suffix,
str_replace(',', '.', Tools::getValue('P24_EXTRA_CHARGE_PERCENT'))
);
Configuration::updateValue(
'P24_INSTALLMENT_PAYMENT_METHOD' . $suffix,
Tools::getValue('P24_INSTALLMENT_PAYMENT_METHOD')
);
Configuration::updateValue(
'P24_ORDER_STATE_1',
Tools::getValue('P24_ORDER_STATE_1')
);
Configuration::updateValue(
'P24_ORDER_STATE_2',
Tools::getValue('P24_ORDER_STATE_2')
);
Configuration::updateValue('P24_CONFIGURATION_VALID' . $suffix, 1);
$output .= $this->getPrzelewy24()->displayConfirmation($lang['Settings saved.']);
} else {
Configuration::updateValue('P24_CONFIGURATION_VALID' . $suffix, 0);
$output .= $this->getPrzelewy24()->displayError(
$lang['Przelewy24 module settings are not configured correctly.' .
' Przelewy24 payment method does not appear in the list in order.']
);
}
}
$output .= $this->getPrzelewy24()->display(
$this->getPrzelewy24()->getBaseFile(),
'views/templates/admin/config_intro.tpl'
);
if ((int)Configuration::get('P24_CONFIGURATION_VALID') < 1) {
$output .= $this->getPrzelewy24()->display(
$this->getPrzelewy24()->getBaseFile(),
'views/templates/admin/config_register_info.tpl'
);
}
return $output;
}
}

View File

@@ -0,0 +1,93 @@
<?php
/**
* Class Przelewy24ServiceInstall
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24ServiceInstall
*/
class Przelewy24ServiceInstall extends Przelewy24Service
{
/**
* Execute.
*/
public function execute()
{
// we check that the Multistore feature is enabled, and if so,
// set the current context to all shops on this installation of PrestaShop.
if (Shop::isFeatureActive()) {
Shop::setContext(Shop::CONTEXT_ALL);
}
Configuration::updateValue('P24_GRAPHICS_PAYMENT_METHOD_LIST', 1);
Configuration::updateValue('P24_PAYMENT_METHOD_LIST', 1);
Configuration::updateValue('P24_PAYMENTS_ORDER_LIST_FIRST', '25,31,112,20,65,');
Przelewy24Helper::addOrderState();
$this->createDatabaseTables();
Configuration::updateValue('P24_PLUGIN_VERSION', $this->getPrzelewy24()->version);
}
/**
* Create database tables.
*/
private function createDatabaseTables()
{
$tableName = addslashes(_DB_PREFIX_ . Przelewy24Recurring::TABLE);
$sql = '
CREATE TABLE IF NOT EXISTS `' . $tableName . '` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`website_id` INT UNSIGNED NOT NULL,
`customer_id` INT UNSIGNED NOT NULL,
`reference_id` VARCHAR(35) NOT NULL,
`expires` VARCHAR(4) NOT NULL,
`mask` VARCHAR (32) NOT NULL,
`card_type` VARCHAR (20) NOT NULL,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `UNIQUE_FIELDS` (`mask`,`card_type`,`expires`,`customer_id`,`website_id`));';
Db::getInstance()->Execute($sql);
$tableName = addslashes(_DB_PREFIX_ . Przelewy24CustomerSetting::TABLE);
$sql = '
CREATE TABLE IF NOT EXISTS`' . $tableName . '` (
`customer_id` INT UNSIGNED NOT NULL PRIMARY KEY,
`card_remember` TINYINT UNSIGNED DEFAULT 0
);';
Db::getInstance()->Execute($sql);
$tableName = addslashes(_DB_PREFIX_ . Przelewy24BlikAlias::TABLE);
$sql = '
CREATE TABLE IF NOT EXISTS`' . $tableName . '` (
`customer_id` INT UNSIGNED NOT NULL PRIMARY KEY,
`alias` VARCHAR(255) DEFAULT 0,
`last_order_id` INT UNSIGNED NULL
);';
Db::getInstance()->Execute($sql);
$p24OrdersTable = addslashes(_DB_PREFIX_ . Przelewy24Order::TABLE);
$sql = '
CREATE TABLE IF NOT EXISTS `' . $p24OrdersTable . '` (
`p24_order_id` INT UNSIGNED NOT NULL PRIMARY KEY,
`pshop_order_id` INT UNSIGNED NOT NULL,
`p24_session_id` VARCHAR(100) NOT NULL
);';
Db::getInstance()->Execute($sql);
$tableName = addslashes(_DB_PREFIX_ . Przelewy24Extracharge::TABLE);
$sql = 'CREATE TABLE IF NOT EXISTS`' . $tableName . '` (
`id_extracharge` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`id_order` INT UNSIGNED NOT NULL,
`extra_charge_amount` INT NOT NULL
);';
Db::getInstance()->Execute($sql);
}
}

View File

@@ -0,0 +1,51 @@
<?php
/**
* Class Przelewy24ServiceOrderRepeatPayment
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24ServiceOrderRepeatPayment
*/
class Przelewy24ServiceOrderRepeatPayment extends Przelewy24Service
{
/**
* Executes action (order repeat).
*
* @return bool|Order
*/
public function execute()
{
if (!$this->getPrzelewy24()->active) {
return false;
}
$link = new Link();
$idOrder = (int)Tools::getValue('id_order');
$order = new Order((int)$idOrder);
$idCart = $order->id_cart;
$secureKey = $order->secure_key;
$moduleId = \Module::getModuleIdByName('przelewy24');
$orderConfirmation = $link->getPageLink('order-confirmation');
$this->getPrzelewy24()->getSmarty()->assign(
'logo_url',
$this->getPrzelewy24()->getPathUri() . 'views/img/logo.png'
);
$this->getPrzelewy24()->getSmarty()->assign(
'redirect_url',
$orderConfirmation .
'?id_cart=' . $idCart .
'&id_module=' . $moduleId .
'&id_order=' . $idOrder .
'&key=' . $secureKey
);
return $order;
}
}

View File

@@ -0,0 +1,286 @@
<?php
/**
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
use PrestaShop\PrestaShop\Core\Payment\PaymentOption;
/**
* Class Przelewy24ServicePaymentOptions
*/
class Przelewy24ServicePaymentOptions extends Przelewy24Service
{
const BASE_URL_LOGO_P24 = 'https://secure.przelewy24.pl/template/201312/bank/';
/**
* Rendered html with information about payment amounts.
*
* @var string|null
*/
private $additionalInformation;
/**
* hookPaymentOptions implementation.
*
* @param array $params
* @param string $text
*
* @return array
* @throws Exception
*/
public function execute($params, $text)
{
$cart = Context::getContext()->cart;
$currency = new Currency($cart->id_currency);
$suffix = Przelewy24Helper::getSuffix($currency->iso_code);
if (!$this->getPrzelewy24()->active || (int)Configuration::get('P24_CONFIGURATION_VALID' . $suffix) < 1) {
return array();
}
$templateVars = $this->getPrzelewy24()->getTemplateVars();
$amountTotal = $templateVars['total'];
$templateVars['extracharge'] = $this->getExtracharge($amountTotal, $suffix);
$templateVars['logo_url'] = $this->getPrzelewy24()->getPathUri() . 'views/img/logo.png';
if ($templateVars['extracharge'] > 0) {
$templateVars['checkTotal'] = Tools::displayPrice(($templateVars['extracharge'] + $templateVars['total']));
$templateVars['extracharge_formatted'] = Tools::displayPrice($templateVars['extracharge']);
}
$this->getPrzelewy24()->getSmarty()->assign(
$templateVars
);
$this->additionalInformation = $this->getPrzelewy24()->fetch(
'module:przelewy24/views/templates/front/payment_option.tpl'
);
$newOptions = array();
$newOption = new PaymentOption();
$newOption->setCallToActionText($text)
->setLogo($this->getPrzelewy24()->getPathUri() . 'views/img/logo_mini.png')
->setAction(
$this->getPrzelewy24()->getContext()->link->getModuleLink(
$this->getPrzelewy24()->name,
'paymentConfirmation',
array(),
true
)
)
->setAdditionalInformation($this->additionalInformation);
$newOptions[] = $newOption;
$newOptions = array_merge($newOptions, $this->getPromotedPayments($params));
return $newOptions;
}
/**
* Get extracharge.
*
* @param float $amount
* @param string $suffix
*
* @return float|int
*/
public function getExtracharge($amount, $suffix = '')
{
$extracharge = 0;
$p24ExtraChangeEnabled = (int)Configuration::get('P24_EXTRA_CHARGE_ENABLED' . $suffix);
$p24ExtraChangePercent = (float)(str_replace(
',',
'.',
Configuration::get('P24_EXTRA_CHARGE_PERCENT' . $suffix)
));
$p24ExtraChangAmount = (float)(str_replace(',', '.', Configuration::get('P24_EXTRA_CHARGE_AMOUNT' . $suffix)));
if (1 === $p24ExtraChangeEnabled) {
$extracharge = $p24ExtraChangAmount;
$amountPercent = round(($amount * ((100 + $p24ExtraChangePercent) / 100)) - $amount, 2);
if ($amountPercent > $p24ExtraChangAmount) {
$extracharge = round($amountPercent, 2);
}
}
return $extracharge;
}
/**
* Set extracharge.
*
* @param Order $order
*/
public function setExtracharge($order)
{
if (!$order instanceof Order) {
return;
}
if ($this->hasExtrachargeOrder($order->id)) {
return;
}
$cart = new Cart($order->id_cart);
$currency = new Currency($cart->id_currency);
$suffix = Przelewy24Helper::getSuffix($currency->iso_code);
$extracharge = number_format($this->getExtracharge($order->total_paid, $suffix), 2);
$order->extra_charge_amount = round($extracharge * 100);
$order->total_paid += $extracharge;
$order->total_paid_tax_excl += $extracharge;
$order->total_paid_tax_incl += $extracharge;
$order->save();
$extracharge = Przelewy24Extracharge::prepareByOrderId($order->id);
$extracharge->extra_charge_amount = $order->extra_charge_amount;
$extracharge->save();
}
/**
* @param int $orderId
*/
public function setExtrachargeByOrderId($orderId)
{
$order = new Order($orderId);
$this->setExtracharge($order);
}
/**
* Get extracharge order id.
*
* @param int $orderId
*
* @return int
*/
public function getExtrachargeOrder($orderId)
{
$extracharge = Przelewy24Extracharge::findOneByOrderId($orderId);
if (!Validate::isLoadedObject($extracharge)) {
return 0;
}
return $extracharge->extra_charge_amount / 100;
}
/**
* Return if the order has an extracharege.
*
* @param int $orderId
*
* @return bool
*/
public function hasExtrachargeOrder($orderId)
{
$extracharge = $this->getExtrachargeOrder($orderId);
return $extracharge > 0;
}
/**
* Get promoted payments.
*
* @param array $params
*
* @return array
* @throws Exception
*/
public function getPromotedPayments($params)
{
$results = array();
if (!Configuration::get('P24_PAYMENT_METHOD_LIST')) {
return $results;
}
$currency = new Currency($params['cart']->id_currency);
$suffix = Przelewy24Helper::getSuffix($currency->iso_code);
$p24Soap = Przelewy24SoapInterfaceFactory::getForSuffix($suffix);
$promotePaymethodList = $p24Soap->getPromotedPaymentList(
Configuration::get('P24_API_KEY' . $suffix),
$currency->iso_code
);
if (!empty($promotePaymethodList['p24_paymethod_list_promote'])) {
foreach ($promotePaymethodList['p24_paymethod_list_promote'] as $key => $item) {
$results[] = $this->getPaymentOption($item, $key);
}
}
$blikPaymentOption = $this->getBlikPaymentOption($params);
if ($blikPaymentOption) {
$results[] = $blikPaymentOption;
}
return $results;
}
/**
* Get blik payment option.
*
* @param array $params
*
* @return PaymentOption|null
* @throws Exception
*/
private function getBlikPaymentOption($params)
{
if (!$params || !isset($params['cart']) || !$params['cart']->id_customer) {
return null;
}
$customer = new Customer((int)$params['cart']->id_customer);
if (!$customer->id || $customer->is_guest) {
return null;
}
// BLIK: Alias UID
$p24BlikSoap = Przelewy24BlikSoapInterfaceFactory::getDefault();
if (((int)Configuration::get('P24_BLIK_UID_ENABLE') > 0) && $p24BlikSoap->testAccess()) {
$newOption = new PaymentOption();
$link = $this->getPrzelewy24()->getContext()->link->getModuleLink(
$this->getPrzelewy24()->name,
'validationBlik',
array('type' => 'UID'),
true
);
$newOption->setCallToActionText($this->getPrzelewy24()->getLangString('Pay with Blik'))
->setLogo($this->getPrzelewy24()->getPathUri() . 'views/img/blik_logo.png')
->setAction($link)
->setAdditionalInformation($this->additionalInformation);
return $newOption;
}
return null;
}
/**
* Get payment option
*
* @param string $title
* @param int $methodId
*
* @return PaymentOption
*/
private function getPaymentOption($title, $methodId)
{
$logoUri = self::BASE_URL_LOGO_P24 . 'logo_' . $methodId . '.gif';
$newOption = new PaymentOption();
$newOption->setCallToActionText($title)
->setLogo($logoUri)
->setAction(
$this->getPrzelewy24()->getContext()->link->getModuleLink(
$this->getPrzelewy24()->name,
'paymentConfirmation',
['payment_method' => $methodId],
true
)
)
->setAdditionalInformation($this->additionalInformation);
return $newOption;
}
}

View File

@@ -0,0 +1,316 @@
<?php
/**
* Class Przelewy24ServicePaymentReturn
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24ServicePaymentReturn
*/
class Przelewy24ServicePaymentReturn extends Przelewy24Service
{
/**
* hookPaymentReturn implementation.
*
* @param array $params
*
* @return array|bool Updated array of parameters is returned otherwise.
* @throws Exception
*/
public function execute($params)
{
if (!$this->getPrzelewy24()->active) {
return false;
}
$lang = $this->getPrzelewy24()->getLangArray();
$order = null;
/** @var $order \PrestaShop\PrestaShop\Adapter\Entity\Order */
if (is_array($params) && isset($params['order'])) {
$order = $params['order'];
$cart = Cart::getCartByOrderId($order->id);
} elseif (isset($params->cart)) {
$cart = $params->cart;
}
$this->getPrzelewy24()->getSmarty()->assign(
'logo_url',
$this->getPrzelewy24()->getPathUri() . 'views/img/logo.png'
);
$s_sid = md5(time());
$servicePaymentOptions = new Przelewy24ServicePaymentOptions(new Przelewy24());
$reference = '';
$status = 'ok';
if (isset($order) && ('przelewy24' === $order->module)) {
if (!$order->hasInvoice() &&
((int)$order->current_state !== (int)Configuration::get('P24_ORDER_STATE_1'))
) {
$order->setCurrentState((int)Configuration::get('P24_ORDER_STATE_1'));
}
$status = ($order->hasInvoice()) ? 'payment' : 'ok';
$reference = $order->reference;
$currency = new Currency($order->id_currency);
$shipping = $cart->getPackageShippingCost((int)$order->id_carrier) * 100;
$amount = Przelewy24Helper::p24AmountFormat($order->total_paid);
$products = $order->getProducts();
$productsInfo = array();
foreach ($products as $value) {
$product = new Product($value['product_id']);
$productsInfo[] = array(
'name' => $product->name[1],
'description' => $product->description_short[1],
'quantity' => (int)$value['product_quantity'],
'price' => (int)($value['product_price'] * 100),
'number' => $value['product_id'],
);
}
$customerId = $order->id_customer;
$description = $lang["Order"] . ': ' . $order->id;
$IdLang = $cart->id_lang;
$totalToPay = Tools::displayPrice(
Przelewy24Helper::p24AmountFormat($order->total_paid) / 100,
$currency,
false
);
if (!$servicePaymentOptions->hasExtrachargeOrder($order->id)) {
$servicePaymentOptions->setExtracharge($order);
}
$extracharge = $servicePaymentOptions->getExtrachargeOrder($order->id);
$currency = new Currency($order->id_currency);
$currencySign = $currency->sign;
} else {
$currency = new Currency($cart->id_currency);
$shipping = $cart->getPackageShippingCost((int)$cart->id_carrier) * 100;
$amount = Przelewy24Helper::p24AmountFormat($cart->getOrderTotal(true, Cart::BOTH));
$products = $cart->getProducts();
$productsInfo = array();
foreach ($products as $product) {
$productsInfo[] = array(
'name' => $product['name'],
'description' => $product['description_short'],
'quantity' => (int)$product['cart_quantity'],
'price' => (int)($product['price'] * 100),
'number' => $product['id_product'],
);
}
$customerId = $cart->id_customer;
$description = $lang["Cart"] . ': ' . $cart->id;
$IdLang = $cart->id_lang;
$suffix = Przelewy24Helper::getSuffix($currency->iso_code);
$extracharge = $servicePaymentOptions->getExtraCharge(
$cart->getOrderTotal(true, Cart::BOTH),
$suffix
);
$totalToPay = Tools::displayPrice(
$cart->getOrderTotal(true, Cart::BOTH) + $extracharge,
$currency,
false
);
if (0 === (int)$amount) {
$status = 'payment';
}
$currencySign = $currency->sign;
}
$suffix = Przelewy24Helper::getSuffix($currency->iso_code);
$p24Class = Przelewy24ClassInterfaceFactory::getForSuffix($suffix);
/** @var Przelewy24Soap $p24Soap */
$p24Soap = Przelewy24SoapInterfaceFactory::getForSuffix($suffix);
$sessionId = $cart->id . '|' . $s_sid;
$customer = new Customer((int)($customerId));
$translations = array(
'virtual_product_name' => $lang['Extra charge [VAT and discounts]'],
'cart_as_product' => $lang['Your order'],
);
$p24Product = new Przelewy24Product($translations);
$p24ProductItems = $p24Product->prepareCartItems($amount, $productsInfo, $shipping);
$addresses = $customer->getAddresses((int)Configuration::get('PS_LANG_DEFAULT'));
$addressObj = array_pop($addresses);
$address = new Address((int)$addressObj['id_address']);
$s_lang = new Country((int)($address->id_country));
$data = array(
'p24_session_id' => $sessionId,
'p24_merchant_id' => Configuration::get('P24_MERCHANT_ID' . $suffix),
'p24_pos_id' => Configuration::get('P24_SHOP_ID' . $suffix),
'p24_email' => $customer->email,
'p24_address' => $address->address1 . " " . $address->address2,
'p24_zip' => $address->postcode,
'p24_city' => $address->city,
'p24_country' => $s_lang->iso_code,
'p24_amount' => $amount,
'p24_currency' => $currency->iso_code,
'shop_name' => $this->getPrzelewy24()->getContext()->shop->name,
'p24_description' => $description,
'cartId' => $cart->id,
'status' => $status,
'p24_url' => $p24Class->trnDirectUrl(),
'p24_url_status' => $this->getPrzelewy24()->getContext()->link->getModuleLink(
'przelewy24',
'paymentStatus',
$order ? ['id_order' => $order->id] : ['id_cart' => $cart->id],
'1' === Configuration::get('PS_SSL_ENABLED')
),
'p24_url_return' => $this->getPrzelewy24()->getContext()->link->getModuleLink(
'przelewy24',
'paymentFinished',
$order ? ['id_order' => $order->id] : ['id_cart' => $cart->id],
'1' === Configuration::get('PS_SSL_ENABLED')
),
'p24_api_version' => P24_VERSION,
'p24_ecommerce' => 'prestashop_' . _PS_VERSION_,
'p24_ecommerce2' => Configuration::get('P24_PLUGIN_VERSION'),
'p24_language' => Tools::strtolower(Language::getIsoById($IdLang)),
'p24_client' => $customer->firstname . ' ' . $customer->lastname,
'p24ProductItems' => $p24ProductItems,
'p24_wait_for_result' => 0,
'p24_shipping' => $shipping,
'total_to_pay' => $totalToPay,
'pay_card_inside_shop' => (int)Configuration::get('P24_PAY_CARD_INSIDE_ENABLE' . $suffix),
'customer_is_guest' => (int)$customer->is_guest,
'logo_url' => $this->getPrzelewy24()->getPathUri() . 'views/img/logo.png',
'validationRequired' => Configuration::get('P24_VERIFYORDER' . $suffix),
'validationLink' => $this->getPrzelewy24()->getContext()->link->getModuleLink(
'przelewy24',
'validateOrderRequest',
array(),
'1' === Configuration::get('PS_SSL_ENABLED')
),
);
$data['p24_sign'] = $p24Class->trnDirectSign($data);
$data['p24_paymethod_graphics'] = Configuration::get('P24_GRAPHICS_PAYMENT_METHOD_LIST' . $suffix);
$data['nav_more_less_path'] = dirname($this->getPrzelewy24()->getBaseFile()) .
'/views/templates/hook/parts/nav_more_less.tpl';
$data['reference'] = $reference;
$paymentMethod = (int)Tools::getValue('payment_method');
if ($paymentMethod > 0 && Configuration::get('P24_PAYMENT_METHOD_LIST' . $suffix)) {
$paymentMethod = (int)Tools::getValue('payment_method');
$promotePaymethodList = $p24Soap->getPromotedPaymentList(
Configuration::get('P24_API_KEY' . $suffix),
$currency->iso_code
);
if (!empty($promotePaymethodList['p24_paymethod_list_promote']) &&
!empty($promotePaymethodList['p24_paymethod_list_promote'][$paymentMethod])) {
$data['payment_method_selected_name'] =
$promotePaymethodList['p24_paymethod_list_promote'][$paymentMethod];
} else {
$paymentMethod = 0;// not available method
}
}
$data['payment_method_selected_id'] = $paymentMethod;
$data['card_remember_input'] = false;
$data['remember_customer_cards'] = Przelewy24CustomerSetting::initialize($customer->id)->card_remember;
// oneClick
if (Przelewy24OneClickHelper::isOneClickEnable($suffix)) {
if (0 === $paymentMethod || in_array($paymentMethod, Przelewy24OneClickHelper::getCardPaymentIds())) {
$data['card_remember_input'] = true;
}
$data['p24_ajax_notices_url'] = $this->getPrzelewy24()->getContext()->link->getModuleLink(
'przelewy24',
'ajaxNotices',
array('card_remember' => 1),
'1' === Configuration::get('PS_SSL_ENABLED')
);
$data['customer_cards'] = Przelewy24Recurring::findArrayByCustomerId($customer->id);
$data['charge_card_url'] = $this->getPrzelewy24()->getContext()->link->getModuleLink(
'przelewy24',
'chargeCard',
array('id_cart' => (int)$cart->id)
);
}
if ($paymentMethod) {
$data['P24_PAYMENT_METHOD_LIST'] = false;
} else {
$data['P24_PAYMENT_METHOD_LIST'] = Configuration::get('P24_PAYMENT_METHOD_LIST' . $suffix);
}
if (Configuration::get('P24_PAYMENT_METHOD_LIST' . $suffix)) {
// payments method list and order
$paymethodList = $p24Soap->getFirstAndSecondPaymentList(
Configuration::get('P24_API_KEY' . $suffix),
$currency->iso_code
);
$data['p24_paymethod_list_first'] = $paymethodList['p24_paymethod_list_first'];
$data['p24_paymethod_list_second'] = $paymethodList['p24_paymethod_list_second'];
$data['p24_paymethod_description'] = $p24Soap->replacePaymentDescriptionsListToOwn(
$p24Soap->availablePaymentMethods(Configuration::get('P24_API_KEY' . $suffix)),
$suffix
);
}
$data['p24_method'] = false;
// Payment with BLIK UID
if ('UID' === Tools::getValue('blik_type')) {
$blikAlias = false;
if ($customer->id) {
$blikAlias = Przelewy24BlikHelper::getSavedAlias($customer);
}
$data['p24_method'] = 'blik_uid';
$data['P24_PAYMENT_METHOD_LIST'] = false;
$data['card_remember_input'] = false;
$data['p24_blik_code'] = true;
$data['p24_blik_alias'] = $blikAlias;
$data['p24_url'] = $this->getPrzelewy24()->getContext()->link->getModuleLink(
'przelewy24',
'chargeBlik',
array('id_order' => (int)Tools::getValue('id_order'))
);
$data['p24_blik_websocket'] = Przelewy24BlikHelper::getWebsocketHost(
(bool)Configuration::get('P24_TEST_MODE' . $suffix)
);
$data['p24_shop_order_id'] = (int)Tools::getValue('id_order');
$data['p24_payment_failed_url'] = $this->getPrzelewy24()->getContext()->link->getModuleLink(
'przelewy24',
'paymentFailed',
array('id_order' => (int)Tools::getValue('id_order'))
);
$data['p24_blik_ajax_verify_url'] = $this->getPrzelewy24()->getContext()->link->getModuleLink(
'przelewy24',
'ajaxVerifyBlik'
);
$data['p24_blik_error_url'] = $this->getPrzelewy24()->getContext()->link->getModuleLink(
'przelewy24',
'ajaxBlikError'
);
}
if (!$order) {
$data['p24_amount'] = $data['p24_amount'] + ($extracharge * 100);
}
$data['extracharge'] = $extracharge;
$data['extrachargeFormatted'] = number_format($extracharge, 2, ',', ' ');
$data['currencySign'] = $currencySign;
$data['p24_sign'] = $p24Class->trnDirectSign($data);
if ((0 === (int)Configuration::get('P24_VERIFYORDER' . $suffix)) || isset($order)) {
return $this->getPrzelewy24()->getSmarty()->assign($data);
}
return $data;
}
}

View File

@@ -0,0 +1,315 @@
<?php
/**
* Class Przelewy24ServiceRefund
*
* This service has the features required for cash returns.
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24ServiceRefund
*/
class Przelewy24ServiceRefund extends Przelewy24Service
{
/**
* Currency suffix.
*
* @var string
*/
private $suffix = '';
/**
* P24 soap api client.
*
* @var SoapClient
*/
private $soap;
/**
* Array of allowed refund statuses.
*
* @var array
*/
private $status = array(
0 => 'Refund error',
1 => 'Refund done',
3 => 'Awaiting for refund',
4 => 'Refund rejected',
);
/**
* Default refund status.
*
* @var string
*/
private $statusDefault = 'Unknown status of refund';
/**
* Przelewy24ServiceRefund constructor.
*
* @param Przelewy24 $przelewy24
* @param string $suffix
* @param Przelewy24Soap $przelewy24Soap
*/
public function __construct(Przelewy24 $przelewy24, $suffix, $przelewy24Soap)
{
$this->setSuffix($suffix);
$this->soap = $przelewy24Soap->getSoapClient();
parent::__construct($przelewy24);
}
/**
* Set suffix.
*
* @param string $suffix
*/
public function setSuffix($suffix)
{
$this->suffix = $suffix;
}
/**
* Get refunds.
*
* @param int $orderId
*
* @return array
*/
public function getRefunds($orderId)
{
$return = array();
try {
$soap = $this->soap;
$result = $soap->GetRefundInfo(
Configuration::get('P24_MERCHANT_ID' . $this->suffix),
Configuration::get('P24_API_KEY' . $this->suffix),
$orderId
);
if ($result && is_array($result->result)) {
$maxToRefund = 0;
$refunds = array();
foreach ($result->result as $key => $value) {
$refunds[$key]['amount_refunded'] = $value->amount;
$date = new DateTime($value->date);
$refunds[$key]['created'] = $date->format('Y-m-d H:i:s');
$refunds[$key]['status'] = $this->getStatusMessage($value->status);
if ((1 === $value->status) || (3 === $value->status)) {
$maxToRefund += $value->amount;
}
}
$return = array(
'maxToRefund' => $maxToRefund,
'refunds' => $refunds,
);
}
return $return;
} catch (Exception $e) {
PrestaShopLogger::addLog(__METHOD__ . ' ' . $e->getMessage(), 1);
return array();
}
}
/**
* Get status message.
*
* @param integer $status
*
* @return string
*/
public function getStatusMessage($status)
{
$status = (int)$status;
$return = $this->statusDefault;
if (isset($this->status[$status])) {
$return = $this->status[$status];
}
return $return;
}
/**
* Check if refund is possible and returns data to refund.
*
* @param int $orderId
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function checkIfRefundIsPossibleAndReturnDataToRefund($orderId)
{
$return = array();
$dataFromDB = $this->getRefundDataFromDB($orderId);
if ($dataFromDB) {
$dataFromP24 = $this->checkIfPaymentCompletedUsingWSAndReturnData($dataFromDB['sessionId']);
if ($dataFromP24) {
$return = array(
'sessionId' => $dataFromDB['sessionId'],
'amount' => isset($dataFromP24->result->amount) ? (int)$dataFromP24->result->amount : 0,
'p24OrderId' => isset($dataFromP24->result->orderId) ? (int)$dataFromP24->result->orderId : 0,
);
}
}
return $return;
}
/**
* Check if payment is completed using ws and return data.
*
* @param $sessionId
*
* @return bool
*/
public function checkIfPaymentCompletedUsingWSAndReturnData($sessionId)
{
try {
$soap = $this->soap;
$result = $soap->GetTransactionBySessionId(
Configuration::get('P24_MERCHANT_ID' . $this->suffix),
Configuration::get('P24_API_KEY' . $this->suffix),
$sessionId
);
if (isset($result->error->errorCode, $result->result->status) &&
(($result->error->errorCode > 0) || (2 !== (int)$result->result->status))
) {
return false;
}
return $result;
} catch (Exception $e) {
PrestaShopLogger::addLog(__METHOD__ . ' ' . $e->getMessage(), 1);
return false;
}
}
/**
* Gets refund data from database.
*
* @param $orderId
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getRefundDataFromDB($orderId)
{
$return = array();
$orderId = (int)$orderId;
$przelewy24Order = new Przelewy24Order();
$result = $przelewy24Order->getByPshopOrderId($orderId);
if ($result) {
$return = array(
'sessionId' => $result->p24_session_id,
'p24OrderId' => $result->p24_order_id,
);
}
return $return;
}
/**
* Requests refund by Przelewy24.
*
* @param string $sessionId
* @param int $p24OrderId
* @param float $amountToRefund
*
* @return false|stdClass
*/
public function refundProcess($sessionId, $p24OrderId, $amountToRefund)
{
$refunds = array(
array(
'sessionId' => $sessionId,
'orderId' => $p24OrderId,
'amount' => $amountToRefund,
),
);
try {
return $this->soap->refundTransaction(
Configuration::get('P24_MERCHANT_ID' . $this->suffix),
Configuration::get('P24_API_KEY' . $this->suffix),
time(),
$refunds
);
} catch (Exception $e) {
PrestaShopLogger::addLog(__METHOD__ . ' ' . $e->getMessage(), 1);
return false;
}
}
/**
* The function checks the availability of the following functions :
* GetTransactionBySessionId
* RefundTransaction
*
* @return bool
*/
public function checkRefundFunction()
{
try {
return (
$this->soapMethodExists('GetTransactionBySessionId') &&
$this->soapMethodExists('RefundTransaction')
);
} catch (Exception $e) {
PrestaShopLogger::addLog(__METHOD__ . ' ' . $e->getMessage(), 1);
return false;
}
}
/**
* The function checks the availability of the following functions :
* GetRefundInfo
*
* @return bool
*/
public function checkGetRefundInfo()
{
try {
return ($this->soapMethodExists('GetRefundInfo'));
} catch (Exception $e) {
PrestaShopLogger::addLog(__METHOD__ . ' ' . $e->getMessage(), 1);
return false;
}
}
/**
* Checks if soap method exists.
*
* @param string $method
*
* @return bool
*/
private function soapMethodExists($method)
{
$return = false;
$list = $this->soap->__getFunctions();
if (is_array($list)) {
foreach ($list as $line) {
$explodeLine = explode(' ', $line, 2);
if (array_key_exists(1, $explodeLine) && (0 === strpos($explodeLine[1], $method))) {
$return = true;
break;
}
}
}
return $return;
}
}

View File

@@ -0,0 +1,419 @@
<?php
/**
* Class Przelewy24Soap
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24Soap
*/
class Przelewy24Soap extends Przelewy24SoapAbstract implements
Przelewy24SoapInterface,
Przelewy24ValidatorSoapInterface
{
/**
* Url of wsdl service.
*
* @var string
*/
protected $wsdlService;
/**
* Przelewy24Soap constructor.
*
* @param Przelewy24ClassInterface $p24Class
* @param int $merchantId
* @param int $posId
* @param string $salt
* @param bool $testMode
* @throws SoapFault
*/
public function __construct(Przelewy24ClassInterface $p24Class, $merchantId, $posId, $salt, $testMode)
{
$this->wsdlService = 'external/' . $merchantId . '.wsdl';
return parent::__construct($p24Class, $merchantId, $posId, $salt, $testMode);
}
/**
* @return SoapClient
*/
public function getSoapClient()
{
return $this->soap;
}
/**
* Returns non pln payment channels.
*
* @param array $paymethodList
*
* @return array
*/
public static function getChannelsNonPln($paymethodList)
{
$channelsNonPln = array(124, 140, 145, 152, 66, 92, 218);
foreach (array_keys($paymethodList) as $key) {
if (!in_array($key, $channelsNonPln)) {
unset($paymethodList[$key]);
}
}
return $paymethodList;
}
/**
* Sets wsdl charge card service (in place of default wsdl for customer).
*/
public function setWsdlChargeCardService()
{
if ($this->p24Class) {
$this->wsdlService = 'external/wsdl/charge_card_service.php?wsdl';
$this->soap = new SoapClient(
$this->p24Class->getHost() . $this->wsdlService,
array('trace' => true, 'exceptions' => true, 'cache_wsdl' => WSDL_CACHE_NONE)
);
}
}
/**
* Tests api access.
*
* @param string $apiKey
*
* @return bool
*/
public function apiTestAccess($apiKey)
{
$access = false;
if (!$this->soap) {
return false;
}
try {
$res = $this->soap->TestAccess($this->posId, $apiKey);
if (!empty($res) && is_bool($res)) {
$access = $res;
}
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
}
return $access;
}
/**
* Checks card recurrence.
*
* @return bool
*/
public function checkCardRecurrency()
{
$have = false;
$this->setWsdlChargeCardService();
if (!$this->soap) {
return false;
}
try {
$res = $this->soap->checkRecurrency($this->posId, $this->salt);
if (!empty($res) && is_bool($res)) {
$have = $res;
}
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
}
return $have;
}
/**
* Validates credentials.
*
* @return bool
*/
public function validateCredentials()
{
$ret = array();
if (!$this->soap) {
return false;
}
try {
$ret = $this->p24Class->testConnection();
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
}
if (isset($ret['error']) && 0 === (int)$ret['error']) {
return true;
}
return false;
}
/**
* Returns available payment methods.
*
* @param string $apiKey
*
* @return array
*/
public function availablePaymentMethods($apiKey)
{
$result = array();
if (!$this->soap) {
return $result;
}
try {
$res = $this->soap->PaymentMethods($this->posId, $apiKey, Context::getContext()->language->iso_code);
if ($res && isset($res->error->errorCode) && 0 === $res->error->errorCode && is_array($res->result)) {
$is218MethodSet = false;
foreach ($res->result as $item) {
if ($item->status) {
$result[$item->id] = $item->name;
if (218 === (int)$item->id) {
$is218MethodSet = true;
}
}
}
if ($is218MethodSet) {
unset($result[142], $result[145]);
}
}
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
}
return $result;
}
/**
* Get payment list.
*
* @param string $apiKey
* @param string $currency
* @param string $firstConfName
* @param bool $secondConfName
*
* @return array
*/
private function getPaymentList($apiKey, $currency, $firstConfName, $secondConfName = false)
{
$suffix = Przelewy24Helper::getSuffix($currency);
$paymethodListFirst = array();
$paymethodListSecond = array();
$paymethodList = $this->availablePaymentMethods($apiKey);
if ($suffix) {
$paymethodList = $this->getChannelsNonPln($paymethodList);
}
$paymethodList = $this->replacePaymentDescriptionsListToOwn($paymethodList, $suffix);
$firstList = Configuration::get($firstConfName . $suffix);
$firstList = explode(',', $firstList);
$secondList = array();
if ($secondConfName) {
$secondList = Configuration::get($secondConfName . $suffix);
$secondList = explode(',', $secondList);
}
if (count($firstList)) {
foreach ($firstList as $item) {
if ((int)$item > 0 && isset($paymethodList[(int)$item])) {
$paymethodListFirst[(int)$item] = $paymethodList[(int)$item];
unset($paymethodList[(int)$item]);
}
}
}
if (count($secondList)) {
foreach ($secondList as $item) {
if ((int)$item > 0 && isset($paymethodList[(int)$item])) {
$paymethodListSecond[(int)$item] = $paymethodList[(int)$item];
unset($paymethodList[(int)$item]);
}
}
}
$paymethodListSecond = $paymethodListSecond + $paymethodList;
return array($paymethodListFirst, $paymethodListSecond);
}
/**
* Replace payment names in array with user defined.
*
* @param array $paymethodList
* @param $suffix
* @return array
*/
public function replacePaymentDescriptionsListToOwn(array $paymethodList, $suffix)
{
foreach ($paymethodList as $bankId => $bankName) {
if (($value = $this->replacePaymentDescriptionToOwn($bankId, $bankName, $suffix)) !== false) {
$paymethodList[$bankId] = $value;
}
}
return $paymethodList;
}
/**
* Replace payment method name to user defined.
*
* @param $bankId
* @param $bankName
* @param $suffix
* @return bool
*/
private function replacePaymentDescriptionToOwn($bankId, $bankName, $suffix)
{
if (($value = Configuration::get("P24_PAYMENT_DESCRIPTION_{$bankId}{$suffix}")) && ($value !== $bankName)) {
return $value;
}
return false;
}
/**
* Get first and second payment list.
*
* @param string $apiKey
* @param string $currency
*
* @return array
*/
public function getFirstAndSecondPaymentList($apiKey, $currency)
{
list($paymethodListFirst, $paymethodListSecond) = $this->getPaymentList(
$apiKey,
$currency,
'P24_PAYMENTS_ORDER_LIST_FIRST',
'P24_PAYMENTS_ORDER_LIST_SECOND'
);
return array(
'p24_paymethod_list_first' => $paymethodListFirst,
'p24_paymethod_list_second' => $paymethodListSecond,
);
}
/**
* Get promoted payment list.
*
* @param string $apiKey
* @param string $currency
*
* @return array
*/
public function getPromotedPaymentList($apiKey, $currency)
{
list($paymethodListFirst, $paymethodListSecond) = $this->getPaymentList(
$apiKey,
$currency,
'P24_PAYMENTS_PROMOTE_LIST',
false
);
return array(
'p24_paymethod_list_promote' => $paymethodListFirst,
'p24_paymethod_list_promote_2' => $paymethodListSecond,
);
}
/**
* Get card reference one click with check card.
*
* @param string $apiKey
* @param int $orderId
*
* @return array
*/
public function getCardReferenceOneClickWithCheckCard($apiKey, $orderId)
{
$orderId = (int)$orderId;
$result = array();
try {
$this->setWsdlChargeCardService();
if (empty($this->soap)) {
throw new Exception('Null pointer: SOAP');
}
$res = $this->soap->GetTransactionReference($this->posId, $apiKey, $orderId);
if ($res && isset($res->error->errorCode) && (0 === $res->error->errorCode) && !empty($res->result)) {
$ref = $res->result->refId;
$hasRecurency = $this->soap->CheckCard($this->posId, $apiKey, $ref);
if ((0 === $hasRecurency->error->errorCode) && $hasRecurency->result) {
return $res->result;
} else {
PrestaShopLogger::addLog('Błędny oneclick_order_id dla orderId: ' . $orderId, 1);
}
} else {
PrestaShopLogger::addLog(
'Błąd dla metody GetTransactionReference: [order_id: ' . $orderId . ']: ' .
print_r($res, true),
1
);
}
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
}
return $result;
}
/**
* Charges card.
*
* @param string $apiKey
* @param string $cardRefId
* @param int $amount
* @param string $currency
* @param string $email
* @param string $sessionId
* @param string $client
* @param string $description
*
* @return null|string
*/
public function chargeCard($apiKey, $cardRefId, $amount, $currency, $email, $sessionId, $client, $description)
{
$p24OrderId = null;
if (!$this->soap) {
return $p24OrderId;
}
$this->setWsdlChargeCardService();
try {
$res = $this->soap->ChargeCard(
$this->posId,
$apiKey,
$cardRefId,
$amount,
$currency,
$email,
$sessionId,
$client,
$description
);
if (!empty($res)) {
if ('0' === (string)$res->error->errorCode) {
$p24OrderId = (string)$res->result->orderId;
} else {
PrestaShopLogger::addLog(print_r($res->error, true), 1);
}
}
} catch (Exception $e) {
PrestaShopLogger::addLog($e->getMessage(), 1);
}
return $p24OrderId;
}
}

View File

@@ -0,0 +1,92 @@
<?php
/**
* Class Przelewy24SoapAbstract
*
* @author Przelewy24
* @copyright Przelewy24
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html
*
*/
/**
* Class Przelewy24SoapAbstract
*/
abstract class Przelewy24SoapAbstract
{
/**
* Url of wsdl service.
*
* @var string
*/
protected $wsdlService;
/**
* Przelewy24 library class (used to communicate with P24).
*
* @var Przelewy24Class
*/
protected $p24Class;
/**
* Merchant id.
*
* @var int
*/
protected $merchantId;
/**
* Shop id.
*
* @var int
*/
protected $posId;
/**
* String used to ensure safety during communication with P24.
*
* @var string
*/
protected $salt;
/**
* Soap client.
*
* @var SoapClient
*/
protected $soap = null;
/**
* Test mode
*
* @var boolean
*/
protected $testMode;
/**
* Przelewy24SoapAbstract constructor.
*
* @param Przelewy24ClassInterface $p24Class
* @param int $merchantId
* @param int $posId
* @param string $salt
* @param bool $testMode
* @throws SoapFault
*/
public function __construct(Przelewy24ClassInterface $p24Class, $merchantId, $posId, $salt, $testMode = false)
{
if (($merchantId <= 0) || ($posId <= 0) || empty($salt)) {
throw new LogicException('The provided parameters for the class are invalid.');
} else {
$this->p24Class = $p24Class;
$this->merchantId = $merchantId;
$this->posId = $posId;
$this->salt = $salt;
$this->testMode = $testMode;
$this->soap = new SoapClient(
$this->p24Class->getHost() . $this->wsdlService,
array('trace' => true, 'exceptions' => true, 'cache_wsdl' => WSDL_CACHE_NONE)
);
}
}
}

View File

@@ -0,0 +1,36 @@
<?php
/*
* 2007-2017 PrestaShop
*
* 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2016 PrestaShop SA
* @version Release: $Revision$
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Location: ../");
exit;