Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .cursorignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/dist/
build/
/logs/
/log/
/cache/
/.git/
/vendor/
/node_modules/
tests/config/env.test.php
tmp/
error_log
8 changes: 4 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
"psr/log": "*"
},
"require-dev": {
"phpunit/phpunit": "^12.1.6",
"phpstan/phpstan": "^1.12.27",
"kint-php/kint": "^6.0.1",
"phpunit/phpunit": "^12.4.5",
"phpstan/phpstan": "^1.12.32",
"kint-php/kint": "^6.1.0",
"monolog/monolog": "^3.9.0",
"friendsofphp/php-cs-fixer": "^3.75.0",
"friendsofphp/php-cs-fixer": "^3.91.2",
"brainmaestro/composer-git-hooks": "^3.0.0"
},
"autoload": {
Expand Down
27 changes: 21 additions & 6 deletions src/Rede/Environment.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,22 @@ class Environment implements RedeSerializable
{
public const PRODUCTION = 'https://api.userede.com.br/erede';

public const SANDBOX = 'https://api.userede.com.br/desenvolvedores';
public const SANDBOX = 'https://sandbox-erede.useredecloud.com.br';

public const VERSION = 'v1';
public const VERSION = 'v2';

private ?string $ip = null;

private ?string $sessionId = null;

private string $endpoint;
private string $baseUrl;

/**
* Creates an environment with its base url and version.
*/
private function __construct(string $baseUrl)
private function __construct(string $baseUrl = self::PRODUCTION)
{
$this->endpoint = sprintf('%s/%s/', $baseUrl, Environment::VERSION);
$this->baseUrl = sprintf('%s/%s/', $baseUrl, Environment::VERSION);
}

/**
Expand All @@ -40,12 +40,27 @@ public static function sandbox(): Environment
return new Environment(Environment::SANDBOX);
}

public function isProduction(): bool
{
return str_starts_with($this->baseUrl, self::PRODUCTION);
}

public function getBaseUrl(): string
{
return $this->baseUrl;
}

public function getBaseUrlOAuth(): string
{
return $this->isProduction() ? 'https://api.userede.com.br' : 'https://rl7-sandbox-api.useredecloud.com.br';
}

/**
* @return string Gets the environment endpoint
*/
public function getEndpoint(string $service): string
{
return $this->endpoint . $service;
return $this->baseUrl . $service;
}

public function getIp(): ?string
Expand Down
204 changes: 204 additions & 0 deletions src/Rede/Http/RedeHttpClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
<?php

namespace Rede\Http;

use Psr\Log\LoggerInterface;
use Rede\eRede;
use Rede\Store;

abstract class RedeHttpClient
{
public const string GET = 'GET';

public const string POST = 'POST';

public const string PUT = 'PUT';

public const string CONTENT_TYPE_JSON = 'application/json; charset=utf8';

public const string CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded';

private ?string $platform = null;

private ?string $platformVersion = null;

public function __construct(protected Store $store, protected ?LoggerInterface $logger = null)
{
}

public function platform(?string $platform, ?string $platformVersion): static
{
$this->platform = $platform;
$this->platformVersion = $platformVersion;

return $this;
}

/**
* @param string|array<string|int,mixed>|object $body
* @param array<string|int, string> $headers
*
* @throws \RuntimeException
*/
protected function request(
string $method,
string $url,
string|array|object $body = '',
array $headers = [],
string $contentType = self::CONTENT_TYPE_JSON,
): RedeResponse {
$curl = curl_init($url);

if (!$curl instanceof \CurlHandle) {
throw new \RuntimeException('Was not possible to create a curl instance.');
}

curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);

switch ($method) {
case self::GET:
break;
case self::POST:
curl_setopt($curl, CURLOPT_POST, true);
break;
default:
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
}

$requestHeaders = [
str_replace(' ', ' ', $this->getUserAgent()),
'Accept: application/json',
'Transaction-Response: brand-return-opened',
];

if ($this->store->getOAuthToken()) {
$requestHeaders[] = 'Authorization: Bearer ' . $this->store->getOAuthToken()->getAccessToken();
}

$parsedBody = $this->parseBody($body, $contentType);
if (!empty($body)) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $parsedBody);

$requestHeaders[] = "Content-Type: $contentType";
} else {
$requestHeaders[] = 'Content-Length: 0';
}

$customHeaders = [];
if (!empty($headers)) {
foreach ($headers as $key => $value) {
$newHeader = is_numeric($key) ? trim($value) : trim($key) . ': ' . trim($value);
if ($newHeader) {
$customHeaders[] = $newHeader;
}
}
}

curl_setopt($curl, CURLOPT_HTTPHEADER, array_merge($customHeaders, $requestHeaders));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$this->logger?->debug(
trim(
sprintf(
"Request Rede\n%s %s\n%s\n\n%s",
$method,
$url,
implode("\n", $headers),
preg_replace('/"(cardHolderName|cardnumber|securitycode)":"[^"]+"/i', '"\1":"***"', $parsedBody)
)
)
);

$response = curl_exec($curl);
$httpInfo = curl_getinfo($curl);

$this->logger?->debug(
sprintf(
"Response Rede\nStatus Code: %s\n\n%s",
$httpInfo['http_code'],
$response
)
);

$this->dumpHttpInfo($httpInfo);

if (curl_errno($curl)) {
throw new \RuntimeException(sprintf('Curl error[%s]: %s', curl_errno($curl), curl_error($curl)));
}

if (!is_string($response)) {
throw new \RuntimeException('Error obtaining a response from the API');
}

curl_close($curl);

return new RedeResponse($httpInfo['http_code'], $response);
}

