Skip to content

Commit

Permalink
Refatoração de todo o suporte a API de Notificação
Browse files Browse the repository at this point in the history
  • Loading branch information
CauanCabral committed May 18, 2012
1 parent 738b2b0 commit 21c8daf
Show file tree
Hide file tree
Showing 6 changed files with 278 additions and 111 deletions.
12 changes: 12 additions & 0 deletions Controller/Component/CheckoutComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
App::uses('PagSeguroCheckout', 'PagSeguro.Lib');

/**
* Wrapper para a lib PagSeguroCheckout ser usada
* junto à controllers.
*
* Extende um pouco as funcionalidades da lib adicionando
* capacidade para auto-redirecionar o usuário para a página
* de pagamentos do PagSeguro
*
* PHP versions 5+
* Copyright 2010-2012, Felipe Theodoro Gonçalves, (http://ftgoncalves.com.br)
Expand All @@ -26,6 +31,13 @@ class CheckoutComponent extends Component {
*/
protected $Controller = null;

/**
* Instância da Lib PagSeguroCheckout
* que é responsável por toda a iteração
* com a API do PagSeguro.
*
* @var PagSeguroCheckout
*/
protected $_PagSeguroCheckout = null;

/**
Expand Down
133 changes: 43 additions & 90 deletions Controller/Component/NotificationsComponent.php
Original file line number Diff line number Diff line change
@@ -1,50 +1,40 @@
<?php
App::uses('Component', 'Controller');
App::uses('PagSeguroNotification', 'PagSeguro.Lib');

/**
* Plugin de integração com a API do PagSeguro e CakePHP.
* Wrapper para a lib PagSeguroNotification ser usada
* junto à controllers.
*
* PHP versions 5+
* Copyright 2010-2011, Felipe Theodoro Gonçalves, (http://ftgoncalves.com.br)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @author Felipe Theodoro Gonçalves
* @author Felipe Theodoro Gonçalves
* @author Cauan Cabral
* @link https://github.com/ftgoncalves/pagseguro/
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @version 2.0
* @version 2.1
*/

App::uses('HttpSocket', 'Network/Http');
App::uses('Xml', 'Utility');

