first commit

This commit is contained in:
2025-03-12 17:06:23 +01:00
commit 2241f7131f
13185 changed files with 1692479 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
<?php
/**
* SOTESHOP/stPlatnosciPlPlugin
*
* Ten plik należy do aplikacji stPlatnosciPlPlugin opartej na licencji (Professional License SOTE).
* Nie zmieniaj tego pliku, jeśli chcesz korzystać z automatycznych aktualizacji oprogramowania.
* Jeśli chcesz wprowadzać swoje modyfikacje do programu, zapoznaj się z dokumentacją, jak zmieniać
* oprogramowanie bez zmiany kodu bazowego http://www.sote.pl/modifications
*
* @package stPlatnosciPlPlugin
* @subpackage configs
* @copyright SOTE (www.sote.pl)
* @license http://www.sote.pl/license/sote (Professional License SOTE)
* @version $Id: config.php 16126 2011-11-15 14:11:22Z michal $
* @author Michal Prochowski <michal.prochowski@sote.pl>
*/
/**
* Dodanie informacji o istnieniu płatności
*/
stPluginHelper::addConfigValue('stPaymentType', 'stPlatnosciPlPlugin', array('name' => 'stPlatnosciPl', 'description' => 'Płatność przez serwis PayU'));
/**
* Włączanie modułu
*/
stPluginHelper::addEnableModule('stPlatnosciPlBackend', 'backend');
stPluginHelper::addEnableModule('stPlatnosciPlFrontend', 'frontend');
/**
* Dodawania routingu
*/
stPluginHelper::addRouting('stPlatnosciPlPlugin', '/platnoscipl', 'stPlatnosciPlBackend', 'index', 'backend');
stPluginHelper::addRouting('stPlatnosciPlPlugin', '/platnoscipl/:action/*', 'stPlatnosciPlFrontend', 'config', 'frontend');
stLicenseTypeHelper::addCommercialModule('stPlatnosciPlPlugin');

View File

@@ -0,0 +1,12 @@
<?php
interface AuthType
{
/**
* @return array
*/
public function getHeaders();
}

View File

@@ -0,0 +1,33 @@
<?php
class AuthType_Basic implements AuthType
{
/**
* @var string
*/
private $authBasicToken;
public function __construct($posId, $signatureKey)
{
if (empty($posId)) {
throw new OpenPayU_Exception_Configuration('PosId is empty');
}
if (empty($signatureKey)) {
throw new OpenPayU_Exception_Configuration('SignatureKey is empty');
}
$this->authBasicToken = base64_encode($posId . ':' . $signatureKey);
}
public function getHeaders()
{
return array(
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Basic ' . $this->authBasicToken
);
}
}

View File

@@ -0,0 +1,39 @@
<?php
class AuthType_Oauth implements AuthType
{
/**
* @var OauthResultClientCredentials
*/
private $oauthResult;
public function __construct($clientId, $clientSecret)
{
if (empty($clientId)) {
throw new OpenPayU_Exception_Configuration('ClientId is empty');
}
if (empty($clientSecret)) {
throw new OpenPayU_Exception_Configuration('ClientSecret is empty');
}
try {
$this->oauthResult = OpenPayU_Oauth::getAccessToken();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception('Oauth error: [code=' . $e->getCode() . '], [message=' . $e->getMessage() . ']');
}
}
public function getHeaders()
{
return array(
'Content-Type: application/json',
'Accept: */*',
'Authorization: Bearer ' . $this->oauthResult->getAccessToken()
);
}
}

View File