private function parseBody(mixed $body, string $contentType): string
{
if (empty($body)) {
return '';
}

if (is_string($body)) {
return $body;
}

if (self::CONTENT_TYPE_FORM_URLENCODED === $contentType) {
return http_build_query($body);
}

return json_encode($body) ?: '';
}

private function getUserAgent(): string
{
$userAgent = sprintf(
'User-Agent: %s',
sprintf(
eRede::USER_AGENT,
phpversion(),
$this->store->getFiliation(),
php_uname('s'),
php_uname('r'),
php_uname('m')
)
);

if (!empty($this->platform) && !empty($this->platformVersion)) {
$userAgent .= sprintf(' %s/%s', $this->platform, $this->platformVersion);
}

$curlVersion = curl_version();

if (is_array($curlVersion)) {
$userAgent .= sprintf(
' curl/%s %s',
$curlVersion['version'] ?? '',
$curlVersion['ssl_version'] ?? ''
);
}

return $userAgent;
}

/**
* @param array<string, mixed> $httpInfo
*/
private function dumpHttpInfo(array $httpInfo): void
{
foreach ($httpInfo as $key => $info) {
if (is_array($info)) {
foreach ($info as $infoKey => $infoValue) {
$this->logger?->debug(sprintf('Curl[%s][%s]: %s', $key, $infoKey, implode(',', $infoValue)));
}

continue;
}

$this->logger?->debug(sprintf('Curl[%s]: %s', $key, $info));
}
}
}
5 changes: 5 additions & 0 deletions src/Rede/Http/RedeResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,9 @@ public function getBody(): string
{
return $this->body;
}

public function isSuccess(): bool
{
return $this->statusCode >= 200 && $this->statusCode < 300;
}
}
92 changes: 92 additions & 0 deletions src/Rede/OAuthToken.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

namespace Rede;

class OAuthToken
{
use SerializeTrait;
use CreateTrait;

public function __construct(
private ?string $access_token = null,
private ?int $expires_in = null,
private ?int $expires_at = null,
private ?string $token_type = null,
private ?string $scope = null,
) {
}

public function isValid(): bool
{
if (empty($this->access_token)) {
return false;
}

if (null !== $this->expires_at && time() >= $this->expires_at) {
return false;
}

return true;
}

// gets and sets
public function getTokenType(): ?string
{
return $this->token_type;
}

public function setTokenType(?string $token_type): static
{
$this->token_type = $token_type;

return $this;
}

public function getAccessToken(): ?string
{
return $this->access_token;
}

public function setAccessToken(?string $access_token): static
{
$this->access_token = $access_token;

return $this;
}

public function getExpiresIn(): ?int
{
return $this->expires_in;
}

public function setExpiresIn(?int $expires_in): static
{
$this->expires_in = $expires_in;

return $this;
}

public function getScope(): ?string
{
return $this->scope;
}

public function setScope(?string $scope): static
{
$this->scope = $scope;

return $this;
}

public function getExpiresAt(): ?int
{
return $this->expires_at;
}

public function setExpiresAt(?int $expires_at): static
{
$this->expires_at = $expires_at;

return $this;
}
}
Loading