diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..15773c3 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,20 @@ +/.editorconfig export-ignore +/.cursorignore export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/.github export-ignore +/.vscode export-ignore +/.cursor export-ignore +/.php-cs-fixer.php export-ignore +/.prettierrc export-ignore +/CONTRIBUTING.md export-ignore +/composer.lock export-ignore +/Makefile export-ignore +/README.md export-ignore +/AGENTS.md export-ignore +/codecov.yml export-ignore +/phpstan.neon export-ignore +/phpunit.xml.dist export-ignore +/tests export-ignore +/package.json export-ignore +/phpunit.xml export-ignore diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..6511b82 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +version: 2 +updates: + - package-ecosystem: 'github-actions' + directory: '/' + commit-message: + # Prefix all commit messages with "chore: " + prefix: 'chore' + schedule: + interval: 'monthly' + open-pull-requests-limit: 10 diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml new file mode 100644 index 0000000..c031e80 --- /dev/null +++ b/.github/workflows/pull_request.yml @@ -0,0 +1,58 @@ +name: Run lint and tests +on: + pull_request: + types: + - opened + - reopened + - ready_for_review + workflow_dispatch: + +env: + PHP_VERSION: 8.3 + PHP_EXTENSIONS: mbstring + PHP_TOOLS: composer:v2, phpunit:11 + +permissions: + id-token: write + contents: read + +jobs: + run-tests: + if: ${{ !github.event.pull_request.draft }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + - name: Install PHP ${{ env.PHP_VERSION }} + uses: shivammathur/setup-php@v2 + with: + coverage: none + php-version: ${{ env.PHP_VERSION }} + extensions: ${{ env.PHP_EXTENSIONS }} + tools: ${{ env.PHP_TOOLS }} + + - name: Get Composer Cache Directory + id: composer-cache + run: | + echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT + - uses: actions/cache@v6 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: | + ${{ runner.os }}-composer- + + - name: Validate composer files + run: composer validate --strict + + - name: Install dependencies + run: composer install --no-interaction --no-progress + + - name: Security audit + run: composer audit --no-dev + + - name: Static analysis + run: composer phpstan + + - name: Run unit tests + run: composer test:unit diff --git a/.gitignore b/.gitignore index 5d13a24..e0abe5f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,8 @@ composer.lock vendor .idea +/.settings/ +/.project +/.buildpath +.vscode/settings.json +/cache diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php new file mode 100644 index 0000000..9766c5b --- /dev/null +++ b/.php-cs-fixer.php @@ -0,0 +1,32 @@ +in(__DIR__) + ->name('*.php') + ->exclude([ + 'cache', + ]) + ->ignoreDotFiles(true) + ->ignoreVCS(true); + +return (new PhpCsFixer\Config()) + ->setParallelConfig(\PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect()) + ->setRiskyAllowed(false) + ->setCacheFile(__DIR__ . '/cache/.php-cs-fixer.cache') + ->setRules([ + '@PSR12' => true, + '@Symfony' => true, + 'fully_qualified_strict_types' => false, // Garantir namespaces completos + 'array_syntax' => ['syntax' => 'short'], + 'binary_operator_spaces' => ['default' => 'single_space'], + 'concat_space' => ['spacing' => 'one'], + 'increment_style' => ['style' => 'post'], + 'yoda_style' => false, + ]) + ->setIndent(' ') + ->setLineEnding("\n") + ->setFinder($finder); diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..f9b6716 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,24 @@ +{ + "parser": "php", + "plugins": [ + "@prettier/plugin-php" + ], + "phpVersion": "8.3", + "printWidth": 150, + "singleQuote": true, + "trailingComma": "all", + "arrowParens": "always", + "tabWidth": 4, + "trailingCommaPHP": true, + "braceStyle": "per-cs", + "requirePragma": false, + "insertPragma": false, + "overrides": [ + { + "files": "*.yml", + "options": { + "tabWidth": 2 + } + } + ] +} \ No newline at end of file diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..82e1ad0 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,17 @@ +{ + "recommendations": [ + "editorconfig.editorconfig", + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode", + "streetsidesoftware.code-spell-checker", + "streetsidesoftware.code-spell-checker-portuguese", + "usernamehw.errorlens", + "eamodio.gitlens", + "seatonjiang.gitmoji-vscode", + "devsense.phptools-vscode", + "phproberto.vscode-php-getters-setters", + "mehedidracula.php-namespace-resolver", + "junstyle.php-cs-fixer", + ], + "unwantedRecommendations": [] +} diff --git a/.vscode/settings.example.json b/.vscode/settings.example.json new file mode 100644 index 0000000..987d31c --- /dev/null +++ b/.vscode/settings.example.json @@ -0,0 +1,44 @@ +{ + "files.eol": "\n", + "eslint.run": "onSave", + "eslint.format.enable": true, + "editor.tabSize": 2, + "php-cs-fixer.executablePath": "${workspaceFolder}/vendor/bin/php-cs-fixer", + "[php]": { + "-editor.defaultFormatter": "junstyle.php-cs-fixer", + "editor.defaultFormatter": "DEVSENSE.phptools-vscode", + "editor.formatOnSave": true, + "editor.tabSize": 4, + "editor.insertSpaces": true, + "editor.trimAutoWhitespace": true, + "editor.bracketPairColorization.enabled": true + }, + "php.format.codeStyle": "PSR-12", + "php.debug.port": 9000, + "php.stubs": [ + "*", + "redis" + ], + "editor.rulers": [ + 150 + ], + "files.insertFinalNewline": true, + "files.readonlyInclude": { + "**/vendor/**/*": true + }, + "javascript.suggest.autoImports": true, + "typescript.suggest.autoImports": true, + "editor.codeActionsOnSave": { + "source.fixAll.eslint": "explicit", + "source.organizeImports": "explicit" + }, + "scss.validate": false, + "editor.defaultFormatter": "esbenp.prettier-vscode", + "[json][jsonc]": { + "editor.defaultFormatter": "vscode.json-language-features" + }, + "[html]": { + "editor.tabSize": 4, + "editor.formatOnSave": false + } +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..f0b57b9 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,103 @@ +# AGENTS.md + +## Contexto do projeto + +- Projeto: `developercielo/api-3.0-php`. +- Tipo: SDK/biblioteca PHP para integração com a [API 3.0 E-commerce da Cielo](https://docs.cielo.com.br/ecommerce-cielo/docs/sobre-api-ecommerce). +- Namespace principal: `Cielo\` (autoload PSR-0 em `src/`). +- Ponto de entrada: `Cielo\API30\Ecommerce\CieloEcommerce`. + +## Stack e versoes + +- PHP: `^8.2` (CI e PHPStan configurados para 8.3). +- Extensoes obrigatorias: `curl`, `json`. +- Composer: `^2.x`. +- Dependencias: `psr/log` (logging opcional via `LoggerInterface`). +- Qualidade: PHPUnit 12, PHPStan 2, PHP-CS-Fixer 3 (dev). + +## Estrutura do codigo + +- `src/Cielo/API30/Merchant.php`: credenciais do lojista (`MerchantId`, `MerchantKey`). +- `src/Cielo/API30/Environment.php`: interface de ambiente (URLs da API). +- `src/Cielo/API30/Ecommerce/Environment.php`: implementacao sandbox/producao. +- `src/Cielo/API30/Ecommerce/CieloEcommerce.php`: facade principal (create, capture, cancel, query, tokenize). +- `src/Cielo/API30/Ecommerce/Sale.php`: pedido/venda com builder fluente. +- `src/Cielo/API30/Ecommerce/Payment.php`: pagamento (credito, debito, pix, boleto, etc.). +- `src/Cielo/API30/Ecommerce/Customer.php`, `Address.php`, `CreditCard.php`, `RecurrentPayment.php`: modelos de dominio. +- `src/Cielo/API30/Ecommerce/CieloSerializable.php`: contrato de serializacao JSON (`JsonSerializable` + `populate`). +- `src/Cielo/API30/Ecommerce/Request/AbstractRequest.php`: base HTTP (cURL, headers, tratamento de resposta). +- `src/Cielo/API30/Ecommerce/Request/*Request.php`: requisicoes especificas (`CreateSale`, `UpdateSale`, `QuerySale`, etc.). +- `src/Cielo/API30/Ecommerce/Request/CieloRequestException.php`, `CieloError.php`: erros da API. +- `tests/Unit/*`: testes unitarios (namespace `TestApp\`). +- `tests/E2E/*`: testes end-to-end (quando existirem; exigem credenciais reais). + +## Padroes de implementacao + +- `CieloEcommerce` delega operacoes para classes `*Request`; nao colocar logica HTTP diretamente na facade. +- Modelos de dominio implementam `CieloSerializable` para montar payloads e desserializar respostas. +- Builders fluentes em `Sale` e `Payment` (`$sale->payment(15700)->creditCard(...)`). +- Requisicoes usam cURL com TLS 1.2, headers `MerchantId`/`MerchantKey` e `RequestId` unico. +- Logging via `Psr\Log\LoggerInterface` e opcional; quando presente, dados de cartao sao mascarados em `AbstractRequest`. +- Preserve compatibilidade retroativa: e um SDK publicado consumido por aplicacoes de pagamento. + +## Diretrizes para alteracoes + +- Evite quebrar assinaturas publicas sem justificativa clara e sem atualizar testes. +- Para novos meios de pagamento ou operacoes, siga o padrao existente: modelo + request + metodo em `CieloEcommerce`. +- Mantenha coesao por modulo (`Ecommerce`, `Request`, modelos de dominio). +- Consulte o manual oficial da Cielo para campos, codigos de erro e fluxos de autenticacao (debito, 3DS, etc.). +- O SDK monta transacoes; redirecionamento do usuario (debito, boleto, pix) fica a cargo da aplicacao consumidora. + +## Qualidade e convencoes + +- Arquivos em UTF-8 e quebra de linha `LF`. +- Indentacao: preferir `4 espacos` (codigo legado pode conter tabs em trechos antigos). +- Convencoes: classe `PascalCase`, metodo/variavel `camelCase`, constante `SCREAMING_SNAKE_CASE`. +- Analise estatica: `phpstan.neon` (nivel 5, PHP 8.3). +- Sempre adicionar/atualizar testes quando alterar comportamento publico. +- Toda alteracao deve terminar com analise estatica e testes antes de concluir a tarefa. + +## Comandos relevantes + +- Validacao completa local: `composer test` (PHPStan + PHPUnit, exclui grupo `payment`). +- PHPStan: `composer phpstan` +- Checar formato: `composer format:check` +- Corrigir formato: `composer format:fix` +- Lint padrao do projeto: `composer lint` +- PHPUnit (todos os testes, exceto grupo `payment`): `composer phpunit` +- Testes unitarios: `composer test:unit` +- Testes E2E: `composer test:e2e` (requer credenciais e ambiente configurados) +- Validar `composer.json`: `composer validate --strict` +- Auditoria de seguranca: `composer audit --no-dev` + +## Seguranca e limites + +- Nunca commitar credenciais: `MerchantId`, `MerchantKey`, tokens de cartao, dados de cartao reais. +- Nunca registrar CVV, numero completo de cartao ou chaves em logs, mensagens de erro ou dumps de debug. +- O SDK ja mascara numero de cartao em logs de debug; preserve esse comportamento ao alterar `AbstractRequest`. +- Evitar alterar `vendor/` e arquivos gerados automaticamente. +- Em erros/excecoes, evitar expor respostas brutas da API com dados sensiveis ao usuario final. +- Testes que chamam a API real devem usar `@group payment` e ficar fora da suite padrao. +- Validar entradas de modelos (valores em centavos, bandeiras, tipos de pagamento) ao adicionar novos campos. + +## Testes e validacao final (obrigatorio) + +- Ao finalizar qualquer alteracao, executar obrigatoriamente: + - `composer phpstan` + - `composer test:unit` +- Para alteracoes que impactam integracao HTTP ou fluxos de pagamento, rodar tambem `composer test:e2e` quando aplicavel. +- Se houver falha em qualquer comando, corrigir e rodar novamente ate passar. +- Nao considerar tarefa concluida sem evidenciar que analise estatica e testes passaram. + +## Commits (obrigatorio) + +Usar Conventional Commits em ingles (en-US): + +- `(): ` +- Tipos: `feat`, `fix`, `refactor`, `chore`, `docs`, `style`, `perf`, `test`, `build`, `ci`, `revert` + +Exemplos: + +- `feat(ecommerce): adicionar suporte a novo meio de pagamento` +- `fix(request): corrigir mascaramento de cartao nos logs de debug` +- `test(unit): cobrir serializacao de pagamento pix` diff --git a/README.md b/README.md index 7e96dfe..5d1877b 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ SDK API-3.0 PHP * [x] Com autorização na primeira recorrência. * [x] Com autorização a partir da primeira recorrência. * [x] Pagamentos por cartão de débito. +* [x] Pagamentos por pix. * [x] Pagamentos por boleto. * [x] Pagamentos por transferência eletrônica. * [x] Cancelamento de autorização. @@ -21,7 +22,7 @@ Por envolver a interface de usuário da aplicação, o SDK funciona apenas como ## Dependências -* PHP >= 5.6 +* PHP >= 8.3 ## Instalando o SDK @@ -29,20 +30,25 @@ Se já possui um arquivo `composer.json`, basta adicionar a seguinte dependênci ```json "require": { - "developercielo/api-3.0-php": "^1.0" + "developercielo/api-3.0-php": "^2.0.0" } ``` -Com a dependência adicionada ao `composer.json`, basta executar: +Adicionar o `repositories` no `composer.json` -``` -composer install +```json +"repositories": [ + { + "type": "vcs", + "url": "https://github.com/edson-nascimento/API-3.0-PHP" + } +], ``` -Alternativamente, você pode executar diretamente em seu terminal: +Com a dependência adicionada ao `composer.json`, basta executar: ``` -composer require "developercielo/api-3.0-php" +composer update ``` ## Produtos e Bandeiras suportadas e suas constantes @@ -424,6 +430,23 @@ try { } ``` +### Criando uma venda com PIX + +```php +customer('Fulano de Tal'); + +$payment = $sale->payment(15700); +$payment->pix(); +$payment->setCapture(true); + +$sale = (new CieloEcommerce($merchant, $environment))->createSale($sale); +// ... +``` + ### Tokenizando um cartão ```php @@ -471,4 +494,4 @@ try { ## Manual -Para mais informações sobre a integração com a API 3.0 da Cielo, vide o manual em: [Integração API 3.0](https://developercielo.github.io/manual/cielo-ecommerce) +Para mais informações sobre a integração com a API 3.0 da Cielo, vide o manual em: [Integração API 3.0](https://docs.cielo.com.br/ecommerce-cielo/docs/sobre-api-ecommerce) diff --git a/composer.json b/composer.json index 60c692e..4e102cc 100644 --- a/composer.json +++ b/composer.json @@ -1,21 +1,49 @@ { - "autoload": { - "psr-0": { - "Cielo": "src" - } - }, "name": "developercielo/api-3.0-php", "description": "Integração com a API 3.0 da Cielo", - "license": "MIT", "type": "library", "require": { - "php": ">=5.6", + "php": "^8.2", "ext-curl": "*", "ext-json": "*", - "psr/log":"^1.1" + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "require-dev": { + "phpunit/phpunit": "^12.5.33", + "phpstan/phpstan": "^2.2.7", + "kint-php/kint": "^6.1.0", + "friendsofphp/php-cs-fixer": "^3.95.18" + }, + "autoload": { + "psr-0": { + "Cielo": "src" + } + }, + "autoload-dev": { + "psr-4": { + "TestApp\\": "tests/" + } }, "suggest": { "monolog/monolog": "Allows more advanced logging of the application flow" }, - "homepage": "https://github.com/DeveloperCielo/API-3.0-PHP" + "homepage": "https://github.com/DeveloperCielo/API-3.0-PHP", + "scripts": { + "phpstan": "phpstan analyse -c phpstan.neon", + "phpunit": "phpunit --configuration phpunit.xml --testdox --exclude-group payment", + "test": [ + "@phpstan", + "@phpunit" + ], + "test:unit": "phpunit tests/Unit --configuration phpunit.xml --testdox", + "test:e2e": "phpunit tests/E2E --configuration phpunit.xml --testdox", + "format:check": "php-cs-fixer fix --dry-run --stop-on-violation", + "format:fix": "php-cs-fixer fix", + "lint": [ + "@format:fix", + "@phpstan" + ] + }, + "license": "MIT", + "minimum-stability": "stable" } diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..be9362d --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,17 @@ +parameters: + level: 5 + phpVersion: 80200 + checkFunctionNameCase: true + checkInternalClassCaseSensitivity: true + reportMaybesInPropertyPhpDocTypes: true + checkExplicitMixedMissingReturn: true + reportMaybesInMethodSignatures: true + reportStaticMethodSignatures: true + checkTooWideReturnTypesInProtectedAndPublicMethods: true + checkDynamicProperties: true + reportAlwaysTrueInLastCondition: true + paths: + - ./ + excludePaths: + - ./vendor/* + ignoreErrors: diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..6d6460d --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,23 @@ + + + + + tests + + + \ No newline at end of file diff --git a/src/Cielo/API30/Ecommerce/Address.php b/src/Cielo/API30/Ecommerce/Address.php index d16e71e..521429a 100644 --- a/src/Cielo/API30/Ecommerce/Address.php +++ b/src/Cielo/API30/Ecommerce/Address.php @@ -3,13 +3,10 @@ namespace Cielo\API30\Ecommerce; /** - * Class Address - * - * @package Cielo\API30\Ecommerce + * Class Address. */ class Address implements CieloSerializable { - private $street; private $number; @@ -26,40 +23,29 @@ class Address implements CieloSerializable private $district; - /** - * @return array - */ - public function jsonSerialize() + public function jsonSerialize(): mixed { return get_object_vars($this); } - /** - * @param \stdClass $data - */ public function populate(\stdClass $data) { - $this->street = isset($data->Street) ? $data->Street : null; - $this->number = isset($data->Number) ? $data->Number : null; + $this->street = isset($data->Street) ? $data->Street : null; + $this->number = isset($data->Number) ? $data->Number : null; $this->complement = isset($data->Complement) ? $data->Complement : null; - $this->zipCode = isset($data->ZipCode) ? $data->ZipCode : null; - $this->city = isset($data->City) ? $data->City : null; - $this->state = isset($data->State) ? $data->State : null; - $this->country = isset($data->Country) ? $data->Country : null; - $this->district = isset($data->District) ? $data->District : null; + $this->zipCode = isset($data->ZipCode) ? $data->ZipCode : null; + $this->city = isset($data->City) ? $data->City : null; + $this->state = isset($data->State) ? $data->State : null; + $this->country = isset($data->Country) ? $data->Country : null; + $this->district = isset($data->District) ? $data->District : null; } - /** - * @return mixed - */ public function getDistrict() { return $this->district; } /** - * @param $district - * * @return $this */ public function setDistrict($district) @@ -69,17 +55,12 @@ public function setDistrict($district) return $this; } - /** - * @return mixed - */ public function getStreet() { return $this->street; } /** - * @param $street - * * @return $this */ public function setStreet($street) @@ -89,17 +70,12 @@ public function setStreet($street) return $this; } - /** - * @return mixed - */ public function getNumber() { return $this->number; } /** - * @param $number - * * @return $this */ public function setNumber($number) @@ -109,17 +85,12 @@ public function setNumber($number) return $this; } - /** - * @return mixed - */ public function getComplement() { return $this->complement; } /** - * @param $complement - * * @return $this */ public function setComplement($complement) @@ -129,17 +100,12 @@ public function setComplement($complement) return $this; } - /** - * @return mixed - */ public function getZipCode() { return $this->zipCode; } /** - * @param $zipCode - * * @return $this */ public function setZipCode($zipCode) @@ -149,17 +115,12 @@ public function setZipCode($zipCode) return $this; } - /** - * @return mixed - */ public function getCity() { return $this->city; } /** - * @param $city - * * @return $this */ public function setCity($city) @@ -169,17 +130,12 @@ public function setCity($city) return $this; } - /** - * @return mixed - */ public function getState() { return $this->state; } /** - * @param $state - * * @return $this */ public function setState($state) @@ -189,17 +145,12 @@ public function setState($state) return $this; } - /** - * @return mixed - */ public function getCountry() { return $this->country; } /** - * @param $country - * * @return $this */ public function setCountry($country) diff --git a/src/Cielo/API30/Ecommerce/CieloEcommerce.php b/src/Cielo/API30/Ecommerce/CieloEcommerce.php index f297d73..b21a37c 100644 --- a/src/Cielo/API30/Ecommerce/CieloEcommerce.php +++ b/src/Cielo/API30/Ecommerce/CieloEcommerce.php @@ -11,37 +11,29 @@ use Psr\Log\LoggerInterface; /** - * The Cielo Ecommerce SDK front-end; + * The Cielo Ecommerce SDK front-end;. */ class CieloEcommerce { - private $merchant; private $environment; private $logger; - /** - * Create an instance of CieloEcommerce choosing the environment where the - * requests will be send - * - * @param Merchant $merchant - * The merchant credentials - * @param Environment environment - * The environment: {@link Environment::production()} or - * {@link Environment::sandbox()} - * @param LoggerInterface|null $logger - */ - public function __construct(Merchant $merchant, Environment $environment = null, LoggerInterface $logger = null) + /** + * Create an instance of CieloEcommerce choosing the environment where the + * requests will be send. + */ + public function __construct(Merchant $merchant, ?Environment $environment = null, ?LoggerInterface $logger = null) { if ($environment == null) { $environment = Environment::production(); } - $this->merchant = $merchant; + $this->merchant = $merchant; $this->environment = $environment; - $this->logger = $logger; + $this->logger = $logger; } /** @@ -49,11 +41,11 @@ public function __construct(Merchant $merchant, Environment $environment = null, * returned by Cielo. * * @param Sale $sale - * The preconfigured Sale + * The preconfigured Sale * * @return Sale The Sale with authorization, tid, etc. returned by Cielo. * - * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException if anything gets wrong. + * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException if anything gets wrong * * @see Error @@ -67,14 +59,14 @@ public function createSale(Sale $sale) } /** - * Query a Sale on Cielo by paymentId + * Query a Sale on Cielo by paymentId. * * @param string $paymentId - * The paymentId to be queried + * The paymentId to be queried * * @return Sale The Sale with authorization, tid, etc. returned by Cielo. * - * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException if anything gets wrong. + * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException if anything gets wrong * * @see Error @@ -88,15 +80,15 @@ public function getSale($paymentId) } /** - * Query a RecurrentPayment on Cielo by RecurrentPaymentId + * Query a RecurrentPayment on Cielo by RecurrentPaymentId. * * @param string $recurrentPaymentId - * The RecurrentPaymentId to be queried + * The RecurrentPaymentId to be queried * * @return \Cielo\API30\Ecommerce\RecurrentPayment - * The RecurrentPayment with authorization, tid, etc. returned by Cielo. + * The RecurrentPayment with authorization, tid, etc. returned by Cielo. * - * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException if anything gets wrong. + * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException if anything gets wrong * * @see Error @@ -110,16 +102,16 @@ public function getRecurrentPayment($recurrentPaymentId) } /** - * Cancel a Sale on Cielo by paymentId and speficying the amount + * Cancel a Sale on Cielo by paymentId and speficying the amount. * - * @param string $paymentId - * The paymentId to be queried - * @param integer $amount - * Order value in cents + * @param string $paymentId + * The paymentId to be queried + * @param int $amount + * Order value in cents * - * @return Sale The Sale with authorization, tid, etc. returned by Cielo. + * @return \Cielo\API30\Ecommerce\Payment * - * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException if anything gets wrong. + * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException if anything gets wrong * * @see Error @@ -136,20 +128,19 @@ public function cancelSale($paymentId, $amount = null) /** * Capture a Sale on Cielo by paymentId and specifying the amount and the - * serviceTaxAmount - * - * @param string $paymentId - * The paymentId to be captured - * @param integer $amount - * Amount of the authorization to be captured - * @param integer $serviceTaxAmount - * Amount of the authorization should be destined for the service - * charge + * serviceTaxAmount. * - * @return \Cielo\API30\Ecommerce\Payment The captured Payment. + * @param string $paymentId + * The paymentId to be captured + * @param int $amount + * Amount of the authorization to be captured + * @param int $serviceTaxAmount + * Amount of the authorization should be destined for the service + * charge * + * @return \Cielo\API30\Ecommerce\Payment the captured Payment * - * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException if anything gets wrong. + * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException if anything gets wrong * * @see Error @@ -166,8 +157,6 @@ public function captureSale($paymentId, $amount = null, $serviceTaxAmount = null } /** - * @param CreditCard $card - * * @return CreditCard */ public function tokenizeCard(CreditCard $card) diff --git a/src/Cielo/API30/Ecommerce/CieloSerializable.php b/src/Cielo/API30/Ecommerce/CieloSerializable.php index 05d13a7..9f7de44 100644 --- a/src/Cielo/API30/Ecommerce/CieloSerializable.php +++ b/src/Cielo/API30/Ecommerce/CieloSerializable.php @@ -3,16 +3,12 @@ namespace Cielo\API30\Ecommerce; /** - * Interface CieloSerializable - * - * @package Cielo\API30\Ecommerce + * Interface CieloSerializable. */ interface CieloSerializable extends \JsonSerializable { /** - * @param \stdClass $data - * - * @return mixed + * @return void */ public function populate(\stdClass $data); } diff --git a/src/Cielo/API30/Ecommerce/CreditCard.php b/src/Cielo/API30/Ecommerce/CreditCard.php index e83b4b8..b8df1f8 100644 --- a/src/Cielo/API30/Ecommerce/CreditCard.php +++ b/src/Cielo/API30/Ecommerce/CreditCard.php @@ -3,82 +3,80 @@ namespace Cielo\API30\Ecommerce; /** - * Class CreditCard - * - * @package Cielo\API30\Ecommerce + * Class CreditCard. */ class CreditCard implements \JsonSerializable, CieloSerializable { /** - * Bandeira Visa + * Bandeira Visa. */ - const VISA = 'Visa'; + public const VISA = 'Visa'; /** - * Bandeira Mastercard + * Bandeira Mastercard. */ - const MASTERCARD = 'Master'; + public const MASTERCARD = 'Master'; /** - * Bandeira American Express + * Bandeira American Express. */ - const AMEX = 'Amex'; + public const AMEX = 'Amex'; /** - * Bandeira ELO + * Bandeira ELO. */ - const ELO = 'Elo'; + public const ELO = 'Elo'; /** - * Bandeira Aura + * Bandeira Aura. */ - const AURA = 'Aura'; + public const AURA = 'Aura'; /** - * Bandeira JCB + * Bandeira JCB. */ - const JCB = 'JCB'; + public const JCB = 'JCB'; /** - * Bandeira Diners + * Bandeira Diners. */ - const DINERS = 'Diners'; + public const DINERS = 'Diners'; /** - * Bandeira Discover + * Bandeira Discover. */ - const DISCOVER = 'Discover'; + public const DISCOVER = 'Discover'; /** - * Bandeira Hipercard + * Bandeira Hipercard. */ - const HIPERCARD = 'Hipercard'; + public const HIPERCARD = 'Hipercard'; - /** @var string $cardNumber */ + /** @var string */ private $cardNumber; - /** @var string $holder */ + /** @var string */ private $holder; - /** @var string $expirationDate */ + /** @var string */ private $expirationDate; - /** @var string $securityCode */ + /** @var string */ private $securityCode; - /** @var bool $saveCard */ + /** @var bool */ private $saveCard = false; - /** @var string $brand */ + /** @var string */ private $brand; - /** @var string $cardToken */ + /** @var string */ private $cardToken; - /** @var string $customerName */ + /** @var string */ private $customerName; - /** @var \stdClass $links */ + /** @var \stdClass */ private $links; /** @@ -88,48 +86,37 @@ class CreditCard implements \JsonSerializable, CieloSerializable */ public static function fromJson($json) { - $object = \json_decode($json); + $object = \json_decode($json); $cardToken = new CreditCard(); $cardToken->populate($object); return $cardToken; } - /** - * @inheritdoc - */ public function populate(\stdClass $data) { - $this->cardNumber = isset($data->CardNumber) ? $data->CardNumber : null; - $this->holder = isset($data->Holder) ? $data->Holder : null; + $this->cardNumber = isset($data->CardNumber) ? $data->CardNumber : null; + $this->holder = isset($data->Holder) ? $data->Holder : null; $this->expirationDate = isset($data->ExpirationDate) ? $data->ExpirationDate : null; - $this->securityCode = isset($data->SecurityCode) ? $data->SecurityCode : null; - $this->saveCard = isset($data->SaveCard) ? !!$data->SaveCard : false; - $this->brand = isset($data->Brand) ? $data->Brand : null; - $this->cardToken = isset($data->CardToken) ? $data->CardToken : null; - $this->links = isset($data->Links) ? $data->Links : new \stdClass(); - $this->customerName = isset($data->CustomerName) ? $data->CustomerName : null; + $this->securityCode = isset($data->SecurityCode) ? $data->SecurityCode : null; + $this->saveCard = isset($data->SaveCard) ? (bool) $data->SaveCard : false; + $this->brand = isset($data->Brand) ? $data->Brand : null; + $this->cardToken = isset($data->CardToken) ? $data->CardToken : null; + $this->links = isset($data->Links) ? $data->Links : new \stdClass(); + $this->customerName = isset($data->CustomerName) ? $data->CustomerName : null; } - /** - * @return array - */ - public function jsonSerialize() + public function jsonSerialize(): mixed { return get_object_vars($this); } - /** - * @return mixed - */ public function getCardNumber() { return $this->cardNumber; } /** - * @param $cardNumber - * * @return $this */ public function setCardNumber($cardNumber) @@ -139,17 +126,12 @@ public function setCardNumber($cardNumber) return $this; } - /** - * @return mixed - */ public function getHolder() { return $this->holder; } /** - * @param $holder - * * @return $this */ public function setHolder($holder) @@ -159,17 +141,12 @@ public function setHolder($holder) return $this; } - /** - * @return mixed - */ public function getExpirationDate() { return $this->expirationDate; } /** - * @param $expirationDate - * * @return $this */ public function setExpirationDate($expirationDate) @@ -179,17 +156,12 @@ public function setExpirationDate($expirationDate) return $this; } - /** - * @return mixed - */ public function getSecurityCode() { return $this->securityCode; } /** - * @param $securityCode - * * @return $this */ public function setSecurityCode($securityCode) @@ -208,8 +180,6 @@ public function getSaveCard() } /** - * @param $saveCard - * * @return $this */ public function setSaveCard($saveCard) @@ -219,17 +189,12 @@ public function setSaveCard($saveCard) return $this; } - /** - * @return mixed - */ public function getBrand() { return $this->brand; } /** - * @param $brand - * * @return $this */ public function setBrand($brand) @@ -239,17 +204,12 @@ public function setBrand($brand) return $this; } - /** - * @return mixed - */ public function getCardToken() { return $this->cardToken; } /** - * @param $cardToken - * * @return $this */ public function setCardToken($cardToken) diff --git a/src/Cielo/API30/Ecommerce/Customer.php b/src/Cielo/API30/Ecommerce/Customer.php index c24dc69..2a04a58 100644 --- a/src/Cielo/API30/Ecommerce/Customer.php +++ b/src/Cielo/API30/Ecommerce/Customer.php @@ -3,13 +3,10 @@ namespace Cielo\API30\Ecommerce; /** - * Class Customer - * - * @package Cielo\API30\Ecommerce + * Class Customer. */ class Customer implements \JsonSerializable { - private $name; private $email; @@ -34,24 +31,18 @@ public function __construct($name = null) $this->setName($name); } - /** - * @return array - */ - public function jsonSerialize() + public function jsonSerialize(): mixed { return get_object_vars($this); } - /** - * @param \stdClass $data - */ public function populate(\stdClass $data) { - $this->name = isset($data->Name) ? $data->Name : null; - $this->email = isset($data->Email) ? $data->Email : null; + $this->name = isset($data->Name) ? $data->Name : null; + $this->email = isset($data->Email) ? $data->Email : null; $this->birthDate = isset($data->Birthdate) ? $data->Birthdate : null; - $this->identity = isset($data->Identity) ? $data->Identity : null; + $this->identity = isset($data->Identity) ? $data->Identity : null; $this->identityType = isset($data->IdentityType) ? $data->IdentityType : null; if (isset($data->Address)) { @@ -89,17 +80,12 @@ public function deliveryAddress() return $address; } - /** - * @return mixed - */ public function getName() { return $this->name; } /** - * @param $name - * * @return $this */ public function setName($name) @@ -109,17 +95,12 @@ public function setName($name) return $this; } - /** - * @return mixed - */ public function getEmail() { return $this->email; } /** - * @param $email - * * @return $this */ public function setEmail($email) @@ -129,17 +110,12 @@ public function setEmail($email) return $this; } - /** - * @return mixed - */ public function getBirthDate() { return $this->birthDate; } /** - * @param $birthDate - * * @return $this */ public function setBirthDate($birthDate) @@ -149,17 +125,12 @@ public function setBirthDate($birthDate) return $this; } - /** - * @return mixed - */ public function getIdentity() { return $this->identity; } /** - * @param $identity - * * @return $this */ public function setIdentity($identity) @@ -169,17 +140,12 @@ public function setIdentity($identity) return $this; } - /** - * @return mixed - */ public function getIdentityType() { return $this->identityType; } /** - * @param $identityType - * * @return $this */ public function setIdentityType($identityType) @@ -189,17 +155,12 @@ public function setIdentityType($identityType) return $this; } - /** - * @return mixed - */ public function getAddress() { return $this->address; } /** - * @param $address - * * @return $this */ public function setAddress($address) @@ -209,17 +170,12 @@ public function setAddress($address) return $this; } - /** - * @return mixed - */ public function getDeliveryAddress() { return $this->deliveryAddress; } /** - * @param $deliveryAddress - * * @return $this */ public function setDeliveryAddress($deliveryAddress) diff --git a/src/Cielo/API30/Ecommerce/Environment.php b/src/Cielo/API30/Ecommerce/Environment.php index 1b1334c..9e11228 100644 --- a/src/Cielo/API30/Ecommerce/Environment.php +++ b/src/Cielo/API30/Ecommerce/Environment.php @@ -3,9 +3,7 @@ namespace Cielo\API30\Ecommerce; /** - * Class Environment - * - * @package Cielo\API30\Ecommerce + * Class Environment. */ class Environment implements \Cielo\API30\Environment { @@ -15,13 +13,10 @@ class Environment implements \Cielo\API30\Environment /** * Environment constructor. - * - * @param $api - * @param $apiQuery */ private function __construct($api, $apiQuery) { - $this->api = $api; + $this->api = $api; $this->apiQuery = $apiQuery; } @@ -30,7 +25,7 @@ private function __construct($api, $apiQuery) */ public static function sandbox() { - $api = 'https://apisandbox.cieloecommerce.cielo.com.br/'; + $api = 'https://apisandbox.cieloecommerce.cielo.com.br/'; $apiQuery = 'https://apiquerysandbox.cieloecommerce.cielo.com.br/'; return new Environment($api, $apiQuery); @@ -41,14 +36,14 @@ public static function sandbox() */ public static function production() { - $api = 'https://api.cieloecommerce.cielo.com.br/'; + $api = 'https://api.cieloecommerce.cielo.com.br/'; $apiQuery = 'https://apiquery.cieloecommerce.cielo.com.br/'; return new Environment($api, $apiQuery); } /** - * Gets the environment's Api URL + * Gets the environment's Api URL. * * @return string the Api URL */ @@ -58,7 +53,7 @@ public function getApiUrl() } /** - * Gets the environment's Api Query URL + * Gets the environment's Api Query URL. * * @return string Api Query URL */ diff --git a/src/Cielo/API30/Ecommerce/Payment.php b/src/Cielo/API30/Ecommerce/Payment.php index 574f88a..e885696 100644 --- a/src/Cielo/API30/Ecommerce/Payment.php +++ b/src/Cielo/API30/Ecommerce/Payment.php @@ -3,26 +3,25 @@ namespace Cielo\API30\Ecommerce; /** - * Class Payment - * - * @package Cielo\API30\Ecommerce + * Class Payment. */ class Payment implements \JsonSerializable { + public const PAYMENTTYPE_CREDITCARD = 'CreditCard'; - const PAYMENTTYPE_CREDITCARD = 'CreditCard'; + public const PAYMENTTYPE_DEBITCARD = 'DebitCard'; - const PAYMENTTYPE_DEBITCARD = 'DebitCard'; + public const PAYMENTTYPE_ELECTRONIC_TRANSFER = 'ElectronicTransfer'; - const PAYMENTTYPE_ELECTRONIC_TRANSFER = 'ElectronicTransfer'; + public const PAYMENTTYPE_BOLETO = 'Boleto'; - const PAYMENTTYPE_BOLETO = 'Boleto'; + public const PAYMENTTYPE_PIX = 'Pix'; - const PROVIDER_BRADESCO = 'Bradesco'; + public const PROVIDER_BRADESCO = 'Bradesco'; - const PROVIDER_BANCO_DO_BRASIL = 'BancoDoBrasil'; + public const PROVIDER_BANCO_DO_BRASIL = 'BancoDoBrasil'; - const PROVIDER_SIMULADO = 'Simulado'; + public const PROVIDER_SIMULADO = 'Simulado'; private $serviceTaxAmount; @@ -50,7 +49,7 @@ class Payment implements \JsonSerializable private $authorizationCode; - private $softDescriptor = ""; + private $softDescriptor = ''; private $returnUrl; @@ -108,6 +107,12 @@ class Payment implements \JsonSerializable private $instructions; + private $acquirerTransactionId; + + private $qrcodeBase64Image; + + private $qrCodeString; + /** * Payment constructor. * @@ -121,8 +126,6 @@ public function __construct($amount = 0, $installments = 1) } /** - * @param $json - * * @return Payment */ public static function fromJson($json) @@ -133,18 +136,14 @@ public static function fromJson($json) return $payment; } - /** - * @param \stdClass $data - */ public function populate(\stdClass $data) { - $this->serviceTaxAmount = isset($data->ServiceTaxAmount) ? $data->ServiceTaxAmount : null; - $this->installments = isset($data->Installments) ? $data->Installments : null; - $this->interest = isset($data->Interest) ? $data->Interest : null; - $this->capture = isset($data->Capture) ? !!$data->Capture : false; - $this->authenticate = isset($data->Authenticate) ? !!$data->Authenticate : false; - $this->recurrent = isset($data->Recurrent) ? !!$data->Recurrent : false; + $this->installments = isset($data->Installments) ? $data->Installments : null; + $this->interest = isset($data->Interest) ? $data->Interest : null; + $this->capture = isset($data->Capture) ? (bool) $data->Capture : false; + $this->authenticate = isset($data->Authenticate) ? (bool) $data->Authenticate : false; + $this->recurrent = isset($data->Recurrent) ? (bool) $data->Recurrent : false; if (isset($data->RecurrentPayment)) { $this->recurrentPayment = new RecurrentPayment(false); @@ -162,52 +161,50 @@ public function populate(\stdClass $data) } $this->expirationDate = isset($data->ExpirationDate) ? $data->ExpirationDate : null; - $this->url = isset($data->Url) ? $data->Url : null; - $this->boletoNumber = isset($data->BoletoNumber) ? $data->BoletoNumber : null; - $this->barCodeNumber = isset($data->BarCodeNumber) ? $data->BarCodeNumber : null; - $this->digitableLine = isset($data->DigitableLine) ? $data->DigitableLine : null; - $this->address = isset($data->Address) ? $data->Address : null; + $this->url = isset($data->Url) ? $data->Url : null; + $this->boletoNumber = isset($data->BoletoNumber) ? $data->BoletoNumber : null; + $this->barCodeNumber = isset($data->BarCodeNumber) ? $data->BarCodeNumber : null; + $this->digitableLine = isset($data->DigitableLine) ? $data->DigitableLine : null; + $this->address = isset($data->Address) ? $data->Address : null; $this->authenticationUrl = isset($data->AuthenticationUrl) ? $data->AuthenticationUrl : null; - $this->tid = isset($data->Tid) ? $data->Tid : null; - $this->proofOfSale = isset($data->ProofOfSale) ? $data->ProofOfSale : null; + $this->tid = isset($data->Tid) ? $data->Tid : null; + $this->proofOfSale = isset($data->ProofOfSale) ? $data->ProofOfSale : null; $this->authorizationCode = isset($data->AuthorizationCode) ? $data->AuthorizationCode : null; - $this->softDescriptor = isset($data->SoftDescriptor) ? $data->SoftDescriptor : null; - $this->provider = isset($data->Provider) ? $data->Provider : null; - $this->paymentId = isset($data->PaymentId) ? $data->PaymentId : null; - $this->type = isset($data->Type) ? $data->Type : null; - $this->amount = isset($data->Amount) ? $data->Amount : null; - $this->receivedDate = isset($data->ReceivedDate) ? $data->ReceivedDate : null; - $this->capturedAmount = isset($data->CapturedAmount) ? $data->CapturedAmount : null; - $this->capturedDate = isset($data->CapturedDate) ? $data->CapturedDate : null; - $this->voidedAmount = isset($data->VoidedAmount) ? $data->VoidedAmount : null; - $this->voidedDate = isset($data->VoidedDate) ? $data->VoidedDate : null; - $this->currency = isset($data->Currency) ? $data->Currency : null; - $this->country = isset($data->Country) ? $data->Country : null; - $this->returnCode = isset($data->ReturnCode) ? $data->ReturnCode : null; - $this->returnMessage = isset($data->ReturnMessage) ? $data->ReturnMessage : null; - $this->status = isset($data->Status) ? $data->Status : null; + $this->softDescriptor = isset($data->SoftDescriptor) ? $data->SoftDescriptor : null; + $this->provider = isset($data->Provider) ? $data->Provider : null; + $this->paymentId = isset($data->PaymentId) ? $data->PaymentId : null; + $this->type = isset($data->Type) ? $data->Type : null; + $this->amount = isset($data->Amount) ? $data->Amount : null; + $this->receivedDate = isset($data->ReceivedDate) ? $data->ReceivedDate : null; + $this->capturedAmount = isset($data->CapturedAmount) ? $data->CapturedAmount : null; + $this->capturedDate = isset($data->CapturedDate) ? $data->CapturedDate : null; + $this->voidedAmount = isset($data->VoidedAmount) ? $data->VoidedAmount : null; + $this->voidedDate = isset($data->VoidedDate) ? $data->VoidedDate : null; + $this->currency = isset($data->Currency) ? $data->Currency : null; + $this->country = isset($data->Country) ? $data->Country : null; + $this->returnCode = isset($data->ReturnCode) ? $data->ReturnCode : null; + $this->returnMessage = isset($data->ReturnMessage) ? $data->ReturnMessage : null; + $this->status = isset($data->Status) ? $data->Status : null; $this->links = isset($data->Links) ? $data->Links : []; - $this->assignor = isset($data->Assignor) ? $data->Assignor : null; - $this->demonstrative = isset($data->Demonstrative) ? $data->Demonstrative : null; + $this->assignor = isset($data->Assignor) ? $data->Assignor : null; + $this->demonstrative = isset($data->Demonstrative) ? $data->Demonstrative : null; $this->identification = isset($data->Identification) ? $data->Identification : null; - $this->instructions = isset($data->Instructions) ? $data->Instructions : null; + $this->instructions = isset($data->Instructions) ? $data->Instructions : null; + + $this->acquirerTransactionId = isset($data->AcquirerTransactionId) ? $data->AcquirerTransactionId : null; + $this->qrcodeBase64Image = isset($data->QrcodeBase64Image) ? $data->QrcodeBase64Image : null; + $this->qrCodeString = isset($data->QrCodeString) ? $data->QrCodeString : null; } - /** - * @return array - */ - public function jsonSerialize() + public function jsonSerialize(): mixed { return get_object_vars($this); } /** - * @param $securityCode - * @param $brand - * * @return CreditCard */ public function creditCard($securityCode, $brand) @@ -221,9 +218,6 @@ public function creditCard($securityCode, $brand) } /** - * @param $securityCode - * @param $brand - * * @return CreditCard */ private function newCard($securityCode, $brand) @@ -236,9 +230,6 @@ private function newCard($securityCode, $brand) } /** - * @param $securityCode - * @param $brand - * * @return CreditCard */ public function debitCard($securityCode, $brand) @@ -266,16 +257,22 @@ public function recurrentPayment($authorizeNow = true) } /** - * @return mixed + * @return $this */ + public function pix() + { + $this->setType(self::PAYMENTTYPE_PIX); + $this->setCapture(true); + + return $this; + } + public function getServiceTaxAmount() { return $this->serviceTaxAmount; } /** - * @param $serviceTaxAmount - * * @return $this */ public function setServiceTaxAmount($serviceTaxAmount) @@ -285,17 +282,12 @@ public function setServiceTaxAmount($serviceTaxAmount) return $this; } - /** - * @return mixed - */ public function getInstallments() { return $this->installments; } /** - * @param $installments - * * @return $this */ public function setInstallments($installments) @@ -305,17 +297,12 @@ public function setInstallments($installments) return $this; } - /** - * @return mixed - */ public function getInterest() { return $this->interest; } /** - * @param $interest - * * @return $this */ public function setInterest($interest) @@ -334,8 +321,6 @@ public function getCapture() } /** - * @param $capture - * * @return $this */ public function setCapture($capture) @@ -354,8 +339,6 @@ public function getAuthenticate() } /** - * @param $authenticate - * * @return $this */ public function setAuthenticate($authenticate) @@ -365,17 +348,12 @@ public function setAuthenticate($authenticate) return $this; } - /** - * @return mixed - */ public function getRecurrent() { return $this->recurrent; } /** - * @param $recurrent - * * @return $this */ public function setRecurrent($recurrent) @@ -385,17 +363,12 @@ public function setRecurrent($recurrent) return $this; } - /** - * @return mixed - */ public function getRecurrentPayment() { return $this->recurrentPayment; } /** - * @param $recurrentPayment - * * @return $this */ public function setRecurrentPayment($recurrentPayment) @@ -405,17 +378,12 @@ public function setRecurrentPayment($recurrentPayment) return $this; } - /** - * @return mixed - */ public function getCreditCard() { return $this->creditCard; } /** - * @param CreditCard $creditCard - * * @return $this */ public function setCreditCard(CreditCard $creditCard) @@ -425,17 +393,12 @@ public function setCreditCard(CreditCard $creditCard) return $this; } - /** - * @return mixed - */ public function getDebitCard() { return $this->debitCard; } /** - * @param mixed $debitCard - * * @return $this */ public function setDebitCard($debitCard) @@ -445,17 +408,12 @@ public function setDebitCard($debitCard) return $this; } - /** - * @return mixed - */ public function getAuthenticationUrl() { return $this->authenticationUrl; } /** - * @param $authenticationUrl - * * @return $this */ public function setAuthenticationUrl($authenticationUrl) @@ -465,17 +423,12 @@ public function setAuthenticationUrl($authenticationUrl) return $this; } - /** - * @return mixed - */ public function getTid() { return $this->tid; } /** - * @param $tid - * * @return $this */ public function setTid($tid) @@ -485,17 +438,12 @@ public function setTid($tid) return $this; } - /** - * @return mixed - */ public function getProofOfSale() { return $this->proofOfSale; } /** - * @param $proofOfSale - * * @return $this */ public function setProofOfSale($proofOfSale) @@ -505,17 +453,12 @@ public function setProofOfSale($proofOfSale) return $this; } - /** - * @return mixed - */ public function getAuthorizationCode() { return $this->authorizationCode; } /** - * @param $authorizationCode - * * @return $this */ public function setAuthorizationCode($authorizationCode) @@ -534,8 +477,6 @@ public function getSoftDescriptor() } /** - * @param $softDescriptor - * * @return $this */ public function setSoftDescriptor($softDescriptor) @@ -545,17 +486,12 @@ public function setSoftDescriptor($softDescriptor) return $this; } - /** - * @return mixed - */ public function getReturnUrl() { return $this->returnUrl; } /** - * @param $returnUrl - * * @return $this */ public function setReturnUrl($returnUrl) @@ -565,17 +501,12 @@ public function setReturnUrl($returnUrl) return $this; } - /** - * @return mixed - */ public function getProvider() { return $this->provider; } /** - * @param $provider - * * @return $this */ public function setProvider($provider) @@ -585,17 +516,12 @@ public function setProvider($provider) return $this; } - /** - * @return mixed - */ public function getPaymentId() { return $this->paymentId; } /** - * @param $paymentId - * * @return $this */ public function setPaymentId($paymentId) @@ -605,17 +531,12 @@ public function setPaymentId($paymentId) return $this; } - /** - * @return mixed - */ public function getType() { return $this->type; } /** - * @param $type - * * @return $this */ public function setType($type) @@ -625,17 +546,12 @@ public function setType($type) return $this; } - /** - * @return mixed - */ public function getAmount() { return $this->amount; } /** - * @param $amount - * * @return $this */ public function setAmount($amount) @@ -645,17 +561,12 @@ public function setAmount($amount) return $this; } - /** - * @return mixed - */ public function getReceivedDate() { return $this->receivedDate; } /** - * @param $receivedDate - * * @return $this */ public function setReceivedDate($receivedDate) @@ -665,17 +576,12 @@ public function setReceivedDate($receivedDate) return $this; } - /** - * @return mixed - */ public function getCapturedAmount() { return $this->capturedAmount; } /** - * @param $capturedAmount - * * @return $this */ public function setCapturedAmount($capturedAmount) @@ -685,17 +591,12 @@ public function setCapturedAmount($capturedAmount) return $this; } - /** - * @return mixed - */ public function getCapturedDate() { return $this->capturedDate; } /** - * @param $capturedDate - * * @return $this */ public function setCapturedDate($capturedDate) @@ -705,17 +606,12 @@ public function setCapturedDate($capturedDate) return $this; } - /** - * @return mixed - */ public function getVoidedAmount() { return $this->voidedAmount; } /** - * @param $voidedAmount - * * @return $this */ public function setVoidedAmount($voidedAmount) @@ -725,17 +621,12 @@ public function setVoidedAmount($voidedAmount) return $this; } - /** - * @return mixed - */ public function getVoidedDate() { return $this->voidedDate; } /** - * @param $voidedDate - * * @return $this */ public function setVoidedDate($voidedDate) @@ -745,17 +636,12 @@ public function setVoidedDate($voidedDate) return $this; } - /** - * @return mixed - */ public function getCurrency() { return $this->currency; } /** - * @param $currency - * * @return $this */ public function setCurrency($currency) @@ -765,17 +651,12 @@ public function setCurrency($currency) return $this; } - /** - * @return mixed - */ public function getCountry() { return $this->country; } /** - * @param $country - * * @return $this */ public function setCountry($country) @@ -785,17 +666,12 @@ public function setCountry($country) return $this; } - /** - * @return mixed - */ public function getReturnCode() { return $this->returnCode; } /** - * @param $returnCode - * * @return $this */ public function setReturnCode($returnCode) @@ -805,17 +681,12 @@ public function setReturnCode($returnCode) return $this; } - /** - * @return mixed - */ public function getReturnMessage() { return $this->returnMessage; } /** - * @param $returnMessage - * * @return $this */ public function setReturnMessage($returnMessage) @@ -825,17 +696,12 @@ public function setReturnMessage($returnMessage) return $this; } - /** - * @return mixed - */ public function getStatus() { return $this->status; } /** - * @param $status - * * @return $this */ public function setStatus($status) @@ -845,17 +711,12 @@ public function setStatus($status) return $this; } - /** - * @return mixed - */ public function getLinks() { return $this->links; } /** - * @param $links - * * @return $this */ public function setLinks($links) @@ -865,17 +726,12 @@ public function setLinks($links) return $this; } - /** - * @return mixed - */ public function getExtraDataCollection() { return $this->extraDataCollection; } /** - * @param $extraDataCollection - * * @return $this */ public function setExtraDataCollection($extraDataCollection) @@ -885,17 +741,12 @@ public function setExtraDataCollection($extraDataCollection) return $this; } - /** - * @return mixed - */ public function getExpirationDate() { return $this->expirationDate; } /** - * @param $expirationDate - * * @return $this */ public function setExpirationDate($expirationDate) @@ -905,17 +756,12 @@ public function setExpirationDate($expirationDate) return $this; } - /** - * @return mixed - */ public function getUrl() { return $this->url; } /** - * @param $url - * * @return $this */ public function setUrl($url) @@ -925,17 +771,12 @@ public function setUrl($url) return $this; } - /** - * @return mixed - */ public function getNumber() { return $this->number; } /** - * @param $number - * * @return $this */ public function setNumber($number) @@ -945,17 +786,12 @@ public function setNumber($number) return $this; } - /** - * @return mixed - */ public function getBoletoNumber() { return $this->boletoNumber; } /** - * @param $boletoNumber - * * @return $this */ public function setBoletoNumber($boletoNumber) @@ -965,17 +801,12 @@ public function setBoletoNumber($boletoNumber) return $this; } - /** - * @return mixed - */ public function getBarCodeNumber() { return $this->barCodeNumber; } /** - * @param $barCodeNumber - * * @return $this */ public function setBarCodeNumber($barCodeNumber) @@ -985,17 +816,12 @@ public function setBarCodeNumber($barCodeNumber) return $this; } - /** - * @return mixed - */ public function getDigitableLine() { return $this->digitableLine; } /** - * @param $digitableLine - * * @return $this */ public function setDigitableLine($digitableLine) @@ -1005,17 +831,12 @@ public function setDigitableLine($digitableLine) return $this; } - /** - * @return mixed - */ public function getAddress() { return $this->address; } /** - * @param $address - * * @return $this */ public function setAddress($address) @@ -1025,17 +846,12 @@ public function setAddress($address) return $this; } - /** - * @return mixed - */ public function getAssignor() { return $this->assignor; } /** - * @param $assignor - * * @return $this */ public function setAssignor($assignor) @@ -1045,17 +861,12 @@ public function setAssignor($assignor) return $this; } - /** - * @return mixed - */ public function getDemonstrative() { return $this->demonstrative; } /** - * @param $demonstrative - * * @return $this */ public function setDemonstrative($demonstrative) @@ -1065,17 +876,12 @@ public function setDemonstrative($demonstrative) return $this; } - /** - * @return mixed - */ public function getIdentification() { return $this->identification; } /** - * @param $identification - * * @return $this */ public function setIdentification($identification) @@ -1085,17 +891,12 @@ public function setIdentification($identification) return $this; } - /** - * @return mixed - */ public function getInstructions() { return $this->instructions; } /** - * @param $instructions - * * @return $this */ public function setInstructions($instructions) @@ -1104,4 +905,58 @@ public function setInstructions($instructions) return $this; } + + /** + * @return string|null + */ + public function getAcquirerTransactionId() + { + return $this->acquirerTransactionId; + } + + /** + * @return $this + */ + public function setAcquirerTransactionId($acquirerTransactionId) + { + $this->acquirerTransactionId = $acquirerTransactionId; + + return $this; + } + + /** + * @return string|null + */ + public function getQrcodeBase64Image() + { + return $this->qrcodeBase64Image; + } + + /** + * @return $this + */ + public function setQrcodeBase64Image($qrcodeBase64Image) + { + $this->qrcodeBase64Image = $qrcodeBase64Image; + + return $this; + } + + /** + * @return string|null + */ + public function getQrCodeString() + { + return $this->qrCodeString; + } + + /** + * @return $this + */ + public function setQrCodeString($qrCodeString) + { + $this->qrCodeString = $qrCodeString; + + return $this; + } } diff --git a/src/Cielo/API30/Ecommerce/RecurrentPayment.php b/src/Cielo/API30/Ecommerce/RecurrentPayment.php index 088ccf8..bb144aa 100644 --- a/src/Cielo/API30/Ecommerce/RecurrentPayment.php +++ b/src/Cielo/API30/Ecommerce/RecurrentPayment.php @@ -3,22 +3,19 @@ namespace Cielo\API30\Ecommerce; /** - * Class RecurrentPayment - * - * @package Cielo\API30\Ecommerce + * Class RecurrentPayment. */ class RecurrentPayment implements \JsonSerializable { + public const INTERVAL_MONTHLY = 'Monthly'; - const INTERVAL_MONTHLY = 'Monthly'; + public const INTERVAL_BIMONTHLY = 'Bimonthly'; - const INTERVAL_BIMONTHLY = 'Bimonthly'; + public const INTERVAL_QUARTERLY = 'Quarterly'; - const INTERVAL_QUARTERLY = 'Quarterly'; + public const INTERVAL_SEMIANNUAL = 'SemiAnnual'; - const INTERVAL_SEMIANNUAL = 'SemiAnnual'; - - const INTERVAL_ANNUAL = 'Annual'; + public const INTERVAL_ANNUAL = 'Annual'; private $authorizeNow; private $recurrentPaymentId; @@ -51,8 +48,6 @@ public function __construct($authorizeNow = true) } /** - * @param $json - * * @return RecurrentPayment */ public static function fromJson($json) @@ -68,158 +63,108 @@ public static function fromJson($json) return $recurrentPayment; } - /** - * @param \stdClass $data - */ public function populate(\stdClass $data) { - $this->authorizeNow = isset($data->AuthorizeNow) ? !!$data->AuthorizeNow : false; + $this->authorizeNow = isset($data->AuthorizeNow) ? (bool) $data->AuthorizeNow : false; $this->recurrentPaymentId = isset($data->RecurrentPaymentId) ? $data->RecurrentPaymentId : null; - $this->nextRecurrency = isset($data->NextRecurrency) ? $data->NextRecurrency : null; - $this->startDate = isset($data->StartDate) ? $data->StartDate : null; - $this->endDate = isset($data->EndDate) ? $data->EndDate : null; - $this->interval = isset($data->Interval) ? $data->Interval : null; - - $this->amount = isset($data->Amount) ? $data->Amount : null; - $this->country = isset($data->Country) ? $data->Country : null; - $this->createDate = isset($data->CreateDate) ? $data->CreateDate : null; - $this->currency = isset($data->Currency) ? $data->Currency : null; - $this->currentRecurrencyTry = isset($data->CurrentRecurrencyTry) ? $data->CurrentRecurrencyTry : null; - $this->provider = isset($data->Provider) ? $data->Provider : null; - $this->recurrencyDay = isset($data->RecurrencyDay) ? $data->RecurrencyDay : null; + $this->nextRecurrency = isset($data->NextRecurrency) ? $data->NextRecurrency : null; + $this->startDate = isset($data->StartDate) ? $data->StartDate : null; + $this->endDate = isset($data->EndDate) ? $data->EndDate : null; + $this->interval = isset($data->Interval) ? $data->Interval : null; + + $this->amount = isset($data->Amount) ? $data->Amount : null; + $this->country = isset($data->Country) ? $data->Country : null; + $this->createDate = isset($data->CreateDate) ? $data->CreateDate : null; + $this->currency = isset($data->Currency) ? $data->Currency : null; + $this->currentRecurrencyTry = isset($data->CurrentRecurrencyTry) ? $data->CurrentRecurrencyTry : null; + $this->provider = isset($data->Provider) ? $data->Provider : null; + $this->recurrencyDay = isset($data->RecurrencyDay) ? $data->RecurrencyDay : null; $this->successfulRecurrences = isset($data->SuccessfulRecurrences) ? $data->SuccessfulRecurrences : null; - $this->links = isset($data->Links) ? $data->Links : []; + $this->links = isset($data->Links) ? $data->Links : []; $this->recurrentTransactions = isset($data->RecurrentTransactions) ? $data->RecurrentTransactions : []; - $this->reasonCode = isset($data->ReasonCode) ? $data->ReasonCode : null; + $this->reasonCode = isset($data->ReasonCode) ? $data->ReasonCode : null; $this->reasonMessage = isset($data->ReasonMessage) ? $data->ReasonMessage : null; - $this->status = isset($data->Status) ? $data->Status : null; + $this->status = isset($data->Status) ? $data->Status : null; } - /** - * @return array - */ - public function jsonSerialize() + public function jsonSerialize(): mixed { return get_object_vars($this); } - /** - * @return mixed - */ public function getRecurrentPaymentId() { return $this->recurrentPaymentId; } - /** - * @return mixed - */ public function getReasonCode() { return $this->reasonCode; } - /** - * @return mixed - */ public function getReasonMessage() { return $this->reasonMessage; } - /** - * @return mixed - */ public function getNextRecurrency() { return $this->nextRecurrency; } - /** - * @return mixed - */ public function getAmount() { return $this->amount; } - /** - * @return mixed - */ public function getCountry() { return $this->country; } - /** - * @return mixed - */ public function getCreateDate() { return $this->createDate; } - /** - * @return mixed - */ public function getCurrency() { return $this->currency; } - /** - * @return mixed - */ public function getCurrentRecurrencyTry() { return $this->currentRecurrencyTry; } - /** - * @return mixed - */ public function getProvider() { return $this->provider; } - /** - * @return mixed - */ public function getRecurrencyDay() { return $this->recurrencyDay; } - /** - * @return mixed - */ public function getSuccessfulRecurrences() { return $this->successfulRecurrences; } - /** - * @return mixed - */ public function getStatus() { return $this->status; } - /** - * @return mixed - */ public function getAuthorizeNow() { return $this->authorizeNow; } /** - * @param $authorizeNow - * * @return $this */ public function setAuthorizeNow($authorizeNow) @@ -229,17 +174,12 @@ public function setAuthorizeNow($authorizeNow) return $this; } - /** - * @return mixed - */ public function getStartDate() { return $this->startDate; } /** - * @param $startDate - * * @return $this */ public function setStartDate($startDate) @@ -249,17 +189,12 @@ public function setStartDate($startDate) return $this; } - /** - * @return mixed - */ public function getEndDate() { return $this->endDate; } /** - * @param $endDate - * * @return $this */ public function setEndDate($endDate) @@ -269,17 +204,12 @@ public function setEndDate($endDate) return $this; } - /** - * @return mixed - */ public function getInterval() { return $this->interval; } /** - * @param $interval - * * @return $this */ public function setInterval($interval) diff --git a/src/Cielo/API30/Ecommerce/Request/AbstractRequest.php b/src/Cielo/API30/Ecommerce/Request/AbstractRequest.php index 4c4da2a..78dad14 100644 --- a/src/Cielo/API30/Ecommerce/Request/AbstractRequest.php +++ b/src/Cielo/API30/Ecommerce/Request/AbstractRequest.php @@ -6,54 +6,37 @@ use Psr\Log\LoggerInterface; /** - * Class AbstractSaleRequest - * - * @package Cielo\API30\Ecommerce\Request + * Class AbstractSaleRequest. */ abstract class AbstractRequest { - private $merchant; private $logger; - /** - * AbstractSaleRequest constructor. - * - * @param Merchant $merchant - * @param LoggerInterface|null $logger - */ - public function __construct(Merchant $merchant, LoggerInterface $logger = null) + /** + * AbstractSaleRequest constructor. + */ + public function __construct(Merchant $merchant, ?LoggerInterface $logger = null) { $this->merchant = $merchant; $this->logger = $logger; } - /** - * @param $param - * - * @return mixed - */ - public abstract function execute($param); + abstract public function execute($param); /** - * @param $method - * @param $url - * @param \JsonSerializable|null $content - * - * @return mixed - * * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException * @throws \RuntimeException */ - protected function sendRequest($method, $url, \JsonSerializable $content = null) + protected function sendRequest($method, $url, ?\JsonSerializable $content = null) { $headers = [ 'Accept: application/json', - 'Accept-Encoding: gzip', + // 'Accept-Encoding: gzip', 'User-Agent: CieloEcommerce/3.0 PHP SDK', 'MerchantId: ' . $this->merchant->getId(), 'MerchantKey: ' . $this->merchant->getKey(), - 'RequestId: ' . uniqid() + 'RequestId: ' . uniqid(), ]; $curl = curl_init($url); @@ -84,27 +67,29 @@ protected function sendRequest($method, $url, \JsonSerializable $content = null) if ($this->logger !== null) { $this->logger->debug('Requisição', [ - sprintf('%s %s', $method, $url), - $headers, - json_decode(preg_replace('/("cardnumber"):"([^"]{6})[^"]+([^"]{4})"/i', '$1:"$2******$3"', json_encode($content))) - ] + sprintf('%s %s', $method, $url), + $headers, + json_decode(preg_replace('/("cardnumber"):"([^"]{6})[^"]+([^"]{4})"/i', '$1:"$2******$3"', json_encode($content))), + ] ); } - $response = curl_exec($curl); + $response = curl_exec($curl); $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($this->logger !== null) { $this->logger->debug('Resposta', [ sprintf('Código de status: %s', $statusCode), - json_decode($response) + json_decode($response), ]); } if (curl_errno($curl)) { $message = sprintf('cURL error[%s]: %s', curl_errno($curl), curl_error($curl)); - $this->logger->error($message); + if ($this->logger !== null) { + $this->logger->error($message); + } throw new \RuntimeException($message); } @@ -115,11 +100,6 @@ protected function sendRequest($method, $url, \JsonSerializable $content = null) } /** - * @param $statusCode - * @param $responseBody - * - * @return mixed - * * @throws CieloRequestException */ protected function readResponse($statusCode, $responseBody) @@ -133,28 +113,29 @@ protected function readResponse($statusCode, $responseBody) break; case 400: $exception = null; - $response = json_decode($responseBody); - - foreach ($response as $error) { - $cieloError = new CieloError($error->Message, $error->Code); - $exception = new CieloRequestException('Request Error', $statusCode, $exception); - $exception->setCieloError($cieloError); + $response = json_decode($responseBody); + + if (is_array($response) && count($response) > 0) { + foreach ($response as $error) { + $cieloError = new CieloError($error->Message, $error->Code); + $exception = new CieloRequestException('Request Error', $statusCode, $exception); + $exception->setCieloError($cieloError); + } + } else { + $exception = new CieloRequestException("Request Error $statusCode, response: $responseBody", $statusCode); } throw $exception; + case 401: + throw new CieloRequestException('HTTP 401 NotAuthorized', $statusCode, null); case 404: throw new CieloRequestException('Resource not found', 404, null); default: - throw new CieloRequestException('Unknown status', $statusCode); + throw new CieloRequestException("Unknown statusCode $statusCode, response: $responseBody", $statusCode); } return $unserialized; } - /** - * @param $json - * - * @return mixed - */ - protected abstract function unserialize($json); + abstract protected function unserialize($json); } diff --git a/src/Cielo/API30/Ecommerce/Request/CieloError.php b/src/Cielo/API30/Ecommerce/Request/CieloError.php index 1d4b20a..01a5f4e 100644 --- a/src/Cielo/API30/Ecommerce/Request/CieloError.php +++ b/src/Cielo/API30/Ecommerce/Request/CieloError.php @@ -3,22 +3,16 @@ namespace Cielo\API30\Ecommerce\Request; /** - * Class CieloError - * - * @package Cielo\API30\Ecommerce\Request + * Class CieloError. */ class CieloError { - private $code; private $message; /** * CieloError constructor. - * - * @param $message - * @param $code */ public function __construct($message, $code) { @@ -26,17 +20,12 @@ public function __construct($message, $code) $this->setCode($code); } - /** - * @return mixed - */ public function getCode() { return $this->code; } /** - * @param $code - * * @return $this */ public function setCode($code) @@ -46,17 +35,12 @@ public function setCode($code) return $this; } - /** - * @return mixed - */ public function getMessage() { return $this->message; } /** - * @param $message - * * @return $this */ public function setMessage($message) diff --git a/src/Cielo/API30/Ecommerce/Request/CieloRequestException.php b/src/Cielo/API30/Ecommerce/Request/CieloRequestException.php index 640f87e..b04eab1 100644 --- a/src/Cielo/API30/Ecommerce/Request/CieloRequestException.php +++ b/src/Cielo/API30/Ecommerce/Request/CieloRequestException.php @@ -3,13 +3,10 @@ namespace Cielo\API30\Ecommerce\Request; /** - * Class CieloRequestException - * - * @package Cielo\API30\Ecommerce\Request + * Class CieloRequestException. */ class CieloRequestException extends \Exception { - private $cieloError; /** @@ -24,17 +21,12 @@ public function __construct($message, $code, $previous = null) parent::__construct($message, $code, $previous); } - /** - * @return mixed - */ public function getCieloError() { return $this->cieloError; } /** - * @param CieloError $cieloError - * * @return $this */ public function setCieloError(CieloError $cieloError) diff --git a/src/Cielo/API30/Ecommerce/Request/CreateSaleRequest.php b/src/Cielo/API30/Ecommerce/Request/CreateSaleRequest.php index f3c9659..b96bbdd 100644 --- a/src/Cielo/API30/Ecommerce/Request/CreateSaleRequest.php +++ b/src/Cielo/API30/Ecommerce/Request/CreateSaleRequest.php @@ -8,23 +8,16 @@ use Psr\Log\LoggerInterface; /** - * Class CreateSaleRequest - * - * @package Cielo\API30\Ecommerce\Request + * Class CreateSaleRequest. */ class CreateSaleRequest extends AbstractRequest { - private $environment; - /** - * CreateSaleRequest constructor. - * - * @param Merchant $merchant - * @param Environment $environment - * @param LoggerInterface|null $logger - */ - public function __construct(Merchant $merchant, Environment $environment, LoggerInterface $logger = null) + /** + * CreateSaleRequest constructor. + */ + public function __construct(Merchant $merchant, Environment $environment, ?LoggerInterface $logger = null) { parent::__construct($merchant, $logger); @@ -32,9 +25,8 @@ public function __construct(Merchant $merchant, Environment $environment, Logger } /** - * @param $sale + * @return Sale * - * @return null * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException * @throws \RuntimeException */ @@ -46,8 +38,6 @@ public function execute($sale) } /** - * @param $json - * * @return Sale */ protected function unserialize($json) diff --git a/src/Cielo/API30/Ecommerce/Request/QueryRecurrentPaymentRequest.php b/src/Cielo/API30/Ecommerce/Request/QueryRecurrentPaymentRequest.php index 8309772..c23a840 100644 --- a/src/Cielo/API30/Ecommerce/Request/QueryRecurrentPaymentRequest.php +++ b/src/Cielo/API30/Ecommerce/Request/QueryRecurrentPaymentRequest.php @@ -8,23 +8,16 @@ use Psr\Log\LoggerInterface; /** - * Class QueryRecurrentPaymentRequest - * - * @package Cielo\API30\Ecommerce\Request + * Class QueryRecurrentPaymentRequest. */ class QueryRecurrentPaymentRequest extends AbstractRequest { - private $environment; - /** - * QueryRecurrentPaymentRequest constructor. - * - * @param Merchant $merchant - * @param Environment $environment - * @param LoggerInterface|null $logger - */ - public function __construct(Merchant $merchant, Environment $environment, LoggerInterface $logger = null) + /** + * QueryRecurrentPaymentRequest constructor. + */ + public function __construct(Merchant $merchant, Environment $environment, ?LoggerInterface $logger = null) { parent::__construct($merchant, $logger); @@ -32,9 +25,8 @@ public function __construct(Merchant $merchant, Environment $environment, Logger } /** - * @param $recurrentPaymentId + * @return RecurrentPayment * - * @return null * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException * @throws \RuntimeException */ @@ -46,8 +38,6 @@ public function execute($recurrentPaymentId) } /** - * @param $json - * * @return RecurrentPayment */ protected function unserialize($json) diff --git a/src/Cielo/API30/Ecommerce/Request/QuerySaleRequest.php b/src/Cielo/API30/Ecommerce/Request/QuerySaleRequest.php index e7953b2..7d1560d 100644 --- a/src/Cielo/API30/Ecommerce/Request/QuerySaleRequest.php +++ b/src/Cielo/API30/Ecommerce/Request/QuerySaleRequest.php @@ -8,23 +8,16 @@ use Psr\Log\LoggerInterface; /** - * Class QuerySaleRequest - * - * @package Cielo\API30\Ecommerce\Request + * Class QuerySaleRequest. */ class QuerySaleRequest extends AbstractRequest { - private $environment; - /** - * QuerySaleRequest constructor. - * - * @param Merchant $merchant - * @param Environment $environment - * @param LoggerInterface|null $logger - */ - public function __construct(Merchant $merchant, Environment $environment, LoggerInterface $logger = null) + /** + * QuerySaleRequest constructor. + */ + public function __construct(Merchant $merchant, Environment $environment, ?LoggerInterface $logger = null) { parent::__construct($merchant, $logger); @@ -32,9 +25,8 @@ public function __construct(Merchant $merchant, Environment $environment, Logger } /** - * @param $paymentId + * @return Sale * - * @return null * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException * @throws \RuntimeException */ @@ -46,8 +38,6 @@ public function execute($paymentId) } /** - * @param $json - * * @return Sale */ protected function unserialize($json) diff --git a/src/Cielo/API30/Ecommerce/Request/TokenizeCardRequest.php b/src/Cielo/API30/Ecommerce/Request/TokenizeCardRequest.php index 722e367..6b93ad3 100644 --- a/src/Cielo/API30/Ecommerce/Request/TokenizeCardRequest.php +++ b/src/Cielo/API30/Ecommerce/Request/TokenizeCardRequest.php @@ -8,35 +8,32 @@ use Psr\Log\LoggerInterface; /** - * Class CreateCardTokenRequestHandler - * - * @package AppBundle\Handler\Cielo + * Class CreateCardTokenRequestHandler. */ class TokenizeCardRequest extends AbstractRequest { - private $environment; - /** @var Merchant $merchant */ + + /** + * TODO not used. + * + * @var Merchant + * + * @phpstan-ignore-next-line + */ private $merchant; - /** - * CreateCardTokenRequestHandler constructor. - * - * @param Merchant $merchant - * @param Environment $environment - * @param LoggerInterface|null $logger - */ - public function __construct(Merchant $merchant, Environment $environment, LoggerInterface $logger = null) + /** + * CreateCardTokenRequestHandler constructor. + */ + public function __construct(Merchant $merchant, Environment $environment, ?LoggerInterface $logger = null) { parent::__construct($merchant, $logger); - $this->merchant = $merchant; + $this->merchant = $merchant; $this->environment = $environment; } - /** - * @inheritdoc - */ public function execute($param) { $url = $this->environment->getApiUrl() . '1/card/'; @@ -44,9 +41,6 @@ public function execute($param) return $this->sendRequest('POST', $url, $param); } - /** - * @inheritdoc - */ protected function unserialize($json) { return CreditCard::fromJson($json); diff --git a/src/Cielo/API30/Ecommerce/Request/UpdateSaleRequest.php b/src/Cielo/API30/Ecommerce/Request/UpdateSaleRequest.php index 54b9b02..b5c8480 100644 --- a/src/Cielo/API30/Ecommerce/Request/UpdateSaleRequest.php +++ b/src/Cielo/API30/Ecommerce/Request/UpdateSaleRequest.php @@ -8,13 +8,10 @@ use Psr\Log\LoggerInterface; /** - * Class UpdateSaleRequest - * - * @package Cielo\API30\Ecommerce\Request + * Class UpdateSaleRequest. */ class UpdateSaleRequest extends AbstractRequest { - private $environment; private $type; @@ -23,32 +20,28 @@ class UpdateSaleRequest extends AbstractRequest private $amount; - /** - * UpdateSaleRequest constructor. - * - * @param Merchant $type - * @param Merchant $merchant - * @param Environment $environment - * @param LoggerInterface|null $logger - */ - public function __construct($type, Merchant $merchant, Environment $environment, LoggerInterface $logger = null) + /** + * UpdateSaleRequest constructor. + * + * @param string $type + */ + public function __construct($type, Merchant $merchant, Environment $environment, ?LoggerInterface $logger = null) { parent::__construct($merchant, $logger); $this->environment = $environment; - $this->type = $type; + $this->type = $type; } /** - * @param $paymentId + * @return Payment * - * @return null * @throws \Cielo\API30\Ecommerce\Request\CieloRequestException * @throws \RuntimeException */ public function execute($paymentId) { - $url = $this->environment->getApiUrl() . '1/sales/' . $paymentId . '/' . $this->type; + $url = $this->environment->getApiUrl() . '1/sales/' . $paymentId . '/' . $this->type; $params = []; if ($this->amount != null) { @@ -65,8 +58,6 @@ public function execute($paymentId) } /** - * @param $json - * * @return Payment */ protected function unserialize($json) @@ -74,17 +65,12 @@ protected function unserialize($json) return Payment::fromJson($json); } - /** - * @return mixed - */ public function getServiceTaxAmount() { return $this->serviceTaxAmount; } /** - * @param $serviceTaxAmount - * * @return $this */ public function setServiceTaxAmount($serviceTaxAmount) @@ -94,17 +80,12 @@ public function setServiceTaxAmount($serviceTaxAmount) return $this; } - /** - * @return mixed - */ public function getAmount() { return $this->amount; } /** - * @param $amount - * * @return $this */ public function setAmount($amount) diff --git a/src/Cielo/API30/Ecommerce/Sale.php b/src/Cielo/API30/Ecommerce/Sale.php index 07639e7..a03e101 100644 --- a/src/Cielo/API30/Ecommerce/Sale.php +++ b/src/Cielo/API30/Ecommerce/Sale.php @@ -3,13 +3,10 @@ namespace Cielo\API30\Ecommerce; /** - * Class Sale - * - * @package Cielo\API30\Ecommerce + * Class Sale. */ class Sale implements \JsonSerializable { - private $merchantOrderId; private $customer; @@ -19,7 +16,7 @@ class Sale implements \JsonSerializable /** * Sale constructor. * - * @param null $merchantOrderId + * @param string|int $merchantOrderId */ public function __construct($merchantOrderId = null) { @@ -27,13 +24,11 @@ public function __construct($merchantOrderId = null) } /** - * @param $json - * * @return Sale */ public static function fromJson($json) { - $object = json_decode($json); + $object = json_decode($json) ?: json_decode(gzdecode($json)); $sale = new Sale(); $sale->populate($object); @@ -41,9 +36,6 @@ public static function fromJson($json) return $sale; } - /** - * @param \stdClass $data - */ public function populate(\stdClass $data) { $dataProps = get_object_vars($data); @@ -63,17 +55,12 @@ public function populate(\stdClass $data) } } - /** - * @return array - */ - public function jsonSerialize() + public function jsonSerialize(): mixed { return get_object_vars($this); } /** - * @param $name - * * @return Customer */ public function customer($name) @@ -86,7 +73,6 @@ public function customer($name) } /** - * @param $amount * @param int $installments * * @return Payment @@ -100,17 +86,12 @@ public function payment($amount, $installments = 1) return $payment; } - /** - * @return mixed - */ public function getMerchantOrderId() { return $this->merchantOrderId; } /** - * @param $merchantOrderId - * * @return $this */ public function setMerchantOrderId($merchantOrderId) @@ -120,17 +101,12 @@ public function setMerchantOrderId($merchantOrderId) return $this; } - /** - * @return mixed - */ public function getCustomer() { return $this->customer; } /** - * @param Customer $customer - * * @return $this */ public function setCustomer(Customer $customer) @@ -140,17 +116,11 @@ public function setCustomer(Customer $customer) return $this; } - /** - * @return mixed - */ public function getPayment() { return $this->payment; } - /* - * - */ public function setPayment(Payment $payment) { $this->payment = $payment; diff --git a/src/Cielo/API30/Environment.php b/src/Cielo/API30/Environment.php index 92846ad..f98051b 100644 --- a/src/Cielo/API30/Environment.php +++ b/src/Cielo/API30/Environment.php @@ -3,21 +3,19 @@ namespace Cielo\API30; /** - * Interface Environment - * - * @package Cielo\API30 + * Interface Environment. */ interface Environment { /** - * Gets the environment's Api URL + * Gets the environment's Api URL. * * @return string the Api URL */ public function getApiUrl(); /** - * Gets the environment's Api Query URL + * Gets the environment's Api Query URL. * * @return string the Api Query URL */ diff --git a/src/Cielo/API30/Merchant.php b/src/Cielo/API30/Merchant.php index 586d1bf..6f97431 100644 --- a/src/Cielo/API30/Merchant.php +++ b/src/Cielo/API30/Merchant.php @@ -3,9 +3,7 @@ namespace Cielo\API30; /** - * Class Merchant - * - * @package Cielo\API30 + * Class Merchant. */ class Merchant { @@ -14,18 +12,15 @@ class Merchant /** * Merchant constructor. - * - * @param $id - * @param $key */ public function __construct($id, $key) { - $this->id = $id; + $this->id = $id; $this->key = $key; } /** - * Gets the merchant identification number + * Gets the merchant identification number. * * @return string the merchant identification number on Cielo */ @@ -35,7 +30,7 @@ public function getId() } /** - * Gets the merchant identification key + * Gets the merchant identification key. * * @return string the merchant identification key on Cielo */ diff --git a/tests/Unit/SaleTest.php b/tests/Unit/SaleTest.php new file mode 100644 index 0000000..5acaa8b --- /dev/null +++ b/tests/Unit/SaleTest.php @@ -0,0 +1,52 @@ +assertSame('123', $sale->getMerchantOrderId()); + + $payment = $sale->payment(15800); + $this->assertSame($payment, $sale->getPayment()); + $this->assertSame(15800, $payment->getAmount()); + $this->assertSame(1, $payment->getInstallments()); + + $payment = $sale->payment(15800, 7); + $this->assertSame(7, $payment->getInstallments()); + } + + public function testSalePaymentType(): void + { + $sale = new Sale('123'); + $payment = $sale->payment(27400); + + $payment->creditCard('123', CreditCard::VISA) + ->setExpirationDate('12/2018') + ->setCardNumber('0000000000000001') + ->setHolder('Fulano de Tal') + ->setSaveCard(true); + $this->assertSame(Payment::PAYMENTTYPE_CREDITCARD, $payment->getType()); + $this->assertFalse($payment->getCapture()); + + $payment->debitCard('123', CreditCard::VISA) + ->setExpirationDate('12/2018') + ->setCardNumber('0000000000000001') + ->setHolder('Fulano de Tal') + ->setSaveCard(true); + $this->assertSame(Payment::PAYMENTTYPE_DEBITCARD, $payment->getType()); + $this->assertFalse($payment->getCapture()); + + $payment->pix(); + $this->assertSame(Payment::PAYMENTTYPE_PIX, $payment->getType()); + $this->assertTrue($payment->getCapture()); + } +}