diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..61ead86 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/vendor diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..99f3c91 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,26 @@ +Copyright (c) 2016, CambioReal. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of CambioReal nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..af7cd35 --- /dev/null +++ b/README.md @@ -0,0 +1,76 @@ +# CambioReal PHP Library +This library enables you to integrate CambioReal with any PHP application. + +## Requirements +* PHP >= 5.3 +* cURL + +## Usage +### Setup +To use the CambioReal PHP library you need to setup your app id and app secret. +``` php +\CambioReal\Config::setAppId('your-app-id'); +\CambioReal\Config::setAppSecret('your-app-secret'); +``` + +If you need to change other settings, you can use the following function call: +``` php +\CambioReal\Config::set([ + 'appId' => 'your-app-id', + 'appSecret' => 'your-app-secret', + 'testMode' => true, +]); +``` + +You can change the following settings: +* appId: your app id. It will be different in test and production modes. +* appSecret: your app secret. It will be different in test and production modes. +* testMode: enable or disable the test mode. The default value is _false_. + +To create a new API request, just call one of the following methods on the \CambioReal\CambioReal +class and supply it with the request parameters: +* \CambioReal\CambioReal::cancel +* \CambioReal\CambioReal::get +* \CambioReal\CambioReal::request + +request command example: +``` php +require_once __DIR__ . 'vendor/autoload.php'; + +\CambioReal\Config::setAppId('11250214'); +\CambioReal\Config::setAppSecret('6e556ff76e55...56ff7'); + +$request = \CambioReal\CambioReal::request([ + 'client' => [ + 'name' => 'John Test', + 'email' => 'john@test.com', + ], + 'currency' => 'USD', + 'amount' => 130.00, + 'order_id' => '10000052', + 'duplicate' => false, + 'due_date' => null, + 'products' => [ + [ + 'descricao' => 'Laptop i7', + 'base_value' => 800.00, + 'valor' => 1600.00, + 'qty' => 2, + 'ref' => 1, + ], + [ + 'descricao' => 'Frete', + 'base_value' => 5.00, + 'valor' => 5.00, + 'ref' => 'São Paulo - SP', + ], + ], +]); +``` + +## Changelog +* **1.0.0**: first release. +* **1.1.0**: get and print boleto. +* **1.2.0**: boleto returned in pdf. +* **1.2.1**: Added the amount simulator. +* **1.3.0**: removed the generation of boletos and the boleto endpoint. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..bca0d6e --- /dev/null +++ b/composer.json @@ -0,0 +1,20 @@ +{ + "name": "cambioreal/cambioreal", + "description": "CambioReal PHP library", + "keywords": ["cambioreal", "payment processing", "api"], + "homepage": "https://www.cambioreal.com", + "license": "BSD", + "require": { + "php": ">=5.3.0", + "ext-curl": "*" + }, + "require-dev": { + "phpunit/phpunit": "4.4.*" + }, + "autoload": { + "psr-0": { + "CambioReal": "src" + } + }, + "minimum-stability": "stable" +} \ No newline at end of file diff --git a/examples/bootstrap.php b/examples/bootstrap.php new file mode 100644 index 0000000..9759de8 --- /dev/null +++ b/examples/bootstrap.php @@ -0,0 +1,9 @@ + '', + 'appSecret' => '', + 'testMode' => true, +)); diff --git a/examples/cancel.php b/examples/cancel.php new file mode 100644 index 0000000..6021e6f --- /dev/null +++ b/examples/cancel.php @@ -0,0 +1,43 @@ + array( + 'name' => 'John Test', + 'email' => 'john@test.com', + ), + 'currency' => 'USD', + 'amount' => 130.00, + 'order_id' => '10000052', + 'duplicate' => false, + 'due_date' => null, + 'products' => array( + array( + 'descricao' => 'Laptop i7', + 'base_value' => 800.00, + 'valor' => 1600.00, + 'qty' => 2, + 'ref' => 1, + ), + array( + 'descricao' => 'Frete', + 'base_value' => 5.00, + 'valor' => 5.00, + 'ref' => 'São Paulo - SP', + ), + ), +)); + +/** + * Request para cancelar a cobrança anteriormente criada. + */ +$response = \CambioReal\CambioReal::cancel(array( + 'id' => $request->data->id, + 'token' => $request->data->token +)); + +var_dump($response); \ No newline at end of file diff --git a/examples/checkout.php b/examples/checkout.php new file mode 100644 index 0000000..1fe2bc0 --- /dev/null +++ b/examples/checkout.php @@ -0,0 +1,35 @@ + array( + 'name' => 'John Test', + 'email' => 'john@test.com', + ), + 'currency' => 'USD', + 'amount' => 130.00, + 'order_id' => '10000052', + 'duplicate' => false, + 'due_date' => null, + 'products' => array( + array( + 'descricao' => 'Laptop i7', + 'base_value' => 800.00, + 'valor' => 1600.00, + 'qty' => 2, + 'ref' => 1, + ), + array( + 'descricao' => 'Frete', + 'base_value' => 5.00, + 'valor' => 5.00, + 'ref' => 'São Paulo - SP', + ), + ), +)); + +var_dump($request); \ No newline at end of file diff --git a/examples/get.php b/examples/get.php new file mode 100644 index 0000000..b29f5e6 --- /dev/null +++ b/examples/get.php @@ -0,0 +1,59 @@ + array( + 'name' => 'John Test', + 'email' => 'john@test.com', + ), + 'currency' => 'USD', + 'amount' => 130.00, + 'order_id' => '10000052', + 'duplicate' => false, + 'due_date' => null, + 'products' => array( + array( + 'descricao' => 'Laptop i7', + 'base_value' => 800.00, + 'valor' => 1600.00, + 'qty' => 2, + 'ref' => 1, + ), + array( + 'descricao' => 'Frete', + 'base_value' => 5.00, + 'valor' => 5.00, + 'ref' => 'São Paulo - SP', + ), + ), +)); + +/** + * Request para consultar uma cobrança na CambioReal. + * + * Status possíveis de uma solicitação: + * PENDENTE_ACCOUNT - Conta bancária da empresa está pendente de aprovação. + * AGUARDANDO_CLIENTE - Aguardando cliente gerar o boleto + * BOLETO_GERADO - Boleto gerado + * BOLETO_EXPIRADO - Boleto expirado + * BOLETO_CANCELADO - Boleto cancelado pelo banco + * SOLICITACAO_RECUSADA - Cliente recusou a solicitação de cobrança + * SOLICITACAO_INVALIDA - Solicitação inválida + * SOLICITACAO_CANCELADA - Empresa cancelou a solicitação + * SOLICITACAO_PAGO - Solicitação paga + * SOLICITACAO_FINALIZADA - Solicitação enviada para pagamento ao destinatário + * SOLICITACAO_EXPIRADA - Solicitação expirada + */ +$response = \CambioReal\CambioReal::get(array( + 'id' => $request->data->id, + 'token' => $request->data->token, +)); + +if ($response->status === 'success') +{ + var_dump($response); +} diff --git a/examples/simulator.php b/examples/simulator.php new file mode 100644 index 0000000..115072e --- /dev/null +++ b/examples/simulator.php @@ -0,0 +1,15 @@ + 'USD', + 'amount' => 50.00, + 'take_rates' => false, + 'payment_method' => 'boleto', +)); + +var_dump($request); \ No newline at end of file diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..cbb5968 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,8 @@ + + + + + tests + + + \ No newline at end of file diff --git a/src/CambioReal/Action/AbstractAction.php b/src/CambioReal/Action/AbstractAction.php new file mode 100644 index 0000000..bbee7de --- /dev/null +++ b/src/CambioReal/Action/AbstractAction.php @@ -0,0 +1,63 @@ + + */ +abstract class AbstractAction { + + /** + * Associative array of params + * @var array + */ + protected $params = array(); + + /** + * The HTTP method + * @var string + */ + protected $method = 'POST'; + + /** + * The action URL address + * @var string + */ + protected $action = null; + + /** + * The response type - HTML or JSON + * @var string + */ + protected $_responseType = 'JSON'; + + /** + * Validates the request parameters + * @param CambioReal\Action\Validator $validator The validator instance + * @return mixed + * @throws InvalidArgumentException + */ + abstract protected function validate($validator); + + /** + * Executes the action in the CambioReal API + * @param array $params The request parameters + * @return mixed + */ + public function execute($params) + { + $this->params = $params; + $this->validate(new \CambioReal\Action\Validator($this->params)); + + // Get the HTTP request from the registry + $httpRequest = \CambioReal\Config::getHttpRequest(); + $request = new $httpRequest(); + $request->setParams($this->params) + ->setMethod($this->method) + ->setAction($this->action) + ->setResponseType($this->_responseType); + + return $request->send(); + } + +} diff --git a/src/CambioReal/Action/Cancel.php b/src/CambioReal/Action/Cancel.php new file mode 100644 index 0000000..fc1e608 --- /dev/null +++ b/src/CambioReal/Action/Cancel.php @@ -0,0 +1,33 @@ + + */ +class Cancel extends \CambioReal\Action\AbstractAction { + + /** + * The HTTP method + * @var string + */ + protected $method = 'POST'; + + /** + * The action URL address + * @var string + */ + protected $action = 'cancel'; + + /** + * Validates the request parameters + * @param CambioReal\Action\Validator $validator The validator instance + * @return mixed + * @throws InvalidArgumentException + */ + protected function validate($validator) + { + $validator->required('token'); + } + +} diff --git a/src/CambioReal/Action/Factory.php b/src/CambioReal/Action/Factory.php new file mode 100644 index 0000000..d385348 --- /dev/null +++ b/src/CambioReal/Action/Factory.php @@ -0,0 +1,31 @@ + + */ +class Factory { + + /** + * Returns an instance of the action class + * @param string $name The action name in the form 'doCommand' + * @return \CambioReal\Action\AbstractAction + * @throws RuntimeException + */ + public static function build($className) + { + $className = ucfirst($className); + $class = '\\CambioReal\\Action\\'.$className; + + if (class_exists($class)) + { + return new $class(); + } + else + { + throw new \RuntimeException("Action '$className' doesn't exist."); + } + } + +} diff --git a/src/CambioReal/Action/Get.php b/src/CambioReal/Action/Get.php new file mode 100644 index 0000000..2028e75 --- /dev/null +++ b/src/CambioReal/Action/Get.php @@ -0,0 +1,32 @@ + + */ +class Get extends \CambioReal\Action\AbstractAction +{ + /** + * The HTTP method + * @var string + */ + protected $method = 'GET'; + + /** + * The action URL address + * @var string + */ + protected $action = 'get'; + + /** + * Validates the request parameters + * @param CambioReal\Action\Validator $validator The validator instance + * @return mixed + * @throws InvalidArgumentException + */ + protected function validate($validator) + { + $validator->required('token'); + } +} \ No newline at end of file diff --git a/src/CambioReal/Action/Request.php b/src/CambioReal/Action/Request.php new file mode 100644 index 0000000..74b01ef --- /dev/null +++ b/src/CambioReal/Action/Request.php @@ -0,0 +1,41 @@ + + */ +class Request extends \CambioReal\Action\AbstractAction { + + /** + * The HTTP method + * + * @var string + */ + protected $method = 'POST'; + + /** + * The action URL address + * + * @var string + */ + protected $action = 'request'; + + /** + * Validates the request parameters + * + * @param CambioReal\Action\Validator $validator The validator instance + * @return mixed + * @throws InvalidArgumentException + */ + protected function validate($validator) + { + $validator->required('currency'); + $validator->required('amount'); + $validator->required('order_id'); + $validator->required('client.name'); + $validator->required('client.email'); + $validator->required('products'); + } + +} diff --git a/src/CambioReal/Action/Simulator.php b/src/CambioReal/Action/Simulator.php new file mode 100644 index 0000000..089a4c9 --- /dev/null +++ b/src/CambioReal/Action/Simulator.php @@ -0,0 +1,34 @@ + + */ +class Simulator extends \CambioReal\Action\AbstractAction { + + /** + * The HTTP method + * @var string + */ + protected $method = 'POST'; + + /** + * The action URL address + * @var string + */ + protected $action = 'simulator'; + + /** + * Validates the request parameters + * @param CambioReal\Action\Validator $validator The validator instance + * @return mixed + * @throws InvalidArgumentException + */ + protected function validate($validator) + { + $validator->required('currency'); + $validator->required('amount'); + } + +} diff --git a/src/CambioReal/Action/Validator.php b/src/CambioReal/Action/Validator.php new file mode 100644 index 0000000..033ba53 --- /dev/null +++ b/src/CambioReal/Action/Validator.php @@ -0,0 +1,101 @@ + + */ +class Validator { + + /** + * The request parameters + * @var array + */ + protected $params; + + public function __construct($params) + { + $this->params = $params; + } + + /** + * Verifies if a parameter was supplied + * @param string $key The parameter name (array key) + * @return boolean + * @throws InvalidArgumentException + */ + public function required($key) + { + if ($this->exists($key)) + { + return true; + } + + throw new \InvalidArgumentException("The parameter '$key' was not supplied."); + } + + /** + * Verifies if one of the parameters was supplied + * @param string $key1 The first parameter name (array key) + * @param string $key1 The second parameter name (array key) + * @return boolean + * @throws InvalidArgumentException + */ + public function requiredOne($key1, $key2) + { + if ($this->exists($key1)) + { + // Throw an exception if both parameters exist + if ($this->exists($key2)) + { + throw new \InvalidArgumentException("Either parameter '$key1' or '$key2' must be supplied, but not both."); + } + + return true; + } + else if ($this->exists($key2)) + { + return true; + } + + throw new \InvalidArgumentException("Either the parameter '$key1' or '$key2' must be supplied."); + } + + /** + * Verifies if a parameter exists + * @param string $key The parameter name (array key) + * @return boolean + */ + public function exists($key) + { + // Checks if we need to verify a nested array + if (preg_match('/\.+/', $key)) + { + $keys = explode('.', $key); + $levels = count($keys); + + // Quick workaround + if ($levels == 4) + { + return isset($this->params[$keys[0]][$keys[1]][$keys[2]][$keys3]); + } + else if ($levels == 3) + { + return isset($this->params[$keys[0]][$keys[1]][$keys[2]]); + } + else + { + return isset($this->params[$keys[0]][$keys[1]]); + } + } + + // Non-nested array validation + if (array_key_exists($key, $this->params)) + { + return true; + } + + return false; + } + +} diff --git a/src/CambioReal/CambioReal.php b/src/CambioReal/CambioReal.php new file mode 100644 index 0000000..25884a5 --- /dev/null +++ b/src/CambioReal/CambioReal.php @@ -0,0 +1,35 @@ + + */ +class CambioReal { + + /** + * Library version + * @var string + */ + const VERSION = '1.3.0'; + + /** + * Magic method that calls the Action Factory + * @param string $name The method name + * @param string $args The method arguments ($args[0] for the parameters array) + * @return mixed + * @throws InvalidArgumentException + */ + public static function __callStatic($name, $args) + { + if ( ! isset($args[0])) + { + throw new \InvalidArgumentException('The action call received no arguments.'); + } + + $action = \CambioReal\Action\Factory::build($name); + + return $action->execute($args[0]); + } + +} diff --git a/src/CambioReal/Config.php b/src/CambioReal/Config.php new file mode 100644 index 0000000..0f62c69 --- /dev/null +++ b/src/CambioReal/Config.php @@ -0,0 +1,138 @@ + + */ +class Config { + + /** + * The API URL + */ + const URL_TEST = 'https://sandbox.cambioreal.com/'; + const URL_PRODUCTION = 'https://www.cambioreal.com/'; + + const API_VERSION = 'v1'; + + /** + * The config object instance + * @var \CambioReal\Config + */ + protected static $instance = null; + + /** + * Library settings array + * @var array + */ + protected static $settings = array(); + + /** + * Protected constructor to avoid other instances. + * Sets stuff to default values. + */ + protected function __construct() + { + self::$settings['testMode'] = false; + self::$settings['httpRequest'] = '\\CambioReal\\Http\\Request'; + } + + /** + * Get the class instance (singleton) + * @return \CambioReal\Config + */ + public static function getInstance() + { + if (self::$instance == null) + { + self::$instance = new Config(); + } + + return self::$instance; + } + + /** + * Gets a setting value + * @param string $key The setting name + * @return mixed + * @throws InvalidArgumentException + */ + public static function get($key) + { + self::getInstance(); + + if (array_key_exists($key, self::$settings)) + { + return self::$settings[$key]; + } + + throw new \InvalidArgumentException("The key $key doesn't exist in the config settings."); + } + + /** + * Sets a setting + * @param string $key The setting name + * @param mixed $value The setting value + * @return void + */ + public static function set() + { + self::getInstance(); + + $args = func_get_args(); + + if (is_array($args[0])) + { + foreach ($args[0] as $key => $value) + { + self::$settings[$key] = $value; + } + } + else + { + self::$settings[$args[0]] = $args[1]; + } + } + + /** + * Magic method to get and set settings + * @param string $name The method name + * @param string $args The method arguments + * @return mixed + */ + public static function __callStatic($name, $args) + { + // From 'getIntegrationKey' to 'integrationKey' + $key = lcfirst(preg_replace('/^get|^set/', '', $name)); + + // Magic getter method + if (preg_match('/^get[\w]+/', $name)) + { + return self::get($key); + } + // Magic setter method + else if (preg_match('/^set[\w]+/', $name)) + { + self::set($key, $args[0]); + } + } + + /** + * Gets the current API URL + * @return string + */ + public static function getURL() + { + return (self::$settings['testMode'] ? self::URL_TEST : self::URL_PRODUCTION) . 'service/' . self::API_VERSION . '/checkout/'; + } + + /** + * Gets the base URL for redirect purposes + * @return string + */ + public static function getBaseURL() + { + return (self::$settings['testMode'] ? self::URL_TEST : self::URL_PRODUCTION); + } + +} diff --git a/src/CambioReal/Http/Request.php b/src/CambioReal/Http/Request.php new file mode 100644 index 0000000..6f98138 --- /dev/null +++ b/src/CambioReal/Http/Request.php @@ -0,0 +1,147 @@ + + */ +class Request { + + /** + * The request HTTP method + * @var string + */ + protected $method; + + /** + * The allowed HTTP methods + * @var array + */ + protected $allowedMethods = array('POST', 'GET'); + + /** + * The HTTP action (URI) + * @var string + */ + protected $action; + + /** + * The request parameters + * @var array + */ + protected $params; + + /** + * Flag to call json_decode on response + * @var boolean + */ + protected $decodeResponse = false; + + /** + * Set the request parameters + * @param array $params The request parameters + * @return CambioReal\Http\Request + */ + public function setParams($params) + { + $this->params = $params; + + return $this; + } + + /** + * Set the request HTTP method + * @param string $method The request HTTP method + * @return CambioReal\Http\Request + * @throws InvalidArgumentException + */ + public function setMethod($method) + { + if (!in_array(strtoupper($method), $this->allowedMethods)) + { + throw new \InvalidArgumentException("The HTTP Request doesn't accept $method requests."); + } + + $this->method = $method; + return $this; + } + + /** + * Set the request target URI + * @param string $action The target URI + * @return CambioReal\Http\Request + */ + public function setAction($action) + { + $this->action = Config::getURL() . $action; + return $this; + } + + /** + * Set the decodeResponse flag depending on the response type (JSON or HTML) + * @param string $responseType The response type (JSON or HTML) + * @return CambioReal\Http\Request + */ + + public function setResponseType($responseType) + { + if (strtoupper($responseType) == 'JSON') + { + $this->decodeResponse = true; + } + + return $this; + } + + /** + * Sends the HTTP request + * @return StdClass + */ + public function send() + { + if ( ! ini_get('allow_url_fopen')) + { + throw new \RuntimeException('allow_url_fopen must be enabled to use PHP streams.'); + } + + $params = http_build_query($this->params); + $uri = $this->action; + + if (isset($this->params['token'])) + { + $uri .= '/' . $this->params['token']; + unset($this->params['token']); + } + + $context = stream_context_create(array( + 'http' => array( + 'ignore_errors' => true, + 'method' => $this->method, + 'header' => + "Content-Type: application/x-www-form-urlencoded \r\n" . + "User-Agent: CAMBIOREAL PHP Library " . \CambioReal\CambioReal::VERSION . "\r\n" . + "X-APP-ID: " . Config::getAppId() . "\r\n" . + "X-APP-SECRET: " . Config::getAppSecret(), + 'content' => $params + ) + )); + + $response = file_get_contents($uri, false, $context); + + if ($response && strlen($response)) + { + if ($this->decodeResponse) + { + return json_decode($response); + } + + return $response; + } + + throw new \RuntimeException("Bad HTTP request: {$response}"); + } + +} diff --git a/src/autoload.php b/src/autoload.php new file mode 100644 index 0000000..fa37f99 --- /dev/null +++ b/src/autoload.php @@ -0,0 +1,22 @@ +setExpectedException('InvalidArgumentException', "The parameter 'id' was not supplied."); + \CambioReal\CambioReal::boleto(array()); + } + + public function testValidateToken() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'token' was not supplied."); + \CambioReal\CambioReal::boleto(array('id' => 1)); + } + + public function testRequest() + { + $id = rand(1, 300); + $token = md5(time()); + $request = \CambioReal\CambioReal::boleto(array('id' => $id, 'token' => $token)); + + $this->assertEquals('GET', $request['method']); + $this->assertEquals('http://cambioreal.dev/service/v1/checkout/boleto', $request['action']); + $this->assertEquals(false, $request['decode']); + $this->assertEquals($id, $request['params']['id']); + $this->assertEquals($token, $request['params']['token']); + } +} \ No newline at end of file diff --git a/tests/CambioReal/Action/CancelTest.php b/tests/CambioReal/Action/CancelTest.php new file mode 100644 index 0000000..1dd253a --- /dev/null +++ b/tests/CambioReal/Action/CancelTest.php @@ -0,0 +1,35 @@ + + */ +class CancelTest extends TestCase { + + public function testValidateId() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'id' was not supplied."); + \CambioReal\CambioReal::cancel(array()); + } + + public function testValidateToken() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'token' was not supplied."); + \CambioReal\CambioReal::cancel(array('id' => '123213')); + } + + public function testCancelRequestIsCorrect() + { + $id = 123123123; + $token = md5(time()); + $request = \CambioReal\CambioReal::cancel(array('id' => $id, 'token' => $token)); + + $this->assertEquals('POST', $request['method']); + $this->assertEquals('http://cambiorealdev.dev/service/v1/checkout/cancel', $request['action']); + $this->assertEquals(true, $request['decode'], true); + $this->assertEquals($id, $request['params']['id'], $id); + $this->assertEquals($token, $request['params']['token'], $token); + } + +} diff --git a/tests/CambioReal/Action/FactoryTest.php b/tests/CambioReal/Action/FactoryTest.php new file mode 100644 index 0000000..4bb7a70 --- /dev/null +++ b/tests/CambioReal/Action/FactoryTest.php @@ -0,0 +1,22 @@ + + */ +class FactoryTest extends TestCase { + + public function testBuildValidAction() + { + $this->assertInstanceOf("\\CambioReal\\Action\\Cancel", \CambioReal\Action\Factory::build('cancel')); + } + + public function testBuildInvalidAction() + { + $command = 'fooBar'; + $this->setExpectedException('RuntimeException', "Action 'fooBar' doesn't exist."); + \CambioReal\Action\Factory::build($command); + } + +} diff --git a/tests/CambioReal/Action/GetTest.php b/tests/CambioReal/Action/GetTest.php new file mode 100644 index 0000000..925e49b --- /dev/null +++ b/tests/CambioReal/Action/GetTest.php @@ -0,0 +1,30 @@ +setExpectedException('InvalidArgumentException', "The parameter 'id' was not supplied."); + \CambioReal\CambioReal::get(array()); + } + + public function testValidateTokenRequired() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'token' was not supplied."); + \CambioReal\CambioReal::get(array('id' => 123123)); + } + + public function testRequest() + { + $id = 1312323; + $token = md5(time()); + $request = \CambioReal\CambioReal::get(array('id' => $id, 'token' => $token)); + + $this->assertEquals('GET', $request['method']); + $this->assertEquals('http://cambiorealdev.dev/service/v1/checkout/get', $request['action']); + $this->assertEquals(true, $request['decode']); + $this->assertEquals($id, $request['params']['id']); + $this->assertEquals($token, $request['params']['token']); + } + +} diff --git a/tests/CambioReal/Action/RegisterAccountTest.php b/tests/CambioReal/Action/RegisterAccountTest.php new file mode 100644 index 0000000..e3d5da6 --- /dev/null +++ b/tests/CambioReal/Action/RegisterAccountTest.php @@ -0,0 +1,124 @@ +params = [ + 'email' => 'teste@cambioreal.com', + 'email_confirmation' => 'teste@cambioreal.com', + 'cpf' => '693.891.104-59', + 'nome' => 'Teste CambioReal', + 'data_nasc' => '10/10/1970', + 'phone1' => '+55 (45) 9999-9999', + 'endereco' => 'Av. Tiradentes', + 'cidade' => 'Itaipulândia', + 'estado' => 'PR', + 'zip' => '85880-000', + 'district' => 'Centro', + 'number' => '2045', + ]; + } + + public function testValidateEmail() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'email' was not supplied."); + unset($this->params['email']); + \CambioReal\CambioReal::registerAccount($this->params); + } + + public function testValidateEmailConfirmation() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'email_confirmation' was not supplied."); + unset($this->params['email_confirmation']); + \CambioReal\CambioReal::registerAccount($this->params); + } + + public function testValidateCpf() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'cpf' was not supplied."); + unset($this->params['cpf']); + \CambioReal\CambioReal::registerAccount($this->params); + } + + public function testValidateNome() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'nome' was not supplied."); + unset($this->params['nome']); + \CambioReal\CambioReal::registerAccount($this->params); + } + + public function testValidateDataNasc() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'data_nasc' was not supplied."); + unset($this->params['data_nasc']); + \CambioReal\CambioReal::registerAccount($this->params); + } + + public function testValidatePhone1() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'phone1' was not supplied."); + unset($this->params['phone1']); + \CambioReal\CambioReal::registerAccount($this->params); + } + + public function testValidateEndereco() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'endereco' was not supplied."); + unset($this->params['endereco']); + \CambioReal\CambioReal::registerAccount($this->params); + } + + public function testValidateCidade() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'cidade' was not supplied."); + unset($this->params['cidade']); + \CambioReal\CambioReal::registerAccount($this->params); + } + + public function testValidateEstado() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'estado' was not supplied."); + unset($this->params['estado']); + \CambioReal\CambioReal::registerAccount($this->params); + } + + public function testValidateZip() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'zip' was not supplied."); + unset($this->params['zip']); + \CambioReal\CambioReal::registerAccount($this->params); + } + + public function testValidateDistrict() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'district' was not supplied."); + unset($this->params['district']); + \CambioReal\CambioReal::registerAccount($this->params); + } + + public function testValidateNumber() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'number' was not supplied."); + unset($this->params['number']); + \CambioReal\CambioReal::registerAccount($this->params); + } + + public function testRequest() + { + $request = \CambioReal\CambioReal::registerAccount($this->params); + + $this->assertEquals('POST', $request['method']); + $this->assertEquals('http://cambioreal.dev/service/v1/checkout/register-account', $request['action']); + $this->assertEquals(true, $request['decode']); + + foreach ($this->params as $key => $value) + { + $this->assertEquals($value, $request['params'][$key]); + } + } +} \ No newline at end of file diff --git a/tests/CambioReal/Action/RequestTest.php b/tests/CambioReal/Action/RequestTest.php new file mode 100644 index 0000000..00ba782 --- /dev/null +++ b/tests/CambioReal/Action/RequestTest.php @@ -0,0 +1,100 @@ + + */ +class RequestTest extends TestCase { + + protected $params; + + public function setUp() + { + parent::setUp(); + + $this->params = array( + 'client' => array( + 'name' => 'John Maxxel', + 'email' => 'john@max.com', + ), + 'currency' => 'USD', + 'amount' => 130.00, + 'order_id' => '10000052', + 'duplicate' => false, + 'due_date' => null, + 'products' => array( + array( + 'descricao' => 'Laptop i7', + 'base_value' => 800.00, + 'valor' => 1600.00, + 'qty' => 2, + 'ref' => 1, + ), + array( + 'descricao' => 'Frete', + 'base_value' => 5.00, + 'valor' => 5.00, + 'ref' => 'São Paulo - SP', + ), + ), + ); + } + + public function testValidateCurrencyCode() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'currency' was not supplied."); + unset($this->params['currency']); + \CambioReal\CambioReal::request($this->params); + } + + public function testValidateAmount() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'amount' was not supplied."); + unset($this->params['amount']); + \CambioReal\CambioReal::request($this->params); + } + + public function testValidateClientName() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'client.name' was not supplied."); + unset($this->params['client']['name']); + \CambioReal\CambioReal::request($this->params); + } + + public function testValidateClientEmail() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'client.email' was not supplied."); + unset($this->params['client']['email']); + \CambioReal\CambioReal::request($this->params); + } + + public function testValidateOrderId() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'order_id' was not supplied."); + unset($this->params['order_id']); + \CambioReal\CambioReal::request($this->params); + } + + public function testValidateProducts() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'products' was not supplied."); + unset($this->params['products']); + \CambioReal\CambioReal::request($this->params); + } + + public function testRequestIsCorrect() + { + $request = \CambioReal\CambioReal::request($this->params); + + $this->assertEquals('POST', $request['method']); + $this->assertEquals('http://cambiorealdev.dev/service/v1/checkout/request', $request['action']); + $this->assertEquals(true, $request['decode'], true); + $this->assertEquals($this->params['amount'], $request['params']['amount']); + $this->assertEquals($this->params['currency'], $request['params']['currency']); + $this->assertEquals($this->params['client']['name'], $request['params']['client']['name']); + $this->assertEquals($this->params['client']['email'], $request['params']['client']['email']); + $this->assertEquals($this->params['products'], $request['params']['products']); + } + +} diff --git a/tests/CambioReal/Action/SimulatorTest.php b/tests/CambioReal/Action/SimulatorTest.php new file mode 100644 index 0000000..70bd865 --- /dev/null +++ b/tests/CambioReal/Action/SimulatorTest.php @@ -0,0 +1,36 @@ + + */ +class SimulatorTest extends TestCase { + + public function testValidateCurrency() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'currency' was not supplied."); + \CambioReal\CambioReal::simulator(array()); + } + + public function testValidateAmount() + { + $this->setExpectedException('InvalidArgumentException', "The parameter 'amount' was not supplied."); + \CambioReal\CambioReal::simulator(array('currency' => 'USD')); + } + + public function testSimulatorRequestIsCorrect() + { + $request = \CambioReal\CambioReal::simulator(array( + 'currency' => 'USD', + 'amount' => 50.00, + 'take_rates' => false, + 'payment_method' => 'boleto', + )); + + $this->assertEquals('POST', $request['method']); + $this->assertEquals('http://cambiorealdev.dev/service/v1/checkout/simulator', $request['action']); + $this->assertEquals(true, $request['decode'], true); + } + +} diff --git a/tests/CambioReal/Action/ValidatorTest.php b/tests/CambioReal/Action/ValidatorTest.php new file mode 100644 index 0000000..a620301 --- /dev/null +++ b/tests/CambioReal/Action/ValidatorTest.php @@ -0,0 +1,74 @@ + + */ +class ValidatorTest extends TestCase { + + public function testExists() + { + $params = array('test' => 'yes'); + + $validator = new \CambioReal\Action\Validator($params); + $this->assertTrue($validator->exists('test')); + $this->assertFalse($validator->exists('invalidParameter')); + } + + public function testExistsNested() + { + $params = array( + 'level1' => 'yes', + 'level2' => array( + 'test' => 'yes' + ), + 'level3' => array( + 'test' => array( + 'test' => 'yes' + ) + ) + ); + + $validator = new \CambioReal\Action\Validator($params); + $this->assertTrue($validator->exists('level1')); + $this->assertTrue($validator->exists('level2.test')); + $this->assertTrue($validator->exists('level3.test.test')); + } + + public function testValidateRequired() + { + $params = array('test' => 'yes'); + + $validator = new \CambioReal\Action\Validator($params); + + $this->assertTrue($validator->required('test')); + + $this->setExpectedException('InvalidArgumentException', "The parameter 'foo' was not supplied."); + $validator->required('foo'); + } + + public function testValidateRequiredOrNone() + { + $this->setExpectedException('InvalidArgumentException', "Either the parameter 'param1' or 'param2' must be supplied."); + $validator = new \CambioReal\Action\Validator(array()); + $validator->requiredOne('param1', 'param2'); + } + + public function testValidateRequiredOrBoth() + { + $this->setExpectedException('InvalidArgumentException', "Either parameter 'param1' or 'param2' must be supplied, but not both."); + $validator = new \CambioReal\Action\Validator(array('param1' => 1, 'param2' => 2)); + $validator->requiredOne('param1', 'param2'); + } + + public function testValidateRequiredOne() + { + $validator = new \CambioReal\Action\Validator(array('param1' => 1)); + $this->assertTrue($validator->requiredOne('param1', 'param2')); + + $validator = new \CambioReal\Action\Validator(array('param2' => 2)); + $this->assertTrue($validator->requiredOne('param1', 'param2')); + } + +} diff --git a/tests/CambioReal/CambioRealTest.php b/tests/CambioReal/CambioRealTest.php new file mode 100644 index 0000000..5b0f40c --- /dev/null +++ b/tests/CambioReal/CambioRealTest.php @@ -0,0 +1,22 @@ + + */ +class CambioRealTest extends TestCase { + + public function testCallInvalidAction() + { + $this->setExpectedException('RuntimeException', "Action 'starWars' doesn't exist."); + \CambioReal\CambioReal::starWars('teste'); + } + + public function testCallActionWithoutArguments() + { + $this->setExpectedException('InvalidArgumentException', 'The action call received no arguments.'); + \CambioReal\CambioReal::request(); + } + +} diff --git a/tests/CambioReal/ConfigTest.php b/tests/CambioReal/ConfigTest.php new file mode 100644 index 0000000..3ba450c --- /dev/null +++ b/tests/CambioReal/ConfigTest.php @@ -0,0 +1,44 @@ + + */ +class ConfigTest extends TestCase { + + public function testUrlTestMode() + { + \CambioReal\Config::set('testMode', false); + $this->assertEquals('https://www.cambioreal.com/service/v1/checkout/', \CambioReal\Config::getURL()); + + \CambioReal\Config::set('testMode', true); + $this->assertEquals('http://cambiorealdev.dev/service/v1/checkout/', \CambioReal\Config::getURL()); + } + + public function testSettingCanBeSetAndRetrieved() + { + \CambioReal\Config::set('optionFromTest', 'starWars'); + $this->assertEquals('starWars', \CambioReal\Config::get('optionFromTest')); + } + + public function testInvalidSetting() + { + $this->setExpectedException('InvalidArgumentException'); + \CambioReal\Config::get('invalidConfigTest'); + } + + public function testSetManySettings() + { + \CambioReal\Config::set(array( + 'foo' => true, + 'bar' => '12345678', + )); + + $this->assertEquals(true, \CambioReal\Config::getFoo()); + $this->assertEquals(true, \CambioReal\Config::get('foo')); + $this->assertEquals('12345678', \CambioReal\Config::getBar()); + $this->assertEquals('12345678', \CambioReal\Config::get('bar')); + } + +} diff --git a/tests/Mock/Http/Request.php b/tests/Mock/Http/Request.php new file mode 100644 index 0000000..ce9c535 --- /dev/null +++ b/tests/Mock/Http/Request.php @@ -0,0 +1,24 @@ + + */ +class Request extends \CambioReal\Http\Request { + + /** + * Returns the request options/parameters instead of sending the request + * @return array + */ + public function send() + { + return array( + 'method' => $this->method, + 'action' => $this->action, + 'params' => $this->params, + 'decode' => $this->decodeResponse, + ); + } + +} diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..596c6be --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,22 @@ + + */ +class TestCase extends PHPUnit_Framework_TestCase { + + public function setUp() + { + \CambioReal\Config::set(array( + 'appId' => '1664250130', + 'appSecret' => '$2y$10$nU.tUrnhdxC56F1uXlrbp.SmzUAtdQ/7v29WMqDeaFFZN8mMi3.Ra', + 'httpRequest' => '\\Mock\\Http\\Request', + 'testMode' => true, + )); + } + +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php new file mode 100644 index 0000000..4afbe3d --- /dev/null +++ b/tests/bootstrap.php @@ -0,0 +1,4 @@ +