first commit

This commit is contained in:
2024-11-11 18:46:54 +01:00
commit a630d17338
25634 changed files with 4923715 additions and 0 deletions

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);
}
}
}