@@ -0,0 +1,14 @@
<?php
class AuthType_TokenRequest implements AuthType
{
public function getHeaders()
{
return array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: */*'
);
}
}

View File

@@ -0,0 +1,424 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) 2011-2017 PayU
* @license http://opensource.org/licenses/LGPL-3.0 Open Software License (LGPL 3.0)
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Configuration
{
private static $_availableEnvironment = array('custom', 'secure', 'sandbox');
private static $_availableHashAlgorithm = array('SHA', 'SHA-256', 'SHA-384', 'SHA-512');
private static $env = 'secure';
/**
* Merchant Pos ID for Auth Basic and Notification Consume
*/
private static $merchantPosId = '';
/**
* Signature Key for Auth Basic and Notification Consume
*/
private static $signatureKey = '';
/**
* OAuth protocol - default type
*/
private static $oauthGrantType = OauthGrantType::CLIENT_CREDENTIAL;
/**
* OAuth protocol - client_id
*/
private static $oauthClientId = '';
/**
* OAuth protocol - client_secret
*/
private static $oauthClientSecret = '';
/**
* OAuth protocol - email
*/
private static $oauthEmail = '';
/**
* OAuth protocol - extCustomerId
*/
private static $oauthExtCustomerId;
/**
* OAuth protocol - endpoint address
*/
private static $oauthEndpoint = '';
/**
* OAuth protocol - methods for token cache
*/
private static $oauthTokenCache = null;
/**
* Proxy - host
*/
private static $proxyHost = null;
/**
* Proxy - port
*/
private static $proxyPort = null;
/**
* Proxy - user
*/
private static $proxyUser = null;
/**
* Proxy - password
*/
private static $proxyPassword = null;
private static $serviceUrl = '';
private static $hashAlgorithm = 'SHA-256';
private static $sender = 'Generic';
const API_VERSION = '2.1';
const COMPOSER_JSON = "/composer.json";
const DEFAULT_SDK_VERSION = 'PHP SDK 2.2.10';
const OAUTH_CONTEXT = 'pl/standard/user/oauth/authorize';
/**
* @return string
*/
public static function getApiVersion()
{
return self::API_VERSION;
}
/**
* @param string
* @throws OpenPayU_Exception_Configuration
*/
public static function setHashAlgorithm($value)
{
if (!in_array($value, self::$_availableHashAlgorithm)) {
throw new OpenPayU_Exception_Configuration('Hash algorithm "' . $value . '"" is not available');
}
self::$hashAlgorithm = $value;
}
/**
* @return string
*/
public static function getHashAlgorithm()
{
return self::$hashAlgorithm;
}
/**
* @param string $environment
* @param string $domain
* @param string $api
* @param string $version
* @throws OpenPayU_Exception_Configuration
*/
public static function setEnvironment($environment = 'secure', $domain = 'payu.com', $api = 'api/', $version = 'v2_1/')
{
$environment = strtolower($environment);
$domain = strtolower($domain) . '/';
if (!in_array($environment, self::$_availableEnvironment)) {
throw new OpenPayU_Exception_Configuration($environment . ' - is not valid environment');
}
self::$env = $environment;
if ($environment == 'secure') {
self::$serviceUrl = 'https://' . $environment . '.' . $domain . $api . $version;
self::$oauthEndpoint = 'https://' . $environment . '.' . $domain . self::OAUTH_CONTEXT;
} else if ($environment == 'sandbox') {
self::$serviceUrl = 'https://secure.snd.' . $domain . $api . $version;
self::$oauthEndpoint = 'https://secure.snd.' . $domain . self::OAUTH_CONTEXT;
} else if ($environment == 'custom') {
self::$serviceUrl = $domain . $api . $version;
self::$oauthEndpoint = $domain . self::OAUTH_CONTEXT;
}
}
/**
* @return string
*/
public static function getServiceUrl()
{
return self::$serviceUrl;
}
/**
* @return string
*/
public static function getOauthEndpoint()
{
return self::$oauthEndpoint;
}
/**
* @return string
*/
public static function getEnvironment()
{
return self::$env;
}
/**
* @param string
*/
public static function setMerchantPosId($value)
{
self::$merchantPosId = trim($value);
}
/**
* @return string
*/
public static function getMerchantPosId()
{
return self::$merchantPosId;
}
/**
* @param string
*/
public static function setSignatureKey($value)
{
self::$signatureKey = trim($value);
}
/**
* @return string
*/
public static function getSignatureKey()
{
return self::$signatureKey;
}
/**
* @return string
*/
public static function getOauthGrantType()
{
return self::$oauthGrantType;
}
/**
* @param string $oauthGrantType
* @throws OpenPayU_Exception_Configuration
*/
public static function setOauthGrantType($oauthGrantType)
{
if ($oauthGrantType !== OauthGrantType::CLIENT_CREDENTIAL && $oauthGrantType !== OauthGrantType::TRUSTED_MERCHANT) {
throw new OpenPayU_Exception_Configuration('Oauth grand type "' . $oauthGrantType . '"" is not available');
}
self::$oauthGrantType = $oauthGrantType;
}
/**
* @return string
*/
public static function getOauthClientId()
{
return self::$oauthClientId;
}
/**
* @return string
*/
public static function getOauthClientSecret()
{
return self::$oauthClientSecret;
}
/**
* @param mixed $oauthClientId
*/
public static function setOauthClientId($oauthClientId)
{
self::$oauthClientId = trim($oauthClientId);
}
/**
* @param mixed $oauthClientSecret
*/
public static function setOauthClientSecret($oauthClientSecret)
{
self::$oauthClientSecret = trim($oauthClientSecret);
}
/**
* @return mixed
*/
public static function getOauthEmail()
{
return self::$oauthEmail;
}
/**
* @param mixed $oauthEmail
*/
public static function setOauthEmail($oauthEmail)
{
self::$oauthEmail = $oauthEmail;
}
/**
* @return mixed
*/
public static function getOauthExtCustomerId()
{
return self::$oauthExtCustomerId;
}
/**
* @param mixed $oauthExtCustomerId
*/
public static function setOauthExtCustomerId($oauthExtCustomerId)
{
self::$oauthExtCustomerId = $oauthExtCustomerId;
}
/**
* @return null | OauthCacheInterface
*/
public static function getOauthTokenCache()
{
return self::$oauthTokenCache;
}
/**
* @param OauthCacheInterface $oauthTokenCache
* @throws OpenPayU_Exception_Configuration
*/
public static function setOauthTokenCache($oauthTokenCache)
{
if (!$oauthTokenCache instanceof OauthCacheInterface) {
throw new OpenPayU_Exception_Configuration('Oauth token cache class is not instance of OauthCacheInterface');
}
self::$oauthTokenCache = $oauthTokenCache;
}
/**
* @return string | null
*/
public static function getProxyHost()
{
return self::$proxyHost;
}
/**
* @param string | null $proxyHost
*/
public static function setProxyHost($proxyHost)
{
self::$proxyHost = $proxyHost;
}
/**
* @return int | null
*/
public static function getProxyPort()
{
return self::$proxyPort;
}
/**
* @param int | null $proxyPort
*/
public static function setProxyPort($proxyPort)
{
self::$proxyPort = $proxyPort;
}
/**
* @return string | null
*/
public static function getProxyUser()
{
return self::$proxyUser;
}
/**
* @param string | null $proxyUser
*/
public static function setProxyUser($proxyUser)
{
self::$proxyUser = $proxyUser;
}
/**
* @return string | null
*/
public static function getProxyPassword()
{
return self::$proxyPassword;
}
/**
* @param string | null $proxyPassword
*/
public static function setProxyPassword($proxyPassword)
{
self::$proxyPassword = $proxyPassword;
}
/**
* @param string $sender
*/
public static function setSender($sender)
{
self::$sender = $sender;
}
/**
* @return string
*/
public static function getSender()
{
return self::$sender;
}
/**
* @return string
*/
public static function getFullSenderName()
{
return sprintf("%s@%s", self::getSender(), self::getSdkVersion());
}
/**
* @return string
*/
public static function getSdkVersion()
{
$composerFilePath = self::getComposerFilePath();
if (file_exists($composerFilePath)) {
$fileContent = file_get_contents($composerFilePath);
$composerData = json_decode($fileContent);
if (isset($composerData->version) && isset($composerData->extra[0]->engine)) {
return sprintf("%s %s", $composerData->extra[0]->engine, $composerData->version);
}
}
return self::DEFAULT_SDK_VERSION;
}
/**
* @return string
*/
private static function getComposerFilePath()
{
return realpath(dirname(__FILE__)) . '/../../' . self::COMPOSER_JSON;
}
}

View File

@@ -0,0 +1,167 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) 2011-2016 PayU
* @license http://opensource.org/licenses/LGPL-3.0 Open Software License (LGPL 3.0)
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Http
{
/**
* @param string $pathUrl
* @param string $data
* @param AuthType $authType
* @return mixed
* @throws OpenPayU_Exception_Configuration
* @throws OpenPayU_Exception_Network
*/
public static function doPost($pathUrl, $data, $authType)
{
$response = OpenPayU_HttpCurl::doPayuRequest('POST', $pathUrl, $authType, $data);
return $response;
}
/**
* @param string $pathUrl
* @param AuthType $authType
* @return mixed
* @throws OpenPayU_Exception_Configuration
* @throws OpenPayU_Exception_Network
*/
public static function doGet($pathUrl, $authType)
{
$response = OpenPayU_HttpCurl::doPayuRequest('GET', $pathUrl, $authType);
return $response;
}
/**
* @param string $pathUrl
* @param AuthType $authType
* @return mixed
* @throws OpenPayU_Exception_Configuration
* @throws OpenPayU_Exception_Network
*/
public static function doDelete($pathUrl, $authType)
{
$response = OpenPayU_HttpCurl::doPayuRequest('DELETE', $pathUrl, $authType);
return $response;
}
/**
* @param string $pathUrl
* @param string $data
* @param AuthType $authType
* @return mixed
* @throws OpenPayU_Exception_Configuration
* @throws OpenPayU_Exception_Network
*/
public static function doPut($pathUrl, $data, $authType)
{
$response = OpenPayU_HttpCurl::doPayuRequest('PUT', $pathUrl, $authType, $data);
return $response;
}
/**
* @param $statusCode
* @param null $message
* @throws OpenPayU_Exception
* @throws OpenPayU_Exception_Request
* @throws OpenPayU_Exception_Authorization
* @throws OpenPayU_Exception_Network
* @throws OpenPayU_Exception_ServerMaintenance
* @throws OpenPayU_Exception_ServerError
*/
public static function throwHttpStatusException($statusCode, $message = null)
{
$response = $message->getResponse();
$statusDesc = isset($response->status->statusDesc) ? $response->status->statusDesc : '';
switch ($statusCode) {
case 400:
throw new OpenPayU_Exception_Request($message, $message->getStatus().' - '.$statusDesc, $statusCode);
break;
case 401:
case 403:
throw new OpenPayU_Exception_Authorization($message->getStatus().' - '.$statusDesc, $statusCode);
break;
case 404:
throw new OpenPayU_Exception_Network($message->getStatus().' - '.$statusDesc, $statusCode);
break;
case 408:
throw new OpenPayU_Exception_ServerError('Request timeout', $statusCode);
break;
case 500:
throw new OpenPayU_Exception_ServerError('PayU system is unavailable or your order is not processed.
Error:
[' . $statusDesc . ']', $statusCode);
break;
case 503:
throw new OpenPayU_Exception_ServerMaintenance('Service unavailable', $statusCode);
break;
default:
throw new OpenPayU_Exception_Network('Unexpected HTTP code response', $statusCode);
break;
}
}
/**
* @param $statusCode
* @param ResultError $resultError
* @throws OpenPayU_Exception
* @throws OpenPayU_Exception_Authorization
* @throws OpenPayU_Exception_Network
* @throws OpenPayU_Exception_ServerError
* @throws OpenPayU_Exception_ServerMaintenance
*/
public static function throwErrorHttpStatusException($statusCode, $resultError)
{
switch ($statusCode) {
case 400:
throw new OpenPayU_Exception($resultError->getError().' - '.$resultError->getErrorDescription(), $statusCode);
break;
case 401:
case 403:
throw new OpenPayU_Exception_Authorization($resultError->getError().' - '.$resultError->getErrorDescription(), $statusCode);
break;
case 404:
throw new OpenPayU_Exception_Network($resultError->getError().' - '.$resultError->getErrorDescription(), $statusCode);
break;
case 408:
throw new OpenPayU_Exception_ServerError('Request timeout', $statusCode);
break;
case 500:
throw new OpenPayU_Exception_ServerError('PayU system is unavailable. Error: [' . $resultError->getErrorDescription() . ']', $resultError);
break;
case 503:
throw new OpenPayU_Exception_ServerMaintenance('Service unavailable', $statusCode);
break;
default:
throw new OpenPayU_Exception_Network('Unexpected HTTP code response', $statusCode);
break;
}
}
}

View File

@@ -0,0 +1,109 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) 2011-2016 PayU
* @license http://opensource.org/licenses/LGPL-3.0 Open Software License (LGPL 3.0)
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_HttpCurl
{
/**
* @var
*/
static $headers;
/**
* @param $requestType
* @param $pathUrl
* @param $data
* @param AuthType $auth
* @return array
* @throws OpenPayU_Exception_Configuration
* @throws OpenPayU_Exception_Network
*/
public static function doPayuRequest($requestType, $pathUrl, $auth, $data = null)
{
if (empty($pathUrl)) {
throw new OpenPayU_Exception_Configuration('The endpoint is empty');
}
$ch = curl_init($pathUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestType);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $auth->getHeaders());
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'OpenPayU_HttpCurl::readHeader');
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
if ($proxy = self::getProxy()) {
curl_setopt($ch, CURLOPT_PROXY, $proxy);
if ($proxyAuth = self::getProxyAuth()) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyAuth);
}
}
$response = curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($response === false) {
throw new OpenPayU_Exception_Network(curl_error($ch));
}
curl_close($ch);
return array('code' => $httpStatus, 'response' => trim($response));
}
/**
* @param array $headers
*
* @return mixed
*/
public static function getSignature($headers)
{
foreach($headers as $name => $value)
{
if(preg_match('/X-OpenPayU-Signature/i', $name) || preg_match('/OpenPayu-Signature/i', $name))
return $value;
}
return null;
}
/**
* @param resource $ch
* @param string $header
* @return int
*/
public static function readHeader($ch, $header)
{
if( preg_match('/([^:]+): (.+)/m', $header, $match) ) {
self::$headers[$match[1]] = trim($match[2]);
}
return strlen($header);
}
private static function getProxy()
{
return OpenPayU_Configuration::getProxyHost() != null ? OpenPayU_Configuration::getProxyHost()
. (OpenPayU_Configuration::getProxyPort() ? ':' . OpenPayU_Configuration::getProxyPort() : '') : false;
}
private static function getProxyAuth()
{
return OpenPayU_Configuration::getProxyUser() != null ? OpenPayU_Configuration::getProxyUser()
. (OpenPayU_Configuration::getProxyPassword() ? ':' . OpenPayU_Configuration::getProxyPassword() : '') : false;
}
}

View File

@@ -0,0 +1,40 @@
<?php
class OauthCacheFile implements OauthCacheInterface
{
private $directory;
/**
* @param string $directory
* @throws OpenPayU_Exception_Configuration
*/
public function __construct($directory = null)
{
if ($directory === null) {
$directory = dirname(__FILE__).'/../../../Cache';
}
if (!is_dir($directory) || !is_writable($directory)) {
throw new OpenPayU_Exception_Configuration('Cache directory [' . $directory . '] not exist or not writable.');
}
$this->directory = $directory . (substr($directory, -1) != '/' ? '/' : '');
}
public function get($key)
{
$cache = @file_get_contents($this->directory . md5($key));
return $cache === false ? null : unserialize($cache);
}
public function set($key, $value)
{
return @file_put_contents($this->directory . md5($key), serialize($value));
}
public function invalidate($key)
{
return @unlink($this->directory . md5($key));
}
}

View File

@@ -0,0 +1,26 @@
<?php
interface OauthCacheInterface
{
/**
* @param string $key
* @return null | object
*/
public function get($key);
/**
* @param string $key
* @param object $value
* @return bool
*/
public function set($key, $value);
/**
* @param string $key
* @return bool
*/
public function invalidate($key);
}

View File

@@ -0,0 +1,43 @@
<?php
class OauthCacheMemcached implements OauthCacheInterface
{
private $memcached;
/**
* @param string $host
* @param int $port
* @param int $weight
* @throws OpenPayU_Exception_Configuration
*/
public function __construct($host = 'localhost', $port = 11211, $weight = 0)
{
if (!class_exists('Memcached')) {
throw new OpenPayU_Exception_Configuration('PHP Memcached extension not installed.');
}
$this->memcached = new Memcached('PayU');
$this->memcached->addServer($host, $port, $weight);
$stats = $this->memcached->getStats();
if ($stats[$host . ':' . $port]['pid'] == -1) {
throw new OpenPayU_Exception_Configuration('Problem with connection to memcached server [host=' . $host . '] [port=' . $port . '] [weight=' . $weight . ']');
}
}
public function get($key)
{
$cache = $this->memcached->get($key);
return $cache === false ? null : unserialize($cache);
}
public function set($key, $value)
{
return $this->memcached->set($key, serialize($value));
}
public function invalidate($key)
{
return $this->memcached->delete($key);
}
}

