diff --git a/composer.json b/composer.json index 59104ae..01e36f5 100644 --- a/composer.json +++ b/composer.json @@ -30,7 +30,10 @@ "autoload": { "psr-4": { "Moip\\": "src/" - } + }, + "files": [ + "src/Helper/helpers.php" + ] }, "autoload-dev": { "psr-4": { diff --git a/src/MoipBasicAuth.php b/src/Auth/BasicAuth.php similarity index 91% rename from src/MoipBasicAuth.php rename to src/Auth/BasicAuth.php index c4cd47c..5c1ab7b 100644 --- a/src/MoipBasicAuth.php +++ b/src/Auth/BasicAuth.php @@ -1,13 +1,14 @@ client_id = $client_id; + $this->redirect_uri = $redirect_uri; + + if (is_bool($scope)) { + $this->setScodeAll($scope); + } else { + $this->setScope($scope); + } + + $this->setEndpoint($endpoint); + } + + /** + * Creates a new Request_Session with all the default values. + * A Session is created at construction. + * + * @param float $timeout How long should we wait for a response?(seconds with a millisecond precision, default: 30, example: 0.01). + * @param float $connect_timeout How long should we wait while trying to connect? (seconds with a millisecond precision, default: 10, example: 0.01) + * + * @return \Requests_Session + */ + public function createNewSession($timeout = 30.0, $connect_timeout = 30.0) + { + if (function_exists('posix_uname')) { + $uname = posix_uname(); + $user_agent = sprintf('Mozilla/4.0 (compatible; %s; PHP/%s %s; %s; %s)', + Moip::CLIENT, PHP_SAPI, PHP_VERSION, $uname['sysname'], $uname['machine']); + } else { + $user_agent = sprintf('Mozilla/4.0 (compatible; %s; PHP/%s %s; %s)', + Moip::CLIENT, PHP_SAPI, PHP_VERSION, PHP_OS); + } + $sess = new Requests_Session($this->endpoint); + $sess->options['timeout'] = $timeout; + $sess->options['connect_timeout'] = $connect_timeout; + $sess->options['useragent'] = $user_agent; + + return $sess; + } + + /** + * URI of oauth. + * + * @param $endpoint + * + * @return string + */ + public function getAuthUrl($endpoint = null) + { + if ($endpoint !== null) { + $this->endpoint = $endpoint; + } + $query_string = [ + 'response_type' => self::RESPONSE_TYPE, + 'client_id' => $this->client_id, + 'redirect_uri' => $this->redirect_uri, + 'scope' => implode(',', $this->scope), + ]; + + return $this->endpoint.self::OAUTH_AUTHORIZE.'?'.http_build_query($query_string); + } + + /** + * With the permission granted, you will receive a code that will allow you to retrieve the authentication accessToken and process requests involving another user. + * + * @return mixed + */ + public function authorize() + { + $path = $this->endpoint.self::OAUTH_TOKEN; + $headers = ['Content-Type' => 'application/x-www-form-urlencoded']; + $body = [ + 'client_id' => $this->client_id, + 'client_secret' => $this->client_secret, + 'grant_type' => self::GRANT_TYPE, + 'code' => $this->code, + 'redirect_uri' => $this->redirect_uri, + ]; + + try { + $http_response = $this->createNewSession()->request($path, $headers, $body, 'POST'); + } catch (Requests_Exception $e) { + throw new UnexpectedException($e); + } + + if ($http_response->status_code >= 200 && $http_response->status_code < 300) { + return json_decode($http_response->body); + } elseif ($http_response->status_code >= 400 && $http_response->status_code <= 499) { + throw new ValidationException($http_response->status_code, $http_response->body); + } + + throw new UnexpectedException(); + } + + /** + * @param bool $scope + * + * @return $this + */ + public function setScodeAll($scope) + { + if (!is_bool($scope)) { + throw new InvalidArgumentException('$scope deve ser boolean, foi passado '.gettype($scope)); + } + + if ($scope === false) { + $this->scope = []; + } else { + $this->scope = []; + $this->setReceiveFunds(true) + ->setRefund(true) + ->setManageAccountInfo(true) + ->setRetrieveFinancialInfo(true) + ->setTransferFunds(true) + ->setDefinePreferences(true); + } + + return $this; + } + + /** + * Permission for creation and consultation of ORDERS, PAYMENTS, MULTI ORDERS, MULTI PAYMENTS, CUSTOMERS and consultation of LAUNCHES. + * + * @param bool $receive_funds + * + * @throws \Moip\Exceptions\InvalidArgumentException + * + * @return \Moip\Auth\Connect $this + */ + public function setReceiveFunds($receive_funds) + { + if (!is_bool($receive_funds)) { + throw new InvalidArgumentException('$receive_funds deve ser boolean, foi passado '.gettype($receive_funds)); + } + + if ($receive_funds === true) { + $this->setScope(self::RECEIVE_FUNDS); + } + + return $this; + } + + /** + * Permission to create and consult reimbursements ofORDERS, PAYMENTS. + * + * @param bool $refund + * + * @throws \Moip\Exceptions\InvalidArgumentException + * + * @return \Moip\Auth\Connect $this + */ + public function setRefund($refund) + { + if (!is_bool($refund)) { + throw new InvalidArgumentException('$refund deve ser boolean, foi passado '.gettype($refund)); + } + + if ($refund === true) { + $this->setScope(self::REFUND); + } + + return $this; + } + + /** + * Permission to consult ACCOUNTS registration information. + * + * @param bool $manage_account_info + * + * @throws \Moip\Exceptions\InvalidArgumentException + * + * @return \Moip\Auth\Connect $this + */ + public function setManageAccountInfo($manage_account_info) + { + if (!is_bool($manage_account_info)) { + throw new InvalidArgumentException('$manage_account_info deve ser boolean, foi passado '.gettype($manage_account_info)); + } + + if ($manage_account_info === true) { + $this->setScope(self::MANAGE_ACCOUNT_INFO); + } + + return $this; + } + + /** + * Permission to query balance through the ACCOUNTS endpoint. + * + * @param bool $retrieve_financial_info + * + * @throws \Moip\Exceptions\InvalidArgumentException + * + * @return \Moip\Auth\Connect $this + */ + public function setRetrieveFinancialInfo($retrieve_financial_info) + { + if (!is_bool($retrieve_financial_info)) { + throw new InvalidArgumentException('$retrieve_financial_info deve ser boolean, foi passado '.gettype($retrieve_financial_info)); + } + + if ($retrieve_financial_info === true) { + $this->setScope(self::RETRIEVE_FINANCIAL_INFO); + } + + return $this; + } + + /** + * Permission for bank transfers or for Moip accounts through the TRANSFERS endpoint. + * + * @param bool $transfer_funds + * + * @throws \Moip\Exceptions\InvalidArgumentException + * + * @return \Moip\Auth\Connect $this + */ + public function setTransferFunds($transfer_funds) + { + if (!is_bool($transfer_funds)) { + throw new InvalidArgumentException('$transfer_funds deve ser boolean, foi passado '.gettype($transfer_funds)); + } + + if ($transfer_funds === true) { + $this->setScope(self::TRANSFER_FUNDS); + } + + return $this; + } + + /** + * Permission to create, change, and delete notification preferences through the PREFERENCES endpoint. + * + * @param bool $define_preferences + * + * @throws \Moip\Exceptions\InvalidArgumentException + * + * @return $this + */ + public function setDefinePreferences($define_preferences) + { + if (!is_bool($define_preferences)) { + throw new InvalidArgumentException('$define_preferences deve ser boolean, foi passado '.gettype($define_preferences)); + } + + if ($define_preferences === true) { + $this->setScope(self::DEFINE_PREFERENCES); + } + + return $this; + } + + /** + * Unique identifier of the application that will be carried out the request. + * + * @return mixed + */ + public function getClientId() + { + return $this->client_id; + } + + /** + * Unique identifier of the application that will be carried out the request. + * + * @param mixed $client_id + * + * @return \Moip\Auth\Connect + */ + public function setClientId($client_id) + { + $this->client_id = $client_id; + + return $this; + } + + /** + * Client Redirect URI. + * + * @return mixed + */ + public function getRedirectUri() + { + return $this->redirect_uri; + } + + /** + * Client Redirect URI. + * + * @param mixed $redirect_uri + * + * @return \Moip\Auth\Connect + */ + public function setRedirectUri($redirect_uri) + { + $this->redirect_uri = $redirect_uri; + + return $this; + } + + /** + * Permissions that you want (Possible values depending on the feature.). + * + * @return mixed + */ + public function getScope() + { + return $this->scope; + } + + /** + * Permissions that you want (Possible values depending on the feature.). + * + * @param array|string $scope + * + * @return \Moip\Auth\Connect + */ + public function setScope($scope) + { + if (!in_array($scope, self::SCOPE_ALL, true)) { + throw new InvalidArgumentException(); + } + + if (is_array($scope)) { + $this->scope = $scope; + } + + $this->scope[] = $scope; + + return $this; + } + + /** + * @param string $endpoint + * + * @return \Moip\Auth\Connect + */ + public function setEndpoint(string $endpoint) + { + if (!in_array($endpoint, [self::ENDPOINT_SANDBOX, self::ENDPOINT_PRODUCTION])) { + throw new InvalidArgumentException('Endpoint inválido.'); + } + + $this->endpoint = $endpoint; + + return $this; + } + + /** + * @param mixed $client_secret + * + * @return \Moip\Auth\Connect + */ + public function setClientSecret($client_secret) + { + $this->client_secret = $client_secret; + + return $this; + } + + /** + * @return mixed + */ + public function getClientSecret() + { + return $this->client_secret; + } + + /** + * @param string $code + * + * @return \Moip\Auth\Connect + */ + public function setCode(string $code) + { + $this->code = $code; + + return $this; + } + + /** + * @return string + */ + public function getCode() + { + return $this->code; + } + + /** + * Register hooks as needed. + * + * This method is called in {@see Requests::request} when the user has set + * an instance as the 'auth' option. Use this callback to register all the + * hooks you'll need. + * + * @see Requests_Hooks::register + * + * @param Requests_Hooks $hooks Hook system + */ + public function register(Requests_Hooks &$hooks) + { + // TODO: Implement register() method. + } + + /** + * Specify data which should be serialized to JSON. + * + * @link http://php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed data which can be serialized by json_encode, + * which is a value of any type other than a resource. + * + * @since 5.4.0 + */ + public function jsonSerialize() + { + // TODO: Implement jsonSerialize() method. + } +} diff --git a/src/MoipOAuth.php b/src/Auth/OAuth.php similarity index 88% rename from src/MoipOAuth.php rename to src/Auth/OAuth.php index 7546b29..3b83b46 100644 --- a/src/MoipOAuth.php +++ b/src/Auth/OAuth.php @@ -1,13 +1,14 @@ links = $links; + $this->generateMethods(); + } + + /** + * @return mixed + */ + public function getSelf() + { + return $this->links->self->href; + } + + /** + * @param null|string $pay + * + * @return mixed + */ + public function getCheckout($pay) + { + return $this->links->checkout->$pay->redirectHref; + } + + /** + * @return mixed + */ + public function getAllCheckout() + { + return $this->checkout; + } + + private function generateMethods() + { + $this->checkout = new stdClass(); + + foreach ($this->links->checkout as $method => $link) { + $this->checkout->$method = $link->redirectHref; + } + } +} diff --git a/src/Utils.php b/src/Helper/Utils.php similarity index 98% rename from src/Utils.php rename to src/Helper/Utils.php index 3ef582c..c403b56 100644 --- a/src/Utils.php +++ b/src/Helper/Utils.php @@ -1,6 +1,6 @@ tags around the output of given variable. Similar to debug(). + * + * This function returns the same variable that was passed. + * + * @param mixed $var Variable to print out. + * + * @return mixed the same $var that was passed to this function + * + * @link http://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#pr + * @see debug() + */ + function pr($var) + { + $template = '
%s
'; + printf($template, trim(print_r($var, true))); + + return $var; + } +} diff --git a/src/Moip.php b/src/Moip.php index 86a4893..4642898 100644 --- a/src/Moip.php +++ b/src/Moip.php @@ -2,6 +2,7 @@ namespace Moip; +use Moip\Contracts\Authentication; use Moip\Resource\Account; use Moip\Resource\Customer; use Moip\Resource\Entry; @@ -59,10 +60,10 @@ class Moip /** * Create a new aurhentication with the endpoint. * - * @param \Moip\MoipAuthentication $moipAuthentication - * @param string $endpoint + * @param \Moip\Auth\MoipAuthentication $moipAuthentication + * @param string $endpoint */ - public function __construct(MoipAuthentication $moipAuthentication, $endpoint = self::ENDPOINT_PRODUCTION) + public function __construct(Authentication $moipAuthentication, $endpoint = self::ENDPOINT_PRODUCTION) { $this->moipAuthentication = $moipAuthentication; $this->endpoint = $endpoint; diff --git a/src/MoipAuthentication.php b/src/MoipAuthentication.php deleted file mode 100644 index 240e923..0000000 --- a/src/MoipAuthentication.php +++ /dev/null @@ -1,12 +0,0 @@ -getIfSet('_links'); + + if ($links !== null) { + return new Links($links); + } + } + + /** + * @param $key + * @param $fmt + * @param stdClass|null $data + * + * @return bool|\DateTime|null + */ protected function getIfSetDateFmt($key, $fmt, stdClass $data = null) { $val = $this->getIfSet($key, $data); diff --git a/src/Resource/Orders.php b/src/Resource/Orders.php index 19e13ff..22e81e3 100644 --- a/src/Resource/Orders.php +++ b/src/Resource/Orders.php @@ -109,6 +109,8 @@ protected function initialize() $this->data->amount->subtotals = new stdClass(); $this->data->items = []; $this->data->receivers = []; + $this->data->checkoutPreferences = new stdClass(); + $this->data->checkoutPreferences->redirectUrls = new stdClass(); } /** @@ -421,6 +423,16 @@ public function getUpdatedAt() return $this->getIfSetDateTime('updatedAt'); } + /** + * Get checkout preferences of the order. + * + * @return string + */ + public function getCheckoutPreferences() + { + return $this->getIfSet('checkoutPreferences'); + } + /** * Structure of payment. * @@ -552,4 +564,32 @@ public function setShippingAmount($value) return $this; } + + /** + * Set URL for redirection in case of success. + * + * @param string $urlSuccess UrlSuccess. + * + * @return $this + */ + public function setUrlSuccess($urlSuccess = '') + { + $this->data->checkoutPreferences->redirectUrls->urlSuccess = $urlSuccess; + + return $this; + } + + /** + * Set URL for redirection in case of failure. + * + * @param string $urlFailure UrlFailure. + * + * @return $this + */ + public function setUrlFailure($urlFailure = '') + { + $this->data->checkoutPreferences->redirectUrls->urlFailure = $urlFailure; + + return $this; + } } diff --git a/tests/MoipTest.php b/tests/MoipTest.php index 912f9d7..80eba22 100644 --- a/tests/MoipTest.php +++ b/tests/MoipTest.php @@ -3,17 +3,17 @@ namespace Moip\Tests; use Moip\Exceptions; +use Moip\Helper\Utils; use Moip\Moip; -use Moip\Utils; use Requests_Exception; /** * class MoipTest. */ -class MoipTest extends MoipTestCase +class MoipTest extends TestCase { /** - * Test should return instance of \Moip\Resource\Customer. + * MoipTest should return instance of \Moip\Resource\Customer. */ public function testShouldReceiveInstanceOfCustomer() { @@ -23,7 +23,7 @@ public function testShouldReceiveInstanceOfCustomer() } /** - * Test should return instance of \Moip\Resource\Account. + * MoipTest should return instance of \Moip\Resource\Account. */ public function testShouldReceiveInstanceOfAccount() { @@ -33,7 +33,7 @@ public function testShouldReceiveInstanceOfAccount() } /** - * Test should return instance of \Moip\Resource\Entry. + * MoipTest should return instance of \Moip\Resource\Entry. */ public function testShouldReceiveInstanceOfEntry() { @@ -43,7 +43,7 @@ public function testShouldReceiveInstanceOfEntry() } /** - * Test should return instance of \Moip\Resource\Orders. + * MoipTest should return instance of \Moip\Resource\Orders. */ public function testShouldReceiveInstanceOfOrders() { @@ -53,7 +53,7 @@ public function testShouldReceiveInstanceOfOrders() } /** - * Test should return instance of \Moip\Resource\Payment. + * MoipTest should return instance of \Moip\Resource\Payment. */ public function testShouldReceiveInstanceOfPayment() { @@ -63,7 +63,7 @@ public function testShouldReceiveInstanceOfPayment() } /** - * Test should return instance of \Moip\Resource\Multiorders. + * MoipTest should return instance of \Moip\Resource\Multiorders. */ public function testShouldReceiveInstanceOfMultiorders() { @@ -73,7 +73,7 @@ public function testShouldReceiveInstanceOfMultiorders() } /** - * Test if a \Moip\Exceptions\testShouldRaiseValidationException is thrown and is correctly constructed. + * MoipTest if a \Moip\Exceptions\testShouldRaiseValidationException is thrown and is correctly constructed. */ public function testShouldRaiseValidationException() { @@ -106,7 +106,7 @@ public function testShouldRaiseValidationException() } /** - * Test if \Moip\Exceptios\UnautorizedException is thrown. + * MoipTest if \Moip\Exceptios\UnautorizedException is thrown. */ public function testShouldRaiseUnautorizedException() { @@ -122,7 +122,7 @@ public function testShouldRaiseUnautorizedException() } /** - * Test if UnexpectedException is thrown when 500 http status code is returned. + * MoipTest if UnexpectedException is thrown when 500 http status code is returned. */ public function testShouldRaiseUnexpectedException500() { @@ -137,7 +137,7 @@ public function testShouldRaiseUnexpectedException500() } /** - * Test if UnexpectedException is thrown when a Requests_Exception is thrown. + * MoipTest if UnexpectedException is thrown when a Requests_Exception is thrown. */ public function testShouldRaiseUnexpectedExceptionNetworkError() { @@ -162,7 +162,7 @@ public function testShouldRaiseUnexpectedExceptionNetworkError() } /** - * Test if we can connect to the API endpoints. + * MoipTest if we can connect to the API endpoints. * This is primarily to make user we are using HTTPS urls and the certification verification is ok. */ public function testConnectEndPoints() @@ -177,7 +177,7 @@ public function testConnectEndPoints() } /** - * Test the convertion from money to cents using floats. + * MoipTest the convertion from money to cents using floats. */ public function testToCents() { diff --git a/tests/Resource/CustomerTest.php b/tests/Resource/CustomerTest.php index 45f54a6..6d2074c 100644 --- a/tests/Resource/CustomerTest.php +++ b/tests/Resource/CustomerTest.php @@ -3,15 +3,15 @@ namespace Moip\Tests\Resource; use Moip\Resource\Customer; -use Moip\Tests\MoipTestCase; +use Moip\Tests\TestCase; /** * class CustomerTest. */ -class CustomerTest extends MoipTestCase +class CustomerTest extends TestCase { /** - * Test if the Customer object accepts a \DateTime object and correctly transforms it. + * MoipTest if the Customer object accepts a \DateTime object and correctly transforms it. */ public function testSetBirthDateDateTime() { @@ -23,7 +23,7 @@ public function testSetBirthDateDateTime() } /** - * Test if the Customer object accepts a date string as argument. + * MoipTest if the Customer object accepts a date string as argument. */ public function testSetBirthDateString() { @@ -34,7 +34,7 @@ public function testSetBirthDateString() } /** - * Test customer creation. + * MoipTest customer creation. */ public function testCustomerCreate() { @@ -50,7 +50,7 @@ public function testCustomerCreate() } /** - * Test customer shipping address. + * MoipTest customer shipping address. */ public function testShippingAddress() { diff --git a/tests/Resource/OrdersTest.php b/tests/Resource/OrdersTest.php index 7577dc6..1fe2806 100644 --- a/tests/Resource/OrdersTest.php +++ b/tests/Resource/OrdersTest.php @@ -3,9 +3,9 @@ namespace Moip\Tests\Resource; use Moip\Resource\Orders; -use Moip\Tests\MoipTestCase; +use Moip\Tests\TestCase; -class OrdersTest extends MoipTestCase +class OrdersTest extends TestCase { /** * Send http request. @@ -29,7 +29,7 @@ private function executeOrder(Orders $order = null, $body = null) } /** - * Test creating an order. + * MoipTest creating an order. */ public function testCreateOrder() { @@ -51,7 +51,7 @@ public function testItens() } /** - *Test if the total is correct. + *MoipTest if the total is correct. */ public function testTotal() { @@ -62,7 +62,7 @@ public function testTotal() } /** - * Test if the total is equal to the expected total. + * MoipTest if the total is equal to the expected total. */ public function testTotalConstant() { diff --git a/tests/Resource/PaymentTest.php b/tests/Resource/PaymentTest.php index 1165f71..f039164 100644 --- a/tests/Resource/PaymentTest.php +++ b/tests/Resource/PaymentTest.php @@ -2,14 +2,14 @@ namespace Moip\Tests\Resource; -use Moip\Tests\MoipTestCase; +use Moip\Tests\TestCase; -class PaymentTest extends MoipTestCase +class PaymentTest extends TestCase { //todo: credit card hash /** - * Test creating a credit card payment, passing all credit card data. + * MoipTest creating a credit card payment, passing all credit card data. */ public function testCreditCardPCI() { @@ -26,7 +26,7 @@ public function testCreditCardPCI() } /** - * Test creating a billet payment. + * MoipTest creating a billet payment. */ public function testBillet() { diff --git a/tests/MoipTestCase.php b/tests/TestCase.php similarity index 97% rename from tests/MoipTestCase.php rename to tests/TestCase.php index b49fc13..12086b7 100644 --- a/tests/MoipTestCase.php +++ b/tests/TestCase.php @@ -2,17 +2,17 @@ namespace Moip\Tests; +use Moip\Auth\BasicAuth; use Moip\Moip; -use Moip\MoipBasicAuth; use Moip\Resource\Customer; use Moip\Resource\Orders; -use PHPUnit_Framework_TestCase as TestCase; +use PHPUnit_Framework_TestCase; use Requests_Response; /** - * class MoipTestCase. + * class TestCase. */ -abstract class MoipTestCase extends TestCase +abstract class TestCase extends PHPUnit_Framework_TestCase { /** * Variables representing the test modes. On MOCK mode no http request will be made. @@ -87,10 +87,10 @@ public function setUp() if ($moip_key && $moip_token) { $this->sandbox_mock = self::SANDBOX; - $auth = new MoipBasicAuth($moip_token, $moip_key); + $auth = new BasicAuth($moip_token, $moip_key); } else { $this->sandbox_mock = self::MOCK; - $auth = $this->getMock('\Moip\MoipAuthentication'); + $auth = $this->getMock('\Moip\Contracts\Authentication'); } $this->moip = new Moip($auth, Moip::ENDPOINT_SANDBOX); }