Skip to content

Commit

Permalink
Separação entre ambiente de testes e de produção
Browse files Browse the repository at this point in the history
  • Loading branch information
recovieira committed Jul 24, 2018
1 parent e206922 commit b8c4172
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 12 deletions.
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ $ php index.php
Estrutura breve do conteúdo:

```
├── index.php # contém um exemplo simples de uso
├── Nova Cobrança - Manual de Integração v1.4.pdf # especificação do Banco do Brasil
└── lib # pasta contendo a classe
└── bb.php # arquivo contendo a implementação da requisição do serviço
├── index.php # contém um exemplo simples de uso
├── Nova Cobrança - Manual de Integração v1.4.pdf # especificação do Banco do Brasil
└── lib # pasta contendo a classe
└── bb.php # arquivo contendo a implementação da requisição do serviço
```

### Changelog
Expand All @@ -58,6 +58,9 @@ Lançamento inicial.
#### V 1.1
Evita requisitar uma token toda vez que for registrar um boleto. Armazena a token em cache e requisita uma nova automaticamente quando ela estiver preste a expirar ou já tiver expirado.

#### V 1.2
Permite separar entre o ambiente de teste (pelo método "alterarParaAmbienteDeTestes()") ou de produção (pelo "alterarParaAmbienteDeProducao()"). O exemplo no arquivo "index.php" usa o ambiente de testes.

### Autor
Reginaldo Coimbra Vieira (recovieira@gmail.com)

Expand Down
6 changes: 6 additions & 0 deletions index.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@
'codigoTipoCanalSolicitacao' => 5
);

// Passa para o ambiente de testes. Por padrão, o construtor usa o ambiente de produção.
// Para retornar para o ambiente de produção a qualquer momento, basta chamar o método
// alterarParaAmbienteDeProducao() (ex.: $bb->alterarParaAmbienteDeProducao();)
$bb->alterarParaAmbienteDeTestes();
// $bb->alterarParaAmbienteDeProducao();

// Exemplo de chamada passando os parâmetros com a token.
// Retorna um array com a resposta do Banco do Brasil, se ocorreu tudo bem. Caso contrário, retorna "false".
// A descrição do erro pode ser obtida pelo método "obterErro()".
Expand Down
47 changes: 39 additions & 8 deletions lib/bb.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
<?php
class BBBoletoWebService {
// URL para obtenção do token para registro de boleto
static private $_tokenURL = 'https://oauth.hm.bb.com.br/oauth/token';

// URL para registro de boleto
static private $_url = 'https://cobranca.homologa.bb.com.br:7101/registrarBoleto';
const AMBIENTE_PRODUCAO = 1;
const AMBIENTE_TESTE = 2;

static private $_urls = array(
self::AMBIENTE_PRODUCAO => array(
// URL para obtenção da token para registro de boletos (produção)
'token' => 'https://oauth.bb.com.br/oauth/token',
// URL para registro de boleto (produção)
'registro' => 'https://cobranca.bb.com.br:7101/registrarBoleto'
),
self::AMBIENTE_TESTE => array(
// URL para obtenção da token para testes
'token' => 'https://oauth.hm.bb.com.br/oauth/token',
// URL para registro de boleto para teste
'registro' => 'https://cobranca.homologa.bb.com.br:7101/registrarBoleto'
)
);

private $_clientID;
private $_secret;

// Ambiente do sistema: teste ou produção?
private $_ambiente;

// Tempo limite para obter resposta de 20 segundos
private $_timeout = 20;

Expand All @@ -33,12 +48,28 @@ class BBBoletoWebService {
* @param string $clientid Identificação do requisitante
* @param string $secret Segredo ("Senha") do requisitante
*/
function __construct($clientid, $secret) {
function __construct($clientid, $secret, $ambientedeproducao = true) {
// Usar, por padrão, o caminho definido no atributo estático "_caminhoPastaCache_estatico"
$this->_caminhoPastaCache = self::$_caminhoPastaCache_estatico;

$this->_clientID =& $clientid;
$this->_secret =& $secret;

call_user_func(array($this, 'alterarParaAmbienteDe' . ($ambientedeproducao === true ? 'Producao' : 'Testes')));
}

/**
* Alterar para o ambiente de produção
*/
function alterarParaAmbienteDeProducao() {
$this->_ambiente = self::AMBIENTE_PRODUCAO;
}

/**
* Alterar para o ambiente de testes
*/
function alterarParaAmbienteDeTestes() {
$this->_ambiente = self::AMBIENTE_TESTE;
}

/**
Expand Down Expand Up @@ -132,7 +163,7 @@ function obterToken($naousarcache = true) {

$curl = self::_prepararCurl();
curl_setopt_array($curl, array(
CURLOPT_URL => self::$_tokenURL,
CURLOPT_URL => self::$_urls[$this->_ambiente]['token'],
CURLOPT_POSTFIELDS => 'grant_type=client_credentials&scope=cobranca.registro-boletos',
CURLOPT_HTTPHEADER => array(
'Authorization: Basic ' . base64_encode($this->_clientID . ':' . $this->_secret),
Expand Down Expand Up @@ -244,7 +275,7 @@ function registrarBoleto($parametros, $token = false) {
// Preparar requisição
$curl = self::_prepararCurl();
curl_setopt_array($curl, array(
CURLOPT_URL => self::$_url,
CURLOPT_URL => self::$_urls[$this->_ambiente]['registro'],
CURLOPT_POSTFIELDS => &$requisicao,
CURLOPT_HTTPHEADER => array(
'Content-Type: text/xml;charset=UTF-8',
Expand Down

0 comments on commit b8c4172

Please sign in to comment.