View File

@@ -0,0 +1,123 @@
<?php
class OpenPayU_Oauth
{
/**
* @var OauthCacheInterface
*/
private static $oauthTokenCache;
const CACHE_KEY = 'AccessToken';
/**
* @param string $clientId
* @param string $clientSecret
* @return OauthResultClientCredentials
* @throws OpenPayU_Exception_ServerError
*/
public static function getAccessToken($clientId = null, $clientSecret = null)
{
if (OpenPayU_Configuration::getOauthGrantType() === OauthGrantType::TRUSTED_MERCHANT) {
return self::retrieveAccessToken($clientId, $clientSecret);
}
$cacheKey = self::CACHE_KEY . OpenPayU_Configuration::getOauthClientId();
self::getOauthTokenCache();
$tokenCache = self::$oauthTokenCache->get($cacheKey);
if ($tokenCache instanceof OauthResultClientCredentials && !$tokenCache->hasExpire()) {
return $tokenCache;
}
self::$oauthTokenCache->invalidate($cacheKey);
$response = self::retrieveAccessToken($clientId, $clientSecret);
self::$oauthTokenCache->set($cacheKey, $response);
return $response;
}
/**
* @param $clientId
* @param $clientSecret
* @return OauthResultClientCredentials
* @throws OpenPayU_Exception_ServerError
*/
private static function retrieveAccessToken($clientId, $clientSecret)
{
$authType = new AuthType_TokenRequest();
$oauthUrl = OpenPayU_Configuration::getOauthEndpoint();
$data = array(
'grant_type' => OpenPayU_Configuration::getOauthGrantType(),
'client_id' => $clientId ? $clientId : OpenPayU_Configuration::getOauthClientId(),
'client_secret' => $clientSecret ? $clientSecret : OpenPayU_Configuration::getOauthClientSecret()
);
if (OpenPayU_Configuration::getOauthGrantType() === OauthGrantType::TRUSTED_MERCHANT) {
$data['email'] = OpenPayU_Configuration::getOauthEmail();
$data['ext_customer_id'] = OpenPayU_Configuration::getOauthExtCustomerId();
}
return self::parseResponse(OpenPayU_Http::doPost($oauthUrl, http_build_query($data, '', '&'), $authType));
}
/**
* Parse response from PayU
*
* @param array $response
* @return OauthResultClientCredentials
* @throws OpenPayU_Exception
* @throws OpenPayU_Exception_Authorization
* @throws OpenPayU_Exception_Network
* @throws OpenPayU_Exception_ServerError
* @throws OpenPayU_Exception_ServerMaintenance
*/
private static function parseResponse($response)
{
$httpStatus = $response['code'];
if ($httpStatus == 500) {
$result = new ResultError();
$result->setErrorDescription($response['response']);
OpenPayU_Http::throwErrorHttpStatusException($httpStatus, $result);
}
$message = OpenPayU_Util::convertJsonToArray($response['response'], true);
if (json_last_error() == JSON_ERROR_SYNTAX) {
throw new OpenPayU_Exception_ServerError('Incorrect json response. Response: [' . $response['response'] . ']');
}
if ($httpStatus == 200) {
$result = new OauthResultClientCredentials();
$result->setAccessToken($message['access_token'])
->setTokenType($message['token_type'])
->setExpiresIn($message['expires_in'])
->setGrantType($message['grant_type'])
->calculateExpireDate(new \DateTime());
return $result;
}
$result = new ResultError();
$result->setError($message['error'])
->setErrorDescription($message['error_description']);
OpenPayU_Http::throwErrorHttpStatusException($httpStatus, $result);
}
private static function getOauthTokenCache()
{
$oauthTokenCache = OpenPayU_Configuration::getOauthTokenCache();
if (!$oauthTokenCache instanceof OauthCacheInterface) {
$oauthTokenCache = new OauthCacheFile();
OpenPayU_Configuration::setOauthTokenCache($oauthTokenCache);
}
self::$oauthTokenCache = $oauthTokenCache;
}
}

View File

@@ -0,0 +1,7 @@
<?php
abstract class OauthGrantType
{
const CLIENT_CREDENTIAL = 'client_credentials';
const TRUSTED_MERCHANT = 'trusted_merchant';
}

View File

@@ -0,0 +1,121 @@
<?php
class OauthResultClientCredentials
{
/**
* @var string
*/
private $accessToken;
/**
* @var string
*/
private $tokenType;
/**
* @var string
*/
private $expiresIn;
/**
* @var string
*/
private $grantType;
/**
* @var DateTime
*/
private $expireDate;
/**
* @return string
*/
public function getAccessToken()
{
return $this->accessToken;
}
/**
* @param string $accessToken
* @return OauthResultClientCredentials
*/
public function setAccessToken($accessToken)
{
$this->accessToken = $accessToken;
return $this;
}
/**
* @return string
*/
public function getTokenType()
{
return $this->tokenType;
}
/**
* @param string $tokenType
* @return OauthResultClientCredentials
*/
public function setTokenType($tokenType)
{
$this->tokenType = $tokenType;
return $this;
}
/**
* @return string
*/
public function getExpiresIn()
{
return $this->expiresIn;
}
/**
* @param string $expiresIn
* @return OauthResultClientCredentials
*/
public function setExpiresIn($expiresIn)
{
$this->expiresIn = $expiresIn;
return $this;
}
/**
* @return string
*/
public function getGrantType()
{
return $this->grantType;
}
/**
* @param string $grantType
* @return OauthResultClientCredentials
*/
public function setGrantType($grantType)
{
$this->grantType = $grantType;
return $this;
}
/**
* @return DateTime
*/
public function getExpireDate()
{
return $this->expireDate;
}
/**
* @param DateTime $date
*/
public function calculateExpireDate($date)
{
$this->expireDate = $date->add(new DateInterval('PT' . ($this->expiresIn - 60) . 'S'));
}
public function hasExpire()
{
return ($this->expireDate <= new DateTime());
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) 2011-2016 PayU
* @license http://opensource.org/licenses/LGPL-3.0 Open Software License (LGPL 3.0)
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU
{
protected static function build($data)
{
$instance = new OpenPayU_Result();
if (array_key_exists('status', $data) && $data['status'] == 'WARNING_CONTINUE_REDIRECT') {
$data['status'] = 'SUCCESS';
$data['response']['status']['statusCode'] = 'SUCCESS';
}
$instance->init($data);
return $instance;
}
/**
* @param $data
* @param $incomingSignature
* @throws OpenPayU_Exception_Authorization
*/
public static function verifyDocumentSignature($data, $incomingSignature)
{
$sign = OpenPayU_Util::parseSignature($incomingSignature);
if (false === OpenPayU_Util::verifySignature(
$data,
$sign->signature,
OpenPayU_Configuration::getSignatureKey(),
$sign->algorithm)
) {
throw new OpenPayU_Exception_Authorization('Invalid signature - ' . $sign->signature);
}
}
/**
* @return AuthType
* @throws OpenPayU_Exception
*/
protected static function getAuth()
{
if (OpenPayU_Configuration::getOauthClientId() && OpenPayU_Configuration::getOauthClientSecret()) {
$authType = new AuthType_Oauth(OpenPayU_Configuration::getOauthClientId(), OpenPayU_Configuration::getOauthClientSecret());
} else {
$authType = new AuthType_Basic(OpenPayU_Configuration::getMerchantPosId(), OpenPayU_Configuration::getSignatureKey());
}
return $authType;
}
}

View File

@@ -0,0 +1,58 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) 2011-2016 PayU
* @license http://opensource.org/licenses/LGPL-3.0 Open Software License (LGPL 3.0)
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Exception extends \Exception
{
}
class OpenPayU_Exception_Request extends OpenPayU_Exception
{
/** @var stdClass|null */
private $originalResponseMessage;
public function __construct($originalResponseMessage, $message = "", $code = 0, $previous = null)
{
$this->originalResponseMessage = $originalResponseMessage;
parent::__construct($message, $code, $previous);
}
/** @return null|stdClass */
public function getOriginalResponse()
{
return $this->originalResponseMessage;
}
}
class OpenPayU_Exception_Configuration extends OpenPayU_Exception
{
}
class OpenPayU_Exception_Network extends OpenPayU_Exception
{
}
class OpenPayU_Exception_ServerError extends OpenPayU_Exception
{
}
class OpenPayU_Exception_ServerMaintenance extends OpenPayU_Exception
{
}
class OpenPayU_Exception_Authorization extends OpenPayU_Exception
{
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) 2011-2016 PayU
* @license http://opensource.org/licenses/LGPL-3.0 Open Software License (LGPL 3.0)
* http://www.payu.com
* http://developers.payu.com
*/
/**
* Class OpenPayuOrderStatus
*/
abstract class OpenPayuOrderStatus
{
const STATUS_NEW = 'NEW';
const STATUS_PENDING = 'PENDING';
const STATUS_CANCELED = 'CANCELED';
const STATUS_REJECTED = 'REJECTED';
const STATUS_COMPLETED = 'COMPLETED';
const STATUS_WAITING_FOR_CONFIRMATION = 'WAITING_FOR_CONFIRMATION';
}

View File

