AAAAindex.html000066600000000057151374152720006556 0ustar00 .htaccess000066600000000177151374152720006362 0ustar00 Order allow,deny Deny from all Checkout.php000066600000004160151374152720007036 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ defined('_JEXEC') or die('Restricted access'); define('KLARNA_CHECKOUT_DIR', dirname(__file__) . '/Checkout'); require_once KLARNA_CHECKOUT_DIR . '/ConnectorInterface.php'; require_once KLARNA_CHECKOUT_DIR . '/ResourceInterface.php'; require_once KLARNA_CHECKOUT_DIR . '/Connector.php'; require_once KLARNA_CHECKOUT_DIR . '/BasicConnector.php'; require_once KLARNA_CHECKOUT_DIR . '/Order.php'; require_once KLARNA_CHECKOUT_DIR . '/Digest.php'; require_once KLARNA_CHECKOUT_DIR . '/Exception.php'; require_once KLARNA_CHECKOUT_DIR . '/ConnectionErrorException.php'; require_once KLARNA_CHECKOUT_DIR . '/ConnectorException.php'; require_once KLARNA_CHECKOUT_DIR . '/UserAgent.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/TransportInterface.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/CURLHandleInterface.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/Request.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/Response.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/Transport.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/CURLTransport.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/CURLHeaders.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/CURLHandle.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/CURLFactory.php'; Checkout/ConnectorException.php000066600000002575151374152720012657 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Connector exception * * @category Payment * @package Klarna_Checkout * @author Rickard D. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_ConnectorException extends Klarna_Checkout_Exception { }Checkout/BasicConnector.php000066600000023242151374152720011734 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Basic implementation of the connector interface * * @category Payment * @package Klarna_Checkout * @author Rickard D. * @author Christer G. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_BasicConnector implements Klarna_Checkout_ConnectorInterface { /** * Klarna_Checkout_HTTP_TransportInterface Implementation * * @var Klarna_Checkout_HTTP_TransportInterface */ protected $http; /** * Digester class * * @var Klarna_Checkout_Digest */ protected $digester; /** * Shared Secret used to sign requests * * @var string */ private $_secret; /** * Create a new Checkout Connector * * @param Klarna_Checkout_HTTP_TransportInterface $http transport * @param Klarna_Checkout_Digest $digester Digest Generator * @param string $secret shared secret */ public function __construct( Klarna_Checkout_HTTP_TransportInterface $http, Klarna_Checkout_Digest $digester, $secret ) { $this->http = $http; $this->digester = $digester; $this->_secret = $secret; } /** * Create the user agent identifier to use * * @return Klarna_Checkout_UserAgent */ protected function userAgent() { return new Klarna_Checkout_UserAgent(); } /** * Applying the method on the specific resource * * @param string $method Http methods * @param Klarna_Checkout_ResourceInterface $resource resource * @param array $options Options * * @return mixed */ public function apply( $method, Klarna_Checkout_ResourceInterface $resource, array $options = null ) { switch ($method) { case 'GET': case 'POST': return $this->handle($method, $resource, $options, array()); default: throw new InvalidArgumentException( "{$method} is not a valid HTTP method" ); } } /** * Gets the underlying transport object * * @return Klarna_Checkout_HTTP_TransportInterface Transport object */ public function getTransport() { return $this->http; } /** * Set content (headers, payload) on a request * * @param Klarna_Checkout_ResourceInterface $resource Klarna Checkout Resource * @param string $method HTTP Method * @param string $payload Payload to send with the * request * @param string $url URL for request * * @return Klarna_Checkout_HTTP_Request */ protected function createRequest( Klarna_Checkout_ResourceInterface $resource, $method, $payload, $url ) { // Generate the digest string $digest = $this->digester->create($payload . $this->_secret); $request = $this->http->createRequest($url); $request->setMethod($method); // Set HTTP Headers $request->setHeader('User-Agent', (string)$this->userAgent()); $request->setHeader('Authorization', "Klarna {$digest}"); $request->setHeader('Accept', $resource->getContentType()); if (strlen($payload) > 0) { $request->setHeader('Content-Type', $resource->getContentType()); $request->setData($payload); } return $request; } /** * Get the url to use * * @param Klarna_Checkout_ResourceInterface $resource resource * @param array $options Options * * @return string Url to use for HTTP requests */ protected function getUrl( Klarna_Checkout_ResourceInterface $resource, array $options ) { if (array_key_exists('url', $options)) { return $options['url']; } return $resource->getLocation(); } /** * Get the data to use * * @param Klarna_Checkout_ResourceInterface $resource resource * @param array $options Options * * @return array data to use for HTTP requests */ protected function getData( Klarna_Checkout_ResourceInterface $resource, array $options ) { if (array_key_exists('data', $options)) { return $options['data']; } return $resource->marshal(); } /** * Throw an exception if the server responds with an error code. * * @param Klarna_Checkout_HTTP_Response $result HTTP Response object * * @throws Klarna_Checkout_HTTP_Status_Exception * @return void */ protected function verifyResponse(Klarna_Checkout_HTTP_Response $result) { // Error Status Code recieved. Throw an exception. if ($result->getStatus() >= 400 && $result->getStatus() <= 599) { throw new Klarna_Checkout_ConnectorException( $result->getData(), $result->getStatus() ); } } /** * Act upon the status of a response * * @param Klarna_Checkout_HTTP_Response $result response from server * @param Klarna_Checkout_ResourceInterface $resource associated resource * @param array $visited list of visited locations * * @return Klarna_Checkout_HTTP_Response */ protected function handleResponse( Klarna_Checkout_HTTP_Response $result, Klarna_Checkout_ResourceInterface $resource, array $visited = array() ) { // Check if we got an Error status code back $this->verifyResponse($result); $url = $result->getHeader('Location'); switch ($result->getStatus()) { case 301: // Update location and fallthrough $resource->setLocation($url); case 302: // Don't fallthrough for other than GET if ($result->getRequest()->getMethod() !== 'GET') { break; } case 303: // Detect eternal loops if (in_array($url, $visited)) { throw new Klarna_Checkout_ConnectorException( 'Infinite redirect loop detected.', -1 ); } $visited[] = $url; // Follow redirect return $this->handle( 'GET', $resource, array('url' => $url), $visited ); case 201: // Update Location $resource->setLocation($url); break; case 200: // Update Data on resource $json = json_decode($result->getData(), true); if ($json === null) { throw new Klarna_Checkout_ConnectorException( 'Bad format on response content.', -2 ); } $resource->parse($json); } return $result; } /** * Perform a HTTP Call on the supplied resource using the wanted method. * * @param string $method HTTP Method * @param Klarna_Checkout_ResourceInterface $resource Klarna Order * @param array $options Options * @param array $visited list of visited locations * * @throws Klarna_Checkout_Exception if 4xx or 5xx response code. * @return Result object containing status code and payload */ protected function handle( $method, Klarna_Checkout_ResourceInterface $resource, array $options = null, array $visited = array() ) { if ($options === null) { $options = array(); } // Define the target URL $url = $this->getUrl($resource, $options); // Set a payload if it is a POST call. $payload = ''; if ($method === 'POST') { $payload = json_encode($this->getData($resource, $options)); } // Create a HTTP Request object $request = $this->createRequest($resource, $method, $payload, $url); // $this->_setContent($request, $payload, $method); // Execute the HTTP Request $result = $this->http->send($request); // Handle statuses appropriately. return $this->handleResponse($result, $resource, $visited); } } Checkout/Exception.php000066600000002535151374152720011000 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Basic exception class * * @category Payment * @package Klarna_Checkout * @author Majid G. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_Exception extends Exception { }Checkout/ConnectionErrorException.php000066600000002637151374152720014035 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Connection exception * * @category Payment * @package Klarna_Checkout * @author Rickard D. * @author Christer G. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_ConnectionErrorException extends Klarna_Checkout_Exception { } Checkout/ConnectorInterface.php000066600000003720151374152720012612 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Interface for the resource object * * @category Payment * @package Klarna_Checkout * @author Majid G. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ interface Klarna_Checkout_ConnectorInterface { /** * Applying the method on the specific resource * * @param string $method Http methods * @param Klarna_Checkout_ResourceInterface $resource resource * @param array $options Options * * @return void */ public function apply( $method, Klarna_Checkout_ResourceInterface $resource, array $options = null ); /** * Gets the underlying transport object * * @return Klarna_Checkout_HTTP_TransportInterface Transport object */ public function getTransport(); } Checkout/ResourceInterface.php000066600000004070151374152720012446 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Interface for the resource object * * @category Payment * @package Klarna_Checkout * @author Majid G. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ interface Klarna_Checkout_ResourceInterface { /** * Get the URL of the resource * * @return string */ public function getLocation(); /** * Set the URL of the resource * * @param string $location URL of the resource * * @return void */ public function setLocation($location); /** * Return content type of the resource * * @return string Content type */ public function getContentType(); /** * Update resource with the new data * * @param array $data data * * @return void */ public function parse(array $data); /** * Basic representation of the object * * @return array data */ public function marshal(); } Checkout/Order.php000066600000013015151374152720010110 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Implementation of the order resource * * @category Payment * @package Klarna_Checkout * @author Majid G. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_Order implements Klarna_Checkout_ResourceInterface, ArrayAccess { /** * Base URI that is used to create order resources * * @var string */ public static $baseUri = null; /** * Content Type to use * * @var string */ public static $contentType = null; /** * URI of remote resource * * @var string */ private $_location; /** * Order data * * @var array */ private $_data = array(); /** * Connector * * @var Klarna_Checkout_ConnectorInterface */ protected $connector; /** * Create a new Order object * * @param Klarna_Checkout_ConnectorInterface $connector connector to use * @param string $uri uri of resource * * @return void */ public function __construct( Klarna_Checkout_ConnectorInterface $connector, $uri = null ) { $this->connector = $connector; if ($uri !== null) { $this->setLocation($uri); } } /** * Get the URL of the resource * * @return string */ public function getLocation() { return $this->_location; } /** * Set the URL of the resource * * @param string $location URL of the resource * * @return void */ public function setLocation($location) { $this->_location = strval($location); } /** * Return content type of the resource * * @return string Content type */ public function getContentType() { return self::$contentType; } /** * Replace resource data * * @param array $data data * * @return void */ public function parse(array $data) { $this->_data = $data; } /** * Basic representation of the object * * @return array Data */ public function marshal() { return $this->_data; } /** * Create a new order * * @param array $data data to initialise order resource with * * @return void */ public function create(array $data) { $options = array( 'url' => self::$baseUri, 'data' => $data ); $this->connector->apply('POST', $this, $options); } /** * Fetch order data * * @return void */ public function fetch() { $options = array( 'url' => $this->_location ); $this->connector->apply('GET', $this, $options); } /** * Update order data * * @param array $data data to update order resource with * * @return void */ public function update( array $data ) { $options = array( 'url' => $this->_location, 'data' => $data ); $this->connector->apply('POST', $this, $options); } /** * Get value of a key * * @param string $key Key * * @return mixed data */ public function offsetGet($key) { if (!is_string($key)) { throw new InvalidArgumentException("Key must be string"); } return $this->_data[$key]; } /** * Set value of a key * * @param string $key Key * @param mixed $value Value of the key * * @return void */ public function offsetSet($key, $value) { if (!is_string($key)) { throw new InvalidArgumentException("Key must be string"); } $value = print_r($value, true); throw new RuntimeException( "Use update function to change values. trying to set $key to $value" ); } /** * Check if a key exists in the resource * * @param string $key key * * @return boolean */ public function offsetExists($key) { return array_key_exists($key, $this->_data); } /** * Unset the value of a key * * @param string $key key * * @return void */ public function offsetUnset($key) { throw new RuntimeException( "unset of fields not supported. trying to unset $key" ); } } Checkout/index.html000066600000000000151374152720010307 0ustar00Checkout/UserAgent.php000066600000005541151374152720010737 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * UserAgent string builder * * @category Payment * @package Klarna_Checkout * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_UserAgent { /** * Components of the user-agent * * @var array */ private $_fields; /** * Initialise user-agent with default fields */ public function __construct() { $this->_fields = array( 'Library' => array( 'name' => 'Klarna.ApiWrapper', 'version' => '1.1.0', ), 'OS' => array( 'name' => php_uname('s'), 'version' => php_uname('r') ), 'Language' => array( 'name' => 'PHP', 'version' => phpversion() ) ); } /** * Add a new field to the user agent * * @param string $field Name of field * @param array $data data array with name, version and possibly options * * @return void */ public function addField($field, array $data) { if (array_key_exists($field, $this->_fields)) { throw new Klarna_Checkout_Exception( "Unable to redefine field {$field}" ); } $this->_fields[$field] = $data; } /** * Serialise fields to a user agent string * * @return string */ public function __toString() { $parts = array(); foreach ($this->_fields as $key => $value) { $parts[] = "$key/{$value['name']}_{$value['version']}"; if (array_key_exists('options', $value)) { $parts[] = '(' . implode(' ; ', $value['options']) . ')'; } } return implode(' ', $parts); } } Checkout/HTTP/Transport.php000066600000003147151374152720011615 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Factory of HTTP Transport * * @category Payment * @package Payment_Klarna * @subpackage Unit_Tests * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_Transport { /** * Create a new transport instance * * @return Klarna_Checkout_HTTP_TransportInterface */ public static function create() { return new Klarna_Checkout_HTTP_CURLTransport( new Klarna_Checkout_HTTP_CURLFactory ); } } Checkout/HTTP/TransportInterface.php000066600000005153151374152720013435 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Interface for a Klarna HTTP Transport object * * @category Payment * @package Payment_Klarna * @subpackage Interfaces * @author Klarna * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ interface Klarna_Checkout_HTTP_TransportInterface { /** * Specifies the number of seconds before the connection times out. * * @param int $timeout number of seconds * * @throws InvalidArgumentException If the specified argument * is not of type integer. * @return void */ public function setTimeout($timeout); /** * Gets the number of seconds before the connection times out. * * @return int timeout in number of seconds */ public function getTimeout(); /** * Performs a HTTP request. * * @param Klarna_Checkout_HTTP_Request $request the HTTP request to send. * * @throws Klarna_Checkout_ConnectionErrorException Thrown for unspecified * network or hardware issues. * @return Klarna_Checkout_HTTP_Response */ public function send(Klarna_Checkout_HTTP_Request $request); /** * Creates a HTTP request object. * * @param string $url the request URL. * * @throws InvalidArgumentException If the specified argument * is not of type string. * @return Klarna_Checkout_HTTP_Request */ public function createRequest($url); } Checkout/HTTP/index.html000066600000000000151374152720011066 0ustar00Checkout/HTTP/CURLHeaders.php000066600000004761151374152720011665 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * A simple class handling the header callback for cURL. * * @category Payment * @package Payment_Klarna * @subpackage HTTP * @author Klarna * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_CURLHeaders { /** * Response headers, cleared for each request. * * @var array */ protected $headers; /** * Initializes a new instance of the HTTP cURL class. */ public function __construct() { $this->headers = array(); } /** * Callback method to handle custom headers. * * @param resource $curl the cURL resource. * @param string $header the header data. * * @return int the number of bytes handled. */ public function processHeader($curl, $header) { $curl = null; //TODO replace with regexp, e.g. /^([^:]+):([^:]*)$/ ? $pos = strpos($header, ':'); // Didn't find a colon. if ($pos === false) { // Not real header, abort. return strlen($header); } $key = substr($header, 0, $pos); $value = trim(substr($header, $pos+1)); $this->headers[$key] = trim($value); return strlen($header); } /** * Gets the accumulated headers. * * @return array */ public function getHeaders() { return $this->headers; } } Checkout/HTTP/CURLTransport.php000066600000012411151374152720012275 0ustar00 * @copyright 2012 Klarna AB AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Klarna HTTP transport implementation for cURL * * @category Payment * @package Payment_Klarna * @subpackage HTTP * @author Klarna * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_CURLTransport implements Klarna_Checkout_HTTP_TransportInterface { const DEFAULT_TIMEOUT = 10; /** * @var Klarna_Checkout_HTTP_CURLFactory */ protected $curl; /** * Number of seconds before the connection times out. * * @var int */ protected $timeout; /** * Initializes a new instance of the HTTP cURL class. * * @param Klarna_Checkout_HTTP_CURLFactory $curl factory to for curl handles */ public function __construct(Klarna_Checkout_HTTP_CURLFactory $curl) { $this->curl = $curl; $this->timeout = self::DEFAULT_TIMEOUT; } /** * Sets the number of seconds until a connection times out. * * @param int $timeout number of seconds * * @return void */ public function setTimeout($timeout) { $this->timeout = intval($timeout); } /** * Gets the number of seconds before the connection times out. * * @return int timeout in number of seconds */ public function getTimeout() { return $this->timeout; } /** * Performs a HTTP request. * * @param Klarna_Checkout_HTTP_Request $request the HTTP request to send. * * @throws RuntimeException Thrown if a cURL handle cannot * be initialized. * @throws Klarna_Checkout_ConnectionErrorException Thrown for unspecified * network or hardware issues. * @return Klarna_Checkout_HTTP_Response */ public function send(Klarna_Checkout_HTTP_Request $request) { $curl = $this->curl->handle(); if ($curl === false) { throw new RuntimeException( 'Failed to initialize a HTTP handle.' ); } $url = $request->getURL(); $curl->setOption(CURLOPT_URL, $url); $method = $request->getMethod(); if ($method === 'POST') { $curl->setOption(CURLOPT_POST, true); $curl->setOption(CURLOPT_POSTFIELDS, $request->getData()); } // Convert headers to cURL format. $requestHeaders = array(); foreach ($request->getHeaders() as $key => $value) { $requestHeaders[] = $key . ': ' . $value; } $curl->setOption(CURLOPT_HTTPHEADER, $requestHeaders); $curl->setOption(CURLOPT_RETURNTRANSFER, true); $curl->setOption(CURLOPT_CONNECTTIMEOUT, $this->timeout); $curlHeaders = new Klarna_Checkout_HTTP_CURLHeaders(); $curl->setOption( CURLOPT_HEADERFUNCTION, array(&$curlHeaders, 'processHeader') ); // TODO remove me when real cert is in place $curl->setOption(CURLOPT_SSL_VERIFYPEER, false); $payload = $curl->execute(); $info = $curl->getInfo(); $curl->close(); /* * A failure occured if: * payload is false (e.g. HTTP timeout?). * info is false, then it has no HTTP status code. */ if ($payload === false || $info === false) { throw new Klarna_Checkout_ConnectionErrorException( "Connection to '{$url}' failed." ); } $headers = $curlHeaders->getHeaders(); // Convert Content-Type into a normal header $headers['Content-Type'] = $info['content_type']; $response = new Klarna_Checkout_HTTP_Response( $request, $headers, intval($info['http_code']), strval($payload) ); return $response; } /** * Creates a HTTP request object. * * @param string $url the request URL. * * @throws InvalidArgumentException If the specified argument * is not of type string. * @return Klarna_Checkout_HTTP_Request */ public function createRequest($url) { return new Klarna_Checkout_HTTP_Request($url); } } Checkout/HTTP/CURLHandleInterface.php000066600000003661151374152720013324 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Defines a cURL handle interface * * @category Payment * @package Payment_Klarna * @subpackage HTTP * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ interface Klarna_Checkout_HTTP_CURLHandleInterface { /** * Set an option for the cURL transfer * * @param int $name option the set * @param mixed $value the value to be set on option * * @return void */ public function setOption($name, $value); /** * Perform the cURL session * * @return mixed response */ public function execute(); /** * Get information regarding this transfer * * @return array */ public function getInfo(); /** * Close the cURL session * * @return void */ public function close(); } Checkout/HTTP/Request.php000066600000010605151374152720011246 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Klarna HTTP Request class * * @category Payment * @package Payment_Klarna * @subpackage HTTP * @author Klarna * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_Request { /** * @var string */ protected $url; /** * @var string */ protected $method; /** * @var array */ protected $headers; /** * @var string */ protected $data; /** * Initializes a new instance of the HTTP request class. * * @param string $url the request URL. * * @throws InvalidArgumentException If the specified argument * is not of type string. */ public function __construct($url) { $this->url = $url; $this->method = 'GET'; $this->headers = array(); $this->data = ''; } /** * Gets the request URL. * * @return string the request URL. */ public function getURL() { return $this->url; } /** * Specifies the HTTP method used for the request. * * @param string $method a HTTP method. * * @throws InvalidArgumentException If the specified argument * is not of type string. * @return void */ public function setMethod($method) { $this->method = strtoupper($method); } /** * Gets the HTTP method used for the request. * * @return string a HTTP method */ public function getMethod() { return $this->method; } /** * Specifies a header for the request. * * @param string $name the header name * @param mixed $value the header value * * @throws InvalidArgumentException If the argument name is not of type * string or an empty string. * @return void */ public function setHeader($name, $value) { $this->headers[$name] = strval($value); } /** * Gets a specific header for the request. * * @param string $name the header name * * @throws InvalidArgumentException If the specified argument * is not of type string. * @return string|null the header value or null if it doesn't exist */ public function getHeader($name) { if (!array_key_exists($name, $this->headers)) { return null; } return $this->headers[$name]; } /** * Gets the headers specified for the request. * * @return array */ public function getHeaders() { return $this->headers; } /** * Sets the data (payload) for the request. * * \code * $request->setMethod('POST'); * $request->setData('some data'); * \endcode * * @param string $data the request payload * * @throws InvalidArgumentException If the specified argument * is not of type string. * @return void */ public function setData($data) { $this->data = $data; } /** * Gets the data (payload) for the request. * * @return string the request payload */ public function getData() { return $this->data; } } Checkout/HTTP/Response.php000066600000007040151374152720011413 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Klarna HTTP Response class * * @category Payment * @package Payment_Klarna * @subpackage HTTP * @author Klarna * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_Response { /** * @var int */ protected $status; /** * @var Klarna_Checkout_HTTP_Request */ protected $request; /** * @var array */ protected $headers; /** * @var string */ protected $data; /** * Initializes a new instance of the HTTP response class. * * @param Klarna_Checkout_HTTP_Request $request the origin request. * @param array $headers the response HTTP headers. * @param int $status the HTTP status code. * @param string $data the response payload. */ public function __construct( Klarna_Checkout_HTTP_Request $request, array $headers, $status, $data ) { $this->request = $request; $this->headers = array(); foreach ($headers as $key => $value) { $this->headers[strtolower($key)] = $value; } $this->status = $status; $this->data = $data; } /** * Gets the HTTP status code. * * @return int HTTP status code. */ public function getStatus() { return $this->status; } /** * Gets the HTTP request this response originated from. * * @return Klarna_Checkout_HTTP_Request */ public function getRequest() { return $this->request; } /** * Gets specified HTTP header. * * @param string $name the header name. * * @throws InvalidArgumentException If the specified argument * is not of type string. * @return string|null Null if header doesn't exist, else header value. */ public function getHeader($name) { $name = strtolower($name); if (!array_key_exists($name, $this->headers)) { return null; } return $this->headers[$name]; } /** * Gets the headers specified for the response. * * @return array */ public function getHeaders() { return $this->headers; } /** * Gets the data (payload) for the response. * * @return string the response payload. */ public function getData() { return $this->data; } } Checkout/HTTP/CURLHandle.php000066600000005055151374152720011502 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * A wrapper around the cURL functions * * @category Payment * @package Payment_Klarna * @subpackage HTTP * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_CURLHandle implements Klarna_Checkout_HTTP_CURLHandleInterface { /** * cURL handle * @var resource */ private $_handle = null; /** * Create a new cURL handle */ public function __construct() { if (!extension_loaded('curl')) { throw new RuntimeException( 'cURL extension is requred.' ); } $this->_handle = curl_init(); } /** * Set an option for the cURL transfer * * @param int $name option the set * @param mixed $value the value to be set on option * * @return void */ public function setOption($name, $value) { curl_setopt($this->_handle, $name, $value); } /** * Perform the cURL session * * @return mixed response */ public function execute() { return curl_exec($this->_handle); } /** * Get information regarding this transfer * * @return array */ public function getInfo() { return curl_getinfo($this->_handle); } /** * Close the cURL session * * @return void */ public function close() { curl_close($this->_handle); } } Checkout/HTTP/.htaccess000066600000000177151374152720010706 0ustar00 Order allow,deny Deny from all Checkout/HTTP/CURLFactory.php000066600000003041151374152720011707 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Factory of cURL handles * * @category Payment * @package Payment_Klarna * @subpackage Unit_Tests * @author Klarna * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_CURLFactory { /** * Create a new cURL handle * * @return Klarna_Checkout_HTTP_CURLHandle */ public function handle() { return new Klarna_Checkout_HTTP_CURLHandle(); } } Checkout/Digest.php000066600000003224151374152720010255 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Class to handle the digesting of hash string * * @category Payment * @package Klarna_Checkout * @author Rickard D. * @author Christer G. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_Digest { /** * create a digest from a supplied string * * @param string $digestString string to hash * * @return string Base64 and SHA256 hashed string */ public function create($digestString) { return base64_encode(hash('sha256', $digestString, true)); } } Checkout/Connector.php000066600000003441151374152720010771 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Connector factory * * @category Payment * @package Klarna_Checkout * @author Rickard D. * @author Christer G. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_Connector { /** * Create a new Checkout Connector * * @param string $secret string used to sign requests * * @return Klarna_Checkout_ConnectorInterface */ public static function create($secret) { return new Klarna_Checkout_BasicConnector( Klarna_Checkout_HTTP_Transport::create(), new Klarna_Checkout_Digest, $secret ); } } Checkout/.htaccess000066600000000177151374152720010127 0ustar00 Order allow,deny Deny from all sofortLib_refund.inc.php000066600000012474151376502640011360 0ustar00status */ public function sendRequest() { parent::sendRequest(); return $this->getStatusArray(); } /** * add a new refund to this message * * @param string $transaction transaction id of transfer you want to refund * @param float $amount amount of money to refund, less or equal to amount of original transfer * @param string $comment comment that will be displayed in admin-menu later * @return SofortLib_Refund $this */ public function addRefund($transaction, $amount, $comment = '') { $this->_parameters['refund'][] = array( 'transaction' => $transaction, 'amount' => $amount, 'comment' => $comment, ); return $this; } /** * set data of account * * @param string $bank_code bank code of bank * @param string $account_number account number * @param string $holder Name/Holder of this account * @return SofortLib_Multipay $this */ public function setSenderAccount($bankCode, $accountNumber, $holder = '') { $this->_parameters['sender'] = array( 'holder' => $holder, 'account_number' => $accountNumber, 'bank_code' => $bankCode, ); return $this; } /** * * Setter for title * @param string $arg */ public function setTitle($arg) { $this->_parameters['title'] = $arg; return $this; } /** * * Getter for transactions * @param int $i */ public function getTransactionId($i = 0) { return $this->_response['refunds']['refund'][$i]['transaction']['@data']; } /** * * Getter for amounts * @param int $i */ public function getAmount($i = 0) { return $this->_response['refunds']['refund'][$i]['amount']['@data']; } /** * * Getter for statuses * @param int $i */ public function getStatus($i = 0) { return $this->_response['refunds']['refund'][$i]['status']['@data']; } /** * * Getter for comments * @param int $i */ public function getComment($i = 0) { return $this->_response['refunds']['refund'][$i]['comment']['@data']; } /** * * Getter for refund's title */ public function getTitle() { return $this->_response['refunds']['title']['@data']; } /** * * Getter for refund's errors * @param int $i */ public function getRefundError($i = 0) { return parent::getError('all', $this->_response[$i]); } /** * * Has an error occurred for refund * @param int $i */ public function isRefundError($i = 0) { return $this->_response['refunds']['refund'][$i]['status']['@data'] == 'error'; } /** * * Getter for DTA (MT940) */ public function getDta() { return $this->_response['refunds']['dta']['@data']; } /** * * Getter for response, as an array */ public function getAsArray() { return $this->_response; } /** * * Getter for status array * @deprecated */ public function getStatusArray() { $ret = array(); foreach ($this->_response['refunds']['refund'] as $transaction) { $ret[$transaction['transaction']['@data']] = $transaction['status']['@data']; } return $ret; } /** * Parse the XML (override) * @see SofortLib_Abstract::_parseXml() */ protected function _parseXml() {} /** * Handle errors occurred * @see SofortLib::_handleErrors() */ protected function _handleErrors() { if (!isset($this->_response['refunds']['refund'][0])) { $tmp = $this->_response['refunds']['refund']; unset($this->_response['refunds']['refund']); $this->_response['refunds']['refund'][] = $tmp; } foreach ($this->_response['refunds']['refund'] as $response) { //handle errors if (isset($response['errors']['error'])) { if (!isset($response['errors']['error'][0])) { $tmp = $response['errors']['error']; unset($response['errors']['error']); $response['errors']['error'][0] = $tmp; } foreach ($response['errors']['error'] as $error) { $this->errors['global'][] = $this->_getErrorBlock($error); } } //handle warnings if (isset($response['warnings']['warning'])) { if (!isset($response['warnings']['warning'][0])) { $tmp = $response['warnings']['warning']; unset($response['warnings']['warning']); $response['warnings']['warning'][0] = $tmp; } foreach ($response['warnings']['warning'] as $error) { $this->warnings['global'][] = $this->_getErrorBlock($error); } } } } } ?>sofortLib_ideal_classic.php000066600000007027151376502640012102 0ustar00getRelatedBanks(); //get all iDEAL-Banks * $sofort->getPaymentUrl(); //returns paymentUrl including (including ...&hash=1234567890&...) * * Copyright (c) 2012 SOFORT AG * * Released under the GNU General Public License (Version 2) * [http://www.gnu.org/licenses/gpl-2.0.html] * * $Date: 2012-11-23 17:15:47 +0100 (Fri, 23 Nov 2012) $ * @version SofortLib 1.5.4 $Id: sofortLib_ideal_classic.php 5773 2012-11-23 16:15:47Z dehn $ * @author SOFORT AG http://www.sofort.com (integration@sofort.com) * */ class SofortLib_iDealClassic extends SofortLib_SofortueberweisungClassic { private $_apiUrl = ''; private $_apiKey = ''; private $_relatedBanks = array(); private $_SofortLib_iDeal_Banks = null; protected $_password; protected $_userId; protected $_projectId; protected $_paymentUrl = 'https://www.sofort.com/payment/ideal'; protected $_hashFields = array( 'user_id', 'project_id', 'sender_holder', 'sender_account_number', 'sender_bank_code', 'sender_country_id', 'amount', 'reason_1', 'reason_2', 'user_variable_0', 'user_variable_1', 'user_variable_2', 'user_variable_3', 'user_variable_4', 'user_variable_5', ); /** * * Contructor for SofortLib_iDealClassic * @param string $configKey * @param string $password * @param string $hashFunction */ public function __construct($configKey, $password, $hashFunction = 'sha1') { list($userId, $projectId, $apiKey) = explode(':', $configKey); $this->_password = $password; $this->_userId = $this->params['user_id'] = $userId; $this->_projectId = $this->params['project_id'] = $projectId; $this->_hashFunction = strtolower($hashFunction); $this->_paymentUrl = $this->_getPaymentDomain(); $this->_SofortLib_iDeal_Banks = new SofortLib_iDeal_Banks($configKey, $this->_paymentUrl); } /** * * Set sender's country id * @param string $senderCountryId * @return instance */ public function setSenderCountryId($senderCountryId = 'NL') { $this->params['sender_country_id'] = $senderCountryId; } /** * * Set sender's bank code * @param string $senderBankCode * @return instance */ public function setSenderBankCode($senderBankCode) { $this->params['sender_bank_code'] = $senderBankCode; return $this; } /** * Getter for occurred errors * (non-PHPdoc) * @see SofortLib_SofortueberweisungClassic::getError() */ public function getError(){ return $this->error; } /** * Get related banks of iDeal * @return array */ public function getRelatedBanks() { $this->_SofortLib_iDeal_Banks->sendRequest(); return $this->_SofortLib_iDeal_Banks->getBanks(); } /** * Getter for the payment domain * (non-PHPdoc) * @see SofortLib_SofortueberweisungClassic::_getPaymentDomain() */ protected function _getPaymentDomain() { return (getenv('idealApiUrl') != '') ? getenv('idealApiUrl') : $this->_paymentUrl; } } ?>sofortLib_http.inc.php000066600000015320151376502640011045 0ustar00url = $url; $this->headers = $headers; $this->compression = $compression; $this->proxy = $proxy; } /** * * Getter for information * @param string $opt */ public function getinfo($opt = '') { if (!empty($opt)) { return $this->info[$opt]; } else { return $this->info; } } /** * send data to server with POST request * @param string $data * @param string $url * @param string $headers */ public function post($data, $url = false, $headers = false) { if (function_exists('curl_init')) { return $this->postCurl($data, $url, $headers); } else { return $this->postSocket($data, $url, $headers); } } /** * post data using curl * @param string $data * @param string $url * @param string $headers */ public function postCurl($data, $url = false, $headers = false) { $this->connectionMethod = 'cURL'; if ($url === false) { $url = $this->url; } if ($headers === false) { $headers = $this->headers; } $headers[] = 'User-Agent: SofortLib-php/'.SOFORTLIB_VERSION.'-'.$this->connectionMethod; $process = curl_init($url); // curl_setopt($process, CURLOPT_HTTPHEADER, $headers); curl_setopt($process, CURLOPT_HTTPHEADER, array_merge($headers, array('Expect:'))); curl_setopt($process, CURLOPT_POST, 1); curl_setopt($process, CURLOPT_HEADER, false); if ($this->compression !== false) { curl_setopt($process, CURLOPT_ENCODING, $this->compression); } curl_setopt($process, CURLOPT_TIMEOUT, 15); if ($this->proxy) { curl_setopt($process, CURLOPT_PROXY, $this->proxy); } curl_setopt($process, CURLOPT_POSTFIELDS, $data); curl_setopt($process, CURLOPT_RETURNTRANSFER, 1); curl_setopt($process, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false); $return = curl_exec($process); $this->info = curl_getinfo($process); $this->error = curl_error($process); $this->httpStatus = $this->info['http_code']; $this->_response = $return; curl_close($process); if ($this->error) { return $this->_xmlError('00'.$this->error, $this->_response); } return $return; } /** * * HTTP error handling * @return array(code, message, response[if available]) */ public function getHttpCode() { switch ($this->httpStatus) { case(200): return array('code' => 200, 'message' => $this->_xmlError($this->httpStatus, 'OK'), 'response' => $this->_response); break; case(301): case(302): return array('code' => $this->httpStatus, 'message' => $this->_xmlError($this->httpStatus, 'Redirected Request'), 'response' => $this->_response); break; case(401): $this->error = 'Unauthorized'; return array('code' => 401, 'message' => $this->_xmlError($this->httpStatus, 'Unauthorized'), 'response' => $this->_response); break; case(0): case(404): $this->httpStatus = 404; $this->error = 'URL not found '.$this->url; return array('code' => 404, 'message' => $this->_xmlError($this->httpStatus, 'URL not found '.$this->url), 'response' => ''); break; case(500): $this->error = 'An error occurred'; return array('code' => 500, 'message' => $this->_xmlError($this->httpStatus, 'An error occurred'), 'response' => $this->_response); break; default: return array('code' => $this->httpStatus, 'message' => $this->_xmlError($this->httpStatus, 'Something went wrong, not handled httpStatus'), 'response' => $this->_response); break; } } /** * * Getter for HTTP status code */ public function getHttpStatusCode() { $status = $this->getHttpCode(); return $status['code']; } /** * * Getter for HTTP status message */ public function getHttpStatusMessage() { $status = $this->getHttpCode(); return $status['message']; } /** * this is a fallback with fsockopen if curl is not activated * we still need openssl and ssl wrapper support (PHP >= 4.3.0) * @param string $data * @param string $url * @param array $headers * @return string body */ public function postSocket($data, $url = false, $headers = false) { $this->connectionMethod = 'Socket'; if ($url === false) { $url = $this->url; } if ($headers === false) { $headers = $this->headers; } $headers[] = 'User-Agent: SofortLib-php/'.SOFORTLIB_VERSION.'-'.$this->connectionMethod; $uri = parse_url($url); $out = 'POST '.$uri['path'].' HTTP/1.1'."\r\n"; $out .= 'HOST: '.$uri['host']."\r\n"; $out .= 'Connection: close'."\r\n"; $out .= 'Content-Length: '.strlen($data)."\r\n"; foreach ($headers as $header) { $out .= $header."\r\n"; } $out .= "\r\n".$data; //connect to webservice if (!$fp = fsockopen('ssl://'.$uri['host'], 443, $errno, $errstr, 15)) { $this->error = 'fsockopen() failed, enable ssl and curl: '.$errno.' '.$errstr; return false; } //send data stream_set_timeout($fp, 15); fwrite($fp, $out); //read response $return = ''; while (!feof($fp)) { $return .= fgets($fp, 512); } fclose($fp); //split header/body preg_match('#^(.+?)\r\n\r\n(.*)#ms', $return, $body); //get statuscode preg_match('#HTTP/1.*([0-9]{3}).*#i', $body[1], $status); $this->info['http_code'] = $status[1]; $this->httpStatus = $status[1]; return $body[2]; } /** * * Error method - format an error * @param string $error */ public function error($error) { echo '
cURL Error
'.$error.'
'; die; } /** * * Output an xml error * @param string $code * @param string $message */ private function _xmlError($code, $message) { return '0'.$code.''.$message.''; } } /// \endcond ?>sofortLib_notification.inc.php000066600000004553151376502640012562 0ustar00getNotification(); * * Copyright (c) 2012 SOFORT AG * * Released under the GNU General Public License (Version 2) * [http://www.gnu.org/licenses/gpl-2.0.html] * * $Date: 2012-11-23 17:15:47 +0100 (Fri, 23 Nov 2012) $ * @version SofortLib 1.5.4 $Id: sofortLib_notification.inc.php 5773 2012-11-23 16:15:47Z dehn $ * @author SOFORT AG http://www.sofort.com (integration@sofort.com) * */ class SofortLib_Notification extends SofortLib_Abstract { protected $_parameters = array(); protected $_response = array(); private $_transactionId = ''; private $_time; /** * Constructor for SofortLib_Notification */ public function __construct() { parent::__construct('', '', ''); } /** * reads the input and tries to read the transaction id * * @return array transactionid=>status */ public function getNotification($source = 'php://input') { $data = file_get_contents($source); //we don't really need a huge parser, simply extract the transaction-id if (!preg_match('#([0-9a-z-]+)#i', $data, $matches)) { $this->log(__CLASS__.' <- '.$data); $this->errors['error']['message'] = 'could not parse message'; return false; } $this->_transactionId = $matches[1]; $this->log(__CLASS__.' <- '.$data); preg_match('##i', $data, $matches); if (isset($matches[1])) { $this->_time = $matches[1]; } return $this->_transactionId; } /** * Sending a request is not possible * (non-PHPdoc) * @see SofortLib_Abstract::sendRequest() */ public function sendRequest() { trigger_error('sendRequest() not possible in this case', E_USER_NOTICE); } /** * * Getter for variable time */ public function getTime() { return $this->_time; } /** * * Getter for transaction */ public function getTransactionId() { return $this->_transactionId; } } ?>sofortLib_multipay.inc.php000066600000060413151376502640011735 0ustar00setSofortueberweisung(); //OR setSofortrechnung(), setSofortvorkasse() etc. * $objMultipay->set...($param); //set params for PNAG-API (watch API-documentation for needed params) * $objMultipay->add...($param); //add params for PNAG-API (watch API-documentation for needed params) * $errorsAndWarnings = $objMultipay->validateRequest(); //send param against the PNAG-API without setting an order * ... make own validation of $errorsAndWarnings and if ok ... * $objMultipay->sendRequest(); //set the order at PNAG * $errorsAndWarnings = $objMultipay->getErrors(); //should not occur, if validation was ok * ... make own validation of $errorsAndWarnings and if ok ... * ... finish order in the shopsystem * * Copyright (c) 2012 SOFORT AG * * Released under the GNU General Public License (Version 2) * [http://www.gnu.org/licenses/gpl-2.0.html] * * $Date: 2012-11-23 17:15:47 +0100 (Fri, 23 Nov 2012) $ * @version SofortLib 1.5.4 $Id: sofortLib_multipay.inc.php 5773 2012-11-23 16:15:47Z dehn $ * @author SOFORT AG http://www.sofort.com (integration@sofort.com) * */ class SofortLib_Multipay extends SofortLib_Abstract { protected $_parameters = array(); protected $_response = array(); protected $_xmlRootTag = 'multipay'; private $_paymentMethods = array(); private $_transactionId = ''; private $_paymentUrl = ''; /** * create a new payment object * @param string $apikey your API key * @param int $projectId your project id */ public function __construct($configKey = '') { list($userId, $projectId, $apiKey) = explode(':', $configKey); $apiUrl = (getenv('sofortApiUrl') != '') ? getenv('sofortApiUrl') : 'https://api.sofort.com/api/xml'; parent::__construct($userId, $apiKey, $apiUrl); $this->_parameters['project_id'] = $projectId; } /** * the language code will help in determing what language to * use when displaying the payment form, other data like * browser settings and ip will be used as well * * @param string $arg de|en|nl|fr ... * @return SofortLib_Multipay */ public function setLanguageCode($arg) { $this->_parameters['language_code'] = $arg; return $this; } /** * timeout how long this transaction configuration will be valid for * this is the time between the generation of the payment url and * the user completing the form, should be at least two to three minutes * defaults to unlimited if not set * * @param int $arg timeout in seconds * @return SofortLib_Multipay */ public function setTimeout($arg) { $this->_parameters['timeout'] = $arg; return $this; } /** * set the email address of the customer * this will be used for sofortvorkasse and sofortrechnung * * @param string $arg email address * @return SofortLib_Multipay */ public function setEmailCustomer($arg) { $this->_parameters['email_customer'] = $arg; return $this; } /** * set the phone number of the customer * * @param string $arg phone number * @return SofortLib_Multipay */ public function setPhoneNumberCustomer($arg) { $this->_parameters['phone_customer'] = $arg; return $this; } /** * add another variable this can be your internal order id or similar * * @param string $arg the contents of the variable * @return SofortLib_Multipay */ public function addUserVariable($arg) { $this->_parameters['user_variables']['user_variable'][] = $arg; return $this; } /** * set data of account * * @param string $bank_code bank code of bank * @param string $account_number account number * @param string $holder Name/Holder of this account * @return SofortLib_Multipay $this */ public function setSenderAccount($bankCode, $accountNumber, $holder) { $this->_parameters['sender'] = array( 'bank_code' => $bankCode, 'account_number' => $accountNumber, 'holder' => $holder, ); return $this; } /** * amount of this payment * * @param double $arg * @param string $currency currency of this transaction, default EUR * @return SofortLib_Multipay $this */ public function setAmount($arg, $currency = 'EUR') { $this->_parameters['amount'] = $arg; $this->_parameters['currency_code'] = $currency; return $this; } /** * set the reason values of this transfer * * @param string $arg max 27 characters * @param string $arg2 max 27 characters * @return SofortLib_Multipay $this */ public function setReason($arg, $arg2 = '') { $arg = preg_replace('#[^a-zA-Z0-9+-\.,]#', ' ', $arg); $arg = substr($arg, 0, 27); $arg2 = preg_replace('#[^a-zA-Z0-9+-\.,]#', ' ', $arg2); $arg2 = substr($arg2, 0, 27); $this->_parameters['reasons']['reason'][0] = $arg; $this->_parameters['reasons']['reason'][1] = $arg2; return $this; } /** * * Setter for redirecting the success link automatically * @param boolean $arg */ public function setSuccessLinkRedirect($arg) { $this->_parameters['success_link_redirect'] = $arg; } /** * the customer will be redirected to this url after a successful * transaction, this should be a page where a short confirmation is * displayed * * @param string $arg the url after a successful transaction * @return SofortLib_Multipay */ public function setSuccessUrl($successUrl, $redirect = true) { $this->_parameters['success_url'] = $successUrl; $this->setSuccessLinkRedirect($redirect); return $this; } /** * the customer will be redirected to this url if he uses the * abort link on the payment form, should redirect him back to * his cart or to the payment selection page * * @param string $arg url for aborting the transaction * @return SofortLib_Multipay */ public function setAbortUrl($arg) { $this->_parameters['abort_url'] = $arg; return $this; } /** * if the customer takes too much time or if your timeout is set too short * he will be redirected to this page * * @param string $arg url * @return SofortLib_Multipay */ public function setTimeoutUrl($arg) { $this->_parameters['timeout_url'] = $arg; return $this; } /** * set the url where you want notification about status changes * being sent to. Use SofortLib_Notification and SofortLib_TransactionData * to further process that notification * * @param string $arg url * @return SofortLib_Multipay */ public function setNotificationUrl($arg) { $this->_parameters['notification_urls']['notification_url'] = array($arg); return $this; } /** * you can set set multiple urls for receiving notifications * this might be helpfull if you have several systems for processing * an order (e.g. an ERP system) * * @param string $arg url * @return SofortLib_Multipay */ public function addNotificationUrl($arg) { $this->_parameters['notification_urls']['notification_url'][] = $arg; return $this; } /** * set the email address where you want notification about status changes * being sent to. * * @param string $arg email address * @return SofortLib_Multipay */ public function setNotificationEmail($arg) { $this->_parameters['notification_emails']['notification_email'] = array($arg); return $this; } /** * you can set set multiple emails for receiving notifications * * @param string $arg email * @return SofortLib_Multipay */ public function addNotificationEmail($arg) { $this->_parameters['notification_emails']['notification_email'][] = $arg; return $this; } /** * set the version of this payment module * this is helpfull so the support staff can easily * find out if someone uses an outdated module * * @param string $arg version string of your module * @return SofortLib_Multipay */ public function setVersion($arg) { $this->_parameters['interface_version'] = $arg; return $this; } /** * add sofortueberweisung as payment method * @param double $amount this amount only applies to this payment method * @return SofortLib_Multipay $this */ public function setSofortueberweisung($amount = '') { $this->_paymentMethods[] = 'su'; if (!array_key_exists('su', $this->_parameters) || !is_array($this->_parameters['su'])) { $this->_parameters['su'] = array(); } if (!empty($amount)) { $this->_parameters['su']['amount'] = $amount; } return $this; } /** * add sofortueberweisung as payment method * adds customer protection * @param double $amount this amount only applies to this payment method * @return SofortLib_Multipay $this */ public function setSofortueberweisungCustomerprotection($customerProtection = true) { $this->_paymentMethods[] = 'su'; if (!array_key_exists('su', $this->_parameters) || !is_array($this->_parameters['su'])) { $this->_parameters['su'] = array(); } $this->_parameters['su']['customer_protection'] = $customerProtection ? 1 : 0; return $this; } /** * add sofortlastschrift as payment method * @param double $amount this amount only applies to this payment method * @return SofortLib_Multipay $this */ public function setSofortlastschrift($amount = '') { $this->_paymentMethods[] = 'sl'; if (!array_key_exists('sl', $this->_parameters) || !is_array($this->_parameters['sl'])) { $this->_parameters['sl'] = array(); } if (!empty($amount)) { $this->_parameters['sl']['amount'] = $amount; } return $this; } /** * set the address of the customer for address validation, * this should be the invoice address of the customer * * @param string $firstname * @param string $lastname * @param string $street * @param string $streetNumber * @param string $zipcode * @param string $city * @param int $salutation [2|3] 2=Mr. 3=Mrs. * @param string $country country code, only DE allowed at the moment * @return SofortLib_Multipay $this */ public function setSofortlastschriftAddress($firstname, $lastname, $street, $streetNumber, $zipcode, $city, $salutation, $country = 'DE') { $this->_parameters['sl']['invoice_address']['salutation'] = $salutation; $this->_parameters['sl']['invoice_address']['firstname'] = $firstname; $this->_parameters['sl']['invoice_address']['lastname'] = $lastname; $this->_parameters['sl']['invoice_address']['street'] = $street; $this->_parameters['sl']['invoice_address']['street_number'] = $streetNumber; $this->_parameters['sl']['invoice_address']['zipcode'] = $zipcode; $this->_parameters['sl']['invoice_address']['city'] = $city; $this->_parameters['sl']['invoice_address']['country_code'] = $country; return $this; } /** * add lastschrift as payment method * @param double $amount this amount only applies to this payment method * @return SofortLib_Multipay $this */ public function setLastschrift($amount = '') { $this->_paymentMethods[] = 'ls'; if (!array_key_exists('ls', $this->_parameters) || !is_array($this->_parameters['ls'])) { $this->_parameters['ls'] = array(); } if (!empty($amount)) { $this->_parameters['ls']['amount'] = $amount; } return $this; } /** * * Setter for base checks disabled of Lastschrift */ public function setLastschriftBaseCheckDisabled() { $this->_parameters['ls']['base_check_disabled'] = 1; return $this; } /** * * Setter for extende checks disabled of Lastschrift */ public function setLastschriftExtendedCheckDisabled() { $this->_parameters['ls']['extended_check_disabled'] = 1; return $this; } /** * * Setter for mobile checks disabled of Lastschrift */ public function setLastschriftMobileCheckDisabled() { $this->_parameters['ls']['mobile_check_disabled'] = 1; return $this; } /** * set the address of the customer for address validation, * this should be the invoice address of the customer * * @param string $firstname * @param string $lastname * @param string $street * @param string $streetNumber * @param string $zipcode * @param string $city * @param int $salutation [2|3] 2=Mr. 3=Mrs. * @param string $country country code, only DE allowed at the moment * * @return SofortLib_Multipay object */ public function setLastschriftAddress($firstname, $lastname, $street, $streetNumber, $zipcode, $city, $salutation, $country = 'DE') { $this->_parameters['ls']['invoice_address']['salutation'] = $salutation; $this->_parameters['ls']['invoice_address']['firstname'] = $firstname; $this->_parameters['ls']['invoice_address']['lastname'] = $lastname; $this->_parameters['ls']['invoice_address']['street'] = $street; $this->_parameters['ls']['invoice_address']['street_number'] = $streetNumber; $this->_parameters['ls']['invoice_address']['zipcode'] = $zipcode; $this->_parameters['ls']['invoice_address']['city'] = $city; $this->_parameters['ls']['invoice_address']['country_code'] = $country; return $this; } /** * add sofortrechnung as payment method * if you use this payment method you have to provide * the customer address and cart as well * the total amount of this payment method will * be determined by the total of the cart * * @return SofortLib_Multipay object */ public function setSofortrechnung() { $this->_paymentMethods[] = 'sr'; if (!array_key_exists('sr', $this->_parameters) || !is_array($this->_parameters['sr'])) { $this->_parameters['sr'] = array(); } return $this; } /** * add sofortvorkasse as payment method * @param double $amount this amount only applies to this payment method * * @return SofortLib_Multipay objet */ public function setSofortvorkasse($amount = '') { $this->_paymentMethods[] = 'sv'; if (!array_key_exists('sv', $this->_parameters) || !is_array($this->_parameters['sv'])) { $this->_parameters['sv'] = array(); } if (!empty($amount)) { $this->_parameters['sv']['amount'] = $amount; } return $this; } /** * add sofortvorkasse as payment method * adds customer protection * @param double $amount this amount only applies to this payment method * @return SofortLib_Multipay $this */ public function setSofortvorkasseCustomerprotection($customerProtection = true) { $this->_paymentMethods[] = 'sv'; if (!array_key_exists('sv', $this->_parameters) || !is_array($this->_parameters['sv'])) { $this->_parameters['sv'] = array(); } $this->_parameters['sv']['customer_protection'] = $customerProtection ? 1 : 0; return $this; } /** * set the customer id which will appear on top of the invoice * @param int $arg * @return SofortLib_Multipay $this */ public function setSofortrechnungCustomerId($arg) { $this->_parameters['sr']['customer_id'] = $arg; return $this; } /** * set the order id which will appear on top of the invoice * @param int $arg * @return SofortLib_Multipay $this */ public function setSofortrechnungOrderId($arg) { $this->_parameters['sr']['order_id'] = $arg; return $this; } /** * set debitor vat number for invoice * @param string $vatNumber * @return SofortLib_Multipay $this */ public function setDebitorVatNumber($vatNumber) { $this->_parameters['sr']['debitor_vat_number'] = $vatNumber; return $this; } /** * set the invoice address of the customer * * @param string $firstname * @param string $lastname * @param string $street * @param string $streetNumber * @param string $zipcode * @param string $city * @param int $salutation [2|3] 2 = Mr. 3 = Mrs. * @param string $country country code, only DE allowed at the moment * @return SofortLib_Multipay $this */ public function setSofortrechnungInvoiceAddress($firstname, $lastname, $street, $streetNumber, $zipcode, $city, $salutation, $country = 'DE', $nameAdditive = '', $streetAdditive = '', $companyName = '') { $this->_parameters['sr']['invoice_address']['salutation'] = $salutation; $this->_parameters['sr']['invoice_address']['firstname'] = $firstname; $this->_parameters['sr']['invoice_address']['lastname'] = $lastname; $this->_parameters['sr']['invoice_address']['street'] = $street; $this->_parameters['sr']['invoice_address']['street_number'] = $streetNumber; $this->_parameters['sr']['invoice_address']['zipcode'] = $zipcode; $this->_parameters['sr']['invoice_address']['city'] = $city; $this->_parameters['sr']['invoice_address']['country_code'] = $country; $this->_parameters['sr']['invoice_address']['name_additive'] = $nameAdditive; $this->_parameters['sr']['invoice_address']['street_additive'] = $streetAdditive; $this->_parameters['sr']['invoice_address']['company'] = $companyName; return $this; } /** * set the shipping address of the customer * * @param string $firstname * @param string $lastname * @param string $street * @param string $streetNumber * @param string $zipcode * @param string $city * @param int $salutation [2|3] 1 = Mr. 2 = Mrs. * @param string $country country code, only DE allowed at the moment * @return SofortLib_Multipay $this */ public function setSofortrechnungShippingAddress($firstname, $lastname, $street, $streetNumber, $zipcode, $city, $salutation, $country = 'DE', $nameAdditive = '', $streetAdditive = '', $companyName = '') { $this->_parameters['sr']['shipping_address']['salutation'] = $salutation; $this->_parameters['sr']['shipping_address']['firstname'] = $firstname; $this->_parameters['sr']['shipping_address']['lastname'] = $lastname; $this->_parameters['sr']['shipping_address']['street'] = $street; $this->_parameters['sr']['shipping_address']['street_number'] = $streetNumber; $this->_parameters['sr']['shipping_address']['zipcode'] = $zipcode; $this->_parameters['sr']['shipping_address']['city'] = $city; $this->_parameters['sr']['shipping_address']['country_code'] = $country; $this->_parameters['sr']['shipping_address']['name_additive'] = $nameAdditive; $this->_parameters['sr']['shipping_address']['street_additive'] = $streetAdditive; $this->_parameters['sr']['shipping_address']['company'] = $companyName; return $this; } /** * add one item to the cart * * @param int $itemId unique item id * @param string $productNumber product number, EAN code, ISBN number or similar * @param string $title description of this title * @param double $unit_price gross price of one item * @param int $productType product type number see manual (0=other, 1=shipping, ...) * @param string $description additional description of this item * @param int $quantity default 1 * @param int $tax tax in percent, default 19 */ public function addSofortrechnungItem($itemId, $productNumber, $title, $unitPrice, $productType = 0, $description = '', $quantity = 1, $tax = 19) { $unitPrice = number_format($unitPrice, 2, '.', ''); $tax = number_format($tax, 2, '.', ''); $quantity = intval($quantity); if (empty($title)) { $this->setError('Title must not be empty. Title: '.$title.', Productnumber: '.$productNumber.', Unitprice: '.$unitPrice.', Quantity: '.$quantity.', Description: '.$description); } $this->_parameters['sr']['items']['item'][] = array( 'item_id' => $itemId, 'product_number' => $productNumber, 'product_type' => $productType, 'title' => $title, 'description' => $description, 'quantity' => $quantity, 'unit_price' => $unitPrice, 'tax' => $tax, ); } /** * * Setter for commenting Rechnung by sofort * @param string $comment */ public function setSofortrechungComment($comment) { $this->_parameters['sr']['items']['comment'] = $comment; } /** * Remove one item from cart * @param $itemId * @return boolean */ public function removeSofortrechnungItem($itemId) { $i = 0; foreach ($this->_parameters['sr']['items'] as $item) { if (isset($item['item_id']) && $item['item_id'] == $itemId) { unset($this->_parameters['sr']['items']['item'][$i]); return true; } $i++; } return false; } /** * Update one item in cart * @param $itemId * @param $quantity * @param $unit_price * @return boolean */ public function updateSofortrechnungItem($itemId, $quantity, $unitPrice) { $i = 0; foreach ($this->_parameters['sr']['items'] as $item) { if (isset($item[$i]['item_id']) && $item[$i]['item_id'] == $itemId) { $this->_parameters['sr']['items']['item'][$i]['quantity'] = $quantity; $this->_parameters['sr']['items']['item'][$i]['unit_price'] = $unitPrice; return true; } $i++; } return false; } /** * * Getter for invoice's item * @param int $itemId */ public function getSofortrechnungItemAmount($itemId) { $i = 0; foreach ($this->_parameters['sr']['items'] as $item) { if (isset($item['item_id']) && $item['item_id'] == $itemId) { return $this->_parameters['sr']['items']['item'][$i]['quantity'] * $this->_parameters['sr']['items']['item'][$i]['unit_price']; } $i++; } } /** * * Setter for invoice's time for payment * @param string $arg */ public function setSofortrechnungTimeForPayment($arg) { $this->_parameters['sr']['time_for_payment'] = $arg; return $this; } /** * makes a request against the pnag-API and returns all API-Fault/Warnings * it doesnt result in an order at pnag! * @return bool */ public function sendValidationRequest() { $this->_validateOnly = true; $this->sendRequest(); return isset($this->_response['validation']['status']['@data']) ? true : false; } /** * * Getter for invoice's item * @param int $itemId */ public function getSofortrechnungItem($itemId) { return $this->_parameters['sr']['items'][$itemId]; } /** * * Getter for all invoice's items */ public function getSofortrechnungItems() { return $this->_parameters['sr']['items']; } /** * after configuration and sending this request * you can use this function to redirect the customer * to the payment form * * @return string url of payment form */ public function getPaymentUrl() { $this->_paymentUrl = isset($this->_response['new_transaction']['payment_url']['@data']) ? $this->_response['new_transaction']['payment_url']['@data'] : false; return $this->_paymentUrl; } /** * * Getter for payment method * @param int $i */ public function getPaymentMethod($i = 0) { if ($i < 0 || $i >= count($this->_paymentMethods)) { return false; } return $this->_paymentMethods[$i]; } /** * * Is sofortüberweisung */ public function isSofortueberweisung() { return array_key_exists('su', $this->_parameters); } /** * * Is vorkasse by sofort */ public function isSofortvorkasse() { return array_key_exists('sv', $this->_parameters); } /** * * Check if it is a sofortlastschrift */ public function isSofortlastschrift() { return array_key_exists('sl', $this->_parameters); } /** * * Is lastschrift by sofort */ public function isLastschrift() { return array_key_exists('ls', $this->_parameters); } /** * * Is rechnung by sofort */ public function isSofortrechnung() { return array_key_exists('sr', $this->_parameters); } /** * * Check if consumer protection / customer protection enabled * @param string $product */ public function isConsumerProtection($product) { if (in_array($product, array('su', 'sv'))) { if(isset($this->_parameters[$product]['customer_protection'])) { return $this->_parameters[$product]['customer_protection']; } else { return false; } } else { return false; } } /** * * Check if debit pay check disabled * @param string $product * @param boolean $check */ public function isDebitpayCheckDisabled($product, $check) { if (in_array($product, array('ls', 'sl')) && in_array($check, array('base_check_disabled', 'extended_check_disabled', 'mobile_check_disabled'))) { return $this->_parameters[$product][$check]; } else { return false; } } /** * use this id to track the transaction * * @return string transaction id */ public function getTransactionId() { return $this->_transactionId; } /** * Parse the XML (override) * (non-PHPdoc) * @see SofortLib_Abstract::_parseXml() */ protected function _parseXml() { $this->_transactionId = isset($this->_response['new_transaction']['transaction']['@data']) ? $this->_response['new_transaction']['transaction']['@data'] : false; } } ?>sofortLib.php000066600000042627151376502640007250 0ustar00_userId = $userId; $this->_apiKey = $apiKey; $this->SofortLibHttp = new SofortLib_Http($apiUrl, $this->_getHeaders()); $this->SofortLibLogger = new SofortLibLogger(); $this->enableLogging = (getenv('sofortDebug') == 'true') ? true : false; } /** * Getter for warnings * * @return empty array if no warnings exists ELSE array with warning-codes and warning-messages * @public */ public function getWarnings($paymentMethod = 'all', $message = '') { if ($message == '') { $message = $this->warnings; } else { $message = $this->_parseErrorresponse($message); } $supportedPaymentMethods = $this->_products; if (!in_array($paymentMethod, $supportedPaymentMethods)) { $paymentMethod = 'all'; } $returnArray = array(); //return global + selected payment method foreach ($supportedPaymentMethods as $pm) { if (($paymentMethod == 'all' || $pm == 'global' || $paymentMethod == $pm) && array_key_exists($pm, $message)) { $returnArray = array_merge($returnArray, $message[$pm]); } } return $returnArray; } /** * Getter for errors * * @param (optional) array $message response array * @return emtpy array if no error exist ELSE array with error-codes and error-messages * @public */ public function getErrors($paymentMethod = 'all', $message = '') { if ($message == '') { $message = $this->handleErrors($this->errors); } else { $message = $this->_parseErrorresponse($message); } if (!$this->isError($paymentMethod, $message)) { return array(); } $supportedPaymentMethods = $this->_products; if (!in_array($paymentMethod, $supportedPaymentMethods)) { $paymentMethod = 'all'; } $returnArray = array(); //return global + selected payment method foreach ($supportedPaymentMethods as $pm) { if (($paymentMethod == 'all' || $pm == 'global' || $paymentMethod == $pm) && array_key_exists($pm, $message)) { $returnArray = array_merge($returnArray, $message[$pm]); } } return $returnArray; } /** * * Alter error array and set error message and error code together as one * @param array $errors */ function handleErrors($errors) { $errorKeys = array_keys($errors); foreach($errorKeys as $errorKey) { $i = 0; foreach ($errors[$errorKey] as $partialError) { if (!empty($errors[$errorKey][$i]['field']) && $errors[$errorKey][$i]['field'] !== '') { $errors[$errorKey][$i]['code'] .= '.'.$errors[$errorKey][$i]['field']; } $i++; }; } return $errors; } /** * returns one error message * @see getErrors() for more detailed errors * @param array $message response array * @return string errormessage ELSE false * @public */ public function getError($paymentMethod = 'all', $message = '') { if ($message == '') { $message = $this->errors; } else{ $message = $this->_parseErrorresponse($message); } $supportedPaymentMethods = $this->_products; if (!in_array($paymentMethod, $supportedPaymentMethods)) { $paymentMethod = 'all'; } if (is_array($message)) { if ($paymentMethod == 'all') { foreach ($message as $key => $error) { if (is_array($error) && !empty($error)){ return 'Error: '.$error[0]['code'].':'.$error[0]['message']; } } } else { foreach ($message as $key => $error) { if ($key != 'global' && $key != $paymentMethod) { continue; } if (is_array($error) && !empty($error)){ return 'Error: '.$error[0]['code'].':'.$error[0]['message']; } } } } return false; } /** * * checks (response)-array for warnings * @param array $message response array * @param string $paymentMethod - 'all', 'sr', 'su', 'sv', 'sa', 'ls', 'sl', 'sf' (if unknown then it uses "all") * @return boolean true if warnings found ELSE false * @public */ public function isWarning($paymentMethod = 'all', $message = '') { if ($message == '') { $message = $this->warnings; } if (empty($message)) { return false; } if (!in_array($paymentMethod, $this->_products)) { $paymentMethod = 'all'; } if ($paymentMethod == 'all') { if (is_array($message)) { foreach ($message as $error) { if (!empty($error)) { return true; } } } } else { //paymentMethod-specific search if (is_array($message)) { if ((isset($message[$paymentMethod]) && !empty($message[$paymentMethod])) || (isset($message['global']) && !empty($message['global']))) { return true; } } } return false; } /** * checks (response)-array for error * @param array $message response array * @param string $paymentMethod - 'all', 'sr', 'su', 'sv', 'sa', 'ls', 'sl', 'sf' (if unknown then it uses "all") * @return boolean true if errors found (in given payment-method or in 'global') ELSE false * @public */ public function isError($paymentMethod = 'all', $message = '') { if ($message == '') { $message = $this->errors; } if (empty($message)) { return false; } if (!in_array($paymentMethod, $this->_products)) { $paymentMethod = 'all'; } if ($paymentMethod == 'all') { if (is_array($message)) { foreach ($message as $error) { if (!empty($error)) { return true; } } } } else { //paymentMethod-specific search if (is_array($message)) { if ((isset($message[$paymentMethod]) && !empty($message[$paymentMethod])) || (isset($message['global']) && !empty($message['global']))) { return true; } } } return false; } /** * set Errors * later use getError(), getErrors() or isError() to retrieve them * @param string $message - Detailinformationen about the error * @param string $pos - Position in the errors-array, must be one of: 'global', 'sr', 'su', 'sv', 'sa', 'ls', 'sl', 'sf' * @param string $errorCode - a number or string to specify the errors in the module * @param string $field - if $errorCode deals with a field */ public function setError($message, $pos = 'global', $errorCode = '-1', $field = '') { $supportedErrorsPos = array('global', 'sr', 'su', 'sv', 'sa', 'ls', 'sl', 'sf'); if (!in_array($pos, $supportedErrorsPos)) { $paymentMethod = 'global'; } if (!isset($this->errors[$pos])) { $this->errors[$pos] = array(); } $error = array ('code' => $errorCode, 'message' => $message, 'field' => $field); $this->errors[$pos][] = $error; } /** * delete all warnings * @public */ public function deleteAllWarnings() { $this->errorPos = 'global'; $this->errorCountTemp = 0; $this->warnings = array(); } /** * delete all errors * @public */ public function deleteAllErrors() { $this->errorPos = 'global'; $this->errorCountTemp = 0; $this->errors = array(); } /** * internal send-method, will check http-errorcode and return body * @param String $message message to post * @return string error or body * @protected */ protected function _sendMessage($message) { $response = $this->SofortLibHttp->post($message); if ($response === false) { return $this->SofortLibHttp->error; } $http = $this->SofortLibHttp->getHttpCode(); if (!in_array($http['code'], array('200', '301', '302'))) { return $http['message']; } return $response; } /** * * define all headers here * @private */ private function _getHeaders() { $header = array(); $header[] = 'Authorization: Basic '.base64_encode($this->_userId.':'.$this->_apiKey); $header[] = 'Content-Type: application/xml; charset=UTF-8'; $header[] = 'Accept: application/xml; charset=UTF-8'; $header[] = 'X-Powered-By: PHP/'.phpversion(); return $header; } /** * * prepare $this->errors for insertion of errors * @private */ private function _createErrorArrayStructure() { if (!isset($this->errors[$this->errorPos])) { $this->errors[$this->errorPos] = array(); } if (!isset($this->errors[$this->errorPos][$this->errorCountTemp])) { $this->errors[$this->errorPos][$this->errorCountTemp] = array(); } } /** * * prepare $this->warnings for insertion of errors * @see _createErrorsarrayStructure(); * @private */ private function _createWarningArrayStructure() { if (!isset($this->warnings[$this->errorPos])) { $this->warnings[$this->errorPos] = array(); } if (!isset($this->warnings[$this->errorPos][$this->errorCountTemp])) { $this->warnings[$this->errorPos][$this->errorCountTemp] = array(); } } /** * display stacktrace * @private * @param $provideObject */ private function _backtrace($provideObject = false) { $last = ''; $file = __FILE__; $args = ''; $message = ''; foreach (debug_backtrace($provideObject) as $row) { if ($last != $row['file']) { $message .= "File: $file
\n"; } $last=$row['file']; $message .= ' Line: $row[line]: '; if ($row['class']!='') { $message .= '$row[class]$row[type]$row[function]'; } else { $message .= '$row[function]'; } $message .= '('; $message .= join('', '',$args); $message .= ")
\n"; } return $message; } /** * *Setter for an error * @public * @param string $message * @param boolean $fatal */ public function error($message, $fatal = false){ $errorArray = array('message' => 'Error: '.$message, 'code' => '10'); $this->errors['global'][] = $errorArray; } /** * * error while parsing xml * @public * @param unknown_type $message */ public function fatalError($message){ return $this->error($message, true); } /** * * Enable logging in object * @see SofortLib setLogEnabled * @deprecated * @public */ public function enableLog() { $this->enableLogging = true; return $this; } /** * * Disable logging in object * @see SofortLib setLogDisabled * @deprecated * @public */ public function disableLog() { $this->enableLogging = false; return $this; } /** * * Set logging enable * @uses enableLog(); * @public */ public function setLogEnabled() { $this->enableLogging = true; return $this; } /** * * Set logging disabled * @uses disableLog(); * @public */ public function setLogDisabled() { $this->enableLogging = false; return $this; } /** * * Set the SofortLibLogger object * @param object $SofortLibLogger * @public */ public function setLogger($SofortLibLogger) { $this->SofortLibLogger = $SofortLibLogger; } /** * * log the given string into warning_log.txt * use $this->enableLog(); to enable logging before! * @param string $message */ public function logWarning($message) { if ($this->enableLogging) { $uri = dirname(__FILE__).'/logs/warning_log.txt'; $this->SofortLibLogger->log($message, $uri); } } /** * * log the given string into error_log.txt * use $this->enableLog(); to enable logging before! * @param string $message */ public function logError($message) { if ($this->enableLogging) { $uri = dirname(__FILE__).'/logs/error_log.txt'; $this->SofortLibLogger->log($message, $uri); } } /** * * log the given string into log.txt * use $this->enableLog(); to enable logging before! * @param string $message */ public function log($message) { if ($this->enableLogging) { $uri = $this->_logfilePath ? $this->_logfilePath : dirname(__FILE__).'/logs/log.xml'; $this->SofortLibLogger->log($message, $uri); } } /** * * Set the path of the logfile * @param string $path */ public function setLogfilePath($path) { $this->_logfilePath = $path; } /** * sets the api version which should be used * @param float $version */ public function setApiVersion($version) { $this->_apiVersion = $version; } /** * * Handle Errors occurred */ protected function _handleErrors() { //handle errors if (isset($this->_response['errors']['error'])) { if (!isset($this->_response['errors']['error'][0])) { $tmp = $this->_response['errors']['error']; unset($this->_response['errors']['error']); $this->_response['errors']['error'][0] = $tmp; } foreach ($this->_response['errors']['error'] as $error) { $this->errors['global'][] = $this->_getErrorBlock($error); } } foreach ($this->_products as $product) { if (isset($this->_response['errors'][$product])) { if (!isset($this->_response['errors'][$product]['errors']['error'][0])) { $tmp = $this->_response['errors'][$product]['errors']['error']; unset($this->_response['errors'][$product]['errors']['error']); $this->_response['errors'][$product]['errors']['error'][0] = $tmp; } foreach ($this->_response['errors'][$product]['errors']['error'] as $error) { $this->errors[$product][] = $this->_getErrorBlock($error); } } } //handle warnings if (isset($this->_response['new_transaction']['warnings']['warning'])) { if (!isset($this->_response['new_transaction']['warnings']['warning'][0])) { $tmp = $this->_response['new_transaction']['warnings']['warning']; unset($this->_response['new_transaction']['warnings']['warning']); $this->_response['new_transaction']['warnings']['warning'][0] = $tmp; } foreach ($this->_response['new_transaction']['warnings']['warning'] as $warning) { $this->warnings['global'][] = $this->_getErrorBlock($warning); } } foreach ($this->_products as $product) { if (isset($this->_response['new_transaction']['warnings'][$product])) { if (!isset($this->_response['new_transaction']['warnings'][$product]['warnings']['warning'][0])) { $tmp = $this->_response['new_transaction']['warnings'][$product]['warnings']['warning']; unset($this->_response['new_transaction']['warnings'][$product]['warnings']['warning']); $this->_response['new_transaction']['warnings'][$product]['warnings']['warning'][0] = $tmp; } foreach ($this->_response['new_transaction']['warnings'][$product]['warnings']['warning'] as $warning) { $this->warnings[$product][] = $this->_getErrorBlock($warning); } } } } /** * * parse the XML received or being sent */ protected function _parseXml() {} /** * * Getter for error block * @param unknown_type $error */ protected function _getErrorBlock($error) { $newError['code'] = isset($error['code']['@data']) ? $error['code']['@data'] : ''; $newError['message'] = isset($error['message']['@data']) ? $error['message']['@data'] : ''; $newError['field'] = isset($error['field']['@data']) ? $error['field']['@data'] : ''; return $newError; } /** * * Static debug method * @param mixed $var * @param boolean $showHtml */ public static function debug($var = false, $showHtml = false) { echo "\n
\n";
		$var = print_r($var, true);
		
		if ($showHtml) {
			$var = str_replace('<', '<', str_replace('>', '>', $var));
		}
		
		echo $var . "\n
\n"; } } /// @endcond ?>sofortLib_Logger.inc.php000066600000003411151376502640011303 0ustar00logRotate($uri)) { $this->fp = fopen($uri, 'w'); fclose($this->fp); } $this->fp = fopen($uri, 'a'); fwrite($this->fp, '['.date('Y-m-d H:i:s').'] '.$message."\n"); fclose($this->fp); } /** * Copy the content of the logfile to a backup file if file size got too large * Put the old log file into a tarball for later reference * @param URI $uri */ public function logRotate($uri) { $date = date('Y-m-d_h-i-s', time()); if (file_exists($uri)) { if ($this->fp != null && filesize($uri) != false && filesize($uri) >= $this->maxFilesize) { $oldUri = $uri; // file ending $ending = $ext = pathinfo($oldUri, PATHINFO_EXTENSION); $newUri = dirname($oldUri).'/log_'.$date.'.'.$ending; rename($oldUri, $newUri); if (file_exists($oldUri)) { unlink($oldUri); } return true; } } return false; } } /// \endcond ?>sofortLib_edit_sr.inc.php000066600000013471151376502640011524 0ustar00confirmInvoice('1234-456-789654-31321')->sendRequest(); * * Copyright (c) 2012 SOFORT AG * * Released under the GNU General Public License (Version 2) * [http://www.gnu.org/licenses/gpl-2.0.html] * * $Date: 2012-05-21 16:53:26 +0200 (Mo, 21 Mai 2012) $ * @version SofortLib 1.5.4 $Id: sofortLib_edit_sr.inc.php 4191 2012-05-21 14:53:26Z niehoff $ * @author SOFORT AG http://www.sofort.com (integration@sofort.com) * */ class SofortLib_EditSr extends SofortLib_Abstract { protected $_apiVersion = '1.0'; protected $_parameters = array(); protected $_response = array(); protected $_xmlRootTag = 'edit_sr'; private $_file; /** * * Constructor for SofortLib_EditSr * @param String $apikey your API-key */ public function __construct($configKey = '') { list($userId, $projectId, $apiKey) = explode(':', $configKey); $apiUrl = (getenv('sofortApiUrl') != '') ? getenv('sofortApiUrl') : 'https://api.sofort.com/api/xml'; parent::__construct($userId, $apiKey, $apiUrl); } /** * * Setter for transaction * @param string $transaction * @param int $invoice */ public function setTransaction($transaction, $invoice = 0) { $this->_parameters['invoice'][$invoice]['transaction'] = $transaction; return $this; } /** * * Setter for invoice's number * @param string $invoiceNumber * @param int $invoice */ public function setInvoiceNumber($invoiceNumber, $invoice = 0) { $this->_parameters['invoice'][$invoice]['invoice_number'] = $invoiceNumber; return $this; } /** * * Setter for customer's number * @param string $customerNumber * @param int $invoice */ public function setCustomerNumber($customerNumber, $invoice = 0) { $this->_parameters['invoice'][$invoice]['customer_id'] = $customerNumber; return $this; } /** * * Setter for order's number * @param string $orderNumber * @param int $invoice */ public function setOrderNumber($orderNumber, $invoice = 0) { $this->_parameters['invoice'][$invoice]['order_id'] = $orderNumber; return $this; } /** * set a comment for refunds * just useable with api version 1.0 * @param string $arg */ public function setComment($comment, $invoice = 0) { $this->_parameters['invoice'][$invoice]['comment'] = $comment; return $this; } /** * add one item to the cart if you want to change the invoice * * @param string $itemId itemId * @param double $unit_price gross price of one item * @param int $quantity default 1 */ public function addItem($itemId, $productNumber, $productType, $title, $description, $quantity, $unitPrice, $tax, $invoice = 0) { $unitPrice = number_format($unitPrice, 2, '.', ''); $tax = number_format($tax, 2, '.', ''); $quantity = intval($quantity); $this->_parameters['invoice'][$invoice]['items']['item'][] = array( 'item_id' => $itemId, 'product_number' => $productNumber, 'product_type' => $productType, 'title' => $title, 'description' => $description, 'quantity' => $quantity, 'unit_price' => $unitPrice, 'tax' => $tax, ); } /** * * Update the invoice's cart via passing an array * @param array $cartItems * @param int $invoice */ function updateCart($cartItems = array(), $invoice = 0) { $i = 0; foreach ($cartItems as $cartItem) { $this->_parameters['invoice'][$invoice]['items']['item'][$i]['item_id'] = $cartItem['itemId']; $this->_parameters['invoice'][$invoice]['items']['item'][$i]['product_number'] = $cartItem['productNumber']; $this->_parameters['invoice'][$invoice]['items']['item'][$i]['title'] = $cartItem['title']; $this->_parameters['invoice'][$invoice]['items']['item'][$i]['description'] = $cartItem['description']; $this->_parameters['invoice'][$invoice]['items']['item'][$i]['quantity'] = $cartItem['quantity']; $this->_parameters['invoice'][$invoice]['items']['item'][$i]['unit_price'] = number_format($cartItem['unitPrice'], 2, '.', '') ; $this->_parameters['invoice'][$invoice]['items']['item'][$i]['tax'] = $cartItem['tax']; $i++; } } /** * after you you changed/confirmed an invoice you * can download the new invoice-pdf with this function * @return string url */ public function getInvoiceUrl() { return $this->_file; } /** * Parse the XML (override) * @see SofortLib_Abstract::_parseXml() */ protected function _parseXml() { $this->_file = isset($this->_response['invoice']['download_url']['@data']) ? $this->_response['invoice']['download_url']['@data'] : ''; } /** * Error handling (override) * @see SofortLib::_handleErrors() */ protected function _handleErrors() { if (!isset($this->_response['invoices']['invoice'][0])) { $tmp = $this->_response['invoices']['invoice']; unset($this->_response['invoices']['invoice']); $this->_response['invoices']['invoice'][0] = $tmp; } foreach ($this->_response['invoices']['invoice'] as $response) { //handle errors if (isset($response['errors']['error'])) { if (!isset($response['errors']['error'][0])) { $tmp = $response['errors']['error']; unset($response['errors']['error']); $response['errors']['error'][0] = $tmp; } foreach ($response['errors']['error'] as $error) { $this->errors['sr'][] = $this->_getErrorBlock($error); } } //handle warnings if (isset($response['warnings']['warning'])) { if (!isset($response['warnings']['warning'][0])) { $tmp = $response['warnings']['warning']; unset($response['warnings']['warning']); $response['warnings']['warning'][0] = $tmp; } foreach ($response['warnings']['warning'] as $error) { $this->warnings['sr'][] = $this->_getErrorBlock($error); } } } } } ?>sofortLib_classic_notification.inc.php000066600000011672151376502640014263 0ustar00_password = $password; $this->_userId = $userId; $this->_projectId = $projectId; $this->_hashFunction = strtolower($hashFunction); $this->_statusReason = false; } /** * * Get the Notification details * @param string $request (POST-Data) */ public function getNotification($request) { if (array_key_exists('status_reason', $request) && !empty($request['status_reason'])) { $this->_statusReason = $request['status_reason']; } if (array_key_exists('international_transaction', $request)) { //standard notification $fields = array( 'transaction', 'user_id', 'project_id', 'sender_holder', 'sender_account_number', 'sender_bank_code', 'sender_bank_name', 'sender_bank_bic', 'sender_iban', 'sender_country_id', 'recipient_holder', 'recipient_account_number', 'recipient_bank_code', 'recipient_bank_name', 'recipient_bank_bic', 'recipient_iban', 'recipient_country_id', 'international_transaction', 'amount', 'currency_id', 'reason_1', 'reason_2', 'security_criteria', 'user_variable_0', 'user_variable_1', 'user_variable_2', 'user_variable_3', 'user_variable_4', 'user_variable_5', 'created', ); } else { //ideal $fields = array( 'transaction', 'user_id', 'project_id', 'sender_holder', 'sender_account_number', 'sender_bank_name', 'sender_bank_bic', 'sender_iban', 'sender_country_id', 'recipient_holder', 'recipient_account_number', 'recipient_bank_code', 'recipient_bank_name', 'recipient_bank_bic', 'recipient_iban', 'recipient_country_id', 'amount', 'currency_id', 'reason_1', 'reason_2', 'user_variable_0', 'user_variable_1', 'user_variable_2', 'user_variable_3', 'user_variable_4', 'user_variable_5', 'created', ); } // http-notification with status if (array_key_exists('status', $request) && !empty($request['status'])) { array_push($fields, 'status', 'status_modified'); } $this->params = array(); foreach ($fields as $key) { $this->params[$key] = $request[$key]; } $this->params['project_password'] = $this->_password; $validationHash = $this->_getHashHexValue(implode('|', $this->params), $this->_hashFunction); $messageHash = $request['hash']; $this->_hashCheck = ($validationHash === $messageHash); return $this; } /** * * Check if error occurred * @return boolean */ public function isError() { if (!$this->_hashCheck) { return true; } return false; } /** * * Get error if occurred */ public function getError() { if (!$this->_hashCheck) { return 'hash-check failed'; } return false; } /** * * Getter for transactionId */ public function getTransaction() { return $this->params['transaction']; } /** * * Getter for amount * @return float */ public function getAmount() { return $this->params['amount']; } /** * Getter for user variables * @param int $i */ public function getUserVariable($i = 0) { return $this->params['user_variable_'.$i]; } /** * * Getter for currency * @return string */ public function getCurrency() { return $this->params['currency_id']; } /** * * Getter for time * return timestamp */ public function getTime() { return $this->params['created']; } /** * * Getter for status * @return string */ public function getStatus() { return $this->params['status']; } /** * * Getter for status reason * @return string */ public function getStatusReason() { return $this->_statusReason; } /** * Getter for Hash Hex Value * @param string $data string to be hashed * @return string the hash */ protected function _getHashHexValue($data, $hashFunction = 'sha1') { if ($hashFunction == 'sha1') { return sha1($data); } if ($hashFunction == 'md5') { return md5($data); } //mcrypt installed? if (function_exists('hash') && in_array($hashFunction, hash_algos())) { return hash($hashFunction, $data); } return false; } } ?>sofortLib_transaction_data.inc.php000066600000066021151376502640013410 0ustar00setTransaction('1234-456-789654-31321')->sendRequest(); * * echo $transactionDataObj->getStatus(); * * Copyright (c) 2012 SOFORT AG * * Released under the GNU General Public License (Version 2) * [http://www.gnu.org/licenses/gpl-2.0.html] * * $Date: 2013-04-29 13:22:26 +0200 (Mon, 29 Apr 2013) $ * @version SofortLib 1.5.4 $Id: sofortLib_transaction_data.inc.php 6103 2013-04-29 11:22:26Z dehn $ * @author SOFORT AG http://www.sofort.com (integration@sofort.com) * */ class SofortLib_TransactionData extends SofortLib_Abstract { protected $_parameters = array(); protected $_response = array(); protected $_xmlRootTag = 'transaction_request'; private $_count = 0; /** * * Constructor for SofortLib_TransactionData * @param string $configKey */ public function __construct($configKey = '') { list($userId, $projectId, $apiKey) = explode(':', $configKey); $apiUrl = (getenv('sofortApiUrl') != '') ? getenv('sofortApiUrl') : 'https://api.sofort.com/api/xml'; parent::__construct($userId, $apiKey, $apiUrl); return $this; } /** * use this function if you want to request * detailed information about a single transaction * * @param String $arg * @return SofortLib_TransactionData $this */ public function setTransaction($arg) { $this->_parameters['transaction'] = $arg; return $this; } /** * use this function if you want to request * detailed information about several transactions * at once * * @param String $arg * @return SofortLib_TransactionData $this */ public function addTransaction($arg) { if (is_array($arg)) { foreach($arg as $element) { $this->_parameters['transaction'][] = $element; } } else { $this->_parameters['transaction'][] = $arg; } return $this; } /** * you can request all transactions of a certain time * period * * use setNumber() to limit the results * * @param string $from date possible formats: 2011-01-25 or 2011-01-25T19:01:02+02:00 * @param string $to date possible formats: 2011-01-25 or 2011-01-25T19:01:02+02:00 * @return SofortLib_TransactionData $this * @see setNumber() */ public function setTime($from, $to) { $this->_parameters['from_time'] = $from; $this->_parameters['to_time'] = $to; return $this; } /** * you can limit the number of results * * @param int $number number of results [0-100] * @param int $page result page * @return SofortLib_TransactionData $this * @see setTime() */ public function setNumber($number, $page = '1') { $this->_parameters['number'] = $number; $this->_parameters['page'] = $page; return $this; } /** * returns the state of consumer_protection if set * @param int $i if you request multiple transactions at once you can set the number here * @return boolean */ public function getConsumerProtection($i = 0) { $paymentMethod = $this->getPaymentMethod($i); if (in_array($paymentMethod, array('su', 'sv'))) { if(isset($this->_response[$i][$paymentMethod]['consumer_protection']['@data'])) { return $this->_response[$i][$paymentMethod]['consumer_protection']['@data']; } else { return false; } } else { return false; } } /** * returns the InvoiceAddress * @param int $i if you request multiple transactions at once you can set the number here * @return array */ public function getInvoiceAddress($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } $invoiceAddress = array( 'firstname' => $this->_response[$i]['sr']['invoice_address']['firstname']['@data'], 'lastname' => $this->_response[$i]['sr']['invoice_address']['lastname']['@data'], 'name_additive' => $this->_response[$i]['sr']['invoice_address']['name_additive']['@data'], 'street' => $this->_response[$i]['sr']['invoice_address']['street']['@data'], 'street_number' => $this->_response[$i]['sr']['invoice_address']['street_number']['@data'], 'street_additive' => $this->_response[$i]['sr']['invoice_address']['street_additive']['@data'], 'zipcode' => $this->_response[$i]['sr']['invoice_address']['zipcode']['@data'], 'city' => $this->_response[$i]['sr']['invoice_address']['city']['@data'], 'country_code' => $this->_response[$i]['sr']['invoice_address']['country_code']['@data'], 'salutation' => !empty($this->_response[$i]['sr']['invoice_address']['salutation']['@data']) ? $this->_response[$i]['sr']['invoice_address']['salutation']['@data'] : '', 'company' => $this->_response[$i]['sr']['invoice_address']['company']['@data'], ); return $invoiceAddress; } /** * returns the ShippingAddress * @param int $i if you request multiple transactions at once you can set the number here * @return array */ public function getShippingAddress($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } $shippingAddress = array( 'firstname' => $this->_response[$i]['sr']['shipping_address']['firstname']['@data'], 'lastname' => $this->_response[$i]['sr']['shipping_address']['lastname']['@data'], 'name_additive' => $this->_response[$i]['sr']['shipping_address']['name_additive']['@data'], 'street' => $this->_response[$i]['sr']['shipping_address']['street']['@data'], 'street_number' => $this->_response[$i]['sr']['shipping_address']['street_number']['@data'], 'street_additive' => $this->_response[$i]['sr']['shipping_address']['street_additive']['@data'], 'zipcode' => $this->_response[$i]['sr']['shipping_address']['zipcode']['@data'], 'city' => $this->_response[$i]['sr']['shipping_address']['city']['@data'], 'country_code' => $this->_response[$i]['sr']['shipping_address']['country_code']['@data'], 'salutation' => !empty($this->_response[$i]['sr']['shipping_address']['salutation']['@data']) ? $this->_response[$i]['sr']['shipping_address']['salutation']['@data'] : '', 'company' => $this->_response[$i]['sr']['shipping_address']['company']['@data'], ); return $shippingAddress; } /** * returns the status of a transaction * @param int $i if you request multiple transactions at once you can set the number here * @return string pending|received|loss|refunded */ public function getStatus($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['status']['@data']; } /** * returns the detailed status description of a transaction * @param int $i if you request multiple transactions at once you can set the number here * @return string message */ public function getStatusReason($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['status_reason']['@data']; } /** * returns the time of the last status-change so you can check if sth. changed * @param int $i if you request multiple transactions at once you can set the number here * @return string time e.g. 2011-01-01T12:35:09+01:00 use strtotime() to convert it to unixtime */ public function getStatusModifiedTime($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['status_modified']['@data']; } /** * returns the language code of a transaction * @param int $i if you request multiple transactions at once you can set the number here * @return string language_code */ public function getLanguageCode($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['language_code']['@data']; } /** * returns the total amount of a transaction * @param int $i if you request multiple transactions at once you can set the number here * @return double amount */ public function getAmount($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['amount']['@data']; } /** * * Getter for order number * @param int $i */ public function getOrderNumber($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sr']['shop_order_number']['@data']; } /** * refund, if a transaction was refundend. amount = amountRefunded if everything was refunded * @param int $i if you request multiple transactions at once you can set the number here * @return double amount */ public function getAmountRefunded($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['amount_refunded']['@data']; } /** * * Getter for the amounts received * @param int $i */ public function getAmountReceived($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sv']['received_amount']['@data']; } /** * returns the currency of a transaction * @param int $i if you request multiple transactions at once you can set the number here * @return string EUR|USD|GBP.... */ public function getCurrency($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['currency_code']['@data']; } /** * returns the payment method of a transaction * @param int $i if you request multiple transactions at once you can set the number here * @return string su|sr|sl|sv|ls */ public function getPaymentMethod($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['payment_method']['@data']; } /** * returns the transaction id of a transaction * @param int $i if you request multiple transactions at once you can set the number here * @return string transaction id */ public function getTransaction($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['transaction']['@data']; } /** * * Returns an array containing all items of a transaction * @param int $i if you request multiple transactions at once you can set the number here * @ return array transactions items */ public function getItems($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } $items = array(); if (isset($this->_response[$i]['sr']['items']['item'][0])) { foreach ($this->_response[$i]['sr']['items']['item'] as $key => $item) { $items[$key]['item_id'] = $item['item_id']['@data']; $items[$key]['product_number'] = $item['product_number']['@data']; $items[$key]['product_type'] = $item['product_type']['@data']; $items[$key]['number_type'] = $item['number_type']['@data']; $items[$key]['title'] = $item['title']['@data']; $items[$key]['description'] = $item['description']['@data']; $items[$key]['quantity'] = $item['quantity']['@data']; $items[$key]['unit_price'] = $item['unit_price']['@data']; $items[$key]['tax'] = $item['tax']['@data']; } } return $items; } /** * * Returns an array containing reason of a transaction * @param int $i if you request multiple transactions at once you can set the number here * @ return array transaction reason */ public function getReason($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } $reasons[] = $this->_response[$i]['reasons']['reason'][0]['@data']; $reasons[] = $this->_response[$i]['reasons']['reason'][1]['@data']; return $reasons; } /** * returns the user variable of a transaction * @param int $n number of the variable * @param int $i if you request multiple transactions at once you can set the number here * @return string the content of this variable */ public function getUserVariable($n, $i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } if($n == 0 && !array_key_exists($n, $this->_response[$i]['user_variables']['user_variable'])) { return $this->_response[$i]['user_variables']['user_variable']['@data']; } return $this->_response[$i]['user_variables']['user_variable'][$n]['@data']; } /** * returns the time of a transaction * @param int $i if you request multiple transactions at once you can set the number here * @return string time e.g. 2011-01-01T12:35:09+01:00 use strtotime() to convert it to unixtime */ public function getTime($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['time']['@data']; } /** * returns the project id of a transaction * @param int $i if you request multiple transactions at once you can set the number here * @return int project id */ public function getProjectId($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['project_id']['@data']; } /** * you can request the url to the pdf of a sr-invoice with this function * @param int $i if you request multiple transactions at once you can set the number here * @return string url to the pdf */ public function getInvoiceUrl($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sr']['invoice_url']['@data']; } /** * returns the status of an invoice * @param int $i if you request multiple transactions at once you can set the number here * @return string the status can be pending|received|reminder_1|reminder_2|reminder_3|encashment */ public function getInvoiceStatus($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sr']['invoice_status']['@data']; } /** * returns the status of an invoice * @param int $i if you request multiple transactions at once you can set the number here * @return string the status can be pending|received|reminder_1|reminder_2|reminder_3|encashment */ public function getInvoiceObjection($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sr']['invoice_objection']['@data']; } /** * checks if the transaction was a test * @param int $i if you request multiple transactions at once you can set the number here * @return bool true|false */ public function isTest($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['test']['@data']; } /** * * check if the transaction was a sofortueberweisung * @param int $i if you request multiple transactions at once you can set the number here * @return boolean true|false */ public function isSofortueberweisung($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['payment_method']['@data'] == 'su'; } /** * * check if the transaction was a sofortvorkasse * @param int $i if you request multiple transactions at once you can set the number here * @return boolean true|false */ public function isSofortvorkasse($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['payment_method']['@data'] == 'sv'; } /** * * check if the transaction was a sofortlastschrift * @param int $i if you request multiple transactions at once you can set the number here * @return boolean true|false */ public function isSofortlastschrift($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['payment_method']['@data'] == 'sl'; } /** * * check if the transaction was a lastschrift by sofort * @param int $i if you request multiple transactions at once you can set the number here * @return boolean true|false */ public function isLastschrift($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['payment_method']['@data'] == 'ls'; } /** * * check if the transaction was a sofortrechnung * @param int $i if you request multiple transactions at once you can set the number here * @return boolean true|false */ public function isSofortrechnung($i = 0) { if($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['payment_method']['@data'] == 'sr'; } /** * * check if status of transaction is received * @param int $i if you request multiple transactions at once you can set the number here * @return boolean true|false */ public function isReceived($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['status']['@data'] == 'received'; } /** * * check if status of transaction is loss * @param int $i if you request multiple transactions at once you can set the number here * @return boolean true|false */ public function isLoss($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['status']['@data'] == 'loss'; } /** * * check if status of transaction is pending * @param int $i if you request multiple transactions at once you can set the number here * @return boolean true|false */ public function isPending($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['status']['@data'] == 'pending'; } /** * * check if status of transaction is refunded * @param int $i if you request multiple transactions at once you can set the number here * @return boolean true|false */ public function isRefunded($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['status']['@data'] == 'refunded'; } /** * returns the holder of the receiving account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getRecipientHolder($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['recipient']['holder']['@data']; } /** * * returns the account number of the receiving account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getRecipientAccountNumber($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['recipient']['account_number']['@data']; } /** * * returns the bank code of the receiving account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getRecipientBankCode($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['recipient']['bank_code']['@data']; } /** * * returns the country code of the receiving account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getRecipientCountryCode($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['recipient']['country_code']['@data']; } /** * * returns the bank name of the receiving account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getRecipientBankName($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['recipient']['bank_name']['@data']; } /** * * returns the BIC of the receiving account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getRecipientBic($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['recipient']['bic']['@data']; } /** * * returns the IBAN of the receiving account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getRecipientIban($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['recipient']['iban']['@data']; } /** * returns the holder of the sending account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getSenderHolder($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sender']['holder']['@data']; } /** * * returns the account number of the sending account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getSenderAccountNumber($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sender']['account_number']['@data']; } /** * * returns the bank code of the sending account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getSenderBankCode($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sender']['bank_code']['@data']; } /** * * returns the country code of the sending account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getSenderCountryCode($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sender']['country_code']['@data']; } /** * * returns the bank name of the sending account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getSenderBankName($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sender']['bank_name']['@data']; } /** * * returns the BIC of the sending account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getSenderBic($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sender']['bic']['@data']; } /** * * returns the IBAN of the sending account * @param int $i if you request multiple transactions at once you can set the number here * @return string value */ public function getSenderIban($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sender']['iban']['@data']; } /** * returns the reason the customer needs to use when paying for "Rechnung by sofort" * @param int $n specify reason linenumber, can be 1 or 2; us 0 for an array with all reasons * @param int $i if you request multiple transactions at once you can set the number here * @return string|array reason */ public function getInvoiceReason($n = 0, $i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } if ($n == 1) { return $this->_response[$i]['sr']['reason_1']['@data']; } if ($n == 2) { return $this->_response[$i]['sr']['reason_2']['@data']; } return array($this->_response[$i]['sr']['reason_1']['@data'], $this->_response[$i]['sr']['reason_2']['@data']); } /** * get debitor text (Forderungsabtretung) * @param int $i if you request multiple transactions at once you can set the number here * @return string */ public function getInvoiceDebitorText($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sr']['debitor_text']['@data']; } /** * * date of the invoice * @param int $i if you request multiple transactions at once you can set the number here * @return string */ public function getInvoiceDate($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sr']['invoice_date']['@data']; } /** * * due date of the invoice, only available for confirmed invoices * @param int $i if you request multiple transactions at once you can set the number here * @return string */ public function getInvoiceDueDate($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sr']['due_date']['@data']; } /** * * Getter for invoice number * @param int $i if you request multiple transactions at once you can set the number here * @return string */ public function getInvoiceNumber($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sr']['invoice_number']['@data']; } /** * * invoice receiving bank account * @param int $i if you request multiple transactions at once you can set the number here * @return string */ public function getInvoiceBankHolder($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sr']['recipient_bank_account']['holder']['@data']; } /** * * invoice receiving bank account * @param int $i if you request multiple transactions at once you can set the number here * @return string */ public function getInvoiceBankAccountNumber($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sr']['recipient_bank_account']['account_number']['@data']; } /** * * invoice receiving bank account * @param int $i if you request multiple transactions at once you can set the number here * @return string */ public function getInvoiceBankCode($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sr']['recipient_bank_account']['bank_code']['@data']; } /** * * invoice receiving bank account * @param int $i if you request multiple transactions at once you can set the number here * @return string */ public function getInvoiceBankName($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sr']['recipient_bank_account']['bank_name']['@data']; } /** * get the invoice type * @param int $i if you request multiple transactions at once you can set the number here * @return string (OR or LS) */ public function getInvoiceType($i = 0) { if ($i < 0 || $i >= $this->_count) { return false; } return $this->_response[$i]['sr']['invoice_type']['@data']; } /** * * Getter for count */ public function getCount() { return $this->_count; } /** * Parse the XML (override) * (non-PHPdoc) * @see SofortLib_Abstract::_parseXml() */ protected function _parseXml() { if (isset($this->_response['transactions']['transaction_details'])) { $transactionFromXml = (isset($this->_response['transactions']['transaction_details'][0])) ? $this->_response['transactions']['transaction_details'] : $this->_response['transactions']; $this->_count = count($transactionFromXml); $transactions = array(); foreach ($transactionFromXml as $transaction) { if (!empty($transaction)) { if (isset($transaction['sr']['items']['item']) && !isset($transaction['sr']['items']['item'][0])) { $tmp = $transaction['sr']['items']['item']; unset($transaction['sr']['items']['item']); $transaction['sr']['items']['item'][] = $tmp; unset($tmp); } $transactions[] = $transaction; } } $this->_response = $transactions; $this->_count = count($transactions); } else { $this->_count = 0; } } } ?>sofortLib_sofortueberweisung_classic.php000066600000020370151376502640014761 0ustar00new SofortLib_SofortueberweisungClassic( $userid, $projectid, $password [, $hashfunction='sha1'] ); * $sofort->set...(); //set params for Hashcalculation * $sofort->set...(); //set more params for Hashcalculation * $sofort->getPaymentUrl(); * Notice: sometimes getPaymentUrl() must be overwritten by calling class because of changed hash-params * * * Copyright (c) 2012 SOFORT AG * * Released under the GNU General Public License (Version 2) * [http://www.gnu.org/licenses/gpl-2.0.html] * * $Date: 2012-11-23 17:15:47 +0100 (Fri, 23 Nov 2012) $ * @version SofortLib 1.5.4 $Id: sofortLib_sofortueberweisung_classic.php 5773 2012-11-23 16:15:47Z dehn $ * @author SOFORT AG http://www.sofort.com (integration@sofort.com) * */ class SofortLib_SofortueberweisungClassic { public $params = array(); protected $_password; protected $_userId; protected $_projectId; protected $_hashFunction; protected $_paymentUrl = 'https://www.sofort.com/payment/start'; protected $_hashFields = array( 'user_id', 'project_id', 'sender_holder', 'sender_account_number', 'sender_bank_code', 'sender_country_id', 'amount','currency_id', 'reason_1','reason_2', 'user_variable_0', 'user_variable_1', 'user_variable_2', 'user_variable_3', 'user_variable_4', 'user_variable_5', ); /** * * Constructor for SofortLib_SofortueberweisungClassic * @param int $userId * @param int $projectId * @param string $password * @param string $hashFunction * @param string $paymentUrl */ public function __construct($userId, $projectId, $password, $hashFunction = 'sha1', $paymentUrl = null) { $this->_password = $password; $this->_userId = $this->params['user_id'] = $userId; $this->_projectId = $this->params['project_id'] = $projectId; $this->_hashFunction = strtolower($hashFunction); $this->params['encoding'] = 'UTF-8'; if ($paymentUrl) $this->_paymentUrl = $paymentUrl; $this->_paymentUrl = $this->_getPaymentDomain(); } /** * * Setter for amount * @param float $arg * @param string $currency */ public function setAmount($arg, $currency = 'EUR') { $this->params['amount'] = $arg; $this->params['currency_id'] = $currency; } /** * * Setter for sender and holder * @param unknown_type $senderHolder */ public function setSenderHolder($senderHolder) { $this->params['sender_holder'] = $senderHolder; } /** * * Setter for sender's account number * @param string $senderAccountNumber */ public function setSenderAccountNumber($senderAccountNumber) { $this->params['sender_account_number'] = $senderAccountNumber; } /** * * Set the reason (Verwendungszweck) for sending money * @param string $arg * @param string $arg2 */ public function setReason($arg, $arg2 = '') { $this->params['reason_1'] = preg_replace('#[^a-zA-Z0-9+-\.,]#', ' ', $arg); $this->params['reason_2'] = preg_replace('#[^a-zA-Z0-9+-\.,]#', ' ', $arg2); return $this; } /** * * User variables can be added here * @param string $arg */ public function addUserVariable($arg) { $i = 0; while ($i < 6) { if (array_key_exists('user_variable_'.$i, $this->params)) { $i++; } else { break; } } $this->params['user_variable_'.$i] = $arg; return $this; } /** * the customer will be redirected to this url after a successful * transaction, this should be a page where a short confirmation is * displayed * * @param string $arg the url after a successful transaction * @return SofortLib_Multipay */ public function setSuccessUrl($arg) { $this->params['user_variable_3'] = $arg; return $this; } /** * the customer will be redirected to this url if he uses the * abort link on the payment form, should redirect him back to * his cart or to the payment selection page * * @param string $arg url for aborting the transaction * @return SofortLib_Multipay */ public function setAbortUrl($arg) { $this->params['user_variable_4'] = $arg; return $this; } /** * set the url where you want notification about status changes * being sent to. Use SofortLib_Notification and SofortLib_TransactionData * to further process that notification * * @param string $arg url * @return SofortLib_Multipay */ public function setNotificationUrl($arg) { $this->params['user_variable_5'] = $arg; return $this; } /** * * Setter for interface version * @param string $arg */ public function setVersion($arg) { $this->params['interface_version'] = $arg; return $this; } /** * * Getter for payment URL */ public function getPaymentUrl() { //fields required for hash $hashFields = $this->_hashFields; //build parameter-string for hashing $hashString = ''; foreach ($hashFields as $value) { if (array_key_exists($value, $this->params)) { $hashString .= $this->params[$value]; } $hashString .= '|'; } $hashString .= $this->_password; //calculate hash $hash = $this->getHashHexValue($hashString, $this->_hashFunction); $this->params['hash'] = $hash; //create parameter string $paramString = ''; foreach ($this->params as $key => $value) { $paramString .= $key.'='.urlencode($value).'&'; } $paramString = substr($paramString, 0, -1); //remove last & return $this->_paymentUrl.'?'.$paramString; } /** * * Has an error occurred */ public function isError() { return false; } /** * * Getter for error occurred */ public function getError() { return false; } /** * Get the hash value * @param string $data string to be hashed * @return string the hash */ public function getHashHexValue($data, $hashFunction = 'sha1') { if($hashFunction == 'sha1') { return sha1($data); } if($hashFunction == 'md5') { return md5($data); } //mcrypt installed? if (function_exists('hash') && in_array($hashFunction, hash_algos())) { return hash($hashFunction, $data); } return false; } /** * * Generate a password * @param int [optional] $length length of return value, default 24 * @return string */ public static function generatePassword($length = 24) { $password = ''; //we generate about 5-34 random characters [A-Za-z0-9] in every loop do { $randomBytes = ''; $strong = false; if (function_exists('openssl_random_pseudo_bytes')) { //php >= 5.3 $randomBytes = openssl_random_pseudo_bytes(32, $strong);//get 256bit } if (!$strong) { //fallback $randomBytes = pack('I*', mt_rand()); //get 32bit (pseudo-random) } //convert bytes to base64 and remove special chars $password .= preg_replace('#[^A-Za-z0-9]#', '', base64_encode($randomBytes)); } while (strlen($password) < $length); return substr($password, 0, $length); } /** * checks wich hash algorithms are supported by the server * and returns the best one * * @return sha512|sha256|sha1|md5|empty string */ public function getSupportedHashAlgorithm() { $algorithms = $this->getSupportedHashAlgorithms(); if(is_array($algorithms)) { return $algorithms[0]; } else { return ''; //no hash function found } } /** * checks wich hash algorithms are supported by the server * * @return array with all supported algorithms, preferred as first one (index 0) */ public function getSupportedHashAlgorithms() { $algorithms = array(); if (function_exists('hash') && in_array('sha512', hash_algos())) { $algorithms[] = 'sha512'; } if(function_exists('hash') && in_array('sha256', hash_algos())) { $algorithms[] = 'sha256'; } if(function_exists('sha1')) { //deprecated $algorithms[] = 'sha1'; } if(function_exists('md5')) { //deprecated $algorithms[] = 'md5'; } return $algorithms; } /** * * Getter for payment domain */ protected function _getPaymentDomain() { return (getenv('sofortPaymentUrl') != '') ? getenv('sofortPaymentUrl') : $this->_paymentUrl; } } ?>logs/.htaccess000066600000000177151376502640007330 0ustar00 Order allow,deny Deny from all logs/index.html000066600000000037151376502640007522 0ustar00 logs/log.txt000066600000000000151376502640007035 0ustar00logs/log.xml000066600000004100151376502640007023 0ustar00 156252 71365-156252-51CCAA6F-F942 1 pending not_credited_yet 2013-06-27T23:11:34+02:00 su fr 1.00 0.00 EUR 83650107 Musterman, Petra 2345678902 88888888 Demo Bank PNAGDE00000 DE96888888882345678902 DE Testaccount SOFORT 9999999999 70011110 SOFORT Bank DEKTDE71002 DE71700111109999999999 DE 1.0000 0.00 EUR 1.0000 0 pending not_credited_yet sofortLib_abstract.inc.php000066600000004522151376502640011673 0ustar00_xmlRootTag] = $this->_parameters; $requestData = $this->_prepareRootTag($requestData); $xmlRequest = ArrayToXml::render($requestData); $this->_log($xmlRequest, ' XmlRequest -> '); $xmlResponse = $this->_sendMessage($xmlRequest); try { $this->_response = XmlToArray::render($xmlResponse); } catch (Exception $e) { $this->_response = array('errors' => array('error' => array('code' => array('@data' => '0999'), 'message' => array('@data' => $e->getMessage())))); } $this->_log($xmlResponse, ' XmlResponse <- '); $this->_handleErrors(); $this->_parseXml(); return $this; } /** * * Log XML with message * @param string $xml * @param string $message */ protected function _log($xml, $message) { $this->log(get_class($this).$message.$xml); } /** * * prepare the root tag * @param array $requestData */ private function _prepareRootTag($requestData) { if ($this->_apiVersion) { $requestData[$this->_xmlRootTag]['@attributes']['version'] = $this->_apiVersion; } if ($this->_validateOnly) { $requestData[$this->_xmlRootTag]['@attributes']['validate_only'] = 'yes'; } return $requestData; } } /// \endcond ?>sofortLib_cancel_sr.inc.php000066600000010304151376502640012014 0ustar00confirmInvoice('1234-456-789654-31321')->sendRequest(); * * Copyright (c) 2012 SOFORT AG * * Released under the GNU General Public License (Version 2) * [http://www.gnu.org/licenses/gpl-2.0.html] * * $Date: 2012-05-21 16:53:26 +0200 (Mo, 21 Mai 2012) $ * @version SofortLib 1.5.4 $Id: sofortLib_cancel_sr.inc.php 4191 2012-05-21 14:53:26Z niehoff $ * @author SOFORT AG http://www.sofort.com (integration@sofort.com) * */ class SofortLib_CancelSr extends SofortLib_Abstract { protected $_apiVersion = '1.0'; protected $_parameters = array(); protected $_response = array(); protected $_xmlRootTag = 'cancel_sr'; private $_file; /** * create new confirm object * * @param String $apikey your API-key */ public function __construct($configKey = '') { list($userId, $projectId, $apiKey) = explode(':', $configKey); $apiUrl = (getenv('sofortApiUrl') != '') ? getenv('sofortApiUrl') : 'https://api.sofort.com/api/xml'; parent::__construct($userId, $apiKey, $apiUrl); } /** * Set the transaction you want to confirm/change * @param String $transaction Transaction Id * @return SofortLib_ConfirmSr */ public function setTransaction($transaction, $invoice = 0) { $this->_parameters['invoice'][$invoice]['transaction'] = $transaction; return $this; } /** * set a comment for refunds * @param string $arg */ public function setComment($comment, $invoice = 0) { $this->_parameters['invoice'][$invoice]['comment'] = $comment; return $this; } /** * * Setter for credit note number * @param string $creditNoteNumber * @param int $invoice */ public function setCreditNoteNumber($creditNoteNumber, $invoice = 0) { $this->_parameters['invoice'][$invoice]['credit_note_number'] = $creditNoteNumber; return $this; } /** * cancel the invoice * @param string $transaction the transaction id * @return SofortLib_ConfirmSr */ public function cancelInvoice($transaction = '', $invoice = 0) { if (empty($transaction) && array_key_exists('transaction', $this->_parameters)) { $transaction = $this->_parameters['invoice'][$invoice]['transaction']; } if (!empty($transaction)) { $this->_parameters = NULL; $this->_parameters['invoice'][$invoice]['transaction'] = $transaction; $this->_parameters['invoice'][$invoice]['items'] = array(); } return $this; } /** * after you you changed/confirmed an invoice you * can download the new invoice-pdf with this function * @return string url */ public function getInvoiceUrl() { return $this->_file; } /** * Parse the XML (override) * (non-PHPdoc) * @see SofortLib_Abstract::_parseXml() */ protected function _parseXml() { $this->_file = isset($this->_response['invoice']['download_url']['@data']) ? $this->_response['invoice']['download_url']['@data'] : ''; } /** * Error handling (override) * (non-PHPdoc) * @see SofortLib::_handleErrors() */ protected function _handleErrors() { if (!isset($this->_response['invoices']['invoice'][0])) { $tmp = $this->_response['invoices']['invoice']; unset($this->_response['invoices']['invoice']); $this->_response['invoices']['invoice'][0] = $tmp; } foreach ($this->_response['invoices']['invoice'] as $response) { //handle errors if (isset($response['errors']['error'])) { if (!isset($response['errors']['error'][0])) { $tmp = $response['errors']['error']; unset($response['errors']['error']); $response['errors']['error'][0] = $tmp; } foreach ($response['errors']['error'] as $error) { $this->errors['sr'][] = $this->_getErrorBlock($error); } } //handle warnings if (isset($response['warnings']['warning'])) { if (!isset($response['warnings']['warning'][0])) { $tmp = $response['warnings']['warning']; unset($response['warnings']['warning']); $response['warnings']['warning'][0] = $tmp; } foreach ($response['warnings']['warning'] as $error) { $this->warnings['sr'][] = $this->_getErrorBlock($error); } } } } } ?>sofortLib_confirm_sr.inc.php000066600000020351151376502640012227 0ustar00confirmInvoice('1234-456-789654-31321')->sendRequest(); * * Copyright (c) 2012 SOFORT AG * * Released under the GNU General Public License (Version 2) * [http://www.gnu.org/licenses/gpl-2.0.html] * * $Date: 2012-11-23 17:15:47 +0100 (Fri, 23 Nov 2012) $ * @version SofortLib 1.5.4 $Id: sofortLib_confirm_sr.inc.php 5773 2012-11-23 16:15:47Z dehn $ * @author SOFORT AG http://www.sofort.com (integration@sofort.com) * */ class SofortLib_ConfirmSr extends SofortLib_Abstract { protected $_parameters = array(); protected $_invoices = array(); protected $_response = array(); protected $_xmlRootTag = 'confirm_sr'; protected $_apiVersion = '2.0'; private $_file; /** * create new confirm object * * @param String $apikey your API-key */ public function __construct($configKey = '') { list($userId, $projectId, $apiKey) = explode(':', $configKey); $apiUrl = (getenv('sofortApiUrl') != '') ? getenv('sofortApiUrl') : 'https://api.sofort.com/api/xml'; parent::__construct($userId, $apiKey, $apiUrl); } /** * Set the transaction you want to confirm * @param String $transaction Transaction Id * @return SofortLib_ConfirmSr */ public function setTransaction($transaction, $invoice = 0) { if ($this->_apiVersion == 1) { $this->_parameters['transaction'] = $transaction; } else { $this->_parameters['invoice'][$invoice]['transaction'] = $transaction; } return $this; } /** * * Setter for invoice number * @param String $invoiceNumber * @param object $invoice */ public function setInvoiceNumber($invoiceNumber, $invoice = 0) { $this->setApiVersion('2.0'); $this->_parameters['invoice'][$invoice]['invoice_number'] = $invoiceNumber; return $this; } /** * * Setter for costumer numer * @param string $customerNumber * @param int $invoice */ public function setCustomerNumber($customerNumber, $invoice = 0) { $this->setApiVersion('2.0'); $this->_parameters['invoice'][$invoice]['customer_id'] = $customerNumber; return $this; } /** * * Setter for order number * @param string $orderNumber * @param unknown_type $invoice */ public function setOrderNumber($orderNumber, $invoice = 0) { $this->setApiVersion('2.0'); $this->_parameters['invoice'][$invoice]['order_id'] = $orderNumber; return $this; } /** * set a comment for refunds * just useable with api version 1.0 * @see SofortLib_EditSr * @deprecated * @param string $arg */ public function setComment($comment) { $this->setApiVersion('1.0'); $this->_parameters['comment'] = $comment; return $this; } /** * add one item to the cart if you want to change the invoice * just useable with api version 1.0 * @see SofortLib_EditSr * @deprecated * @param string $productNumber product number, EAN code, ISBN number or similar * @param string $title description of this title * @param double $unit_price gross price of one item * @param int $productType product type number see manual * @param string $description additional description of this item * @param int $quantity default 1 * @param int $tax tax in percent, default 19 */ public function addItem($itemId, $productNumber, $productType, $title, $description, $quantity, $unitPrice, $tax) { $this->setApiVersion('1.0'); $unitPrice = number_format($unitPrice, 2, '.', ''); $tax = number_format($tax, 2, '.', ''); $quantity = intval($quantity); $this->_parameters['items']['item'][] = array( 'item_id' => $itemId, 'product_number' => $productNumber, 'product_type' => $productType, 'title' => $title, 'description' => $description, 'quantity' => $quantity, 'unit_price' => $unitPrice, 'tax' => $tax, ); } /** * TODO: implement removal of items * @see SofortLib_EditSr * @deprecated * @param $productId * @param $quantity */ public function removeItem($productId, $quantity = 0) { $this->setApiVersion('1.0'); if (!isset($this->_parameters['items']['item'][$productId])) { return false; } elseif ($quantity = -1) { unset($this->_parameters['items']['item'][$productId]); return true; } //$this->_parameters['items']['item'][$productId]['quantity'] = $quantity; return true; } /** * * just useable with api version 1.0 * @see SofortLib_EditSr * @deprecated * @param array $cartItems */ function updateCart($cartItems = array()) { $this->setApiVersion('1.0'); if (empty($cartItems)) { $this->_parameters['items'] = array(); return $this; } $i = 0; foreach ($cartItems as $cartItem) { $this->_parameters['items']['item'][$i]['item_id'] = $cartItem['itemId']; $this->_parameters['items']['item'][$i]['product_number'] = $cartItem['productNumber']; $this->_parameters['items']['item'][$i]['title'] = $cartItem['title']; $this->_parameters['items']['item'][$i]['description'] = $cartItem['description']; $this->_parameters['items']['item'][$i]['quantity'] = $cartItem['quantity']; $this->_parameters['items']['item'][$i]['unit_price'] = number_format($cartItem['unitPrice'], 2, '.', '') ; $this->_parameters['items']['item'][$i]['tax'] = $cartItem['tax']; $i++; } return $this; } /** * cancel the invoice * just useable with api version 1.0 * @see SofortLib_EditSr * @deprecated * @param string $transaction the transaction id * @return SofortLib_ConfirmSr */ public function cancelInvoice($transaction = '') { $this->setApiVersion('1.0'); if (empty($transaction) && array_key_exists('transaction', $this->_parameters)) { $transaction = $this->_parameters['transaction']; } if (!empty($transaction)) { $this->_parameters = NULL; $this->_parameters['transaction'] = $transaction; $this->_parameters['items'] = array(); } return $this; } /** * confirm the invoice * @param string $transaction the transaction id * @return SofortLib_ConfirmSr */ public function confirmInvoice($transaction = '') { if ($this->_apiVersion == 1) { if (empty($transaction) && array_key_exists('transaction', $this->_parameters)) { $transaction = $this->_parameters['transaction']; } if (!empty($transaction)) { $this->_parameters = NULL; $this->_parameters['transaction'] = $transaction; } } else { if (!empty($transaction)) { $this->_parameters['invoice'][0]['transaction'] = $transaction; } } return $this; } /** * after you you changed/confirmed an invoice you * can download the new invoice-pdf with this function * @return string url */ public function getInvoiceUrl($i = 0) { return isset($this->_response['invoice'][$i]['download_url']['@data']) ? $this->_response['invoice'][$i]['download_url']['@data'] : ''; } /** * Parse the XML (override) * (non-PHPdoc) * @see SofortLib_Abstract::_parseXml() */ protected function _parseXml() {} /** * Handle errors if occurred * (non-PHPdoc) * @see SofortLib::_handleErrors() */ protected function _handleErrors() { if ($this->_apiVersion == 1) { return parent::_handleErrors(); } if (!isset($this->_response['invoices']['invoice'][0])) { $tmp = $this->_response['invoices']['invoice']; unset($this->_response['invoices']['invoice']); $this->_response['invoices']['invoice'][0] = $tmp; } foreach ($this->_response['invoices']['invoice'] as $response) { //handle errors if (isset($response['errors']['error'])) { if (!isset($response['errors']['error'][0])) { $tmp = $response['errors']['error']; unset($response['errors']['error']); $response['errors']['error'][0] = $tmp; } foreach ($response['errors']['error'] as $error) { $this->errors['sr'][] = $this->_getErrorBlock($error); } } //handle warnings if (isset($response['warnings']['warning'])) { if (!isset($response['warnings']['warning'][0])) { $tmp = $response['warnings']['warning']; unset($response['warnings']['warning']); $response['warnings']['warning'][0] = $tmp; } foreach ($response['warnings']['warning'] as $error) { $this->warnings['sr'][] = $this->_getErrorBlock($error); } } } } } ?>sofortLib_ideal_banks.inc.php000066600000003066151376502640012326 0ustar00_banks; } /** * Parse the xml (override) * (non-PHPdoc) * @see SofortLib_Abstract::_parseXml() */ protected function _parseXml() { if (isset($this->_response['ideal']['banks']['bank'][0]['code']['@data'])) { foreach($this->_response['ideal']['banks']['bank'] as $key => $bank) { $this->_banks[$key]['code'] = $bank['code']['@data']; $this->_banks[$key]['name'] = $bank['name']['@data']; } } } } ?>helper/xml_to_array.php000066600000017440151376502640011257 0ustar00 '€', ); /** * Loads XML into array representation. * @param string $input * @param int $maxDepth * @throws XmlToArrayException */ public function __construct($input, $maxDepth = 20) { if (!is_string($input)) throw new XmlToArrayException('No valid input.'); $this->_maxDepth = $maxDepth; $XMLParser = xml_parser_create(); xml_parser_set_option($XMLParser, XML_OPTION_SKIP_WHITE, false); xml_parser_set_option($XMLParser, XML_OPTION_CASE_FOLDING, false); xml_parser_set_option($XMLParser, XML_OPTION_TARGET_ENCODING, 'UTF-8'); xml_set_character_data_handler($XMLParser, array($this, '_contents')); xml_set_default_handler($XMLParser, array($this, '_default')); xml_set_element_handler($XMLParser, array($this, '_start'), array($this, '_end')); xml_set_external_entity_ref_handler($XMLParser, array($this, '_externalEntity')); xml_set_notation_decl_handler($XMLParser, array($this, '_notationDecl')); xml_set_processing_instruction_handler($XMLParser, array($this, '_processingInstruction')); xml_set_unparsed_entity_decl_handler($XMLParser, array($this, '_unparsedEntityDecl')); if (!xml_parse($XMLParser, $input, true)) { $errorCode = xml_get_error_code($XMLParser); $message = sprintf('%s. line: %d, char: %d'.($this->_tagStack ? ', tag: %s' : ''), xml_error_string($errorCode), xml_get_current_line_number($XMLParser), xml_get_current_column_number($XMLParser)+1, implode('->', $this->_tagStack)); xml_parser_free($XMLParser); throw new XmlToArrayException($message, $errorCode); } xml_parser_free($XMLParser); } /** * * Log messages (debugging purpose) * @param string $msg * @param int $type */ public function log($msg, $type = 2) { if (class_exists('Object')) { !($this->_Object instanceof Object) && $this->_Object = new Object(); return $this->_Object->log($msg, $type); } return false; } /** * Returns parsed XML as array structure * @return array */ public function toArray($simpleStructure = false) { return $this->_CurrentXmlToArrayNode->render($simpleStructure); } /** * Static entry point * @param string $input * @param bool $simpleStructure * @param int $maxDepth only parse XML to the provided depth * @return array * @throws XmlToArrayException */ public static function render($input, $simpleStructure = false, $maxDepth = 20) { $Instance = new XmlToArray($input, $maxDepth); return $Instance->toArray($simpleStructure); } /** * Handles cdata of the XML (user data between the tags) * @param resource $parser a resource handle of the XML parser * @param string $data */ private function _contents($parser, $data) { if (trim($data) !== '' && $this->_CurrentXmlToArrayNode instanceof XmlToArrayNode) $this->_CurrentXmlToArrayNode->setData($data); } /** * Default handler for all other XML sections not implemented as callback * @param resource $parser a resource handle of the XML parser * @param mixed $data * @throws XmlToArrayException */ private function _default($parser, $data) { $data = trim($data); if (in_array($data, get_html_translation_table(HTML_ENTITIES))) { $this->_CurrentXmlToArrayNode instanceof XmlToArrayNode && $this->_CurrentXmlToArrayNode->setData(html_entity_decode($data)); } elseif ($data && isset(self::$_htmlEntityExceptions[$data])) { $this->_CurrentXmlToArrayNode instanceof XmlToArrayNode && $this->_CurrentXmlToArrayNode->setData(self::$_htmlEntityExceptions[$data]); } elseif ($data && is_string($data) && strpos($data, '