class NotificationsComponent extends Component {

public $timeout = 20;

public $pgURI = array(
'host' => 'ws.pagseguro.uol.com.br',
'path' => '/v2/transactions/notifications/',
'scheme' => 'https',
'port' => '443'
);

/**
*
*
* @var Controller
*/
protected $Controller = null;

public $__config = array();

/**
* Código de 39 caracteres que identifica a notificação
* recebida
*
* @var string
* Instância da Lib PagSeguroNotification
* que é responsável por toda a iteração
* com a API do PagSeguro.
*
* @var PagSeguroNotification
*/
public $notificationCode = null;
protected $_PagSeguroNotification = null;

/**
* Construtor padrão
*
Expand All @@ -53,90 +43,53 @@ class NotificationsComponent extends Component {
*/
public function __construct(ComponentCollection $collection, $settings = array()) {
parent::__construct($collection, $settings);

$this->_PagSeguroNotification = new PagSeguroNotification($settings);
}

/**
*
* @param Controller &$controller
* @return void
*/
public function initialize(&$controller) {
$this->Controller =& $controller;

if (Configure::read('PagSeguro') != false && is_array(Configure::read('PagSeguro'))) {
$this->__config = array_merge($this->__config, Configure::read('PagSeguro'));
$this->__configValidates();
}
}

/**
* Sobrescreve as configurações em tempo de execução.
* Caso nenhum parâmetro seja passado, retorna as configurações
* atuais.
*
* Força configurações em tempo de execução
* @param array $config
* @return mixed Array com as configurações caso não seja
* passado parâmetro, nada caso contrário.
*/
public function config($config) {
$this->__config = array_merge($this->__config, $config);
$this->__configValidates();
public function config($config = null) {
return $this->_PagSeguroNotification->config($config);
}

/**
* Validação de uma notificação recebida
*
* @param CakeRequest $request Dados da requisição a ser testada
* @return bool Válido ou não
*/
public function isNotification($request) {
if(
$request->is('post') &&
isset($request->data['notificationCode']) &&
isset($request->data['notificationType']) &&
strlen($request->data['notificationCode']) == 39 &&
$request->data['notificationType'] == 'transaction'
) {
$this->notificationCode = $request->data['notificationCode'];

return true;
}

return false;
* Retorna o último erro na lib
*
* @return string
*/
public function getErrors() {
return $this->_PagSeguroNotification->lastError;
}

/**
* Valida a notificação recebida e requisita da API do PagSeguro a situação de um pagamento,
* converte o retorno de XML para Array e então o retorna.
*
* @param string $code Código da notificação
* @return mixed array com dos dados da notificação em caso de sucesso, null em caso de falha
* Requisita e retorna a notificação enviada pelo PagSeguro
*
* @param CakeRequest $request Objeto da requisição enviada pelo PagSeguro
* @return mixed array com dos dados da notificação em caso de sucesso, false em caso de falha
*/
public function getNotification($code = null) {
if(!empty($code) && is_string($code)) {
$this->notificationCode = $code;
public function read(CakeRequest $request) {
try{
return $this->_PagSeguroNotification->read($request);
}

$HttpSocket = new HttpSocket(array('timeout' => $this->timeout));

$this->pgURI['path'] .= '/' . $this->notificationCode;

$response = $HttpSocket->get($this->pgURI, array('email' => $this->__config['email'], 'token' => $this->__config['token']));

if(empty($response['body']) || $response->body == 'Not Found') {
catch(PagSeguroException $e) {
return false;
}

return Xml::toArray(Xml::build($response['body']));
}

/**
* Valida as configurações, disparando uma exceção quando
* forem inválidas.
*
* @return void
*/
private function __configValidates() {
if (!isset($this->__config['email']))
throw new CakeException ('Não foi informado o email do vendedor.');
if (!isset($this->__config['token']))
throw new CakeException ('Não foi informado o token.');

// Validação de acordo com API 2.0 do PagSeguro
if(strlen($this->__config['email']) > 60)
throw new CakeException ('Email do vendedor extrapola limite de 60 caracteres da API.');
if(strlen($this->__config['token']) > 32)
throw new CakeException ('Token extrapola limite de 32 caracteres da API.');
}
}
39 changes: 29 additions & 10 deletions Lib/PagSeguro.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,32 +62,48 @@ public function config($config = null) {
}

/**
* Envia os dados para API do PagSeguro usando método POST.
* Envia os dados para API do PagSeguro usando método especificado.
*
* @throws PagSeguroException
* @param array $data
* @param string $method
* @return array
*/
protected function _sendData($data) {
protected function _sendData($data, $method = 'POST') {
$this->_settingsValidates();

$HttpSocket = new HttpSocket(array(
'timeout' => $this->timeout
));

$return = $HttpSocket->request(array(
'method' => 'POST',
'method' => $method,
'uri' => $this->URI,
'header' => array(
'Content-Type' => "application/x-www-form-urlencoded; charset={$this->charset}"
),
'body' => $data
));

if($return->body == 'Unauthorized')
throw PagSeguro('O Token ou E-mail foi rejeitado pelo PagSeguro. Verifique as configurações.');
switch ($return->code) {
case 200:
break;
case 400:
throw new PagSeguroException('A requisição foi rejeitada pela API do PagSeguro. Verifique as configurações.');
case 401:
throw new PagSeguroException('O Token ou E-mail foi rejeitado pelo PagSeguro. Verifique as configurações.');
case 404:
throw new PagSeguroException('Recurso não encontrado. Verifique os dados enviados.');
default:
throw new PagSeguroException('Erro desconhecido com a API do PagSeguro. Verifique suas configurações.');
}

$response = Xml::toArray(Xml::build($return->body));
try {
$response = Xml::toArray(Xml::build($return->body));
}
catch(XmlException $e) {
throw new PagSeguroException('A resposta do PagSeguro não é um XML válido.');
}

if($this->_parseResponseErrors($response))
throw new PagSeguroException("Erro com os dados enviados no PagSeguro.");
Expand Down Expand Up @@ -132,11 +148,14 @@ protected function _parseResponseErrors($data) {
* @return void
*/
protected function _settingsValidates() {
$fields = array('email', 'token');
$fields = array('email' => 60, 'token' => 32);

foreach($fields as $fieldName => $length) {
if (!isset($this->settings[$fieldName]) || empty($this->settings[$fieldName]))
throw new PagSeguroException("Erro de configuração - Atributo '{$fieldName}' não definido.");

foreach($fields as $field) {
if (!isset($this->settings[$field]) || empty($this->settings[$field]))
throw new PagSeguroException("Erro de configuração - Atributo '{$field}' não definido.");
if(strlen($this->settings[$fieldName]) > $length)
throw new PagSeguroException("Erro de configuração - Atributo '{$fieldName}' excede limite de {$length} caracteres da API.");
}
}
}
18 changes: 7 additions & 11 deletions Lib/PagSeguroCheckout.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public function __construct($settings = array()) {

parent::__construct($settings);

$this->URI['resource'] = '/v2/checkout/';
$this->URI['path'] = '/v2/checkout/';
}

/**
Expand Down Expand Up @@ -204,7 +204,6 @@ public function finalize() {
}
catch(PagSeguroException $e) {
$this->lastError = $e->getMessage();

return false;
}
}
Expand All @@ -218,19 +217,16 @@ public function finalize() {
protected function _settingsValidates() {
parent::_settingsValidates();

$fields = array('currency');

foreach($fields as $field) {
if (!isset($this->settings[$field]) || empty($this->settings[$field]))
throw new PagSeguroException("Erro de configuração - Atributo '{$field}' não definido.");
}
if(!isset($this->settings['currency']) || empty($this->settings['currency']))
throw new PagSeguroException("Erro de configuração - Atributo 'currency' não definido.");
if($this->settings['currency'] !== 'BRL')
throw new PagSeguroException("Erro de configuração - Atributo 'currency' só aceita o valor 'BRL'.");
}

/**
* Recebe o Xml com os dados redirecionamento ou erros.
* Iniciando o redirecionamento
* Recebe o XML convertido para Array com os dados de redirecionamento ou erros.
*
* @param String $res
* @param array $data
* @return array
*/
protected function _parseResponse($data) {
Expand Down
Loading

0 comments on commit 21c8daf

Please sign in to comment.