@@ -0,0 +1,224 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) 2011-2016 PayU
* @license http://opensource.org/licenses/LGPL-3.0 Open Software License (LGPL 3.0)
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Result
{
private $status = '';
private $error = '';
private $success = 0;
private $request = '';
private $response = '';
private $sessionId = '';
private $message = '';
private $countryCode = '';
private $reqId = '';
/**
* @access public
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* @access public
* @param $value
*/
public function setStatus($value)
{
$this->status = $value;
}
/**
* @access public
* @return string
*/
public function getError()
{
return $this->error;
}
/**
* @access public
* @param $value
*/
public function setError($value)
{
$this->error = $value;
}
/**
* @access public
* @return int
*/
public function getSuccess()
{
return $this->success;
}
/**
* @access public
* @param $value
*/
public function setSuccess($value)
{
$this->success = $value;
}
/**
* @access public
* @return string
*/
public function getRequest()
{
return $this->request;
}
/**
* @access public
* @param $value
*/
public function setRequest($value)
{
$this->request = $value;
}
/**
* @access public
* @return string
*/
public function getResponse()
{
return $this->response;
}
/**
* @access public
* @param $value
*/
public function setResponse($value)
{
$this->response = $value;
}
/**
* @access public
* @return string
*/
public function getSessionId()
{
return $this->sessionId;
}
/**
* @access public
* @param $value
*/
public function setSessionId($value)
{
$this->sessionId = $value;
}
/**
* @access public
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* @access public
* @param $value
*/
public function setMessage($value)
{
$this->message = $value;
}
/**
* @access public
* @return string
*/
public function getCountryCode()
{
return $this->countryCode;
}
/**
* @access public
* @param $value
*/
public function setCountryCode($value)
{
$this->countryCode = $value;
}
/**
* @access public
* @return string
*/
public function getReqId()
{
return $this->reqId;
}
/**
* @access public
* @param $value
*/
public function setReqId($value)
{
$this->reqId = $value;
}
public function init($attributes)
{
$attributes = OpenPayU_Util::parseArrayToObject($attributes);
if (!empty($attributes)) {
foreach ($attributes as $name => $value) {
$this->set($name, $value);
}
}
}
public function set($name, $value)
{
$this->{$name} = $value;
}
public function __get($name)
{
if (isset($this->{$name}))
return $this->name;
return null;
}
public function __call($methodName, $args) {
if (preg_match('~^(set|get)([A-Z])(.*)$~', $methodName, $matches)) {
$property = strtolower($matches[2]) . $matches[3];
if (!property_exists($this, $property)) {
throw new Exception('Property ' . $property . ' not exists');
}
switch($matches[1]) {
case 'get':
$this->checkArguments($args, 0, 0, $methodName);
return $this->get($property);
case 'default':
throw new Exception('Method ' . $methodName . ' not exists');
}
}
}
}

View File

@@ -0,0 +1,59 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) 2011-2016 PayU
* @license http://opensource.org/licenses/LGPL-3.0 Open Software License (LGPL 3.0)
* http://www.payu.com
* http://developers.payu.com
*/
class ResultError
{
/**
* @var string
*/
private $error;
/**
* @var string
*/
private $errorDescription;
/**
* @return string
*/
public function getError()
{
return $this->error;
}
/**
* @param string $error
* @return ResultError
*/
public function setError($error)
{
$this->error = $error;
return $this;
}
/**
* @return string
*/
public function getErrorDescription()
{
return $this->errorDescription;
}
/**
* @param string $errorDescription
* @return ResultError
*/
public function setErrorDescription($errorDescription)
{
$this->errorDescription = $errorDescription;
return $this;
}
}

View File

@@ -0,0 +1,316 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) 2011-2016 PayU
* @license http://opensource.org/licenses/LGPL-3.0 Open Software License (LGPL 3.0)
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Util
{
/**
* Function generate sign data
*
* @param array $data
* @param string $algorithm
* @param string $merchantPosId
* @param string $signatureKey
*
* @return string
*
* @throws OpenPayU_Exception_Configuration
*/
public static function generateSignData(array $data, $algorithm = 'SHA-256', $merchantPosId = '', $signatureKey = '')
{
if (empty($signatureKey))
throw new OpenPayU_Exception_Configuration('Merchant Signature Key should not be null or empty.');
if (empty($merchantPosId))
throw new OpenPayU_Exception_Configuration('MerchantPosId should not be null or empty.');
$contentForSign = '';
ksort($data);
foreach ($data as $key => $value) {
$contentForSign .= $key . '=' . urlencode($value) . '&';
}
if (in_array($algorithm, array('SHA-256', 'SHA'))) {
$hashAlgorithm = 'sha256';
$algorithm = 'SHA-256';
} else if ($algorithm == 'SHA-384') {
$hashAlgorithm = 'sha384';
$algorithm = 'SHA-384';
} else if ($algorithm == 'SHA-512') {
$hashAlgorithm = 'sha512';
$algorithm = 'SHA-512';
}
$signature = hash($hashAlgorithm, $contentForSign . $signatureKey);
$signData = 'sender=' . $merchantPosId . ';algorithm=' . $algorithm . ';signature=' . $signature;
return $signData;
}
/**
* Function returns signature data object
*
* @param string $data
*
* @return null|object
*/
public static function parseSignature($data)
{
if (empty($data)) {
return null;
}
$signatureData = array();
$list = explode(';', rtrim($data, ';'));
if (empty($list)) {
return null;
}
foreach ($list as $value) {
$explode = explode('=', $value);
if (count($explode) != 2) {
return null;
}
$signatureData[$explode[0]] = $explode[1];
}
return (object)$signatureData;
}
/**
* Function returns signature validate
*
* @param string $message
* @param string $signature
* @param string $signatureKey
* @param string $algorithm
*
* @return bool
*/
public static function verifySignature($message, $signature, $signatureKey, $algorithm = 'MD5')
{
if (isset($signature)) {
if ($algorithm === 'MD5') {
$hash = md5($message . $signatureKey);
} else if (in_array($algorithm, array('SHA', 'SHA1', 'SHA-1'))) {
$hash = sha1($message . $signatureKey);
} else {
$hash = hash('sha256', $message . $signatureKey);
}
if (strcmp($signature, $hash) == 0) {
return true;
}
}
return false;
}
/**
* Function builds OpenPayU Json Document
*
* @param string $data
* @param string $rootElement
*
* @return null|string
*/
public static function buildJsonFromArray($data, $rootElement = '')
{
if (!is_array($data)) {
return null;
}
if (!empty($rootElement)) {
$data = array($rootElement => $data);
}
$data = self::setSenderProperty($data);
return json_encode($data);
}
/**
* @param string $data
* @param bool $assoc
* @return mixed|null
*/
public static function convertJsonToArray($data, $assoc = false)
{
if (empty($data)) {
return null;
}
return json_decode($data, $assoc);
}
/**
* @param array $array
* @return bool|stdClass
*/
public static function parseArrayToObject($array)
{
if (!is_array($array)) {
return $array;
}
if (self::isAssocArray($array)) {
$object = new stdClass();
} else {
$object = array();
}
if (is_array($array) && count($array) > 0) {
foreach ($array as $name => $value) {
$name = trim($name);
if (isset($name)) {
if (is_numeric($name)) {
$object[] = self::parseArrayToObject($value);
} else {
$object->$name = self::parseArrayToObject($value);
}
}
}
return $object;
}
return false;
}
/**
* @return mixed
*/
public static function getRequestHeaders()
{
if (!function_exists('apache_request_headers')) {
$headers = array();
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
}
}
return $headers;
} else {
return apache_request_headers();
}
}
/**
* @param $array
* @param string $namespace
* @param array $outputFields
* @return string
*/
public static function convertArrayToHtmlForm($array, $namespace = "", &$outputFields)
{
$i = 0;
$htmlOutput = "";
$assoc = self::isAssocArray($array);
foreach ($array as $key => $value) {
if ($namespace && $assoc) {
$key = $namespace . '.' . $key;
} elseif ($namespace && !$assoc) {
$key = $namespace . '[' . $i++ . ']';
}
if (is_array($value)) {
$htmlOutput .= self::convertArrayToHtmlForm($value, $key, $outputFields);
} else {
$htmlOutput .= sprintf("<input type=\"hidden\" name=\"%s\" value=\"%s\" />\n", $key, $value);
$outputFields[$key] = $value;
}
}
return $htmlOutput;
}
/**
* @param $arr
* @return bool
*/
public static function isAssocArray($arr)
{
$arrKeys = array_keys($arr);
sort($arrKeys, SORT_NUMERIC);
return $arrKeys !== range(0, count($arr) - 1);
}
/**
* @param $namespace
* @param $key
* @return string
*/
public static function changeFormFieldFormat($namespace, $key)
{
if ($key === $namespace && $key[strlen($key) - 1] == 's') {
return substr($key, 0, -1);
}
return $key;
}
/**
* @param array $data
* @return array
*/
private static function setSenderProperty($data)
{
$data['properties'][0] = array(
'name' => 'sender',
'value' => OpenPayU_Configuration::getFullSenderName()
);
return $data;
}
public static function statusDesc($response)
{
$msg = '';
switch ($response) {
case 'SUCCESS':
$msg = 'Request has been processed correctly.';
break;
case 'DATA_NOT_FOUND':
$msg = 'Data indicated in the request is not available in the PayU system.';
break;
case 'WARNING_CONTINUE_3_DS':
$msg = '3DS authorization required.Redirect the Buyer to PayU to continue the 3DS process by calling OpenPayU.authorize3DS().';
break;
case 'WARNING_CONTINUE_CVV':
$msg = 'CVV/CVC authorization required. Call OpenPayU.authorizeCVV() method.';
break;
case 'ERROR_SYNTAX':
$msg = 'BIncorrect request syntax. Supported formats are JSON or XML.';
break;
case 'ERROR_VALUE_INVALID':
$msg = 'One or more required values are incorrect.';
break;
case 'ERROR_VALUE_MISSING':
$msg = 'One or more required values are missing.';
break;
case 'BUSINESS_ERROR':
$msg = 'PayU system is unavailable. Try again later.';
break;
case 'ERROR_INTERNAL':
$msg = 'PayU system is unavailable. Try again later.';
break;
case 'GENERAL_ERROR':
$msg = 'Unexpected error. Try again later.';
break;
}
return $msg;
}
}

View File

