Skip to content

Commit

Permalink
Adiciona header User-Agent aos requests feitos pelo SDK (#309)
Browse files Browse the repository at this point in the history
* client: build user-agent string

Implement an user-agent string builder to be user during requests to
Pagar.me's API. It'll be usefull to indentify applications requests.

Co-authored-by: Murilo Souza <[email protected]>

* client: inform user-agent on requests

Since a user-agent string is builded, it should be present on every
request. It add the builded string to the client.

Co-authored-by: Murilo Souza <[email protected]>

* client: refactor the code

Create a constant for custom user-agent header. Also, refactor the test
to work well in different php versions.

Co-authored-by: Murilo Souza <[email protected]>

* client: avoid php send an undefined index notice

Inform a blank user-agent if it's not informed from the client during
instantiation

* doc: add how to inform custom headers

Add how developers could inform custom headers on every request

* travis-ci: remove travis-ci config file

Remove travis since the project is using circle-ci

* refactor: remove irrelevant user_agent property

Since the user-agent info won't be used by developers after it sent to
sdk, there's no reason to maintain a property on Client class. It
removes the property and its getter method and remove tests that was
used to validate that.
  • Loading branch information
leonampd committed Sep 20, 2018
1 parent 597c54d commit 782fb99
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 29 deletions.
29 changes: 0 additions & 29 deletions .travis.yml

This file was deleted.

14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,20 @@ require('vendor/autoload.php');
$pagarme = new PagarMe\Client('SUA_CHAVE_DE_API');
```

### Definindo headers customizados

1. Se necessário for é possível definir headers http customizados para os requests. Para isso basta informá-los durante a instanciação do objeto `Client`:

```php
<?php
require('vendor/autoload.php');

$pagarme = new PagarMe\Client(
'SUA_CHAVE_DE_API',
['headers' => ['MEU_HEADER_CUSTOMIZADO' => 'VALOR HEADER CUSTOMIZADO']]
);
```

E então, você pode poderá utilizar o cliente para fazer requisições ao Pagar.me, como nos exemplos abaixo.

## Transações
Expand Down
43 changes: 43 additions & 0 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ class Client
*/
const BASE_URI = 'https://api.pagar.me:443/1/';

/**
* @var string header used to identify application's requests
*/
const PAGARME_USER_AGENT_HEADER = 'X-PagarMe-User-Agent';

/**
* @var \GuzzleHttp\Client
*/
Expand Down Expand Up @@ -134,6 +139,12 @@ public function __construct($apiKey, array $extras = null)
$options = array_merge($options, $extras);
}

$userAgent = isset($options['headers']['User-Agent']) ?
$options['headers']['User-Agent'] :
'';

$options['headers'] = $this->addUserAgentHeaders($userAgent);

$this->http = new HttpClient($options);

$this->transactions = new Transactions($this);
Expand Down Expand Up @@ -190,6 +201,38 @@ public function getApiKey()
return $this->apiKey;
}

/**
* Build an user-agent string to be informed on requests
*
* @param string $customUserAgent
*
* @return string
*/
private function buildUserAgent($customUserAgent = '')
{
return trim(sprintf(
'%s PHP/%s',
$customUserAgent,
phpversion()
));
}

/**
* Append new keys (the default and pagarme) related to user-agent
*
* @param string $customUserAgent
* @return array
*/
private function addUserAgentHeaders($customUserAgent = '')
{
return [
'User-Agent' => $this->buildUserAgent($customUserAgent),
self::PAGARME_USER_AGENT_HEADER => $this->buildUserAgent(
$customUserAgent
)
];
}

/**
* @return \PagarMe\Endpoints\Transactions
*/
Expand Down
42 changes: 42 additions & 0 deletions tests/unit/ClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,48 @@ public function testRequestFailedResponse()
$response = $client->request(Endpoint::POST, 'transactions');
}

public function testSuccessfulResponseWithCustomUserAgentHeader()
{
$container = [];
$history = Middleware::history($container);
$mock = new MockHandler([
new Response(200, [], '{"status":"Ok!"}'),
]);
$handler = HandlerStack::create($mock);
$handler->push($history);

$client = new Client(
'apiKey',
[
'handler' => $handler,
'headers' => ['User-Agent' => 'MyCustomApplication/10.2.2']
]
);

$response = $client->request(Endpoint::POST, 'transactions');

$this->assertEquals($response->status, "Ok!");
$this->assertEquals(
'api_key=apiKey',
$container[0]['request']->getUri()->getQuery()
);

$expectedUserAgent = sprintf(
'MyCustomApplication/10.2.2 PHP/%s',
phpversion()
);
$this->assertEquals(
$expectedUserAgent,
$container[0]['request']->getHeaderLine('User-Agent')
);
$this->assertEquals(
$expectedUserAgent,
$container[0]['request']->getHeaderLine(
Client::PAGARME_USER_AGENT_HEADER
)
);
}

public function testTransactions()
{
$client = new Client('apiKey');
Expand Down

0 comments on commit 782fb99

Please sign in to comment.