diff --git a/README.md b/README.md index 56c787c..96b3c10 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ SDK Moip-PHP - API O Moip-PHP é uma biblioteca que implementa uma camada de abstração para geração do XML de instruções do Moip, permitindo que você integre aos serviços de API sem poluir seu código com várias linhas de XML. Um exemplo rápido: +```php include_once "autoload.inc.php"; $moip = new Moip(); @@ -19,10 +20,11 @@ O Moip-PHP $moip->validate('Basic'); print_r($moip->send()); - +``` O Moip-PHP utiliza o padrão Fluent Interfaces, portanto, você pode fazer o exemplo acima da seguinte forma: +```php include_once "autoload.inc.php"; $moip = new Moip(); @@ -35,6 +37,8 @@ O Moip-PHP utiliza o padr ->setReason('Teste do Moip-PHP') ->validate('Basic') ->send()); +``` + ------------------------------------- Métodos disponíveis @@ -50,20 +54,55 @@ M Moip() +```php $moip = new Moip(); +``` + ------------------------------------- setEnvironment() ---------- -Método que define o ambiente em qual o requisição será processada, 'test' para definir que será em ambiente de testes Moip o Sandbox, a omissão desse método define que a requisição deverá ser processada em ambiente real, de produção Moip. +Método que define o ambiente em qual o requisição será processada, passando `true` para definir que será em ambiente de testes Moip o Sandbox, a omissão desse método define que a requisição deverá ser processada em ambiente real, de produção Moip. Importante: ao definir o ambiente certifique-se de que está utilizando a autenticação correspondente ao ambiente, no Moip cada ambiente possui suas própria chaves de autenticação API. -setEnvironment($environment) -$environment : String ('test') +setEnvironment($testing) +$testing : bool (false) + +```php + $moip->setEnvironment(true); +``` + +------------------------------------- + +setPaymentType() +---------- +Método que define o tipo de pagamento, que será validado. Basic + +setPaymentType($tipo) +$tipo : String ('Basic' ou 'Identification') + +1. Basic : Irá realizar a validação dos dados mínimos de para uma requisição XML ao Moip. +2. Identification : Irá validar os dados necessários para se processar um XML com identificação Moip, usados geralmente para redirecionar o cliente já no segundo step da pagina de pagamento no checkout Moip ou usar o Moip Transaparente. + +```php + $moip->setPaymentType('Basic'); +``` + +------------------------------------- + +setEncoding() +---------- +Método que define o qual o encoding da sua página atualmente. O padrão é UTF-8. Normalmente, para páginas em português são utilizados as codificações ISO-8859-1 e Windows-1252. + +setEncoding($encoding) +$encoding : String + +```php + $moip->setEnvironment(true); +``` - $moip->setEnvironment('test'); ------------------------------------- setCredential() @@ -76,10 +115,12 @@ O par $credential : Array('key','token') +```php $moip->setCredential(array( 'key' => 'SUA_KEY', 'token' => 'SEU_TOKEN' )); +``` ------------------------------------- @@ -94,7 +135,9 @@ O m $validateType : String ('Basic' ou 'Identification') +```php $moip->validate('Identification'); +``` ------------------------------------- @@ -108,7 +151,10 @@ setUniqueID($id) $id : String +```php $moip->setUniqueID('ABCD123456789'); +``` + ------------------------------------- setValue() @@ -120,9 +166,12 @@ O m setValue($value) -$value : Numeric +$value : Float +```php $moip->setValue('100.00'); +``` + ------------------------------------- setAdds() @@ -133,9 +182,12 @@ O m setAdds($value) -$value : Numeric +$value : Float +```php $moip->setAdds('15.00'); +``` + ------------------------------------- setDeduct() @@ -149,7 +201,10 @@ setDeduct($value) $value : Numeric +```php $moip->setDeduct('15.00'); +``` + ------------------------------------- setReason() @@ -163,7 +218,10 @@ setReason($value) $value : String +```php $moip->setReason('Pagamento de teste do Moip-PHP'); +``` + ------------------------------------- setPayer() @@ -192,6 +250,7 @@ setPayer($value) $value : Array ('name','email','payerId','identity', 'phone','billingAddress' => Array('address','number','complement','city','neighborhood','state','country','zipCode','phone')) +```php $moip->setPayer(array('name' => 'Nome Sobrenome', 'email' => 'email@cliente.com.br', 'payerId' => 'id_usuario', @@ -204,6 +263,8 @@ $value : Array ('name','email','payerId','identity', 'phone','billingAddress' => 'country' => 'BRA', 'zipCode' => '01230-000', 'phone' => '(11)8888-8888'))); +``` + ------------------------------------- addPaymentWay() @@ -221,11 +282,14 @@ addPaymentWay($way) $way : String ('billet','financing','debit','creditCard','debitCard') +```php $moip->addPaymentWay('creditCard'); $moip->addPaymentWay('billet'); $moip->addPaymentWay('financing'); $moip->addPaymentWay('debit'); $moip->addPaymentWay('debitCard'); +``` + ------------------------------------- setBilletConf() @@ -247,12 +311,15 @@ $instructions : Array() $uriLogo : String +```php $moip->setBilletConf("2011-04-06", false, array("Primeira linha", "Segunda linha", "Terceira linha"), "http://seusite.com.br/logo.gif"); +``` + ------------------------------------- addMessage() @@ -266,7 +333,10 @@ addMessage($msg) $msg : String +```php $moip->addMessage('Seu pedido contem os produtos X,Y e Z.'); +``` + ------------------------------------- setReturnURL() @@ -277,7 +347,10 @@ setReturnURL($url) $url : String +```php $moip->setReturnURL('https://meusite.com.br/cliente/pedido/bemvindodevolta'); +``` + ------------------------------------- setNotificationURL() @@ -288,7 +361,68 @@ setNotificationURL($url) $url : String +```php $moip->setNotificationURL('https://meusite.com.br/nasp/'); +``` + +------------------------------------- + +getStatus() +--------------- +Método que retorna o status de um token. Caso não seja passado nenhum parâmetro, retorna o status do token atual. + +getStatus($paymentToken = null) + +$paymentToken : String (null) + +```php + echo $moip->getStatus()->status; +``` + +------------------------------------- + +removeInstruction() +--------------- +O método removeInstruction() remove uma instrução previamente enviada. Retorna MoipResponse + +removeInstruction($paymentToken) + +$paymentToken : String + +```php + $moip->removeInstruction('92D091R2I0Y9X0E4T2K034L2H2V4H2J6L9R0S0T0K0N0L0T0Y9H879H144O8'); +``` + +------------------------------------- + +getJavascript() +--------------- +O método getJavascript() retorna a URL para inclusão do arquivo de javascript para o checkout transparente. + +getJavascript($include_https) + +$include_https : Boolean (true) + +```php + +``` + +------------------------------------- + +getWidget() +--------------- +O método getWidget() retorna o widget para o checkout transparente, para ser incluido no body do HTML, com o token e respectivos callbacks em Javscript + +getWidget($success, $error) + +$success : String + +$error : String + +```php + getWidget('payment_success', 'payment_error'); ?> +``` + ------------------------------------- addComission() @@ -314,6 +448,7 @@ $percentageValue: Boolean $ratePayer : Boolean +```php $moip->addComission('Razão do Split', 'recebedor_secundario', '5.00'); @@ -322,6 +457,8 @@ $ratePayer : Boolean '12.00', true, true); +``` + ------------------------------------- addParcel() @@ -345,9 +482,12 @@ $rate : Number $transfer : Boolean +```php $moip->addParcel('2', '4'); $moip->addParcel('5', '7', '1.00'); $moip->addParcel('8', '12', null, true); +``` + ------------------------------------- setReceiver() @@ -362,7 +502,10 @@ setReceiver($receiver) $receiver : String +```php $moip->setReceiver('integracao@labs.moip.com.br'); +``` + ------------------------------------- getXML() @@ -372,6 +515,7 @@ O m getXML() +```php $moip = new Moip(); $moip->setEnvironment('test'); $moip->setCredential(array( @@ -384,8 +528,10 @@ getXML() $moip->validate('Basic'); print_r($moip->getXML()); +``` - //IRÃ? IMPRIMIR +```xml + //IRÁ IMPRIMIR @@ -396,6 +542,8 @@ getXML() +``` + ------------------------------------- send() @@ -409,6 +557,7 @@ O m send() +```php $moip = new Moip(); $moip->setEnvironment('test'); $moip->setCredential(array( @@ -421,14 +570,18 @@ send() $moip->validate('Basic'); print_r($moip->send()); +``` - //IRÃ? IMPRIMIR - stdClass Object +``` + //IRÁ IMPRIMIR + MoipResponse Object ( - [response] => 1 - [error] => + [response] => true + [error] => false [xml] => 201209042007216380000000989104SucessoM2C031R2Q0Z9W0Y4Q2S0H0W7E2G1Z6P3E8C0C0W050T01070Y9Y8V9G1F0F4 ) +``` + ------------------------------------- getAnswer() @@ -442,6 +595,7 @@ O m getAnswer() +```php $moip = new Moip(); $moip->setEnvironment('test'); $moip->setCredential(array( @@ -456,15 +610,19 @@ getAnswer() $moip->send(); print_r($moip->getAnswer()); +``` - //IRÃ? IMPRIMIR - stdClass Object +``` + //IRÁ IMPRIMIR + MoipResponse Object ( - [response] => 1 - [error] => + [response] => true + [error] => false [token] => 92D091R2I0Y9X0E4T2K034L2H2V4H2J6L9R0S0T0K0N0L0T0Y9H879H144O8 [payment_url] => https://desenvolvedor.moip.com.br/sandbox/Instrucao.do?token=92D091R2I0Y9X0E4T2K034L2H2V4H2J6L9R0S0T0K0N0L0T0Y9H879H144O8 ) +``` + ------------------------------------- queryParcel() @@ -494,6 +652,7 @@ $rate : Number $simulatedValue: Number +```php $moip = new Moip(); $moip->setEnvironment('test'); $moip->setCredential(array( @@ -504,8 +663,10 @@ $simulatedValue: Number print_r($moip->queryParcel('integracao@labs.moip.com.br', '4', '1.99', '100.00')); +``` - //IRÃ? IMPRIMIR +``` + //IRÁ IMPRIMIR Array ( [response] => 1 @@ -547,4 +708,6 @@ $simulatedValue: Number ) +``` + --------------- \ No newline at end of file diff --git a/lib/Moip.php b/lib/Moip.php index 08f1bef..27554de 100644 --- a/lib/Moip.php +++ b/lib/Moip.php @@ -3,12 +3,12 @@ /** * Library to help PHP users of Moip's API * - * @author Herberth Amaral - * @author Wesley Willians - * @author Alê Borba - * @author Vagner Fiuza Vieira - * @author Paulo Cesar - * @version 1.6 + * @author Herberth Amaral + * @author Wesley Willians + * @author Alê Borba + * @author Vagner Fiuza Vieira + * @author Paulo Cesar + * @version 1.7 * @license BSD License */ @@ -25,121 +25,130 @@ class Moip { * * @var string */ - public $encoding = 'UTF-8'; - /** - * Associative array with two keys. 'key'=>'your_key','token'=>'your_token' - * - * @var array - */ - protected $credential; - /** - * Define the payment's reason - * - * @var string - */ - protected $reason; - /** - * The application's environment - * - * @var MoipEnvironment - */ - protected $environment = null; - /** - * Transaction's unique ID - * - * @var string - */ - protected $uniqueID; - /** - * Associative array of payment's way - * - * @var array - */ - protected $payment_ways = array('billet' => 'BoletoBancario', - 'financing' => 'FinanciamentoBancario', - 'debit' => 'DebitoBancario', - 'creditCard' => 'CartaoCredito', - 'debitCard' => 'CartaoDebito'); - /** - * Associative array of payment's institutions - * - * @var array - */ - protected $institution = array('moip' => 'MoIP', - 'visa' => 'Visa', - 'american_express' => 'AmericanExpress', - 'mastercard' => 'Mastercard', - 'diners' => 'Diners', - 'banco_brasil' => 'BancoDoBrasil', - 'bradesco' => 'Bradesco', - 'itau' => 'Itau', - 'real' => 'BancoReal', - 'unibanco' => 'Unibanco', - 'aura' => 'Aura', - 'hipercard' => 'Hipercard', - 'paggo' => 'Paggo', //oi paggo - 'banrisul' => 'Banrisul' - ); - /** - * Associative array of delivery's type - * - * @var array - */ - protected $delivery_type = array('proprio' => 'Proprio', 'correios' => 'Correios'); - /** - * Associative array with type of delivery's time - * - * @var array - */ - protected $delivery_type_time = array('corridos' => 'Corridos', 'uteis' => 'Uteis'); - /** - * Payment method - * - * @var array - */ - protected $payment_method; - /** - * Arguments of payment method - * - * @var array - */ - protected $payment_method_args; - /** - * Payment's type - * - * @var string - */ - protected $payment_type; - /** - * Associative array with payer's information - * - * @var array - */ - protected $payer; - /** - * Server's answer - * - * @var MoipResponse - */ - public $answer; - /** - * The transaction's value - * - * @var float - */ - protected $value; - /** - * Simple XML object - * - * @var SimpleXMLElement - */ - protected $xml; - /** - * Simple XML object - * - * @var object - */ - public $errors; + protected $encoding = 'UTF-8'; + /** + * Associative array with two keys. 'key'=>'your_key','token'=>'your_token' + * + * @var array + */ + protected $credential; + /** + * Define the payment's reason + * + * @var string + */ + protected $reason; + /** + * The application's environment + * + * @var MoipEnvironment + */ + protected $environment = null; + /** + * Transaction's unique ID + * + * @var string + */ + protected $uniqueID; + /** + * Associative array of payment's way + * + * @var array + */ + protected $payment_ways = array( + 'billet' => 'BoletoBancario', + 'financing' => 'FinanciamentoBancario', + 'debit' => 'DebitoBancario', + 'creditCard' => 'CartaoCredito', + 'debitCard' => 'CartaoDebito' + ); + /** + * Associative array of payment's institutions + * + * @var array + */ + protected $institution = array( + 'moip' => 'MoIP', + 'visa' => 'Visa', + 'american_express' => 'AmericanExpress', + 'mastercard' => 'Mastercard', + 'diners' => 'Diners', + 'banco_brasil' => 'BancoDoBrasil', + 'bradesco' => 'Bradesco', + 'itau' => 'Itau', + 'real' => 'BancoReal', + 'unibanco' => 'Unibanco', + 'aura' => 'Aura', + 'hipercard' => 'Hipercard', + 'paggo' => 'Paggo', //oi paggo + 'banrisul' => 'Banrisul' + ); + /** + * Associative array of delivery's type + * + * @var array + */ + protected $delivery_type = array( + 'proprio' => 'Proprio', + 'correios' => 'Correios' + ); + /** + * Associative array with type of delivery's time + * + * @var array + */ + protected $delivery_type_time = array( + 'corridos' => 'Corridos', + 'uteis' => 'Uteis' + ); + /** + * Payment method + * + * @var array + */ + protected $payment_method; + /** + * Arguments of payment method + * + * @var array + */ + protected $payment_method_args; + /** + * Payment's type + * + * @var string + */ + protected $payment_type; + /** + * Associative array with payer's information + * + * @var array + */ + protected $payer; + /** + * Server's answer + * + * @var MoipResponse + */ + public $answer; + /** + * The transaction's value + * + * @var float + */ + protected $value; + /** + * Simple XML object + * + * @var SimpleXMLElement + */ + protected $xml; + /** + * Simple XML object + * + * @var object + */ + public $errors; /** * @var array */ @@ -152,22 +161,30 @@ class Moip { * @var float */ protected $deduction; - /** - * Method construct - * - * @access public - */ - public function __construct() { - $this->setEnvironment(); - if (!$this->payment_type) { - $this->payment_type = 'Basic'; - } + /** + * Method construct + * + * @param bool $testing Set true if in testing environment + * - $this->initXMLObject(); - } + */ + public function __construct($testing = false) + { + $this->setEnvironment($testing); + $this->payment_type = 'Basic'; + $this->initXMLObject(); + } - private function convert_encoding($text, $post = false) + /** + * Moip uses UTF-8 responses and posts. Needed to convert to UTF-8 + * + * @param string $text + * @param bool $post + * + * @return string + */ + protected function convertEncoding($text, $post = false) { if ($post) { @@ -180,638 +197,997 @@ private function convert_encoding($text, $post = false) { return $text; } + return mb_convert_encoding($text, $this->encoding, 'UTF-8'); } } - /** - * Method initXMLObject() - * - * Start a new XML structure for the requests - * - * @return void - * @access private - */ - private function initXMLObject() { - $this->xml = new SimpleXmlElement(''); - $this->xml->addChild('InstrucaoUnica'); - } - - /** - * Method setPaymentType() - * - * Define the payment's type between 'Basic' or 'Identification' - * - * @param string $tipo Can be 'Basic' or 'Identification' - * @return Moip - * @access public - */ - public function setPaymentType($tipo) { - if ($tipo == 'Basic' || $tipo == 'Identification') { - $this->payment_type = $tipo; - } else { - $this->setError("Error: The variable type must contain values 'Basic' or 'Identification'"); - } - - return $this; - } - - /** - * Method setCredential() - * - * Set the credentials(key,token) required for the API authentication. - * - * @param array $credential Array with the credentials token and key - * @return Moip - * @access public - */ - public function setCredential($credential) { - if (!isset($credential['token']) or - !isset($credential['key']) or - strlen($credential['token']) != 32 or - strlen($credential['key']) != 40) - $this->setError("Error: credential invalid"); - - $this->credential = $credential; - return $this; - } - - /** - * Method setEnvironment() - * - * Define the environment for the API utilization. - * - * @param bool $testing If true, will use the sandbox environment + /** + * Set the current page encoding. ISO needs to be converted to UTF-8 + * + * @param $encoding + * + * @throws Exception + * @return Moip + */ + public function setEncoding($encoding) + { + $encoding = strtoupper($encoding); + + if (in_array($encoding, mb_list_encodings()) !== false) + { + $this->encoding = $encoding; + } + else + { + throw new Exception('Invalid encoding specified: ' . $encoding); + } + + return $this; + } + + /** + * Method initXMLObject() + * + * Start a new XML structure for the requests + * + * @return void + */ + protected function initXMLObject() + { + $this->xml = new SimpleXmlElement(''); + $this->xml->addChild('InstrucaoUnica'); + } + + /** + * Method setPaymentType() + * + * Define the payment's type between 'Basic' or 'Identification' + * + * @param string $tipo Can be 'Basic' or 'Identification' + * + * @return Moip + */ + public function setPaymentType($tipo) + { + if (in_array($tipo, array('Basic', 'Identification')) !== false) + { + $this->payment_type = $tipo; + } + else + { + $this->setError("Error: The variable type must contain values 'Basic' or 'Identification'"); + } + + return $this; + } + + /** + * Method setCredential() + * + * Set the credentials(key,token) required for the API authentication. + * + * @param array $credential Array with the credentials token and key + * + * @return Moip + */ + public function setCredential($credential) + { + if ( + !isset($credential['token']) or + !isset($credential['key']) or + strlen($credential['token']) != 32 or + strlen($credential['key']) != 40 + ) + { + $this->setError("Error: credential invalid"); + } + + $this->credential = $credential; + + return $this; + } + + /** + * Method setEnvironment() + * + * Define the environment for the API utilization. + * + * @param bool $testing If true, will use the sandbox environment + * * @return Moip - */ - public function setEnvironment($testing = false) { - if (empty($this->environment)) + */ + public function setEnvironment($testing = false) + { + if ($this->environment instanceof MoipEnvironment) { - $this->environment = new MoipEnvironment(); + unset($this->environment); } - if ($testing) { - $this->environment->name = "Sandbox"; - $this->environment->base_url = "https://desenvolvedor.moip.com.br/sandbox"; - } else { - $this->environment->name = "Produção"; - $this->environment->base_url = "https://www.moip.com.br"; - } + if ($testing) + { + $this->environment = new MoipEnvironment('https://desenvolvedor.moip.com.br/sandbox', 'Sandbox'); + } + else + { + $this->environment = new MoipEnvironment('https://www.moip.com.br', 'Produção'); + } - return $this; - } + return $this; + } - /** - * Method validate() - * - * Make the data validation + /** + * Method validate() + * + * Make the data validation + * + * @param string $validateType Identification or Basic, defaults to Basic * - * @param string $validateType Identification or Basic, defaults to Basic - * @return Moip - * @access public - */ - public function validate($validateType = "Basic") { + * @return Moip + */ + public function validate($validateType = "Basic") + { - $this->setPaymentType($validateType); + $this->setPaymentType($validateType); - if (!isset($this->credential) or - !isset($this->reason) or - !isset($this->uniqueID)) - $this->setError("[setCredential], [setReason] and [setUniqueID] are required"); + if (empty($this->credential) or empty($this->reason) or empty($this->uniqueID)) + { + $this->setError("[setCredential], [setReason] and [setUniqueID] are required"); + } - $payer = $this->payer; + $payer = $this->payer; - if ($this->payment_type == 'Identification') { + if ($this->payment_type === 'Identification') + { $varNotSeted = ''; - $dataValidate = array('name', - 'email', - 'payerId', - 'billingAddress'); - - $dataValidateAddress = array('address', - 'number', - 'complement', - 'neighborhood', - 'city', - 'state', - 'country', - 'zipCode', - 'phone'); - - foreach ($dataValidate as $key) { - if (!isset($payer[$key])) { - $varNotSeted .= ' [' . $key . '] '; - } - } - - foreach ($dataValidateAddress as $key) { - if (!isset($payer['billingAddress'][$key])) { - $varNotSeted .= ' [' . $key . '] '; - } - } - - if ($varNotSeted !== '') { - $this->setError('Error: The following data required were not informed: ' . $varNotSeted . '.'); + $dataValidate = array( + 'name', + 'email', + 'payerId', + 'billingAddress' + ); + + $dataValidateAddress = array( + 'address', + 'number', + 'complement', + 'neighborhood', + 'city', + 'state', + 'country', + 'zipCode', + 'phone' + ); + + foreach ($dataValidate as $key) + { + if (!isset($payer[$key])) + { + $varNotSeted .= ' [' . $key . '] '; + } + } + + foreach ($dataValidateAddress as $key) + { + if (!isset($payer['billingAddress'][$key])) + { + $varNotSeted .= ' [' . $key . '] '; + } + } + + if ($varNotSeted !== '') + { + $this->setError('Error: The following data required were not informed: ' . $varNotSeted . '.'); } - } - return $this; - } - - /** - * Method setUniqueID() - * - * Set the unique ID for the transaction - * - * @param int $id Unique ID for each transaction - * @return Moip - * @access public - */ - public function setUniqueID($id) { - $this->uniqueID = $id; - return $this; - } - - /** - * Method setReason() - * - * Set the short description of transaction. eg. Order Number. - * - * @param string $reason The reason fo transaction - * @return Moip - * @access public - */ - public function setReason($reason) { - $this->reason = $reason; - return $this; - } - - /** - * Method addPaymentWay() - * - * Add a payment's method - * - * @param string $way The payment method. Options: 'billet','financing','debit','creditCard','debitCard'. - * @return Moip - * @access public - */ - public function addPaymentWay($way) { - if (!isset($this->payment_ways[$way])) - $this->setError("Error: Payment method unavailable"); - else - $this->payment_way[] = $way; - - return $this; - } - - /** - * Method billetConf() - * - * Add a payment's method - * - * @param int $expiration expiration in days or dateTime. - * @param boolean $workingDays expiration should be counted in working days? - * @param array $instructions Additional payment instructions can be array of message or a message in string - * @param string $uriLogo URL of the image to be displayed on docket (75x40) - * @return void - * @access public - */ - public function setBilletConf($expiration, $workingDays=false, $instructions = null, $uriLogo = null) { - - if (!isset($this->xml->InstrucaoUnica->Boleto)) { - $this->xml->InstrucaoUnica->addChild('Boleto'); - - if (is_numeric($expiration)) { - $this->xml->InstrucaoUnica->Boleto->addChild('DiasExpiracao', $expiration); - - if ($workingDays) - $this->xml->InstrucaoUnica->Boleto->DiasExpiracao->addAttribute('Tipo', 'Uteis'); - else - $this->xml->InstrucaoUnica->Boleto->DiasExpiracao->addAttribute('Tipo', 'Corridos'); - }else { - $this->xml->InstrucaoUnica->Boleto->addChild('DataVencimento', $expiration); - } - - if (isset($instructions)) { - if (is_array($instructions)) { - $numeroInstrucoes = 1; - foreach ($instructions as $instrucaostr) { - $this->xml->InstrucaoUnica->Boleto->addChild('Instrucao' . $numeroInstrucoes, $instrucaostr); - $numeroInstrucoes++; - } - } else { - $this->xml->InstrucaoUnica->Boleto->addChild('Instrucao1', $instructions); - } - } - - if (isset($uriLogo)) - $this->xml->InstrucaoUnica->Boleto->addChild('URLLogo', $uriLogo); - } - } - - /** - * Method setPayer() - * - * Set contacts informations for the payer. - * - * @param array $payer Contact information for the payer. - * @return Moip - * @access public - */ - public function setPayer($payer) { - $this->payer = $payer; - return $this; - } - - /** - * Method setValue() - * - * Set the transaction's value - * - * @param float $value The transaction's value - * @return Moip - * @access public - */ - public function setValue($value) { - $this->value = $value; - return $this; - } - - /** - * Method setAdds() - * - * Adds a value on payment. Can be used for collecting fines, shipping and other - * - * @param float $value The value to add. - * @return Moip - * @access public - */ - public function setAdds($value) { - $this->adds = $value; - return $this; - } - - /** - * Method setDeduct() - * - * Deducts a payment amount. It is mainly used for discounts. - * - * @param float $value The value to deduct - * @return Moip - * @access public - */ - public function setDeduct($value) { - $this->deduction = $value; - return $this; - } - - /** - * Method addMessage() - * - * Add a message in the instruction to be displayed to the payer. - * - * @param string $msg Message to be displayed. - * @return Moip - * @access public - */ - public function addMessage($msg) { - if (!isset($this->xml->InstrucaoUnica->Mensagens)) { - $this->xml->InstrucaoUnica->addChild('Mensagens'); - } - - $this->xml->InstrucaoUnica->Mensagens->addChild('Mensagem', $msg); - return $this; - } - - /** - * Method setReturnURL() - * - * Set the return URL, which redirects the client after payment. - * - * @param string $url Return URL + } + + return $this; + } + + /** + * Method setUniqueID() + * + * Set the unique ID for the transaction + * + * @param mixed $id Unique ID for each transaction + * * @return Moip - * @access public - */ - public function setReturnURL($url) { - if (!isset($this->xml->InstrucaoUnica->URLRetorno)) { - $this->xml->InstrucaoUnica->addChild('URLRetorno', $url); - } + */ + public function setUniqueID($id) + { + $this->uniqueID = $id; + return $this; - } - - /** - * Method setNotificationURL() - * - * Set the notification URL, which sends information about changes in payment status - * - * @param string $url Notification URL - * @access public - */ - public function setNotificationURL($url) { - if (!isset($this->xml->InstrucaoUnica->URLNotificacao)) { - $this->xml->InstrucaoUnica->addChild('URLNotificacao', $url); - } - } - - /** - * Method setError() - * - * Set Erroe alert - * - * @param String $error Error alert - * @return Moip - * @access public - */ - public function setError($error) { - $this->errors = $error; - - return $this; - } - - /** - * Method addComission() - * - * Allows to specify commissions on the payment, like fixed values or percent. - * - * @param string $reason reason for commissioning - * @param string $receiver login Moip the secondary receiver - * @param number $value value of the division of payment - * @param boolean $percentageValue percentage value should be - * @param boolean $ratePayer this secondary recipient will pay the fee Moip + } + + /** + * Method setReason() + * + * Set the short description of transaction. eg. Order Number. + * + * @param string $reason The reason fo transaction + * * @return Moip - * @access public - */ - public function addComission($reason, $receiver, $value, $percentageValue=false, $ratePayer=false) { - - if (!isset($this->xml->InstrucaoUnica->Comissoes)) - $this->xml->InstrucaoUnica->addChild('Comissoes'); - - if (is_numeric($value)) { - - $split = $this->xml->InstrucaoUnica->Comissoes->addChild('Comissionamento'); - $split->addChild('Comissionado')->addChild('LoginMoIP', $receiver); - $split->addChild('Razao', $reason); - - if ($percentageValue == false) - $split->addChild('ValorFixo', $value); - if ($percentageValue == true) - $split->addChild('ValorPercentual', $value); - if ($ratePayer == true) - $this->xml->InstrucaoUnica->Comissoes->addChild('PagadorTaxa')->addChild('LoginMoIP', $receiver); - }else { - $this->setError('Error: Value must be numeric.'); - } - - return $this; - } - - /** - * Method addParcel() - * - * Allows to add a order to parceling. - * - * @param int $min The minimum number of parcels. - * @param int $max The maximum number of parcels. - * @param float $rate The percentual value of rates - * @param boolean $transfer "true" defines the amount of interest charged by MoIP installment to be paid by the payer - * @return Moip - * @access public - */ - public function addParcel($min, $max, $rate=null, $transfer=false) { - if (!isset($this->xml->InstrucaoUnica->Parcelamentos)) { - $this->xml->InstrucaoUnica->addChild('Parcelamentos'); - } - - $parcela = $this->xml->InstrucaoUnica->Parcelamentos->addChild('Parcelamento'); - if (is_numeric($min) && $min <= 12) - $parcela->addChild('MinimoParcelas', $min); - else - $this->setError('Error: Minimum parcel can not be greater than 12.'); - - if (is_numeric($max) && $max <= 12) - $parcela->addChild('MaximoParcelas', $max); - else - $this->setError('Error: Maximum amount can not be greater than 12.'); - - $parcela->addChild('Recebimento', 'AVista'); - - if ($transfer === false) { - if (isset($rate)) { - if (is_numeric($rate)) - $parcela->addChild('Juros', $rate); - else - $this->setError('Error: Rate must be numeric'); - } - }else { - if (is_bool($transfer)) - $parcela->addChild('Repassar', $transfer); - else - $this->setError('Error: Transfer must be boolean'); - } - - return $this; - } - - /** - * Method setReceiving() - * - * Allows to add a order to parceling. - * - * @param string $receiver login Moip the secondary receiver - * @return Moip - * @access public - */ - public function setReceiver($receiver) { - if (!isset($this->xml->InstrucaoUnica->Recebedor)) { - $this->xml->InstrucaoUnica->addChild('Recebedor') - ->addChild('LoginMoIP', $receiver); - } - - return $this; - } - - /** - * Method getXML() - * - * Returns the XML that is generated. Useful for debugging. - * - * @return string - * @access public - */ - public function getXML() { - - if ($this->payment_type == "Identification") - $this->xml->InstrucaoUnica->addAttribute('TipoValidacao', 'Transparente'); - - $this->xml->InstrucaoUnica->addChild('IdProprio', $this->uniqueID); - $this->xml->InstrucaoUnica->addChild('Razao', $this->reason); - - if (empty($this->value)) - $this->setError('Error: The transaction amount must be specified.'); - - $this->xml->InstrucaoUnica->addChild('Valores') - ->addChild('Valor', $this->value) - ->addAttribute('moeda', 'BRL'); - - if (isset($this->deduction)) { - $this->xml->InstrucaoUnica->Valores->addChild('Deducao', $this->deduction) - ->addAttribute('moeda', 'BRL'); - } - - if (isset($this->adds)) { - $this->xml->InstrucaoUnica->Valores->addChild('Acrescimo', $this->adds) - ->addAttribute('moeda', 'BRL'); - } - - if (!empty($this->payment_way)) { - $instrucao = $this->xml->InstrucaoUnica; - $formas = $instrucao->addChild('FormasPagamento'); - - foreach ($this->payment_way as $way) { - $formas->addChild('FormaPagamento', $this->payment_ways[$way]); - } - } - - - if (!empty($this->payer)) { - $p = $this->payer; - $this->xml->InstrucaoUnica->addChild('Pagador'); - (isset($p['name'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('Nome', $this->payer['name']) : null; - (isset($p['email'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('Email', $this->payer['email']) : null; - (isset($p['payerId'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('IdPagador', $this->payer['payerId']) : null; - (isset($p['identity'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('Identidade', $this->payer['identity']) : null; - (isset($p['phone'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('TelefoneCelular', $this->payer['phone']) : null; - - $p = $this->payer['billingAddress']; - $this->xml->InstrucaoUnica->Pagador->addChild('EnderecoCobranca'); - (isset($p['address'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Logradouro', $this->payer['billingAddress']['address']) : null; - - (isset($p['number'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Numero', $this->payer['billingAddress']['number']) : null; - - (isset($p['complement'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Complemento', $this->payer['billingAddress']['complement']) : null; - - (isset($p['neighborhood'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Bairro', $this->payer['billingAddress']['neighborhood']) : null; - - (isset($p['city'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Cidade', $this->payer['billingAddress']['city']) : null; - - (isset($p['state'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Estado', $this->payer['billingAddress']['state']) : null; - - (isset($p['country'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Pais', $this->payer['billingAddress']['country']) : null; - - (isset($p['zipCode'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('CEP', $this->payer['billingAddress']['zipCode']) : null; - - (isset($p['phone'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('TelefoneFixo', $this->payer['billingAddress']['phone']) : null; - } - - $return = $this->convert_encoding($this->xml->asXML(), true); - $this->initXMLObject(); - return str_ireplace("\n", "", $return); - } - - /** - * Method send() - * - * Send the request to the server - * - * @param object $client The server's connection - * @return MoipResponse - * @access public - */ - public function send($client=null) { - $this->validate(); - - if ($client == null) - $client = new MoipClient(); - - $url = $this->environment->base_url . '/ws/alpha/EnviarInstrucao/Unica'; - - return $this->answer = $client->curlPost($this->credential['token'] . ':' . $this->credential['key'], - $this->getXML(), - $url, $this->errors); - } - - /** - * Method getAnswer() - * - * Gets the server's answer - * @param boolean $return_xml_as_string Return the answer XMl string - * @return MoipResponse|string - * @access public - */ - public function getAnswer($return_xml_as_string = false) { - if ($this->answer->response == true) { - if ($return_xml_as_string) { - return $this->answer->xml; - } - - $xml = new SimpleXmlElement($this->answer->xml); + */ + public function setReason($reason) + { + $this->reason = $reason; - return new MoipResponse(array( - 'response' => $xml->Resposta->Status == 'Sucesso' ? true : false, - 'error' => $xml->Resposta->Status == 'Falha' ? $this->convert_encoding((string)$xml->Resposta->Erro) : false, - 'token' => (string) $xml->Resposta->Token, - 'payment_url' => $xml->Resposta->Status == 'Sucesso' ? (string) $this->environment->base_url . "/Instrucao.do?token=" . (string) $xml->Resposta->Token : false, - )); - } else { - return $this->answer->error; - } - } - - /** - * Method verifyParcelValues() - * - * Get all informations about the parcelling of user defined by $login_moip - * - * @param string $login The client's login for Moip services - * @param int $maxParcel The total parcels - * @param float $rate The rate's percents of the parcelling. - * @param float $simulatedValue The value for simulation - * @return array - * @access public - */ - public function queryParcel($login, $maxParcel, $rate, $simulatedValue) { - if (!isset($this->credential)) - $this->setError("You must specify the credentials (token / key) and enriroment"); - - - $client = new MoipClient(); - - $url = $this->environment->base_url . "/ws/alpha/ChecarValoresParcelamento/$login/$maxParcel/$rate/$simulatedValue"; - $credential = $this->credential['token'] . ':' . $this->credential['key']; - $answer = $client->curlGet($credential, $url, $this->errors); - - if ($answer->response) { - $xml = new SimpleXmlElement($answer->xml); - - if ($xml->Resposta->Status == "Sucesso") - $response = true; - else - $response = false; - - $return = array('response' => $response, - 'installment' => array()); - - $i = 1; - foreach ($xml->Resposta->ValorDaParcela as $parcela) { - $attrib = $parcela->attributes(); - $return['installment']["$i"] = array('total' => (string) $attrib['Total'], 'rate' => (string) $attrib['Juros'], 'value' => (string) $attrib['Valor']); - $i++; - } - return $return; - } + return $this; + } - return $answer; - } + /** + * Method addPaymentWay() + * + * Add a payment's method + * + * @param string $way The payment method. Options: 'billet','financing','debit','creditCard','debitCard'. + * + * @return Moip + */ + public function addPaymentWay($way) + { + if (!isset($this->payment_ways[$way])) + { + $this->setError("Error: Payment method unavailable"); + } + else + { + $this->payment_way[] = $way; + } -} + return $this; + } + + /** + * Method billetConf() + * + * Add a payment's method + * + * @param int $expiration expiration in days or dateTime. + * @param boolean $workingDays expiration should be counted in working days? + * @param array $instructions Additional payment instructions can be array of message or a message in string + * @param string $uriLogo URL of the image to be displayed on docket (75x40) + * + * @return Moip + */ + public function setBilletConf($expiration, $workingDays = false, $instructions = null, $uriLogo = null) + { + + if (!isset($this->xml->InstrucaoUnica->Boleto)) + { + $this->xml->InstrucaoUnica->addChild('Boleto'); + + if (is_numeric($expiration)) + { + $this->xml->InstrucaoUnica->Boleto->addChild('DiasExpiracao', $expiration); + + if ($workingDays) + { + $this->xml->InstrucaoUnica->Boleto->DiasExpiracao->addAttribute('Tipo', 'Uteis'); + } + else + { + $this->xml->InstrucaoUnica->Boleto->DiasExpiracao->addAttribute('Tipo', 'Corridos'); + } + } + else + { + $this->xml->InstrucaoUnica->Boleto->addChild('DataVencimento', $expiration); + } + + if (isset($instructions)) + { + if (is_array($instructions)) + { + $numeroInstrucoes = 1; + foreach ($instructions as $instrucaostr) + { + $this->xml->InstrucaoUnica->Boleto->addChild('Instrucao' . $numeroInstrucoes, $instrucaostr); + $numeroInstrucoes++; + } + } + else + { + $this->xml->InstrucaoUnica->Boleto->addChild('Instrucao1', $instructions); + } + } + + if (isset($uriLogo)) + { + $this->xml->InstrucaoUnica->Boleto->addChild('URLLogo', $uriLogo); + } + } + + return $this; + } + + /** + * Clean the value, and parse correctly as currency (x.xx) + * + * @param $value + * + * @return float + */ + protected function makeCurrency($value) + { + if (is_string($value)) + { + if (strpos($value, ',') !== false && strpos($value, '.') === false) + { + $value = floatval(str_replace(',', '.', $value)); + } + elseif (strpos($value, ',') === false && strpos($value, '.') !== false) + { + $value = floatval($value); + } + elseif (strpos($value, ',') !== false && strpos($value, '.') !== false) + { + $pos = strrchr($value, '.'); + if (strpos($pos, ',') !== false) + { + $value = str_replace('.', '', $value); + } + $value = floatval(str_replace(',', '.', $value)); + } + else + { + $value = floatval($value); + } + } + elseif (is_int($value)) + { + $value = floatval($value); + } + elseif (!$value) + { + $value = 0.0; + } -class MoipEnvironment { - public $base_url; - public $name; + return number_format($value, 2, '.', ''); + } - function __construct($base_url = '', $name = '') + /** + * Method setPayer() + * + * Set contacts informations for the payer. + * + * @param array $payer Contact information for the payer. + * + * @return Moip + */ + public function setPayer($payer) { - $this->base_url = $base_url; - $this->name = $name; + $this->payer = $payer; + + return $this; } -} \ No newline at end of file + + /** + * Method setValue() + * + * Set the transaction's value + * + * @param float $value The transaction's value + * + * @return Moip + */ + public function setValue($value) + { + $this->value = $this->makeCurrency($value); + + return $this; + } + + /** + * Method setAdds() + * + * Adds a value on payment. Can be used for collecting fines, shipping and other + * + * @param float $value The value to add. + * + * @return Moip + */ + public function setAdds($value) + { + $this->adds = $this->makeCurrency($value); + + return $this; + } + + /** + * Method setDeduct() + * + * Deducts a payment amount. It is mainly used for discounts. + * + * @param float $value The value to deduct + * + * @return Moip + */ + public function setDeduct($value) + { + $this->deduction = $this->makeCurrency($value); + + return $this; + } + + /** + * Method addMessage() + * + * Add a message in the instruction to be displayed to the payer. + * + * @param string $msg Message to be displayed. + * + * @return Moip + */ + public function addMessage($msg) + { + if (!isset($this->xml->InstrucaoUnica->Mensagens)) + { + $this->xml->InstrucaoUnica->addChild('Mensagens'); + } + + $this->xml->InstrucaoUnica->Mensagens->addChild('Mensagem', $msg); + + return $this; + } + + /** + * Method setReturnURL() + * + * Set the return URL, which redirects the client after payment. + * + * @param string $url Return URL + * + * @return Moip + */ + public function setReturnURL($url) + { + if (!isset($this->xml->InstrucaoUnica->URLRetorno)) + { + $this->xml->InstrucaoUnica->addChild('URLRetorno', $url); + } + + return $this; + } + + /** + * Method setNotificationURL() + * + * Set the notification URL, which sends information about changes in payment status + * + * @param string $url Notification URL + * + * @return Moip + */ + public function setNotificationURL($url) + { + if (!isset($this->xml->InstrucaoUnica->URLNotificacao)) + { + $this->xml->InstrucaoUnica->addChild('URLNotificacao', $url); + } + + return $this; + } + + /** + * Method setError() + * + * Set Erroe alert + * + * @param String $error Error alert + * + * @return Moip + */ + public function setError($error) + { + $this->errors = $error; + + return $this; + } + + /** + * Method addComission() + * + * Allows to specify commissions on the payment, like fixed values or percent. + * + * @param string $reason reason for commissioning + * @param string $receiver login Moip the secondary receiver + * @param number $value value of the division of payment + * @param boolean $percentageValue percentage value should be + * @param boolean $ratePayer this secondary recipient will pay the fee Moip + * + * @return Moip + */ + public function addComission($reason, $receiver, $value, $percentageValue = false, $ratePayer = false) + { + + if (!isset($this->xml->InstrucaoUnica->Comissoes)) + { + $this->xml->InstrucaoUnica->addChild('Comissoes'); + } + + if (is_numeric($value)) + { + + $split = $this->xml->InstrucaoUnica->Comissoes->addChild('Comissionamento'); + $split->addChild('Comissionado')->addChild('LoginMoIP', $receiver); + $split->addChild('Razao', $reason); + + if ($percentageValue == false) + { + $split->addChild('ValorFixo', $value); + } + if ($percentageValue == true) + { + $split->addChild('ValorPercentual', $value); + } + if ($ratePayer == true) + { + $this->xml->InstrucaoUnica->Comissoes->addChild('PagadorTaxa')->addChild('LoginMoIP', $receiver); + } + } + else + { + $this->setError('Error: Value must be numeric.'); + } + + return $this; + } + + /** + * Method addParcel() + * + * Allows to add a order to parceling. + * + * @param int $min The minimum number of parcels. + * @param int $max The maximum number of parcels. + * @param float $rate The percentual value of rates + * @param boolean $transfer "true" defines the amount of interest charged by MoIP installment to be paid by the payer + * + * @return Moip + */ + public function addParcel($min, $max, $rate = null, $transfer = false) + { + if (!isset($this->xml->InstrucaoUnica->Parcelamentos)) + { + $this->xml->InstrucaoUnica->addChild('Parcelamentos'); + } + + $parcela = $this->xml->InstrucaoUnica->Parcelamentos->addChild('Parcelamento'); + if (is_numeric($min) && $min <= 12) + { + $parcela->addChild('MinimoParcelas', $min); + } + else + { + $this->setError('Error: Minimum parcel can not be greater than 12.'); + } + + if (is_numeric($max) && $max <= 12) + { + $parcela->addChild('MaximoParcelas', $max); + } + else + { + $this->setError('Error: Maximum amount can not be greater than 12.'); + } + + $parcela->addChild('Recebimento', 'AVista'); + + if ($transfer === false) + { + if (isset($rate)) + { + if (is_numeric($rate)) + { + $parcela->addChild('Juros', $rate); + } + else + { + $this->setError('Error: Rate must be numeric'); + } + } + } + else + { + if (is_bool($transfer)) + { + $parcela->addChild('Repassar', $transfer); + } + else + { + $this->setError('Error: Transfer must be boolean'); + } + } + + return $this; + } + + /** + * Method setReceiving() + * + * Allows to add a order to parceling. + * + * @param string $receiver login Moip the secondary receiver + * + * @return Moip + */ + public function setReceiver($receiver) + { + if (!isset($this->xml->InstrucaoUnica->Recebedor)) + { + $this->xml->InstrucaoUnica->addChild('Recebedor') + ->addChild('LoginMoIP', $receiver); + } + + return $this; + } + + public function removeInstruction($paymentToken) + { + $answer = $this->doRequest('RemoverInstrucaoPost', "{$paymentToken}", 'POST'); + + if ($answer->response !== false) + { + $xml_answer = simplexml_load_string($answer->xml); + + if ($xml_answer && !isset($xml_answer->Resposta->Erro)) + { + return new MoipResponse(self::xml2array($xml_answer)); + } + else + { + return new MoipResponse(self::xml2array($xml_answer->Resposta)); + } + } + + return new MoipResponse(array()); + } + + /** + * GET request for common instructions + * + * @param string $name Name of the instruction, like VisualizarInstrucaoUnica, RemoverInstrucaoPost, etc + * @param string $content Token + * @param string $method GET or POST + * + * @throws InvalidArgumentException + * @return MoipResponse + */ + public function doRequest($name, $content = null, $method = 'GET') + { + $client = new MoipClient(); + + $url = $this->environment->base_url . '/ws/alpha/' . $name; + $credentials = $this->credential['token'] . ':' . $this->credential['key']; + + switch (strtoupper($method)) + { + case 'GET': + $url .= '/' . ($content ? $content : $this->getAnswer()->token); + $answer = $client->curlGet($credentials, $url); + break; + case 'POST': + if (empty($content)) + { + throw new InvalidArgumentException('doRequest for POST needs content'); + } + $answer = $client->curlPost($credentials, $content, $url); + break; + default: + throw new InvalidArgumentException('$method must be GET or POST'); + } + + unset($client); + + return $answer; + } + + protected static function xml2array($xml) + { + return json_decode(json_encode((array)$xml), true); + } + + /** + * Method getUniqueInstruction() + * + * @param $paymentToken + * + * @return MoipResponse + */ + public function getUniqueInstruction($paymentToken = null) + { + $answer = $this->doRequest('VisualizarInstrucaoUnica', $paymentToken); + + if ($answer->response !== false) + { + $xml_answer = simplexml_load_string($answer->xml); + + if ($xml_answer && isset($xml_answer->RespostaVisualizarInstrucaoUnica)) + { + $out = self::xml2array($xml_answer->RespostaVisualizarInstrucaoUnica->InstrucaoUnica); + } + else + { + $out = self::xml2array($xml_answer); + } + + return new MoipResponse($out); + } + + return new MoipResponse(array()); + } + + /** + * Method getStatus() + * + * Get the status of the current token or the param token + * + * @param string $paymentToken + * + * @return MoipResponse + */ + public function getPaymentStatus($paymentToken = null) + { + $answer = $this->doRequest('ConsultarInstrucao', $paymentToken); + + if ($answer->response !== false) + { + $xml_answer = simplexml_load_string($answer->xml); + + if ($xml_answer && isset($xml_answer->RespostaConsultar->Autorizacao)) + { + unset($xml_answer->RespostaConsultar->Autorizacao->Recebedor); + + $out = self::xml2array($xml_answer->RespostaConsultar->Autorizacao); + $out['status_pagamento'] = (int)$xml_answer->RespostaConsultar->Autorizacao->Pagamento[0]->Status->attributes()->Tipo; + } + else + { + $out = self::xml2array($xml_answer); + } + return new MoipResponse($out); + } + + return new MoipResponse(array()); + } + + /** + * Method getXML() + * + * Returns the XML that is generated. Useful for debugging. + * + * @return string + */ + public function getXML() + { + + if ($this->payment_type == "Identification") + { + $this->xml->InstrucaoUnica->addAttribute('TipoValidacao', 'Transparente'); + } + + $this->xml->InstrucaoUnica->addChild('IdProprio', $this->uniqueID); + $this->xml->InstrucaoUnica->addChild('Razao', $this->reason); + + if (empty($this->value)) + { + $this->setError('Error: The transaction amount must be specified.'); + } + + $this->xml->InstrucaoUnica->addChild('Valores') + ->addChild('Valor', $this->value) + ->addAttribute('moeda', 'BRL'); + + if (isset($this->deduction)) + { + $this->xml->InstrucaoUnica->Valores->addChild('Deducao', $this->deduction) + ->addAttribute('moeda', 'BRL'); + } + + if (isset($this->adds)) + { + $this->xml->InstrucaoUnica->Valores->addChild('Acrescimo', $this->adds) + ->addAttribute('moeda', 'BRL'); + } + + if (!empty($this->payment_way)) + { + $instrucao = $this->xml->InstrucaoUnica; + $formas = $instrucao->addChild('FormasPagamento'); + + foreach ($this->payment_way as $way) + { + $formas->addChild('FormaPagamento', $this->payment_ways[$way]); + } + } + + if (!empty($this->payer)) + { + $p = $this->payer; + $this->xml->InstrucaoUnica->addChild('Pagador'); + (isset($p['name'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('Nome', $this->payer['name']) : null; + (isset($p['email'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('Email', $this->payer['email']) : null; + (isset($p['payerId'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('IdPagador', $this->payer['payerId']) : null; + (isset($p['identity'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('Identidade', $this->payer['identity']) : null; + (isset($p['phone'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('TelefoneCelular', $this->payer['phone']) : null; + + $p = $this->payer['billingAddress']; + $this->xml->InstrucaoUnica->Pagador->addChild('EnderecoCobranca'); + + (isset($p['address'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Logradouro', $this->payer['billingAddress']['address']) : null; + + (isset($p['number'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Numero', $this->payer['billingAddress']['number']) : null; + + (isset($p['complement'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Complemento', $this->payer['billingAddress']['complement']) : null; + + (isset($p['neighborhood'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Bairro', $this->payer['billingAddress']['neighborhood']) : null; + + (isset($p['city'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Cidade', $this->payer['billingAddress']['city']) : null; + + (isset($p['state'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Estado', $this->payer['billingAddress']['state']) : null; + + (isset($p['country'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Pais', $this->payer['billingAddress']['country']) : null; + + (isset($p['zipCode'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('CEP', $this->payer['billingAddress']['zipCode']) : null; + + (isset($p['phone'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('TelefoneFixo', $this->payer['billingAddress']['phone']) : null; + } + + $return = $this->convertEncoding($this->xml->asXML(), true); + $this->initXMLObject(); + + return str_replace("\n", "", $return); + } + + /** + * Method send() + * + * Send the request to the server + * + * @param object $client The server's connection + * + * @return MoipResponse + */ + public function send($client = null) + { + $this->validate(); + + if ($client == null) + { + $client = new MoipClient(); + } + + $url = $this->environment->base_url . '/ws/alpha/EnviarInstrucao/Unica'; + + return + $this->answer = + $client->curlPost($this->credential['token'] . ':' . $this->credential['key'], + $this->getXML(), + $url, + $this->errors + ); + } + + /** + * Get the Checkout Transparent javascript URL according to the environment + * + * @param bool $include_https In IE, including https:// inside an http:// site raises an error + * + * @return string + */ + public function getJavascript($include_https = true) + { + return ($include_https ? $this->environment->base_url : str_replace('https://', '//', $this->environment->base_url)) . '/transparente/MoipWidget-v2.js'; + } + + /** + * Return the HTML widget with the token and callbacks attached + * + * @param string $success Name of success function callback in Javascript + * @param string $error Name of error function callback in Javascript + * + * @return string + */ + public function getWidget($success, $error) + { + $token = $this->getAnswer()->token; + $html = <<<"HTML" +
+HTML; + + return $html; + } + + /** + * Method getAnswer() + * + * Gets the server's answer + * + * @param boolean $return_xml_as_string Return the answer XMl string + * + * @return MoipResponse|string String will be returned in case of an error + */ + public function getAnswer($return_xml_as_string = false) + { + if ($this->answer->response === true) + { + if ($return_xml_as_string) + { + return $this->answer->xml; + } + + $xml = new SimpleXmlElement($this->answer->xml); + + return new MoipResponse(array( + 'response' => $xml->Resposta->Status == 'Sucesso' ? true : false, + 'error' => $xml->Resposta->Status == 'Falha' ? $this->convertEncoding((string)$xml->Resposta->Erro) : false, + 'token' => (string)$xml->Resposta->Token, + 'payment_url' => $xml->Resposta->Status == 'Sucesso' ? (string)$this->environment->base_url . "/Instrucao.do?token=" . (string)$xml->Resposta->Token : false, + )); + } + else + { + return $this->answer->error; + } + } + + /** + * Method verifyParcelValues() + * + * Get all informations about the parcelling of user defined by $login_moip + * + * @param string $login The client's login for Moip services + * @param int $maxParcel The total parcels + * @param float $rate The rate's percents of the parcelling. + * @param float $simulatedValue The value for simulation + * + * @return array + */ + public function queryParcel($login, $maxParcel, $rate, $simulatedValue) + { + if (!isset($this->credential)) + { + $this->setError("You must specify the credentials (token / key) and enriroment"); + } + + $client = new MoipClient(); + + $url = $this->environment->base_url . "/ws/alpha/ChecarValoresParcelamento/$login/$maxParcel/$rate/$simulatedValue"; + $credential = $this->credential['token'] . ':' . $this->credential['key']; + $answer = $client->curlGet($credential, $url, $this->errors); + + if ($answer->response) + { + $xml = new SimpleXmlElement($answer->xml); + + if ($xml->Resposta->Status === "Sucesso") + { + $response = true; + } + else + { + $response = false; + } + + $return = array( + 'response' => $response, + 'installment' => array() + ); + + $i = 1; + foreach ($xml->Resposta->ValorDaParcela as $parcela) + { + $attrib = $parcela->attributes(); + $return['installment']["$i"] = array('total' => (string)$attrib['Total'], 'rate' => (string)$attrib['Juros'], 'value' => (string)$attrib['Valor']); + $i++; + } + + return $return; + } + + return $answer; + } +} diff --git a/lib/MoipClient.php b/lib/MoipClient.php index d49f4dd..e9f12f6 100644 --- a/lib/MoipClient.php +++ b/lib/MoipClient.php @@ -3,155 +3,162 @@ /** * MoIP's API connection class * - * @author Herberth Amaral - * @author Paulo Cesar - * @version 0.0.2 + * @author Herberth Amaral + * @author Paulo Cesar + * @version 0.0.3 * @license BSD License + * @package Moip + * @subpackage MoipClient */ -class MoIPClient { - - /** - * Method send() - * - * Send the request to API's server - * - * @param string $credentials Token and key to the authentication - * @param string $xml The XML request - * @param string $url The server's URL - * @param string $method Method used to send the request +class MoipClient { + + /** + * Method send() + * + * Send the request to API's server + * + * @param string $credentials Token and key to the authentication + * @param string $xml The XML request + * @param string $url The server's URL + * @param string $method Method used to send the request + * * @throws Exception * @return MoipResponse - */ - public function send($credentials, $xml, $url='https://desenvolvedor.moip.com.br/sandbox/ws/alpha/EnviarInstrucao/Unica', $method='POST') { - $header[] = "Authorization: Basic " . base64_encode($credentials); - if (!function_exists('curl_init')){ - throw new Exception('This library needs cURL extension'); + */ + public function send($credentials, $xml, $url = 'https://desenvolvedor.moip.com.br/sandbox/ws/alpha/EnviarInstrucao/Unica', $method = 'POST') + { + $header[] = "Authorization: Basic " . base64_encode($credentials); + if (!function_exists('curl_init')) + { + throw new Exception('This library needs cURL extension'); + } + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_HTTPHEADER, $header); + curl_setopt($curl, CURLOPT_USERPWD, $credentials); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0"); + + if ($method == 'POST') + { + curl_setopt($curl, CURLOPT_POST, true); } - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, $url); - curl_setopt($curl, CURLOPT_HTTPHEADER, $header); - curl_setopt($curl, CURLOPT_USERPWD, $credentials); - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0"); - - if ($method == 'POST') curl_setopt($curl, CURLOPT_POST, true); - if ($xml != '') curl_setopt($curl, CURLOPT_POSTFIELDS, $xml); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - $ret = curl_exec($curl); - $err = curl_error($curl); - curl_close($curl); + if ($xml != '') + { + curl_setopt($curl, CURLOPT_POSTFIELDS, $xml); + } + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + $ret = curl_exec($curl); + $err = curl_error($curl); + curl_close($curl); - return new MoipResponse(array('resposta' => $ret, 'erro' => $err)); - } + return new MoipResponse(array('resposta' => $ret, 'erro' => $err)); + } - /** + /** * @param string $credentials token / key authentication Moip - * @param string $xml url request - * @param string $url url request - * @param string $error errors + * @param string $xml url request + * @param string $url url request + * @param string $error errors + * * @return MoipResponse - */ - function curlPost($credentials, $xml, $url, $error=null) { - - if (!$error) { - $header[] = "Expect:"; - $header[] = "Authorization: Basic " . base64_encode($credentials); - - $ch = curl_init(); - $options = array(CURLOPT_URL => $url, - CURLOPT_HTTPHEADER => $header, - CURLOPT_SSL_VERIFYPEER => false, - CURLOPT_POST => true, - CURLOPT_POSTFIELDS => $xml, - CURLOPT_RETURNTRANSFER => true, - CURLINFO_HEADER_OUT => true - ); - - curl_setopt_array($ch, $options); - $ret = curl_exec($ch); - $err = curl_error($ch); - $info = curl_getinfo($ch); - curl_close($ch); - - - if ($info['http_code'] == "200") - return new MoipResponse(array('response' => true, 'error' => null, 'xml' => $ret)); - else if ($info['http_code'] == "500") - return new MoipResponse(array('response' => false, 'error' => 'Error processing XML', 'xml' => null)); - else if ($info['http_code'] == "401") - return new MoipResponse(array('response' => false, 'error' => 'Authentication failed', 'xml' => null)); - else - return new MoipResponse(array('response' => false, 'error' => $err, 'xml' => null)); - } else { - return new MoipResponse(array('response' => false, 'error' => $error, 'xml' => null)); - } - } - - - /** - * @param string $credentials token / key authentication Moip - * @param string $url url request - * @param string $error errors - * @return MoipResponse - */ - function curlGet($credentials, $url, $error=null) { - - if (!$error) { - $header[] = "Expect:"; - $header[] = "Authorization: Basic " . base64_encode($credentials); - - $ch = curl_init(); - $options = array(CURLOPT_URL => $url, - CURLOPT_HTTPHEADER => $header, - CURLOPT_SSL_VERIFYPEER => false, - CURLOPT_RETURNTRANSFER => true - ); - - curl_setopt_array($ch, $options); - $ret = curl_exec($ch); - $err = curl_error($ch); - $info = curl_getinfo($ch); - curl_close($ch); - - - if ($info['http_code'] == "200") - return new MoipResponse(array('response' => true, 'error' => null, 'xml' => $ret)); - else if ($info['http_code'] == "500") - return new MoipResponse(array('response' => false, 'error' => 'Error processing XML', 'xml' => null)); - else if ($info['http_code'] == "401") - return new MoipResponse(array('response' => false, 'error' => 'Authentication failed', 'xml' => null)); - else - return new MoipResponse(array('response' => false, 'error' => $err, 'xml' => null)); - } else { - return new MoipResponse(array('response' => false, 'error' => $error, 'xml' => null)); - } - } - -} - -/** - * Read-only response - * @property boolean|string $response - * @property string $error - * @property string $xml - * @property string $payment_url - * @property string $token - */ -class MoipResponse { - private $response; - - function __construct(array $response) + */ + function curlPost($credentials, $xml, $url, $error = null) { - $this->response = $response; + if (!$error) + { + $header[] = "Expect:"; + $header[] = "Authorization: Basic " . base64_encode($credentials); + + $ch = curl_init(); + $options = array( + CURLOPT_URL => $url, + CURLOPT_HTTPHEADER => $header, + CURLOPT_SSL_VERIFYPEER => false, + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => $xml, + CURLOPT_RETURNTRANSFER => true, + CURLINFO_HEADER_OUT => true + ); + + curl_setopt_array($ch, $options); + $ret = curl_exec($ch); + $err = curl_error($ch); + $info = curl_getinfo($ch); + curl_close($ch); + + if ($info['http_code'] === 200) + { + return new MoipResponse(array('response' => true, 'error' => null, 'xml' => $ret)); + } + else if ($info['http_code'] === 500) + { + return new MoipResponse(array('response' => false, 'error' => 'Error processing XML', 'xml' => null)); + } + else if ($info['http_code'] === 401) + { + return new MoipResponse(array('response' => false, 'error' => 'Authentication failed', 'xml' => null)); + } + else + { + return new MoipResponse(array('response' => false, 'error' => $err, 'xml' => null)); + } + } + else + { + return new MoipResponse(array('response' => false, 'error' => $error, 'xml' => null)); + } } - function __get($name) + /** + * @param string $credentials token / key authentication Moip + * @param string $url url request + * @param string $error errors + * + * @return MoipResponse + */ + function curlGet($credentials, $url, $error = null) { - if (isset($this->response[$name])) + if (!$error) + { + $header[] = "Expect:"; + $header[] = "Authorization: Basic " . base64_encode($credentials); + + $ch = curl_init(); + $options = array( + CURLOPT_URL => $url, + CURLOPT_HTTPHEADER => $header, + CURLOPT_SSL_VERIFYPEER => false, + CURLOPT_RETURNTRANSFER => true + ); + + curl_setopt_array($ch, $options); + $ret = curl_exec($ch); + $err = curl_error($ch); + $info = curl_getinfo($ch); + curl_close($ch); + + if ($info['http_code'] === 200) + { + return new MoipResponse(array('response' => true, 'error' => null, 'xml' => $ret)); + } + else if ($info['http_code'] === 500) + { + return new MoipResponse(array('response' => false, 'error' => 'Error processing XML', 'xml' => null)); + } + else if ($info['http_code'] === 401) + { + return new MoipResponse(array('response' => false, 'error' => 'Authentication failed', 'xml' => null)); + } + else + { + return new MoipResponse(array('response' => false, 'error' => $err, 'xml' => null)); + } + } + else { - return $this->response[$name]; + return new MoipResponse(array('response' => false, 'error' => $error, 'xml' => null)); } - return null; } } \ No newline at end of file diff --git a/lib/MoipEnvironment.php b/lib/MoipEnvironment.php new file mode 100644 index 0000000..09f7e57 --- /dev/null +++ b/lib/MoipEnvironment.php @@ -0,0 +1,40 @@ +BSD License + */ +/** + * @property string $base_url Complete URI of the environment without trailing slash + * @property string $name Name of the environment + */ +class MoipEnvironment { + + private $_base_url; + private $_name; + + function __construct($base_url, $name) + { + $this->_base_url = $base_url; + $this->_name = $name; + } + + function __get($name) + { + if ($name === 'base_url') + { + return $this->_base_url; + } + elseif ($name === 'name') + { + return $this->_name; + } + + return null; + } +} \ No newline at end of file diff --git a/lib/MoipResponse.php b/lib/MoipResponse.php new file mode 100644 index 0000000..3d17e3e --- /dev/null +++ b/lib/MoipResponse.php @@ -0,0 +1,134 @@ +BSD License + * @package Moip + * @subpackage MoipResponse + */ + +/** + * Read-only response + * @property boolean|string $response + * @property string $error + * @property string $xml + * @property string $payment_url + * @property string $token + */ +class MoipResponse implements Serializable, Countable { + + private $response = array(); + private $strtolower_keys = array(); + + function flatten() + { + $flat = array(); + $collector = function ($v, $k) use (&$flat) + { + $flat[$k] = $v; + }; + + array_walk_recursive($this->response, $collector); + + $this->response = $flat; + } + + private function set_keys() + { + if ($this->response) + { + $this->strtolower_keys = array_change_key_case( + array_combine( + array_keys($this->response), + array_keys($this->response) + ) + ); + } + else + { + $this->strtolower_keys = array(); + } + } + + function __construct(array $response, $flatten = true) + { + $this->response = $response; + + if ($flatten) + { + $this->flatten(); + } + + $this->set_keys(); + } + + private function to_key($name) + { + $name = strtolower($name); + if (isset($this->strtolower_keys[$name])) + { + return $this->strtolower_keys[$name]; + } + return false; + } + + function __get($name) + { + if ($name = $this->to_key($name)) + { + return $this->response[$name]; + } + + return null; + } + + function __isset($name) + { + return $this->to_key($name) !== false; + } + + public function serialize($json = false, $lowercase = false) + { + if ($json) + { + return json_encode($this->response, true); + } + else + { + return serialize($this->response); + } + } + + public function unserialize($serialized) + { + if ($response = json_decode($serialized)) + { + if (function_exists('json_last_error') && json_last_error() === JSON_ERROR_NONE) + { + $this->response = $response; + } + } + else + { + $this->response = unserialize($serialized); + } + + $this->set_keys(); + } + + public function count() + { + return count($this->response); + } + + public function as_array($lowercase = false) + { + return !is_null($this->strtolower_keys) ? + ($lowercase ? array_combine(array_keys($this->strtolower_keys), $this->response) : $this->response) + : + (array()); + } +} diff --git a/lib/MoipStatus.php b/lib/MoipStatus.php index fa31ab8..ff04f73 100644 --- a/lib/MoipStatus.php +++ b/lib/MoipStatus.php @@ -5,6 +5,7 @@ * Verificação de status da conta do MoIP. Atualmente somente com suporte à verificação de saldo e ultimas transações. * @author Herberth Amaral * @version 0.0.2 + * @deprecated * @package MoIP */