@@ -0,0 +1,266 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) 2011-2018 PayU
* @license http://opensource.org/licenses/LGPL-3.0 Open Software License (LGPL 3.0)
* http://www.payu.com
* http://developers.payu.com
*/
/**
* Class OpenPayU_Order
*/
class OpenPayU_Order extends OpenPayU
{
const ORDER_SERVICE = 'orders/';
const ORDER_TRANSACTION_SERVICE = 'transactions';
const SUCCESS = 'SUCCESS';
/**
* @var array Default form parameters
*/
protected static $defaultFormParams = array(
'formClass' => '',
'formId' => 'payu-payment-form',
'submitClass' => '',
'submitId' => '',
'submitContent' => '',
'submitTarget' => '_blank'
);
/**
* Creates new Order
* - Sends to PayU OrderCreateRequest
*
* @param array $order A array containing full Order
* @return object $result Response array with OrderCreateResponse
* @throws OpenPayU_Exception
*/
public static function create($order)
{
$data = OpenPayU_Util::buildJsonFromArray($order);
if (empty($data)) {
throw new OpenPayU_Exception('Empty message OrderCreateRequest');
}
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::ORDER_SERVICE;
$result = self::verifyResponse(OpenPayU_Http::doPost($pathUrl, $data, $authType), 'OrderCreateResponse');
return $result;
}
/**
* Retrieves information about the order
* - Sends to PayU OrderRetrieveRequest
*
* @param string $orderId PayU OrderId sent back in OrderCreateResponse
* @return OpenPayU_Result $result Response array with OrderRetrieveResponse
* @throws OpenPayU_Exception
*/
public static function retrieve($orderId)
{
if (empty($orderId)) {
throw new OpenPayU_Exception('Empty value of orderId');
}
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::ORDER_SERVICE . $orderId;
$result = self::verifyResponse(OpenPayU_Http::doGet($pathUrl, $authType), 'OrderRetrieveResponse');
return $result;
}
/**
* Retrieves information about the order transaction
* - Sends to PayU TransactionRetrieveRequest
*
* @param string $orderId PayU OrderId sent back in OrderCreateResponse
* @return OpenPayU_Result $result Response array with TransactionRetrieveResponse
* @throws OpenPayU_Exception
*/
public static function retrieveTransaction($orderId)
{
if (empty($orderId)) {
throw new OpenPayU_Exception('Empty value of orderId');
}
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::ORDER_SERVICE . $orderId . '/' . self::ORDER_TRANSACTION_SERVICE;
$result = self::verifyResponse(OpenPayU_Http::doGet($pathUrl, $authType), 'TransactionRetrieveResponse');
return $result;
}
/**
* Cancels Order
* - Sends to PayU OrderCancelRequest
*
* @param string $orderId PayU OrderId sent back in OrderCreateResponse
* @return OpenPayU_Result $result Response array with OrderCancelResponse
* @throws OpenPayU_Exception
*/
public static function cancel($orderId)
{
if (empty($orderId)) {
throw new OpenPayU_Exception('Empty value of orderId');
}
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::ORDER_SERVICE . $orderId;
$result = self::verifyResponse(OpenPayU_Http::doDelete($pathUrl, $authType), 'OrderCancelResponse');
return $result;
}
/**
* Updates Order status
* - Sends to PayU OrderStatusUpdateRequest
*
* @param string $orderStatusUpdate A array containing full OrderStatus
* @return OpenPayU_Result $result Response array with OrderStatusUpdateResponse
* @throws OpenPayU_Exception
*/
public static function statusUpdate($orderStatusUpdate)
{
if (empty($orderStatusUpdate)) {
throw new OpenPayU_Exception('Empty order status data');
}
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
$data = OpenPayU_Util::buildJsonFromArray($orderStatusUpdate);
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::ORDER_SERVICE . $orderStatusUpdate['orderId'] . '/status';
$result = self::verifyResponse(OpenPayU_Http::doPut($pathUrl, $data, $authType), 'OrderStatusUpdateResponse');
return $result;
}
/**
* Consume notification message
*
* @access public
* @param $data string Request array received from with PayU OrderNotifyRequest
* @return null|OpenPayU_Result Response array with OrderNotifyRequest
* @throws OpenPayU_Exception
*/
public static function consumeNotification($data)
{
if (empty($data)) {
throw new OpenPayU_Exception('Empty value of data');
}
$headers = OpenPayU_Util::getRequestHeaders();
$incomingSignature = OpenPayU_HttpCurl::getSignature($headers);
self::verifyDocumentSignature($data, $incomingSignature);
return OpenPayU_Order::verifyResponse(array('response' => $data, 'code' => 200), 'OrderNotifyRequest');
}
/**
* Verify response from PayU
*
* @param string $response
* @param string $messageName
* @return null|OpenPayU_Result
* @throws OpenPayU_Exception
* @throws OpenPayU_Exception_Authorization
* @throws OpenPayU_Exception_Network
* @throws OpenPayU_Exception_ServerError
* @throws OpenPayU_Exception_ServerMaintenance
*/
public static function verifyResponse($response, $messageName)
{
$data = array();
$httpStatus = $response['code'];
$message = OpenPayU_Util::convertJsonToArray($response['response'], true);
$data['status'] = isset($message['status']['statusCode']) ? $message['status']['statusCode'] : null;
if (json_last_error() == JSON_ERROR_SYNTAX) {
$data['response'] = $response['response'];
} elseif (isset($message[$messageName])) {
unset($message[$messageName]['Status']);
$data['response'] = $message[$messageName];
} elseif (isset($message)) {
$data['response'] = $message;
unset($message['status']);
}
$result = self::build($data);
if ($httpStatus == 200 || $httpStatus == 201 || $httpStatus == 422 || $httpStatus == 301 || $httpStatus == 302) {
return $result;
}
OpenPayU_Http::throwHttpStatusException($httpStatus, $result);
}
/**
* Generate a form body for hosted order
*
* @access public
* @param array $order an array containing full Order
* @param array $params an optional array with form elements' params
* @return string Response html form
* @throws OpenPayU_Exception_Configuration
*/
public static function hostedOrderForm($order, $params = array())
{
$orderFormUrl = OpenPayU_Configuration::getServiceUrl() . 'orders';
$formFieldValuesAsArray = array();
$htmlFormFields = OpenPayU_Util::convertArrayToHtmlForm($order, '', $formFieldValuesAsArray);
$signature = OpenPayU_Util::generateSignData(
$formFieldValuesAsArray,
OpenPayU_Configuration::getHashAlgorithm(),
OpenPayU_Configuration::getMerchantPosId(),
OpenPayU_Configuration::getSignatureKey()
);
$formParams = array_merge(self::$defaultFormParams, $params);
$htmlOutput = sprintf("<form method=\"POST\" action=\"%s\" id=\"%s\" class=\"%s\">\n", $orderFormUrl, $formParams['formId'], $formParams['formClass']);
$htmlOutput .= $htmlFormFields;
$htmlOutput .= sprintf("<input type=\"hidden\" name=\"OpenPayu-Signature\" value=\"%s\" />", $signature);
$htmlOutput .= sprintf("<button type=\"submit\" formtarget=\"%s\" id=\"%s\" class=\"%s\">%s</button>", $formParams['submitTarget'], $formParams['submitId'], $formParams['submitClass'], $formParams['submitContent']);
$htmlOutput .= "</form>\n";
return $htmlOutput;
}
}

View File

@@ -0,0 +1,87 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) 2011-2016 PayU
* @license http://opensource.org/licenses/LGPL-3.0 Open Software License (LGPL 3.0)
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Refund extends OpenPayU
{
/**
* Function make refund for order
* @param $orderId
* @param $description
* @param int $amount Amount of refund in pennies
* @return null|OpenPayU_Result
* @throws OpenPayU_Exception
*/
public static function create($orderId, $description, $amount = null)
{
if (empty($orderId)) {
throw new OpenPayU_Exception('Invalid orderId value for refund');
}
if (empty($description)) {
throw new OpenPayU_Exception('Invalid description of refund');
}
$refund = array(
'orderId' => $orderId,
'refund' => array('description' => $description)
);
if (!empty($amount)) {
$refund['refund']['amount'] = (int)$amount;
}
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
$pathUrl = OpenPayU_Configuration::getServiceUrl().'orders/'. $refund['orderId'] . '/refund';
$data = OpenPayU_Util::buildJsonFromArray($refund);
$result = self::verifyResponse(OpenPayU_Http::doPost($pathUrl, $data, $authType), 'RefundCreateResponse');
return $result;
}
/**
* @param string $response
* @param string $messageName
* @return OpenPayU_Result
*/
public static function verifyResponse($response, $messageName='')
{
$data = array();
$httpStatus = $response['code'];
$message = OpenPayU_Util::convertJsonToArray($response['response'], true);
$data['status'] = isset($message['status']['statusCode']) ? $message['status']['statusCode'] : null;
if (json_last_error() == JSON_ERROR_SYNTAX) {
$data['response'] = $response['response'];
} elseif (isset($message[$messageName])) {
unset($message[$messageName]['Status']);
$data['response'] = $message[$messageName];
} elseif (isset($message)) {
$data['response'] = $message;
unset($message['status']);
}
$result = self::build($data);
if ($httpStatus == 200 || $httpStatus == 201 || $httpStatus == 422 || $httpStatus == 302) {
return $result;
} else {
OpenPayU_Http::throwHttpStatusException($httpStatus, $result);
}
}
}

View File

@@ -0,0 +1,75 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) 2011-2016 PayU
* @license http://opensource.org/licenses/LGPL-3.0 Open Software License (LGPL 3.0)
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Retrieve extends OpenPayU
{
const PAYMETHODS_SERVICE = 'paymethods';
/**
* Get Pay Methods from POS
* @param string $lang
* @return null|OpenPayU_Result
* @throws OpenPayU_Exception
* @throws OpenPayU_Exception_Configuration
*/
public static function payMethods($lang = null)
{
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
if (!$authType instanceof AuthType_Oauth) {
throw new OpenPayU_Exception_Configuration('Retrieve works only with OAuth');
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::PAYMETHODS_SERVICE;
if ($lang !== null) {
$pathUrl .= '?lang=' . $lang;
}
$response = self::verifyResponse(OpenPayU_Http::doGet($pathUrl, $authType));
return $response;
}
/**
* @param string $response
* @return null|OpenPayU_Result
*/
public static function verifyResponse($response)
{
$data = array();
$httpStatus = $response['code'];
$message = OpenPayU_Util::convertJsonToArray($response['response'], true);
$data['status'] = isset($message['status']['statusCode']) ? $message['status']['statusCode'] : null;
if (json_last_error() == JSON_ERROR_SYNTAX) {
$data['response'] = $response['response'];
} elseif (isset($message)) {
$data['response'] = $message;
unset($message['status']);
}
$result = self::build($data);
if ($httpStatus == 200 || $httpStatus == 201 || $httpStatus == 422 || $httpStatus == 302 || $httpStatus == 400 || $httpStatus == 404) {
return $result;
} else {
OpenPayU_Http::throwHttpStatusException($httpStatus, $result);
}
}
}

View File

@@ -0,0 +1,75 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) 2011-2017 PayU
* @license http://opensource.org/licenses/LGPL-3.0 Open Software License (LGPL 3.0)
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Token extends OpenPayU
{
const TOKENS_SERVICE = 'tokens';
/**
* Deleting a payment token
* @param string $token
* @return null|OpenPayU_Result
* @throws OpenPayU_Exception
* @throws OpenPayU_Exception_Configuration
*/
public static function delete($token)
{
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
if (!$authType instanceof AuthType_Oauth) {
throw new OpenPayU_Exception_Configuration('Delete token works only with OAuth');
}
if (OpenPayU_Configuration::getOauthGrantType() !== OauthGrantType::TRUSTED_MERCHANT) {
throw new OpenPayU_Exception_Configuration('Token delete request is available only for trusted_merchant');
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::TOKENS_SERVICE . '/' . $token;
$response = self::verifyResponse(OpenPayU_Http::doDelete($pathUrl, $authType));
return $response;
}
/**
* @param string $response
* @return null|OpenPayU_Result
*/
public static function verifyResponse($response)
{
$data = array();
$httpStatus = $response['code'];
$message = OpenPayU_Util::convertJsonToArray($response['response'], true);
$data['status'] = isset($message['status']['statusCode']) ? $message['status']['statusCode'] : null;
if (json_last_error() == JSON_ERROR_SYNTAX) {
$data['response'] = $response['response'];
} elseif (isset($message)) {
$data['response'] = $message;
unset($message['status']);
}
$result = self::build($data);
if ($httpStatus == 204) {
return $result;
} else {
OpenPayU_Http::throwHttpStatusException($httpStatus, $result);
}
}
}

View File

@@ -0,0 +1,191 @@
<?php
/**
* SOTESHOP/stPlatnosciPlPlugin
*
* Ten plik należy do aplikacji stPlatnosciPlPlugin opartej na licencji (Professional License SOTE).
* Nie zmieniaj tego pliku, jeśli chcesz korzystać z automatycznych aktualizacji oprogramowania.
* Jeśli chcesz wprowadzać swoje modyfikacje do programu, zapoznaj się z dokumentacją, jak zmieniać
* oprogramowanie bez zmiany kodu bazowego http://www.sote.pl/modifications
*
* @package stPlatnosciPlPlugin
* @subpackage libs
* @copyright SOTE (www.sote.pl)
* @license http://www.sote.pl/license/sote (Professional License SOTE)
* @version $Id: stPlatnosciPl.class.php 12825 2011-05-17 13:27:06Z michal $
* @author Michal Prochowski <michal.prochowski@sote.pl>
*/
/**
* Adres Płatności.pl
*/
define('PLATNOSCIPL_URL', 'https://www.platnosci.pl/paygw/UTF/');
/**
* Klasa stPlatnosciPl
*
* @package stPlatnosciPlPlugin
* @subpackage libs
*/
class stPlatnosciPl implements stPaymentInterface
{
/**
* Tablica z konfiguracją
* @var array
*/
private $config = array();
private $valid = false;
/**
* Konstruktor - ładownianie konfiguracji
*/
public function __construct()
{
$this->initialize();
}
public function getLogoPath()
{
return '/plugins/stPlatnosciPlPlugin/images/payu.png';
}
public function isAutoRedirectEnabled()
{
return stConfig::getInstance('stPlatnosciPlBackend')->get('autoredirect');
}
public function initialize($currency = null)
{
$config = stPaymentType::getConfiguration(__CLASS__);
$this->currency = $currency ? $currency : stCurrency::getInstance(sfContext::getInstance())->get()->getShortcut();
$this->valid = isset($config['configuration_check']) && $config['configuration_check'];
if ($this->valid)
{
$this->config = isset($config[$this->currency]['enabled']) ? $config[$this->currency] : array();
if ($this->config)
{
OpenPayU_Configuration::setEnvironment('secure');
OpenPayU_Configuration::setMerchantPosId($this->config['pos_id']); // POS ID (Checkout)
OpenPayU_Configuration::setSignatureKey($this->config['md5_secound_key']); //Second MD5 key. You will find it in admin panel.
}
}
}
/**
* Obsługa funkcji call
*
* @param $method
* @param $arguments
* @return mixed string/bool
*/
public function __call($method, $arguments)
{
return stPaymentType::call($method, $this->config);
}
public function getOrderFormurl(Order $order)
{
$sf_context = sfContext::getInstance();
$controller = $sf_context->getController();
$i18n = $sf_context->getI18N();
$lang = strtolower(stPaymentType::getLanguage());
/**
* @var stWebRequest $request
*/
$request = $sf_context->getRequest();
sfLoader::loadHelpers(array('Helper', 'stUrl'));
$data['notifyUrl'] = $controller->genUrl('@stPlatnosciPlPlugin?action=statusReport&id='.$order->getId().'&hash='.$order->getHashCode(), true);
$data['continueUrl'] = $controller->genUrl('@stPlatnosciPlPlugin?action=returnSuccess', true);
$data['customerIp'] = $_SERVER['REMOTE_ADDR'];
$data['merchantPosId'] = OpenPayU_Configuration::getMerchantPosId();
$data['description'] = $i18n->__("Zamówienie nr", null, 'stOrder').' '.$order->getNumber();
$data['additionalDescription'] = "SOTE";
$data['currencyCode'] = $this->currency;
$data['totalAmount'] = intval(stPrice::round($order->getUnpaidAmount() * 100, 0));
$data['extOrderId'] = $order->getNumber() . ' - ' . time();
$data['products'] = array(
array(
'name' => $data['description'],
'unitPrice' => $data['totalAmount'],
'quantity' => 1,
)
);
$data['buyer']['email'] = $order->getOptClientEmail();
list($first, $last) = explode(' ', $order->getOptClientName(), 2);
$data['buyer']['firstName'] = $first;
$data['buyer']['lastName'] = $last;
$data['buyer']['language'] = $lang;
self::log("stPlatnosciPL::getOrderFromUrl() - Create with data: ". json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
$result = OpenPayU_Order::create($data);
if ($result->getStatus() == 'SUCCESS')
{
$redirect = $result->getResponse()->redirectUri.'&lang='.$lang;
self::log("stPlatnosciPL::getOrderFromUrl() - Success redirecting to: ".$redirect);
return $redirect;
}
self::log("stPlatnosciPL::getOrderFromUrl() - Failed: ".json_encode($result, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
return null;
}
public function getOrderNotify($data)
{
if (!empty($data))
{
$result = OpenPayU_Order::verifyResponse(array('response' => $data, 'code' => 200), 'OrderNotifyRequest');
if ($result && $result->getResponse()->order)
{
$this->initialize($result->getResponse()->order->currencyCode);
}
$result = OpenPayU_Order::consumeNotification($data);
if ($result->getResponse()->order->orderId)
{
/* Check if OrderId exists in Merchant Service, update Order data by OrderRetrieveRequest */
$order = OpenPayU_Order::retrieve($result->getResponse()->order->orderId);
if($order->getStatus() == 'SUCCESS')
{
return $result->getResponse()->order;
}
}
}
return null;
}
/**
* Sprawdzenie czy płatność została skonfiguraowana
*
* @return bool
*/
public function checkPaymentConfiguration()
{
if (SF_APP == 'frontend' && !$this->config)
{
return false;
}
return $this->valid;
}
public static function log($message)
{
stPayment::log("payu", $message);
}
}

View File

@@ -0,0 +1,18 @@
<?php
class stPlatnosciPlListener
{
public static function postOrderSummary(sfEvent $event)
{
if (stConfig::getInstance('stPlatnosciPlBackend')->get('autoredirect'))
{
// $action = $event->getSubject();
// if ($action->order->showPayment())
// {
// sfLoader::loadHelpers(array('Helper', 'stUrl'));
// sfContext::getInstance()->getController()->redirect(st_url_for('@stPaymentPay?id='.$action->id.'&hash_code='.$action->hash_code));
// }
}
}
}

View File

@@ -0,0 +1,197 @@
<?php
/**
* SOTESHOP/stPlatnosciPlPlugin
*
* Ten plik należy do aplikacji stPlatnosciPlPlugin opartej na licencji (Professional License SOTE).
* Nie zmieniaj tego pliku, jeśli chcesz korzystać z automatycznych aktualizacji oprogramowania.
* Jeśli chcesz wprowadzać swoje modyfikacje do programu, zapoznaj się z dokumentacją, jak zmieniać
* oprogramowanie bez zmiany kodu bazowego http://www.sote.pl/modifications
*
* @package stPlatnosciPlPlugin
* @subpackage actions
* @copyright SOTE (www.sote.pl)
* @license http://www.sote.pl/license/sote (Professional License SOTE)
* @version $Id: actions.class.php 15168 2011-09-20 11:56:58Z michal $
* @author Michal Prochowski <michal.prochowski@sote.pl>
*/
/**
* Klasa stPlatnosciPlBackendActions
*
* @package stPlatnosciPlPlugin
* @subpackage actions
*/
class stPlatnosciPlBackendActions extends stActions
{
/**
* Wyświetla konfigurację modułu
*/
public function executeIndex()
{
$this->labels = $this->getLabels();
$this->config = stConfig::getInstance($this->getContext());
if (!$this->config->get('configuration_check')) {
$notice = $this->getContext()->getI18n()->__('Jeśli nie masz jeszcze konta w PayU, załóż je')."&nbsp;".'<a href="https://registration.payu.com/boarding/#/form?lang=pl&nsf=true&origin=pl&partnerId=p3h2qb6k" target="_blank">'.$this->getContext()->getI18n()->__('tutaj').'</a>';
$this->setFlash("info", $notice, false);
}
if ($this->getRequest()->getMethod() == sfRequest::POST)
{
$this->config->setFromRequest('config');
$data = $this->getRequestParameter('config');
$this->config->set('configuration_check', false);
foreach ($this->getCurrencies() as $currency)
{
$shortcut = $currency->getShortcut();
$value = $this->config->get($shortcut);
if (isset($value['enabled']) && $value['enabled'])
{
$this->config->set('configuration_check', true);
break;
}
}
$this->config->save();
$this->setFlash('notice', 'Twoje zmiany zostały zapisane');
}
$this->config->load();
}
public function validateIndex()
{
if ($this->getRequest()->getMethod() == sfRequest::POST)
{
stAuthUsersListener::checkModificationCredentials($this, $this->getRequest(), $this->getModuleName());
$data = $this->getRequestParameter('config');
$i18n = $this->getContext()->getI18N();
foreach ($this->getCurrencies() as $currency)
{
$shortcut = $currency->getShortcut();
if (!isset($data[$shortcut]))
{
continue;
}
$ok = true;
if (!$data[$shortcut]['pos_id'] || !$data[$shortcut]['md5_secound_key'])
{
$ok = false;
$this->getRequest()->setError('config{'.$shortcut.'}{currency}', $shortcut);
}
if (!$data[$shortcut]['pos_id'])
{
$this->getRequest()->setError('config{'.$shortcut.'}{pos_id}', $i18n->__('Proszę uzupełnić pole.'));
}
if (!$data[$shortcut]['md5_secound_key'])
{
$this->getRequest()->setError('config{'.$shortcut.'}{md5_secound_key}', $i18n->__('Proszę uzupełnić pole.'));
}
if ($ok)
{
try
{
OpenPayU_Configuration::setEnvironment('secure');
OpenPayU_Configuration::setMerchantPosId($data[$shortcut]['pos_id']); // POS ID (Checkout)
OpenPayU_Configuration::setSignatureKey($data[$shortcut]['md5_secound_key']);
$order['notifyUrl'] = 'http://localhost/';
$order['customerIp'] = $_SERVER['REMOTE_ADDR'];
$order['merchantPosId'] = OpenPayU_Configuration::getMerchantPosId();
$order['description'] = 'New order';
$order['currencyCode'] = $shortcut;
$order['totalAmount'] = 3200;
$order['products'][0]['name'] = 'Product1';
$order['products'][0]['unitPrice'] = 3200;
$order['products'][0]['quantity'] = 1;
$result = OpenPayU_Order::create($order);
if ($result->getStatus() == 'ERROR_INCONSISTENT_CURRENCIES')
{
$this->getRequest()->setError('config{'.$shortcut.'}{currency}', $shortcut);
$this->getRequest()->setError('config{'.$shortcut.'}{payu}', $i18n->__('Brak zgodności z walutą "sklepu" PayU (Podaj konfigurację punktu płatności zgodną z wybraną walutą lub skontaktuj się z PayU)'));
}
}
catch(OpenPayU_Exception_Authorization $e)
{
$this->getRequest()->setError('config{'.$shortcut.'}{currency}', $shortcut);
$this->getRequest()->setError('config{'.$shortcut.'}{pos_id}', $i18n->__('Podana konfiguracja punktu płatności jest nieprawidłowa'));
$this->getRequest()->setError('config{'.$shortcut.'}{md5_secound_key}', $i18n->__('Podana konfiguracja punktu płatności jest nieprawidłowa'));
}
catch(OpenPayU_Exception $e)
{
$this->getRequest()->setError('config{'.$shortcut.'}{currency}', $shortcut);
$this->getRequest()->setError('config{'.$shortcut.'}{payu}', $i18n->__('Wystąpił problem z połączeniem z usługą PayU (%%error%%)', array('%%error%%' => $e->getMessage())));
}
}
}
}
return !$this->getRequest()->hasErrors();
}
public function getCurrencies()
{
if (!isset($this->currencies))
{
$this->currencies = CurrencyPeer::doSelectActive();
}
return $this->currencies;
}
public function getLabels()
{
$i18n_posid = $this->getContext()->getI18n()->__('Id punktu płatności (pos_id)');
$i18n_md5 = $this->getContext()->getI18n()->__('Drugi klucz (md5)');
$i18n_curency = $this->getContext()->getI18n()->__('Waluta');
$labels = array();
foreach ($this->getCurrencies() as $currency)
{
$shortcut = $currency->getShortcut();
$labels['config{'.$shortcut.'}{payu}'] = 'PayU';
$labels['config{'.$shortcut.'}{currency}'] = $i18n_curency;
$labels['config{'.$shortcut.'}{pos_id}'] = $i18n_posid;
$labels['config{'.$shortcut.'}{md5_secound_key}'] = $i18n_md5;
}
return $labels;
}
/**
* Akcja w przypadku błędu w uzupełnianiu pól
*/
public function handleErrorIndex()
{
$this->webRequest = new stWebRequest();
$this->config = stConfig::getInstance($this->getContext());
if ($this->getRequest()->getMethod() == sfRequest::POST)
{
$this->config->setFromRequest('config');
}
$this->labels = $this->getLabels();
return sfView::SUCCESS;
}
}

View File

@@ -0,0 +1,13 @@
<?php
class stPlatnosciPlBackendComponents extends sfComponents
{
public function executeListMenu()
{
}
}
?>

View File

@@ -0,0 +1,19 @@
<div class="list-menu">
<ul>
<li class="selected">
<?php echo link_to(__('PayU'),'stPlatnosciPlBackend/index')?>
</li>
<li>
<?php if (sfContext::getInstance()->getUser()->getCulture() == 'pl_PL'): ?>
<a href="https://www.sote.pl/docs/payu" target="_blank"><?php echo __('Dokumentacja'); ?></a>
<?php else: ?>
<a href="https://www.soteshop.com/docs/payu" target="_blank"><?php echo __('Documentation'); ?></a>
<?php endif; ?>
</li>
</ul>
</div>
<div class="clr"></div>

View File

@@ -0,0 +1,49 @@
<?php use_helper('I18N', 'stAdminGenerator', 'Validation');?>
<?php echo st_get_admin_head('stPlatnosciPlPlugin', __('PayU', array()), __('',array()),array('stPayment'));?>
<?php st_view_slot_start('application-menu') ?>
<?php st_include_component('stPlatnosciPlBackend', 'listMenu') ?>
<?php st_view_slot_end() ?>
<?php st_include_partial('stAdminGenerator/message', array('labels' => $labels));?>
<?php echo form_tag('platnoscipl/index', array('id' => 'sf_admin_config_form', 'name' => 'sf_admin_config_form', 'class' => 'admin_form'));?>
<fieldset>
<div class="content">
<div class="row">
<?php echo st_admin_get_form_field('config[autoredirect]', __('Automatyczne przekierowanie'), 1, 'checkbox_tag', array('checked' => $config->get('autoredirect'), 'help' => __('Przekierowuje automatycznie na stronę płatności po złożeniu zamówienia'))) ?>
</div>
<div class="clr"></div>
</div>
</fieldset>
<?php foreach ($currencies as $currency): $shortcut = $currency->getShortcut(); $current = $config->get($shortcut); $enabled = $current ? $current['enabled'] : false; ?>
<fieldset>
<h2><?php echo __('Waluta');?> <?php echo $shortcut ?></h2>
<div class="content">
<div class="row">
<?php echo st_admin_get_form_field('config['.$shortcut.'][enabled]', __('Aktywuj'), 1, 'checkbox_tag', array('checked' => $enabled, 'class' => 'payu_enable', 'size' => '60')) ?>
<div class="clr"></div>
</div>
<div class="row">
<?php echo st_admin_get_form_field('config['.$shortcut.'][pos_id]', __('Numer PosId'), $current ? $current['pos_id'] : '', 'input_tag', array('required' => true, 'disabled' => !$enabled, 'size' => '60')) ?>
<div class="clr"></div>
</div>
<div class="row">
<?php echo st_admin_get_form_field('config['.$shortcut.'][md5_secound_key]', __('Drugi klucz (md5)'), $current ? $current['md5_secound_key'] : '', 'input_tag', array('required' => true, 'disabled' => !$enabled, 'size' => '60')) ?>
<div class="clr"></div>
</div>
</div>
</fieldset>
<?php endforeach ?>
<?php echo st_get_admin_actions(array(
array('type' => 'save', 'label' => __('Zapisz', null, 'stAdminGeneratorPlugin'))
)) ?>
</form>
<div class="clr"></div>
<?php echo st_get_admin_foot();?>
<script type="text/javascript">
jQuery(function($) {
$('.payu_enable').change(function() {
var checkbox = $(this);
checkbox.closest('.content').find('input[type=text]').attr('disabled', !checkbox.prop('checked'))
});
});
</script>

View File

@@ -0,0 +1,144 @@
<?php
/**
* SOTESHOP/stPlatnosciPlPlugin
*
* Ten plik należy do aplikacji stPlatnosciPlPlugin opartej na licencji (Professional License SOTE).
* Nie zmieniaj tego pliku, jeśli chcesz korzystać z automatycznych aktualizacji oprogramowania.
* Jeśli chcesz wprowadzać swoje modyfikacje do programu, zapoznaj się z dokumentacją, jak zmieniać
* oprogramowanie bez zmiany kodu bazowego http://www.sote.pl/modifications
*
* @package stPlatnosciPlPlugin
* @subpackage actions
* @copyright SOTE (www.sote.pl)
* @license http://www.sote.pl/license/sote (Professional License SOTE)
* @version $Id: actions.class.php 5335 2010-05-28 11:39:59Z michal $
* @author Michal Prochowski <michal.prochowski@sote.pl>
*/
/**
* Klasa stPlatnosciPlFrontendActions
*
* @package stPlatnosciPlPlugin
* @subpackage actions
*/
class stPlatnosciPlFrontendActions extends stActions
{
/**
* Pozytywny powrót z płatności
*/
public function executeReturnSuccess()
{
if ($this->hasRequestParameter('error'))
{
return $this->redirect('@stPlatnosciPlPlugin?action=returnFail');
}
$this->smarty = new stSmarty($this->getModuleName());
}
/**
* Negatywny powrót z płatności
*/
public function executeReturnFail()
{
$this->smarty = new stSmarty($this->getModuleName());
$webpage = WebpagePeer::retrieveByState('CONTACT');
if ($webpage)
{
sfLoader::loadHelpers(array('Helper', 'stUrl'));
$this->smarty->assign('contact_url', st_url_for('stWebpageFrontend/index?url='.$webpage->getFriendlyUrl()));
}
}
public function executeProcessPayment()
{
$this->smarty = new stSmarty('stPlatnosciPlFrontend');
$api = new stPlatnosciPl();
$order = OrderPeer::retrieveByIdAndHashCode($this->getRequestParameter('id'), $this->getRequestParameter('hash'));
try
{
$url = $api->getOrderFormUrl($order);
if ($url)
{
return $this->renderJSON(array('redirect' => $url));
}
}
catch (OpenPayU_Exception $e)
{
stPlatnosciPl::log("Process Payment - Exception: in file ".$e->getFile().' on line '.$e->getLine().' with message'.$e->getMessage());
}
sfLoader::loadHelpers(array('Helper', 'stUrl'));
return $this->renderJSON(array('redirect' => st_url_for('stPlatnosciPlFrontend/returnFail?type=process')));
}
/**
* Odbieranie statusu transakcji
*/
public function executeStatusReport()
{
$body = file_get_contents('php://input');
$data = trim($body);
stPlatnosciPl::log("Status Report Request: ".$data);
$api = new stPlatnosciPl();
try
{
$order = $api->getOrderNotify($data);
} catch (OpenPayU_Exception $e) {
stPlatnosciPl::log("Process Payment - Exception: in file ".$e->getFile().' on line '.$e->getLine().' with message'.$e->getMessage());
throw $e;
}
if ($order && $order->status == 'COMPLETED')
{
$payment_id = null;
if ($this->hasRequestParameter('id'))
{
$order = OrderPeer::retrieveByIdAndHashCode($this->getRequestParameter('id'), $this->getRequestParameter('hash'));
if (null !== $order)
{
$payment = $order->getOrderPayment();
if (!$payment)
{
stPlatnosciPl::log("Status Report: Payment for order id {$this->getRequestParameter('id')} does not exist");
}
}
else
{
stPlatnosciPl::log("Status Report: Order with id {$this->getRequestParameter('id')} does not exist");
}
}
else
{
list($id) = explode(':', $order->extOrderId);
$payment = PaymentPeer::retrieveByPK($id);
if (!$payment)
{
stPlatnosciPl::log("Status Report: Payment with id $id does not exist");
}
}
if ($payment)
{
$payment->setStatus(true);
$payment->save();
stPlatnosciPl::log("Status Report: Payment with id {$payment->getId()} paid successfully");
}
}
return $this->renderText('OK');
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* SOTESHOP/stPlatnosciPlPlugin
*
* Ten plik należy do aplikacji stPlatnosciPlPlugin opartej na licencji (Professional License SOTE).
* Nie zmieniaj tego pliku, jeśli chcesz korzystać z automatycznych aktualizacji oprogramowania.
* Jeśli chcesz wprowadzać swoje modyfikacje do programu, zapoznaj się z dokumentacją, jak zmieniać
* oprogramowanie bez zmiany kodu bazowego http://www.sote.pl/modifications
*
* @package stPlatnosciPlPlugin
* @subpackage actions
* @copyright SOTE (www.sote.pl)
* @license http://www.sote.pl/license/sote (Professional License SOTE)
* @version $Id: components.class.php 10 2009-08-24 09:32:18Z michal $
* @author Michal Prochowski <michal.prochowski@sote.pl>
*/
/**
* Klasa stPlatnosciPlFrontendComponents
*
* @package stPlatnosciPlPlugin
* @subpackage actions
*/
class stPlatnosciPlFrontendComponents extends sfComponents {
/**
* Pokazywanie formularza płatności
*/
public function executeShowPayment() {
$this->smarty = new stSmarty('stPlatnosciPlFrontend');
$api = new stPlatnosciPl();
$order = stPaymentType::getOrderInSummary();
try
{
$url = $api->getOrderFormUrl($order);
if ($url)
{
return $this->getController()->redirect($url);
}
}
catch (OpenPayU_Exception $e)
{
stPlatnosciPl::log("stPlatnosciPl::getOrderFormUrl() - Exception:\n".$e->getFile().':'.$e->getLine().':'.$e->getMessage());
}
$webpage = WebpagePeer::retrieveByState('CONTACT');
if ($webpage)
{
sfLoader::loadHelpers(array('Helper', 'stUrl'));
$this->smarty->assign('contact_url', st_url_for('stWebpageFrontend/index?url='.$webpage->getFriendlyUrl()));
}
}
}

View File

@@ -0,0 +1,4 @@
<?php
st_theme_use_stylesheet('stPayment.css');
st_theme_use_stylesheet('stPlatnosciPlPlugin.css');
$smarty->display('platnoscipl_show_payment.html');

View File

@@ -0,0 +1 @@
<?php echo $sig;

View File

@@ -0,0 +1,11 @@
<?php
st_theme_use_stylesheet('stPayment.css');
if ($sf_request->getParameter('type') == 'process')
{
$smarty->display('platnoscipl_show_payment.html');
}
else
{
$smarty->display('platnoscipl_return_fail.html');
}

View File

@@ -0,0 +1,3 @@
<?php
st_theme_use_stylesheet('stPayment.css');
$smarty->display('platnoscipl_return_success.html');

View File

@@ -0,0 +1,8 @@
<div class="st_application">
<h1 class="st_title">
{__ text="Płatność"}
</h1>
<p style="text-align: center; margin-bottom: 20px;">
{__ text="Płatność nie została zrealizowana."}
</p>
</div>

View File

@@ -0,0 +1,8 @@
<div class="st_application">
<h1 class="st_title">
{__ text="Płatność"}
</h1>
<p style="text-align: center; margin-bottom: 20px;">
{__ text="Dziękujemy za dokonanie płatności."}
</p>
</div>

View File

@@ -0,0 +1,48 @@
<div id="st_frame_platnoscipl">
{if $check_configuration == true}
<div id="st_txt_platnoscipl">
<p>{__ text="Wybierz płatność i kliknij przycisk"} <b>{__ text='"Zapłać"'}</b> {__ text="aby przejść do serwisu PayU."}</p>
</div>
<div class="st_logo_platnosci">
<img src="/images/frontend/theme/default/stPlatnosciPlPlugin/logo.png" alt="Płatności.pl"/>
</div>
{$form_start}
{$hidden_pos_id}
{$hidden_pos_auth_key}
{$hidden_session_id}
{$hidden_amount}
{$hidden_desc}
{$hidden_order_id}
{$hidden_first_name}
{$hidden_last_name}
{$hidden_street}
{$hidden_street_hn}
{$hidden_street_an}
{$hidden_city}
{$hidden_post_code}
{$hidden_email}
{$hidden_language}
{$hidden_client_ip}
<script language="JavaScript" type="text/javascript" src="https://www.platnosci.pl/paygw/UTF/js/{$pos_id}/{$md5_first_key}/paytype.js"></script>
<script language="JavaScript" type="text/javascript">{$variant_name}</script>
{if $payback == true}
<br class="st_clear-all" />
<div id="st_form-payment-input_tag" class="st_row">
{$payback_login_label}
<div class="st_field">
{$payback_login}
</div>
</div>
{/if}
<div id="st_form-payment-submit" class="st_button-container">
<div class="st_button st_align-right">
<div class="st_button-left">
{$pay_submit}
</div>
</div>
</div>
</form>
{else}
{__ text="Płatność została błędnie skonfigurowana."}
{/if}
</div>

View File

@@ -0,0 +1,26 @@
<div id="st_box_payment" class="box roundies">
<div class="content">
<p><img src="/plugins/stPlatnosciPlPlugin/images/payu.png" alt=""/></p>
<p>{__ text="Płatność nie została zrealizowana."}</p>
{if $contact_url}
<form action="{$contact_url}" class="buttons" method="get">
<p>
<button type="submit" class="important roundies">
<span class="arrow_right">{__ text="Skontaktuj się z nami"}</span>
</button>
</p>
</form>
{/if}
</div>
</div>
{literal}
<script type="text/javascript">
jQuery(function($) {
$('#st_box_payment form').submit(function() {
var form = $(this);
window.location = form.attr('action');
return false;
});
});
</script>
{/literal}

View File

@@ -0,0 +1,24 @@
<div id="st_box_payment" class="box roundies">
<div class="content">
<p><img src="/plugins/stPlatnosciPlPlugin/images/payu.png" alt=""/></p>
<p>{__ text="Dziękujemy za dokonanie płatności."}</p>
<form action="{$homepage_url}" class="buttons" method="get">
<p>
<button type="submit" class="important roundies">
<span>{__ text="Wróć do zakupów" langCatalogue="stBasket"}</span>
</button>
</p>
</form>
</div>
</div>
{literal}
<script type="text/javascript">
jQuery(function($) {
$('#st_box_payment form').submit(function() {
var form = $(this);
window.location = form.attr('action');
return false;
});
});
</script>
{/literal}

View File

@@ -0,0 +1,26 @@
<div id="st_box_payment">
<img src="/plugins/stPlatnosciPlPlugin/images/payu.png" alt=""/><br />
<p style="text-align: center">
{__ text="Wystąpił problem z połączeniem się z serwisem PayU."}
{if $contact_url}
<form action="{$contact_url}" class="buttons" method="get">
<p>
<button type="submit" class="important roundies">
<span class="arrow_right">{__ text="Skontaktuj się z nami"}</span>
</button>
</p>
</form>
{/if}
</p>
</div>
{literal}
<script type="text/javascript">
jQuery(function($) {
$('#st_box_payment form').submit(function() {
var form = $(this);
window.location = form.attr('action');
return false;
});
});
</script>
{/literal}

View File

@@ -0,0 +1,23 @@
{set layout="one_column"}
<div id="payment">
<div class="panel panel-default center-block">
<div class="panel-heading">
{__ text="PayU"}
</div>
<div class="panel-body text-center">
<p>
<img src="/plugins/stPlatnosciPlPlugin/images/payu.png" alt="" style="width: 150px" />
</p>
<p>
{__ text="Płatność nie została zrealizowana."}<br/>
</p>
{if $contact_url}
<p>
<a href="{$contact_url}" class="btn btn-primary">
{__ text="Skontaktuj się z nami"}
</a>
</p>
{/if}
</div>
</div>
</div>

View File

@@ -0,0 +1,15 @@
{set layout="one_column"}
<div id="payment">
<div class="panel panel-default center-block">
<div class="panel-heading">
{__ text="PayU"}
</div>
<div class="panel-body text-center">
<p>
<img src="/plugins/stPlatnosciPlPlugin/images/payu.png" alt="" style="width: 150px" />
</p>
<p>{__ text="Dziękujemy za dokonanie płatności."}</p>
<a href="{$homepage_url}" class="btn btn-primary">{__ text="Wróć do zakupów" langCatalogue="stBasket"}</a>
</div>
</div>
</div>

View File

@@ -0,0 +1,20 @@
<div class="panel panel-default center-block">
<div class="panel-heading">
{__ text="PayU"}
</div>
<div id="payu-panel-body" class="panel-body text-center">
<p>
<img src="/plugins/stPlatnosciPlPlugin/images/payu.png" alt="" style="width: 150px" />
</p>
<p>
{__ text="Wystąpił problem z połączeniem się z serwisem PayU."}
</p>
{if $contact_url}
<p>
<a href="{$contact_url}" class="btn btn-primary">
{__ text="Skontaktuj się z nami"}
</a>
</p>
{/if}
</div>
</div>