From 51e411bef2f2861c8caeaecafcdff8fadfc25f53 Mon Sep 17 00:00:00 2001 From: Leonam Pereira Dias Date: Thu, 9 Aug 2018 10:47:02 -0300 Subject: [PATCH 01/26] transactions: create pending_review status const There's a new status `pending_review` on Pagar.me's API. This PR aims to create a new const and a method `isPendingReview` on `AbstractTransaction` public interface --- lib/Transaction/AbstractTransaction.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/Transaction/AbstractTransaction.php b/lib/Transaction/AbstractTransaction.php index ca08262..40ab1fe 100644 --- a/lib/Transaction/AbstractTransaction.php +++ b/lib/Transaction/AbstractTransaction.php @@ -16,6 +16,7 @@ abstract class AbstractTransaction const WAITING_PAYMENT = 'waiting_payment'; const PENDING_REFUND = 'pending_refund'; const REFUSED = 'refused'; + const PENDING_REVIEW = 'pending_review'; /** * @var int @@ -483,6 +484,14 @@ public function isRefused() return $this->status == self::REFUSED; } + /** + * @return boolean + */ + public function isPendingReview() + { + return $this->status == self::PENDING_REVIEW; + } + /** * @return \PagarMe\Sdk\SplitRule\SplitRuleCollection * @codeCoverageIgnore From 3c1ebee1be312a1665a21100123573b6e450976a Mon Sep 17 00:00:00 2001 From: Eduardo Stuart Date: Sun, 16 Sep 2018 20:04:28 +0200 Subject: [PATCH 02/26] fix - customers without address --- lib/Customer/CustomerBuilder.php | 8 +++++--- tests/unit/Customer/CustomerBuilderTest.php | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/lib/Customer/CustomerBuilder.php b/lib/Customer/CustomerBuilder.php index 427720c..b2a0f74 100644 --- a/lib/Customer/CustomerBuilder.php +++ b/lib/Customer/CustomerBuilder.php @@ -10,9 +10,11 @@ trait CustomerBuilder */ private function buildCustomer($customerData) { - $customerData->address = new Address( - get_object_vars($customerData->addresses[0]) - ); + if (count($customerData->addresses) > 0) { + $customerData->address = new Address( + get_object_vars($customerData->addresses[0]) + ); + } $customerData->phone = new Phone($customerData->phones[0]); diff --git a/tests/unit/Customer/CustomerBuilderTest.php b/tests/unit/Customer/CustomerBuilderTest.php index d4de497..d4ba3da 100644 --- a/tests/unit/Customer/CustomerBuilderTest.php +++ b/tests/unit/Customer/CustomerBuilderTest.php @@ -50,4 +50,18 @@ public function mustNotCreateCustomerFromResponse() $this->assertNull($customer); } + + /** + * @test + */ + public function mustCreateCustomerWithoutAddressCorrectly() + { + // @codingStandardsIgnoreLine + $payload = '{"object":"customer","document_number":"25123317171","document_type":"cpf","name":"John Doe","email":"john@test.com","born_at":null,"gender":null,"date_created":"2016-12-28T19:38:28.618Z","id":122444,"addresses":[],"phones":[{"object":"phone","ddi":"55","ddd":"11","number":"44445555","id":65844}]}'; + + $customer = $this->buildCustomer(json_decode($payload)); + + $this->assertInstanceOf('PagarMe\Sdk\Customer\Customer', $customer); + $this->assertInstanceOf('\DateTime', $customer->getDateCreated()); + } } From 12a71231fb45b45fb095c6400c0be32235499711 Mon Sep 17 00:00:00 2001 From: Eduardo Stuart Date: Sun, 16 Sep 2018 20:05:53 +0200 Subject: [PATCH 03/26] fix - customers without phone --- lib/Customer/CustomerBuilder.php | 4 +++- tests/unit/Customer/CustomerBuilderTest.php | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/Customer/CustomerBuilder.php b/lib/Customer/CustomerBuilder.php index b2a0f74..1e4ebc5 100644 --- a/lib/Customer/CustomerBuilder.php +++ b/lib/Customer/CustomerBuilder.php @@ -16,7 +16,9 @@ private function buildCustomer($customerData) ); } - $customerData->phone = new Phone($customerData->phones[0]); + if (count($customerData->phones) > 0) { + $customerData->phone = new Phone($customerData->phones[0]); + } $customerData->date_created = new \DateTime( $customerData->date_created diff --git a/tests/unit/Customer/CustomerBuilderTest.php b/tests/unit/Customer/CustomerBuilderTest.php index d4ba3da..87ab05b 100644 --- a/tests/unit/Customer/CustomerBuilderTest.php +++ b/tests/unit/Customer/CustomerBuilderTest.php @@ -64,4 +64,18 @@ public function mustCreateCustomerWithoutAddressCorrectly() $this->assertInstanceOf('PagarMe\Sdk\Customer\Customer', $customer); $this->assertInstanceOf('\DateTime', $customer->getDateCreated()); } + + /** + * @test + */ + public function mustCreateCustomerWithoutPhoneCorrectly() + { + // @codingStandardsIgnoreLine + $payload = '{"object":"customer","document_number":"25123317171","document_type":"cpf","name":"John Doe","email":"john@test.com","born_at":null,"gender":null,"date_created":"2016-12-28T19:38:28.618Z","id":122444,"addresses":[{"object":"address","street":"Rua Teste","complementary":null,"street_number":"123","neighborhood":"Centro","city":null,"state":null,"zipcode":"01034020","country":null,"id":68136}],"phones":[]}'; + + $customer = $this->buildCustomer(json_decode($payload)); + + $this->assertInstanceOf('PagarMe\Sdk\Customer\Customer', $customer); + $this->assertInstanceOf('\DateTime', $customer->getDateCreated()); + } } From f8778caeb1f8b5c7177744a4d7b4252ecd6597d5 Mon Sep 17 00:00:00 2001 From: Murilo Henrique Date: Tue, 8 Jan 2019 12:37:12 -0200 Subject: [PATCH 04/26] readme: adds usage instructions --- README.md | 1120 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 1107 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 0cfd8c2..465c601 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,1124 @@ - - # Pagar.me PHP SDK -PHP integration for [Pagar.me API](https://docs.pagar.me/api/) + + +
+ +Integração em PHP para a [Pagar.me API](https://docs.pagar.me/)
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/4c34cc13-e52f-492e-a2f2-dbcd398135a2/mini.png)](https://insight.sensiolabs.com/projects/4c34cc13-e52f-492e-a2f2-dbcd398135a2) [![Coverage Status](https://coveralls.io/repos/github/pagarme/pagarme-php/badge.svg?branch=V3)](https://coveralls.io/github/pagarme/pagarme-php?branch=V3) -## Installation -Via Composer +# Índice + +- [Instalação e configuração](#Instalação-e-configuração) +- [Utilizando a SDK](#Utilizando-a-SDK) + - [Parâmetros page e count](#Parâmetros-page-e-count) + - [Transações](#Transações) + - [Criando uma transação](#Criando-uma-transação) + - [Capturando uma transação](#Capturando-uma-transação) + - [Estornando uma transação](#Estornando-uma-transação) + - [Estornando uma transação parcialmente](#Estornando-uma-transação-parcialmente) + - [Estornando uma transação com split](#Estornando-uma-transação-com-split) + - [Retornando transações](#Retornando-transações) + - [Retornando uma transação](#Retornando-uma-transação) + - [Retornando recebíveis de uma transação](#Retornando-recebíveis-de-uma-transação) + - [Retornando um recebível de uma transação](#Retornando-um-recebível-de-uma-transação) + - [Retornando o histórico de operações de uma transação](#Retornando-o-histórico-de-operações-de-uma-transação) + - [Notificando cliente sobre boleto a ser pago](#Notificando-cliente-sobre-boleto-a-ser-pago) + - [Retornando eventos de uma transação](#Retornando-eventos-de-uma-transação) + - [Calculando Pagamentos Parcelados](#Calculando-pagamentos-parcelados) + - [Testando pagamento de boletos](#Testando-pagamento-de-boletos) + - [Estornos](#Estornos) + - [Cartões](#Cartões) + - [Criando cartões](#Criando-cartões) + - [Retornando cartões](#Retornando-cartões) + - [Retornando um cartão](#Retornando-um-cartão) + - [Planos](#Planos) + - [Criando planos](#Criando-planos) + - [Retornando planos](#Retornando-planos) + - [Retornando um plano](#Retornando-um-plano) + - [Atualizando um plano](#Atualizando-um-plano) + - [Assinaturas](#Assinaturas) + - [Criando assinaturas](#Criando-assinaturas) + - [Split com assinatura](#Split-com-assinatura) + - [Retornando uma assinatura](#Retornando-uma-assinatura) + - [Retornando assinaturas](#Retornando-assinaturas) + - [Atualizando uma assinatura](#Atualizando-uma-assinatura) + - [Cancelando uma assinatura](#Cancelando-uma-assinatura) + - [Transações de assinatura](#Transações-de-assinatura) + - [Pulando cobranças](#Pulando-cobranças) + - [Postbacks](#Postbacks) + - [Retornando postbacks](#Retornando-postbacks) + - [Retornando um postback](#Retornando-um-postback) + - [Reenviando um Postback](#Reenviando-um-postback) + - [Saldo do recebedor principal](#Saldo-do-recebedor-principal) + - [Operações de saldo](#Operações-de-saldo) + - [Histórico das operações](#Histórico-das-operações) + - [Histórico de uma operação específica](#Histórico-de-uma-operação-específica) + - [Recebível](#Recebível) + - [Retornando recebíveis](#Retornando-recebíveis) + - [Retornando um recebível](#Retornando-um-recebível) + - [Transferências](#Transferências) + - [Criando uma transferência](#Criando-uma-transferência) + - [Retornando transferências](#Retornando-transferências) + - [Retornando uma transferência](#Retornando-uma-transferência) + - [Cancelando uma transferência](#Cancelando-uma-transferência) + - [Antecipações](#Antecipações) + - [Criando uma antecipação](#Criando-uma-antecipação) + - [Obtendo os limites de antecipação](#Obtendo-os-limites-de-antecipação) + - [Confirmando uma antecipação building](#Confirmando-uma-antecipação-building) + - [Cancelando uma antecipação pending](#Cancelando-uma-antecipação-pending) + - [Deletando uma antecipação building](#Deletando-uma-antecipação-building) + - [Retornando antecipações](#Retornando-antecipações) + - [Contas bancárias](#Contas-bancárias) + - [Criando uma conta bancária](#Criando-uma-conta-bancária) + - [Retornando uma conta bancária](#Retornando-uma-conta-bancária) + - [Retornando contas bancárias](#Retornando-contas-bancárias) + - [Recebedores](#Recebedores) + - [Criando um recebedor](#Criando-um-recebedor) + - [Retornando recebedores](#Retornando-recebedores) + - [Retornando um recebedor](#Retornando-um-recebedor) + - [Atualizando um recebedor](#Atualizando-um-recebedor) + - [Saldo de um recebedor](#Saldo-de-um-recebedor) + - [Operações de saldo de um recebedor](#Operações-de-saldo-de-um-recebedor) + - [Operação de saldo específica de um recebedor](#Operação-de-saldo-específica-de-um-recebedor) + - [Clientes](#Clientes) + - [Criando um cliente](#Criando-um-cliente) + - [Retornando clientes](#Retornando-clientes) + - [Retornando um cliente](#Retornando-um-cliente) +- [Suporte](#Suporte) +- [Licença](#Licença) +- [Contribuindo](#Contribuindo) + +# Instalação e configuração + +Para utilizar a biblioteca, você pode instalá-la via composer, com o comando: + ```sh -composer require 'pagarme/pagarme-php' +composer require 'pagarme/pagarme-php-v3.7.10' ``` -## Usage -### Basic -First you need to create an PagarMe object with your API-KEY (Avaliable on your [dashboard](https://dashboard.pagar.me/#/myaccount/apikeys)) +Então, basta importá-la para dentro de seu arquivo e instanciar o objeto `PagarMe`: + ```php +require __DIR__.'/vendor/autoload.php'; + $apiKey = 'ak_test_grXijQ4GicOa2BLGZrDRTR5qNQxJW0'; $pagarMe = new \PagarMe\Sdk\PagarMe($apiKey); ``` -### Wiki -Check the [wiki](https://github.com/pagarme/pagarme-php/wiki) for detailed documentation. -### Contributing +Nota: todos os exemplos listados aqui utilizam o objeto `$pagarMe` instanciado acima. + +# Utilizando a SDK + +## Parâmetros page e count + +`$page` representa o número da página e `$count` representa a quantidade de registros. Então, se você utilizar, `$page = 2` e `$count = 20` para buscar um objeto, serão retornados os 20~40 objetos mais recentes + +## Transações + +Nesta seção será explicado como utilizar transações no Pagar.me com essa biblioteca. + +### Criando uma transação + +```php + 13933139]; + +$customer = new \PagarMe\Sdk\Customer\Customer( + [ + 'name' => 'John Dove', + 'email' => 'john@site.com', + 'document_number' => '09130141095', + 'address' => [ + 'street' => 'rua teste', + 'street_number' => 42, + 'neighborhood' => 'centro', + 'zipcode' => '01227200', + 'complementary' => 'Apto 42', + 'city' => 'São Paulo', + 'state' => 'SP', + 'country' => 'Brasil' + ], + 'phone' => [ + 'ddd' => "15", + 'number' =>"987523421" + ], + 'born_at' => '15021994', + 'sex' => 'M' + ] +); + +$card = $pagarMe->card()->create( + '4242424242424242', + 'JOHN DOVE', + '0722' +); + +$recipient1 = $pagarMe->recipient()->get('re_civb4p9l7004xbm6dhsetkpj8'); +$recipient2 = $pagarMe->recipient()->get('re_civb4o6zr003u3m6e8dezzja6'); + +$splitRule1 = $pagarMe->splitRule()->percentageRule( + 40, + $recipient1, + true, // liable + true, // chargeProcessingFee, + true // chargeReminder +); + +$splitRule2 = $pagarMe->splitRule()->percentageRule( + 60, + $recipient, + true, // liable + true, // chargeProcessingFee, + false // chargeReminder +); + +$splitrules = new PagarMe\Sdk\SplitRule\SplitRuleCollection(); +$splitrules[0] = $splitRule1; +$splitrules[1] = $splitRule2; + +// Credit Card Transaction +$transaction = $pagarMe->transaction()->creditCardTransaction( + $amount, + $card, + $customer, + $installments, + $capture, + $postbackUrl, + $metadata, + ["split_rules" => $splitrules] +); + +// Boleto Transaction +$transaction2 = $pagarMe->transaction()->boletoTransaction( + $amount, + $customer, + $postbackUrl, + $metadata, + ["split_rules" => $splitrules] +); +``` + +### Capturando uma transação + +```php +transaction()->get(4752390); +$amountToCapture = 1000; +$metadata = ['idProduto' => '123']; // Parâmetro opcional + +$splitRules = new \PagarMe\Sdk\SplitRule\SplitRuleCollection(); // Parâmetro opcional + +$recipient1 = $pagarMe->recipient()->get('re_cjqgt03fv02bq4k6e3xbxxbia'); +$recipient2 = $pagarMe->recipient()->get('re_cjm0lfmy3001zaq6espflawv2'); + +$splitRule1 = $pagarMe->splitRule()->percentageRule( + 40, + $recipient1, + true, // liable + true, // chargeProcessingFee, + true // chargeReminder +); + +$splitRule2 = $pagarMe->splitRule()->percentageRule( + 60, + $recipient2, + true, // liable + true, // chargeProcessingFee, + false // chargeReminder +); + +$splitRules[] = $splitRule1; +$splitRules[] = $splitRule2; + +$pagarMe->transaction()->capture($transaction, $amountToCapture, $metadata, $splitRules); + +``` + +### Estornando uma transação + +```php +transaction()->get("1627830"); + +// Credit Card Refund +$transaction = $pagarMe->transaction()->creditCardRefund($transaction); + +// Boleto Refund +$bankAccount = $pagarMe->bankAccount()->create( + '341', + '0932', + '58054', + '5', + '26268738888', + 'API BANK ACCOUNT', + '1' +); + +$transaction = $pagarMe->transaction()->boletoRefund($transaciton, $bankAccount); +``` + +Esta funcionalidade também funciona com estornos parciais, ou estornos com split. Por exemplo: + +### Estornando uma transação parcialmente + +```php +transaction()->get("1627835"); +$amountRefunded = 20000; + +// Credit card +$transaction = $pagarMe->transaction()->creditCardRefund( + $transaction, + $amountRefunded +); + +// Boleto +$transaction = $pagarMe->transaction()->boletoRefund( + $transaciton, + $bankAccount, + $amountRefunded +); +``` + +### Estornando uma transação com split + +``` +Não possui essa feature. +``` + +### Retornando transações + +```php +transaction()->getList($page, $count); +``` + +### Retornando uma transação + +```php +transaction()->get($transactionId); +``` + +### Retornando recebíveis de uma transação + +``` +Não possui essa feature. +``` + +### Retornando um recebível de uma transação + +``` +Não possui essa feature. +``` + +### Retornando o histórico de operações de uma transação + +``` +Não possui essa feature. +``` + +### Notificando cliente sobre boleto a ser pago + +``` +Não possui essa feature. +``` + +### Retornando eventos de uma transação + +```php +$transactionId = "1627864"; +$transaction = $pagarMe->transaction()->get($transactionId); +$transactionEvents = $pagarMe->transaction()->events($transaction); +``` + +### Calculando pagamentos parcelados + +Essa rota não é obrigatória para uso. É apenas uma forma de calcular pagamentos parcelados com o Pagar.me. + +Para fins de explicação, utilizaremos os seguintes valores: + +`amount`: 1000, +`free_installments`: 4, +`max_installments`: 12, +`interest_rate`: 3 + +O parâmetro `free_installments` decide a quantidade de parcelas sem juros. Ou seja, se ele for preenchido com o valor `4`, as quatro primeiras parcelas não terão alteração em seu valor original. + +Nessa rota, é calculado juros simples, efetuando o seguinte calculo: + +valorTotal = valorDaTransacao * ( 1 + ( taxaDeJuros * numeroDeParcelas ) / 100 ) + +Então, utilizando os valores acima, na quinta parcela, a conta ficaria dessa maneira: + +valorTotal = 1000 * (1 + (3 * 5) / 100) + +Então, o valor a ser pago na quinta parcela seria de 15% da compra, totalizando 1150. + +Você pode usar o código abaixo caso queira utilizar essa rota: + +```php +calculation()->calculateInstallmentsAmount( + $amount, + $rate, + $rateFreeInstallments, + $maxInstallments +); + +$totalAmount = $installments[2]["total_amount"]; +$installmentAmount = $installments[2]["installment_amount"]; +``` + +### Testando pagamento de boletos + +```php +transaction()->payTransaction(1627871); +``` + +## Estornos + +Você pode visualizar todos os estornos que ocorreram em sua conta, com esse código: + +``` +Não possui essa feature. +``` + +## Cartões + +Sempre que você faz uma requisição através da nossa API, nós guardamos as informações do portador do cartão, para que, futuramente, você possa utilizá-las em novas cobranças, ou até mesmo implementar features como one-click-buy. + +### Criando cartões + +```php +card()->create( + $cardNumber, + $cardHolderName, + $cardExpirationDate, + $cardCvv +); + +//Create with card_hash +$card = $pagarMe->card()->createFromHash('card_hash'); +``` + +### Retornando cartões + +``` +Não possui essa feature. +``` + +### Retornando um cartão + +```php +$cardId = 'card_cj428xxsx01dt3f6dvre6belx'; +$card = $pagarMe->card()->get(cardId); +``` + +## Planos + +Representa uma configuração de recorrência a qual um cliente consegue assinar. +É a entidade que define o preço, nome e periodicidade da recorrência + +### Criando planos + +```php +$amount = 15000; +$days = 30; +$name = 'The Pro Plan - Platinum - Best Ever'; +$trialDays = 0; +$paymentsMethods = ['credit_card', 'boleto']; +$charges = null; +$installments = 1; + +$plan = $pagarMe->plan()->create( + $amount, + $days, + $name, + $trialDays, + $paymentsMethods, + $charges, + $installments +); +``` + +### Retornando planos + +```php +plan()->getList($page, $count); +``` + +### Retornando um plano + +```php +plan()->get(164526); +``` + +### Atualizando um plano + +```php +plan()->get(163871); +$oldPlan->setName('The Pro Plan - Susan'); +$oldPlan->setTrialDays('7'); + +$newPlan = $pagarMe->plan()->update($oldPlan); +``` + +## Assinaturas + +### Criando assinaturas + +```php +plan()->get($planId); + +$cardId = 'card_cizri9czn00csfi6e1ygzw9vz'; +$card = $pagarMe->card()->get($cardId); +$metadata = ['idAssinatura' => '123']; +$extraAttributtes = [ + 'soft_descriptor' => 'Minha empresa' +]; + +$postbackUrl = 'http://requestb.in/zyn5obzy'; + +$customer = new \PagarMe\Sdk\Customer\Customer( + [ + 'name' => 'John Dove', + 'email' => 'john@site.com', + 'document_number' => '09130141095', + 'address' => new \PagarMe\Sdk\Customer\Address([ + 'street' => 'rua teste', + 'street_number' => 42, + 'neighborhood' => 'centro', + 'zipcode' => '01227200', + 'complementary' => 'Apto 42', + 'city' => 'São Paulo', + 'state' => 'SP', + 'country' => 'Brasil' + ]), + 'phone' => new \PagarMe\Sdk\Customer\Phone([ + 'ddd' => "15", + 'number' =>"987523421" + ]), + 'born_at' => '15021994', + 'sex' => 'M' + ] +); + +// Credit card subscription +$subscription = $pagarMe->subscription()->createCardSubscription( + $plan, + $card, + $customer, + $postbackUrl, + $metadata, + $extraAttributes +); + +// Boleto Subscription +$subscription = $pagarMe->subscription()->createBoletoSubscription( + $transaction, + $customer, + $postbackUrl, + $metadata, + $extraAttributtes +); +``` + +### Split com assinatura + +```php +plan()->get($planId); + +$cardId = 'card_cizri9czn00csfi6e1ygzw9vz'; +$card = $pagarMe->card()->get($cardId); +$metadata = ['idAssinatura' => '123']; + +$postbackUrl = 'http://requestb.in/zyn5obzy'; + +$customer = new \PagarMe\Sdk\Customer\Customer( + [ + 'name' => 'John Dove', + 'email' => 'john@site.com', + 'document_number' => '09130141095', + 'address' => new \PagarMe\Sdk\Customer\Address([ + 'street' => 'rua teste', + 'street_number' => 42, + 'neighborhood' => 'centro', + 'zipcode' => '01227200', + 'complementary' => 'Apto 42', + 'city' => 'São Paulo', + 'state' => 'SP', + 'country' => 'Brasil' + ]), + 'phone' => new \PagarMe\Sdk\Customer\Phone([ + 'ddd' => "15", + 'number' =>"987523421" + ]), + 'born_at' => '15021994', + 'sex' => 'M' + ] +); + +$splitRules = new \PagarMe\Sdk\SplitRule\SplitRuleCollection(); + +$recipient1 = $pagarMe->recipient()->get('re_cjqgt03fv02bq4k6e3xbxxbia'); +$recipient2 = $pagarMe->recipient()->get('re_cjm0lfmy3001zaq6espflawv2'); + +$splitRule1 = $pagarMe->splitRule()->percentageRule( + 40, + $recipient1, + true, // liable + true, // chargeProcessingFee, + true // chargeReminder +); + +$splitRule2 = $pagarMe->splitRule()->percentageRule( + 60, + $recipient2, + true, // liable + true, // chargeProcessingFee, + false // chargeReminder +); + +$splitRules[] = $splitRule1; +$splitRules[] = $splitRule2; + + +// Credit card subscription +$subscription = $pagarMe->subscription()->createCardSubscription( + $plan, + $card, + $customer, + $postbackUrl, + $metadata, + ['split_rules' => $splitRules] +); + +// Boleto Subscription +$subscription = $pagarMe->subscription()->createBoletoSubscription( + $transaction, + $customer, + $postbackUrl, + $metadata, + ['split_rules' => $splitRules] +); +``` + +### Retornando uma assinatura + +```php +subscription()->get(205881); +``` + +### Retornando assinaturas + +```php +subscription()->getList($page, $count); +``` + +### Atualizando uma assinatura + +```php +subscription()->get(184577); +$newPlan = $pagarMe->plan()->get(166234); +$subscription->setPlan($newPlan); +$subscription->setPaymentMethod('credit_card'); +$card = $pagarMe->card()->get('card_cj41mpuhc01bb3f6d8exeo072'); +$subscription->setCard($card); + +$updatedSubscription = $pagarMe->subscription()->update($subscription); +``` + +### Cancelando uma assinatura + +```php +subscription()->get($subscriptionId); +$subscription = $pagarMe->subscription()->cancel($subscription); +``` + +### Transações de assinatura + +```php +subscription()->get($subscriptionId); +$transactions = $pagarMe->subscription()->transactions($subscription); +``` + +### Pulando cobranças + +``` +Não possui essa feature. +``` + +## Postbacks + +Ao criar uma transação ou uma assinatura você tem a opção de passar o parâmetro `postback_url` na requisição. Essa é uma URL do seu sistema que irá então receber notificações a cada alteração de status dessas transações/assinaturas. + +Para obter informações sobre postbacks, 3 informações serão necessárias, sendo elas: `model`, `model_id` e `postback_id`. + +`model`: Se refere ao objeto que gerou aquele POSTback. Pode ser preenchido com o valor `transaction` ou `subscription`. + +`model_id`: Se refere ao ID do objeto que gerou ao POSTback, ou seja, é o ID da transação ou assinatura que você quer acessar os POSTbacks. + +`postback_id`: Se refere à notificação específica. Para cada mudança de status de uma assinatura ou transação, é gerado um POSTback. Cada POSTback pode ter várias tentativas de entregas, que podem ser identificadas pelo campo `deliveries`, e o ID dessas tentativas possui o prefixo `pd_`. O campo que deve ser enviado neste parâmetro é o ID do POSTback, que deve ser identificado pelo prefixo `po_`. + +### Retornando postbacks + +```php +$transactionId = 1159049; +$transaction = $pagarMe->transaction()->get(transactionId); +$postbacks = $pagarMe->postback()->getList($transaction); +``` + +### Retornando um postback + +```php +transaction()->get($transactionId); + +$postbackId = 'po_ciat6ssga0022k06ng8vxg'; +$postbacks = $pagarMe->postback()->get( + $transaction, + $postbackId +); +``` + +### Reenviando um postback + +```php +transaction()->get($transactionId); + +$postbackId = 'po_cj4haa8l4131bpi73glgzbnpp'; +$postbacks = $pagarMe->postback()->redeliver( + $transaction, + $postbackId +); +``` + +### Validando uma requisição de postback + +```php +postback()->validateRequest($postbackBody, $signature) { + echo "POSTback válido"; +} else { + echo "POSTback inválido"; +} +``` + +Observação: o código acima serve somente de exemplo para que o processo de validação funcione. Recomendamos que utilize ferramentas fornecidas por bibliotecas ou frameworks para recuperar estas informações de maneira mais adequada. + +## Saldo do recebedor principal + +Para saber o saldo de sua conta, você pode utilizar esse código: + +```php +balance()->get(); +``` + +## Operações de saldo + +Com este objeto você pode acompanhar todas as movimentações financeiras ocorridas em sua conta Pagar.me. + +### Histórico das operações + +```php +balanceOperation()->getList(); +``` + +### Histórico de uma operação específica + +``` +$operation = $pagarme->balanceOperation()->get(4861); +``` + +## Recebível + +Objeto contendo os dados de um recebível. O recebível (payable) é gerado automaticamente após uma transação ser paga. Para cada parcela de uma transação é gerado um recebível, que também pode ser dividido por recebedor (no caso de um split ter sido feito). + +### Retornando recebíveis + +```php +payable()->getList($page, $count); +``` + +### Retornando um recebível + +```php +payable()->get("573310"); +``` + +## Transferências + +Transferências representam os saques de sua conta. + +### Criando uma transferência + +```php +recipient()->get('re_citkg218g00hl8q6dh1pr5mld'); + +$transfer = $pagarMe->transfer()->create( + $amount, + $recipient +); +``` + +### Retornando transferências + +```php +transfer()->getList($page, $count) +``` + +### Retornando uma transferência + +```php +transfer()->get("16264"); +``` + +### Cancelando uma transferência + +```php +transfer()->get("16264"); +$canceledTransfer = $pagarMe->transfer()->cancel($transfer); +``` + +## Antecipações + +Para entender o que são as antecipações, você deve acessar esse [link](https://docs.pagar.me/docs/overview-antecipacao). + +### Criando uma antecipação + +```php + $recipientId +]); + +$date = new \DateTime(); +$date->add(new \DateInterval("P10D")); +$timeframe = 'end'; +$requestedAmount = 13000; +$build = true; +$anticipation = $pagarMe->bulkAnticipation()->create( + $recipient, + $date, + $timeframe, + $requestedAmount, + $build +); +``` + +### Obtendo os limites de antecipação + +```php + recipientId +]); + +$paymentDate = new \DateTime(); +$paymentDate->add(new \DateInterval("P10D")); +$timeframe = 'end'; +$limits = $pagarMe->bulkAnticipation()->limits( + $recipient, + $paymentDate, + $timeframe +); +``` + +### Confirmando uma antecipação building + +```php + "re_ciu4jif1j007td56dsm17yew9" +]); + +$anticipation = new PagarMe\Sdk\BulkAnticipation\BulkAnticipation([ + "id" => "ba_cj3uppown001gvm6dqgmjw2ce" +]); + +$anticipation = $pagarMe->bulkAnticipation()->confirm( + $recipient, + $anticipation +); +``` + +### Cancelando uma antecipação pending + +```php + "re_ciu4jif1j007td56dsm17yew9" +]); + +$anticipation = new PagarMe\Sdk\BulkAnticipation\BulkAnticipation([ + "id" => "ba_cj3ur2rpl002bpn6ektsnc9lu" +]); + +$anticipation = $pagarMe->bulkAnticipation()->cancel( + $recipient, + $anticipation +); +``` + +### Deletando uma antecipação building + +```php + "re_ciu4jif1j007td56dsm17yew9" +]); + +$anticipation = new PagarMe\Sdk\BulkAnticipation\BulkAnticipation([ + "id" => "ba_cj3us6nal0022v86daxfamp4t" +]); + +$anticipation = $pagarMe->bulkAnticipation()->delete( + $recipient, + $anticipation +); +``` + +### Retornando antecipações + +```php + $recipientId +]); +$anticipationList = $pagarMe->bulkAnticipation()->getList( + $recipient, + $page, + $count +); +``` + +## Contas bancárias + +Contas bancárias identificam para onde será enviado o dinheiro de futuros pagamentos. + +### Criando uma conta bancária + +```php +bankAccount()->create( + $bankCode, + $agenciaNumber, + $accountNumber, + $accountDigit, + $documentNumber, + $legalName, + $agenciaDigit +); +``` + +## Retornando uma conta bancária + +```php +bankAccount()->get($bankAccountId); +``` + +## Retornando contas bancárias + +```php +bankAccount()->getList($page, $count); +``` + +# Recebedores + +Para dividir uma transação entre várias entidades, é necessário ter um recebedor para cada uma dessas entidades. Recebedores contém informações da conta bancária para onde o dinheiro será enviado, e possuem outras informações para saber quanto pode ser antecipado por ele, ou quando o dinheiro de sua conta será sacado automaticamente. + +## Criando um recebedor + +```php + 17490076 +]); + +$transferInterval = "monthly"; +$transferDay = 13; +$transferEnabled = true; +$automaticAnticipationEnabled = true; +$anticipatableVolumePercentage = 42; +$recipient = $pagarMe->recipient()->create( + $bankAccount, + $transferInterval, + $transferDay, + $transferEnabled, + $automaticAnticipationEnabled, + $anticipatableVolumePercentage +); +``` + +### Retornando recebedores + +```php +recipient()->getList($page, $count); +``` + +### Retornando um recebedor + +```php +recipient()->get($recipientId); +``` + +### Atualizando um recebedor + +```php + $recipientId, + "anticipatable_volume_percentage" => "50", + "transfer_enabled" => true, + "transfer_interval" => "monthly", + "transfer_day" => 15, + "bank_account" => new \PagarMe\Sdk\BankAccount\BankAccount([ + "id" => "17492906" + ]) +]); + +$updatedRecipient = $pagarMe->recipient()->update( + $recipient +); +``` + +### Saldo de um recebedor + +```php +recipient()->get($recipientId); +$balance = $pagarMe->recipient()->balance($recipient); +``` + +### Operações de saldo de um recebedor + +```php +recipient()->get($recipientId); +$balance = $pagarMe->recipient()->balanceOperations($recipient, $page, $count); +``` + +### Operação de saldo específica de um recebedor + +```php +recipient()->get($recipientId); +$balanceOperationId = 2043993; +$operation = $pagarMe->recipient()->balanceOperation($recipient, $balanceOperationId); +``` + +## Clientes + +Clientes representam os usuários de sua loja, ou negócio. Este objeto contém informações sobre eles, como nome, e-mail e telefone, além de outros campos. + +### Criando um cliente + +```php +customer()->create( + 'John Dove', + 'john@site.com', + '09130141095', + /** @var $address \PagarMe\Sdk\Customer\Address */ + $address, + /** @var $phone \PagarMe\Sdk\Customer\Phone */ + $phone, + '15021994', + 'M' +); +``` + +### Retornando clientes + +```php +customer()->getList(); +``` + +### Retornando um cliente + +```php +customer()->get(11222); +``` + +# Suporte + +Se você tiver qualquer problema ou sugestão, por favor abra uma issue [aqui](https://github.com/pagarme/pagarme-php/issues). + +# Contribuindo -**Also** checkout our [contributing guide](CONTRIBUTING.md) before you send us any contribution. +Veja nosso [guia de contribuição](CONTRIBUTING.md) antes de nos enviar sua contribuição. From 99f11c7049ba0d33814f562b837771a2ae986594 Mon Sep 17 00:00:00 2001 From: Leonam Pereira Dias Date: Tue, 23 Apr 2019 11:00:44 -0300 Subject: [PATCH 05/26] client: reorder guzzle version compatibility check (#328) It's an edge case but, if two versions of guzzle is installed at the same time, reordering and check the presence of `\GuzzleHttp\Client::createRequest` method avoid errors. --- lib/Client.php | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/lib/Client.php b/lib/Client.php index 6052a1f..bc73437 100644 --- a/lib/Client.php +++ b/lib/Client.php @@ -80,7 +80,18 @@ public function send(RequestInterface $apiRequest) */ private function buildRequest($apiRequest) { - if (class_exists('\\GuzzleHttp\\Message\\Request')) { + if (class_exists('\\GuzzleHttp\\Psr7\\Request')) { + return new \GuzzleHttp\Psr7\Request( + $apiRequest->getMethod(), + $apiRequest->getPath(), + ['Content-Type' => 'application/json'], + json_encode($this->buildBody($apiRequest)) + ); + } + + if (class_exists('\\GuzzleHttp\\Message\\Request') + && method_exists($this->client, 'createRequest') + ) { $options = array_merge( $this->requestOptions, ['json' => $this->buildBody($apiRequest)] @@ -92,15 +103,6 @@ private function buildRequest($apiRequest) ); } - if (class_exists('\\GuzzleHttp\\Psr7\\Request')) { - return new \GuzzleHttp\Psr7\Request( - $apiRequest->getMethod(), - $apiRequest->getPath(), - ['Content-Type' => 'application/json'], - json_encode($this->buildBody($apiRequest)) - ); - } - throw new \Exception("Can't build request"); } From 7c6000632c4766ad133facdfdefddf7176e56e3a Mon Sep 17 00:00:00 2001 From: Lucas Oliveira Date: Fri, 17 May 2019 17:48:49 -0300 Subject: [PATCH 06/26] transaction: create analyzing status (#332) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This pull request adds a new const and method `ìsAnalyzing` on `AbstractTransaction` public interface. --- lib/Transaction/AbstractTransaction.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/Transaction/AbstractTransaction.php b/lib/Transaction/AbstractTransaction.php index 40ab1fe..c5a8ef8 100644 --- a/lib/Transaction/AbstractTransaction.php +++ b/lib/Transaction/AbstractTransaction.php @@ -17,6 +17,7 @@ abstract class AbstractTransaction const PENDING_REFUND = 'pending_refund'; const REFUSED = 'refused'; const PENDING_REVIEW = 'pending_review'; + const ANALYZING = 'analyzing'; /** * @var int @@ -492,6 +493,14 @@ public function isPendingReview() return $this->status == self::PENDING_REVIEW; } + /** + * @return boolean + */ + public function isAnalyzing() + { + return $this->status == self::ANALYZING; + } + /** * @return \PagarMe\Sdk\SplitRule\SplitRuleCollection * @codeCoverageIgnore From 97545f554828c195784d805370eda1326389ac16 Mon Sep 17 00:00:00 2001 From: Murilo Henrique Nascimento Souza Date: Fri, 24 May 2019 11:35:39 -0300 Subject: [PATCH 07/26] headers: add X-PagarMe-User-Agent and User-Agent (#330) * add X-PagarMe-User-Agent to requests * fix: update sdk version --- lib/PagarMe.php | 6 ++- lib/RequestHeaders.php | 65 +++++++++++++++++++++++++++++++ tests/unit/RequestHeadersTest.php | 46 ++++++++++++++++++++++ 3 files changed, 116 insertions(+), 1 deletion(-) create mode 100644 lib/RequestHeaders.php create mode 100644 tests/unit/RequestHeadersTest.php diff --git a/lib/PagarMe.php b/lib/PagarMe.php index bec8f1a..aad7501 100644 --- a/lib/PagarMe.php +++ b/lib/PagarMe.php @@ -25,6 +25,8 @@ class PagarMe { + const VERSION = '3.8.1'; + /** * @param Client */ @@ -136,13 +138,15 @@ public function __construct( $headers = [], $requestOptions = [] ) { + $requestHeaders = new RequestHeaders(); + $this->client = new Client( new GuzzleClient( [ 'base_url' => 'https://api.pagar.me/1/', 'base_uri' => 'https://api.pagar.me/1/', 'defaults' => [ - 'headers' => $headers + 'headers' => $requestHeaders->getSdkHeaders($headers) ] ] ), diff --git a/lib/RequestHeaders.php b/lib/RequestHeaders.php new file mode 100644 index 0000000..2349306 --- /dev/null +++ b/lib/RequestHeaders.php @@ -0,0 +1,65 @@ +addUserAgentHeader($headers); + $headerWithPagarMeUserAgent = $this->addPagarMeUserAgentHeader( + $headerWithUserAgent + ); + + return $headerWithPagarMeUserAgent; + } + + /** + * @param array $headers + * + * @return array + */ + private function addPagarMeUserAgentHeader($headers) + { + if (isset($headers['X-PagarMe-User-Agent'])) { + $headers['X-PagarMe-User-Agent'] .= ' ' . $this->getDefaultHeaders(); + + return $headers; + } + + $headers['X-PagarMe-User-Agent'] = $this->getDefaultHeaders(); + + return $headers; + } + + /** + * @param array $headers + * + * @return array + */ + private function addUserAgentHeader($headers) + { + if (isset($headers['User-Agent'])) { + $headers['User-Agent'] .= ' ' . $this->getDefaultHeaders(); + + return $headers; + } + + $headers['User-Agent'] = $this->getDefaultHeaders(); + + return $headers; + } + + /** + * @return string + */ + private function getDefaultHeaders() + { + return 'pagarme-php/' . PagarMe::VERSION; + } +} diff --git a/tests/unit/RequestHeadersTest.php b/tests/unit/RequestHeadersTest.php new file mode 100644 index 0000000..473474a --- /dev/null +++ b/tests/unit/RequestHeadersTest.php @@ -0,0 +1,46 @@ +getSdkHeaders([]); + $expectedUserAgent = sprintf( + 'pagarme-php/%s', + PagarMe::VERSION + ); + $expectedHeaders = [ + 'X-PagarMe-User-Agent' => $expectedUserAgent, + 'User-Agent' => $expectedUserAgent + ]; + + $this->assertEquals($defaultHeaders, $expectedHeaders); + + $filledHeaders = [ + 'X-PagarMe-User-Agent' => 'Magento/1.9.1.0', + 'User-Agent' => 'Magento/1.9.1.0' + ]; + + $sdkHeadersFilled = $requestHeaders->getSdkHeaders($filledHeaders); + + $expectedUserAgent = sprintf( + 'Magento/1.9.1.0 pagarme-php/%s', + PagarMe::VERSION + ); + $expectedHeaders = [ + 'X-PagarMe-User-Agent' => $expectedUserAgent, + 'User-Agent' => $expectedUserAgent + ]; + + $this->assertEquals($sdkHeadersFilled, $expectedHeaders); + } +} From 577dc1d5f43bd5bb723cc791f780d24e7b6bec47 Mon Sep 17 00:00:00 2001 From: willian-soaresferreira Date: Tue, 8 Sep 2020 18:04:07 -0300 Subject: [PATCH 08/26] fix: refactor useragent header v3 --- lib/RequestHeaders.php | 2 +- tests/unit/RequestHeadersTest.php | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/lib/RequestHeaders.php b/lib/RequestHeaders.php index 2349306..38b76f2 100644 --- a/lib/RequestHeaders.php +++ b/lib/RequestHeaders.php @@ -60,6 +60,6 @@ private function addUserAgentHeader($headers) */ private function getDefaultHeaders() { - return 'pagarme-php/' . PagarMe::VERSION; + return 'pagarme-php/' . PagarMe::VERSION . ' php/' . phpversion(); } } diff --git a/tests/unit/RequestHeadersTest.php b/tests/unit/RequestHeadersTest.php index 473474a..c74058d 100644 --- a/tests/unit/RequestHeadersTest.php +++ b/tests/unit/RequestHeadersTest.php @@ -15,8 +15,9 @@ public function mustReturnCorrectHeaders() $requestHeaders = new RequestHeaders(); $defaultHeaders = $requestHeaders->getSdkHeaders([]); $expectedUserAgent = sprintf( - 'pagarme-php/%s', - PagarMe::VERSION + 'pagarme-php/%s php/%s', + PagarMe::VERSION, + phpversion() ); $expectedHeaders = [ 'X-PagarMe-User-Agent' => $expectedUserAgent, @@ -33,8 +34,9 @@ public function mustReturnCorrectHeaders() $sdkHeadersFilled = $requestHeaders->getSdkHeaders($filledHeaders); $expectedUserAgent = sprintf( - 'Magento/1.9.1.0 pagarme-php/%s', - PagarMe::VERSION + 'Magento/1.9.1.0 pagarme-php/%s php/%s', + PagarMe::VERSION, + phpversion() ); $expectedHeaders = [ 'X-PagarMe-User-Agent' => $expectedUserAgent, From 83a1f6afc0d179c63ba9c4c24f8cbaf6f4dcb747 Mon Sep 17 00:00:00 2001 From: willian-soaresferreira Date: Tue, 8 Sep 2020 20:21:25 -0300 Subject: [PATCH 09/26] tests: fix discover installments --- tests/acceptance/features/transaction.feature | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/acceptance/features/transaction.feature b/tests/acceptance/features/transaction.feature index 4873156..91cac30 100644 --- a/tests/acceptance/features/transaction.feature +++ b/tests/acceptance/features/transaction.feature @@ -10,9 +10,9 @@ Feature: Transaction Then a paid transaction must be created Examples: | number | holder | expiration | amount | installments | - | 4556425889100276 | João Silva | 0623 | 20000 | 1 | + | 4556425889100276 | João Silva | 0623 | 20000 | 3 | | 5435375979338399 | Maria Silva | 0623 | 9900 | 7 | - | 30171632321686 | Pedro Silva | 0623 | 250 | 3 | + | 30171632321686 | Pedro Silva | 0623 | 250 | 1 | | 341611978581611 | Cesar Silva | 0623 | 1337 | 12 | | 6062825718246608 | Carla Silva | 0623 | 123456 | 10 | | 6363685469431429 | Marta Silva | 0623 | 1000001 | 1 | @@ -25,9 +25,9 @@ Feature: Transaction And the transaction must be refunded Examples: | number | holder | expiration | amount | installments | - | 4539225249511077 | João Silva | 0623 | 1000 | 1 | + | 4539225249511077 | João Silva | 0623 | 1000 | 3 | | 5326284789092430 | Maria Silva | 0623 | 1300 | 7 | - | 36016500807288 | Pedro Silva | 0623 | 1500 | 3 | + | 36016500807288 | Pedro Silva | 0623 | 1500 | 1 | | 377255656605321 | Cesar Silva | 0623 | 2100 | 12 | | 6062820984030620 | Carla Silva | 0623 | 4000 | 10 | | 5041754009357643 | Marta Silva | 0623 | 5000 | 1 | @@ -40,9 +40,9 @@ Feature: Transaction And the transaction must be refunded with "" Examples: | number | holder | expiration | amount | installments | value | - | 4539225249511077 | João Silva | 0623 | 1000 | 1 | 500 | + | 4539225249511077 | João Silva | 0623 | 1000 | 3 | 500 | | 5326284789092430 | Maria Silva | 0623 | 1300 | 7 | 700 | - | 36016500807288 | Pedro Silva | 0623 | 1500 | 3 | 1300 | + | 36016500807288 | Pedro Silva | 0623 | 1500 | 1 | 1300 | | 377255656605321 | Cesar Silva | 0623 | 2100 | 12 | 2000 | | 6062820984030620 | Carla Silva | 0623 | 4000 | 10 | 1337 | | 5041754009357643 | Marta Silva | 0623 | 5000 | 1 | 2500 | @@ -54,9 +54,9 @@ Feature: Transaction Then a authorized transaction must be created Examples: | number | holder | expiration | amount | installments | - | 4556655568781331 | João Silva | 0623 | 20000 | 1 | + | 4556655568781331 | João Silva | 0623 | 20000 | 3 | | 5312843659611045 | Maria Silva | 0623 | 9900 | 7 | - | 38207356445228 | Pedro Silva | 0623 | 250 | 3 | + | 38207356445228 | Pedro Silva | 0623 | 250 | 1 | | 371604330597394 | Cesar Silva | 0623 | 1337 | 12 | | 6062824410079680 | Carla Silva | 0623 | 123456 | 10 | | 5041754485700738 | Marta Silva | 0623 | 1000001 | 1 | @@ -69,9 +69,9 @@ Feature: Transaction Then a paid transaction must be created Examples: | number | holder | expiration | amount | installments | - | 4539927448873758 | João Silva | 0623 | 20000 | 1 | + | 4539927448873758 | João Silva | 0623 | 20000 | 3 | | 5475972816746627 | Maria Silva | 0623 | 9900 | 7 | - | 30323500265699 | Pedro Silva | 0623 | 250 | 3 | + | 30323500265699 | Pedro Silva | 0623 | 250 | 1 | | 371733354333913 | Cesar Silva | 0623 | 1337 | 12 | | 6062822300852208 | Carla Silva | 0623 | 123456 | 10 | | 4514161325131598 | Marta Silva | 0623 | 1000001 | 1 | @@ -84,9 +84,9 @@ Feature: Transaction Then a paid transaction must be created with "" paid amount Examples: | number | holder | expiration | amount | installments | capture | - | 4556111382970890 | João Silva | 0623 | 20000 | 1 | 14900 | + | 4556111382970890 | João Silva | 0623 | 20000 | 3 | 14900 | | 5157798910157725 | Maria Silva | 0623 | 9900 | 7 | 9899 | - | 30257387840192 | Pedro Silva | 0623 | 250 | 3 | 230 | + | 30257387840192 | Pedro Silva | 0623 | 250 | 1 | 230 | | 345066740083873 | Cesar Silva | 0623 | 1337 | 12 | 509 | | 6062827431932910 | Carla Silva | 0623 | 123456 | 10 | 78910 | | 4514164981119485 | Marta Silva | 0623 | 1000001 | 1 | 10001 | From 3eec91e0cbf780d547a27984aad9275596619411 Mon Sep 17 00:00:00 2001 From: willian-soaresferreira Date: Tue, 8 Sep 2020 20:29:44 -0300 Subject: [PATCH 10/26] tests: fix payables async --- tests/acceptance/TransactionContext.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/acceptance/TransactionContext.php b/tests/acceptance/TransactionContext.php index dff5fcc..922d31f 100644 --- a/tests/acceptance/TransactionContext.php +++ b/tests/acceptance/TransactionContext.php @@ -244,6 +244,8 @@ public function thenTransactionMustBeRetriavable() */ public function thenTransactionPayablesMustBeRetriavable() { + sleep(10); + $payables = self::getPagarMe() ->transaction() ->payables($this->transaction->getId()); From bbada4128ec65d799f992edc71b8ebad91969f7b Mon Sep 17 00:00:00 2001 From: willian-soaresferreira Date: Thu, 10 Sep 2020 12:16:50 -0300 Subject: [PATCH 11/26] tests: specific guzzle version for php 7.2 support --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index c3937e6..862dec5 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ "license": "MIT", "require": { "php": ">=5.4.0", - "guzzlehttp/guzzle": ">=5.3" + "guzzlehttp/guzzle": "5.3.4" }, "require-dev": { "ext-mbstring": "*", From 4c2a949b0dd697bab9da406774cc75d1cd9c0ede Mon Sep 17 00:00:00 2001 From: willian-soaresferreira Date: Thu, 10 Sep 2020 16:33:13 -0300 Subject: [PATCH 12/26] bump version to 3.8.2 --- lib/PagarMe.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/PagarMe.php b/lib/PagarMe.php index aad7501..0a028bf 100644 --- a/lib/PagarMe.php +++ b/lib/PagarMe.php @@ -25,7 +25,7 @@ class PagarMe { - const VERSION = '3.8.1'; + const VERSION = '3.8.2'; /** * @param Client From 3ad6c3538644456fd9ca96df3eed1b5c87491196 Mon Sep 17 00:00:00 2001 From: Matheus-Maciel Date: Mon, 16 Nov 2020 22:35:55 -0300 Subject: [PATCH 13/26] feature/add-pix-payment-method-pagarme-V3 --- lib/PagarMe.php | 18 +++++ lib/PixAdditionalField/PixAdditionalField.php | 42 ++++++++++ .../PixAdditionalFieldBuilder.php | 25 ++++++ .../PixAdditionalFieldCollection.php | 81 +++++++++++++++++++ .../PixAdditionalFieldHandler.php | 23 ++++++ lib/PixAdditionalFieldSerializer.php | 29 +++++++ lib/Transaction/PixTransaction.php | 73 +++++++++++++++++ .../Request/PixTransactionCreate.php | 40 +++++++++ .../Request/PixTransactionRefund.php | 55 +++++++++++++ lib/Transaction/TransactionBuilder.php | 4 + lib/Transaction/TransactionHandler.php | 55 ++++++++++++- 11 files changed, 444 insertions(+), 1 deletion(-) create mode 100644 lib/PixAdditionalField/PixAdditionalField.php create mode 100644 lib/PixAdditionalField/PixAdditionalFieldBuilder.php create mode 100644 lib/PixAdditionalField/PixAdditionalFieldCollection.php create mode 100644 lib/PixAdditionalField/PixAdditionalFieldHandler.php create mode 100644 lib/PixAdditionalFieldSerializer.php create mode 100644 lib/Transaction/PixTransaction.php create mode 100644 lib/Transaction/Request/PixTransactionCreate.php create mode 100644 lib/Transaction/Request/PixTransactionRefund.php diff --git a/lib/PagarMe.php b/lib/PagarMe.php index 0a028bf..ece8b32 100644 --- a/lib/PagarMe.php +++ b/lib/PagarMe.php @@ -10,6 +10,7 @@ use PagarMe\Sdk\Recipient\RecipientHandler; use PagarMe\Sdk\Plan\PlanHandler; use PagarMe\Sdk\SplitRule\SplitRuleHandler; +use PagarMe\Sdk\PixAdditionalField\PixAdditionalFieldHandler; use PagarMe\Sdk\Transfer\TransferHandler; use PagarMe\Sdk\Company\CompanyHandler; use PagarMe\Sdk\BankAccount\BankAccountHandler; @@ -67,6 +68,11 @@ class PagarMe */ private $splitRuleHandler; + /** + * @param PixAdditionalFieldHandler + */ + private $pixAdditionalFieldHandler; + /** * @param TransferHandler */ @@ -240,6 +246,18 @@ public function splitRule() return $this->splitRuleHandler; } + /** + * @return PixAdditionalFieldHandler + */ + public function pixAdditionalField() + { + if (!$this->pixAdditionalFieldHandler instanceof PixAdditionalFieldHandler) { + $this->pixAdditionalFieldHandler = new PixAdditionalFieldHandler(); + } + + return $this->pixAdditionalFieldHandler; + } + /** * @return transferHandler */ diff --git a/lib/PixAdditionalField/PixAdditionalField.php b/lib/PixAdditionalField/PixAdditionalField.php new file mode 100644 index 0000000..31d536d --- /dev/null +++ b/lib/PixAdditionalField/PixAdditionalField.php @@ -0,0 +1,42 @@ +fill($pixAdditionalFieldData); + } + + /** + * @return string + * @codeCoverageIgnore + */ + public function getName() + { + return $this->name; + } + + /** + * @return string + * @codeCoverageIgnore + */ + public function getValue() + { + return $this->value; + } +} diff --git a/lib/PixAdditionalField/PixAdditionalFieldBuilder.php b/lib/PixAdditionalField/PixAdditionalFieldBuilder.php new file mode 100644 index 0000000..ea2c289 --- /dev/null +++ b/lib/PixAdditionalField/PixAdditionalFieldBuilder.php @@ -0,0 +1,25 @@ +date_created = new \DateTime($field->date_created); + $field->date_updated = new \DateTime($field->date_updated); + $fields[] = new PixAdditionalField(get_object_vars($field)); + } + } + + return $fields; + } +} diff --git a/lib/PixAdditionalField/PixAdditionalFieldCollection.php b/lib/PixAdditionalField/PixAdditionalFieldCollection.php new file mode 100644 index 0000000..b59a8a5 --- /dev/null +++ b/lib/PixAdditionalField/PixAdditionalFieldCollection.php @@ -0,0 +1,81 @@ +fields[] = $value; + } else { + $this->fields[$offset] = $value; + } + } + + public function offsetExists($offset) + { + return isset($this->fields[$offset]); + } + + public function offsetUnset($offset) + { + unset($this->fields[$offset]); + } + + public function offsetGet($offset) + { + return isset($this->fields[$offset]) ? $this->fields[$offset] : null; + } + + public function rewind() + { + $this->position = 0; + } + + public function current() + { + return $this->fields[$this->position]; + } + + public function key() + { + return $this->position; + } + + public function next() + { + ++$this->position; + } + + public function valid() + { + return isset($this->fields[$this->position]); + } + + /** + * @return int + */ + public function count() + { + return count($this->fields); + } +} diff --git a/lib/PixAdditionalField/PixAdditionalFieldHandler.php b/lib/PixAdditionalField/PixAdditionalFieldHandler.php new file mode 100644 index 0000000..e511c07 --- /dev/null +++ b/lib/PixAdditionalField/PixAdditionalFieldHandler.php @@ -0,0 +1,23 @@ + $name, + 'value' => $value, + ] + ); + } +} diff --git a/lib/PixAdditionalFieldSerializer.php b/lib/PixAdditionalFieldSerializer.php new file mode 100644 index 0000000..616e9cc --- /dev/null +++ b/lib/PixAdditionalFieldSerializer.php @@ -0,0 +1,29 @@ + $pixAdditionalField) { + $field = [ + 'name' => $pixAdditionalField->getName(), + 'value' => $pixAdditionalField->getValue() + ]; + + $fields[$key] = $field; + } + + return $fields; + } +} diff --git a/lib/Transaction/PixTransaction.php b/lib/Transaction/PixTransaction.php new file mode 100644 index 0000000..ba5e38f --- /dev/null +++ b/lib/Transaction/PixTransaction.php @@ -0,0 +1,73 @@ +paymentMethod = self::PAYMENT_METHOD; + } + + /** + * @return \DateTime + * @codeCoverageIgnore + */ + public function getPixExpirationDate() + { + return $this->pixExpirationDate; + } + + /** + * @return string + * @codeCoverageIgnore + */ + public function getPixQrCode() + { + return $this->pixQrCode; + } + + /** + * @return string + * @codeCoverageIgnore + */ + public function getSoftDescriptor() + { + return $this->softDescriptor; + } + + /** + * @return \PagarMe\Sdk\PixAdditionalField\PixAdditionalFieldCollection + * @codeCoverageIgnore + */ + public function getPixAdditionalFields() + { + return $this->pixAdditionalFields; + } +} diff --git a/lib/Transaction/Request/PixTransactionCreate.php b/lib/Transaction/Request/PixTransactionCreate.php new file mode 100644 index 0000000..5dbd3ff --- /dev/null +++ b/lib/Transaction/Request/PixTransactionCreate.php @@ -0,0 +1,40 @@ +transaction = $transaction; + } + + /** + * return array + */ + public function getPayload() + { + $basicData = parent::getPayload(); + + $pixData = [ + 'pix_expiration_date' => $this->transaction->getPixExpirationDate(), + 'soft_descriptor' => $this->transaction->getSoftDescriptor(), + ]; + + if ($this->transaction->getPixAdditionalFields() instanceof PixAdditionalFieldCollection) { + $pixData['pix_additional_fields'] = $this->getPixAdditionalFieldsInfo( + $this->transaction->getPixAdditionalFields() + ); + } + + return array_merge($basicData, $pixData); + } +} diff --git a/lib/Transaction/Request/PixTransactionRefund.php b/lib/Transaction/Request/PixTransactionRefund.php new file mode 100644 index 0000000..c2f30a4 --- /dev/null +++ b/lib/Transaction/Request/PixTransactionRefund.php @@ -0,0 +1,55 @@ +transaction = $transaction; + $this->amount = $amount; + } + + /** + * @param string + */ + public function getPayload() + { + return [ + 'amount' => $this->amount + ]; + } + + /** + * @param string + */ + public function getPath() + { + return sprintf('transactions/%d/refund', $this->transaction->getId()); + } + + /** + * @param string + */ + public function getMethod() + { + return self::HTTP_POST; + } +} diff --git a/lib/Transaction/TransactionBuilder.php b/lib/Transaction/TransactionBuilder.php index aead47a..bd94823 100644 --- a/lib/Transaction/TransactionBuilder.php +++ b/lib/Transaction/TransactionBuilder.php @@ -54,6 +54,10 @@ private function buildTransaction($transactionData) return new CreditCardTransaction(get_object_vars($transactionData)); } + if ($transactionData->payment_method == PixTransaction::PAYMENT_METHOD) { + return new PixTransaction(get_object_vars($transactionData)); + } + throw new UnsupportedTransaction( sprintf( 'Transaction type: %s, is not supported', diff --git a/lib/Transaction/TransactionHandler.php b/lib/Transaction/TransactionHandler.php index 52c2211..40037df 100644 --- a/lib/Transaction/TransactionHandler.php +++ b/lib/Transaction/TransactionHandler.php @@ -7,6 +7,7 @@ use PagarMe\Sdk\Payable\PayableBuilder; use PagarMe\Sdk\Transaction\Request\CreditCardTransactionCreate; use PagarMe\Sdk\Transaction\Request\BoletoTransactionCreate; +use PagarMe\Sdk\Transaction\Request\PixTransactionCreate; use PagarMe\Sdk\Transaction\Request\TransactionGet; use PagarMe\Sdk\Transaction\Request\TransactionList; use PagarMe\Sdk\Transaction\Request\TransactionCapture; @@ -14,12 +15,14 @@ use PagarMe\Sdk\Transaction\Request\TransactionPayables; use PagarMe\Sdk\Transaction\Request\CreditCardTransactionRefund; use PagarMe\Sdk\Transaction\Request\BoletoTransactionRefund; +use PagarMe\Sdk\Transaction\Request\PixTransactionRefund; use PagarMe\Sdk\Transaction\Request\TransactionPay; use PagarMe\Sdk\BankAccount\BankAccount; use PagarMe\Sdk\Card\Card; use PagarMe\Sdk\Customer\Customer; use PagarMe\Sdk\Recipient\Recipient; use PagarMe\Sdk\SplitRule\SplitRuleCollection; +use PagarMe\Sdk\PixAdditionalField\PixAdditionalFieldCollection; class TransactionHandler extends AbstractHandler { @@ -102,9 +105,46 @@ public function boletoTransaction( return $this->buildTransaction($response); } + /** + * @param int $amount + * @param \PagarMe\Sdk\Customer\Customer $customer + * @param string $postBackUrl + * @param mixed $metadata + * @param \DateTime $pixExpirationDate + * @param array $extraAttributes + * @return PixTransaction + */ + public function pixTransaction( + $amount, + Customer $customer, + $postBackUrl, + $metadata = null, + $pixExpirationDate = null, + $extraAttributes = [] + ) { + $transactionData = array_merge( + [ + 'amount' => $amount, + 'customer' => $customer, + 'postbackUrl' => $postBackUrl, + 'metadata' => $metadata, + 'pix_expiration_date' => $pixExpirationDate + ], + $extraAttributes + ); + + $transaction = new PixTransaction($transactionData); + + $request = new PixTransactionCreate($transaction); + + $response = $this->client->send($request); + + return $this->buildTransaction($response); + } + /** * @param int $transactionId - * @return BoletoTransaction | CreditCardTransaction + * @return BoletoTransaction | CreditCardTransaction | PixTransaction */ public function get($transactionId) { @@ -207,6 +247,19 @@ public function boletoRefund( return $this->buildTransaction($response); } + /** + * @param PixTransaction $transaction + * @param int $amount + * @return PixTransaction + */ + public function pixRefund(PixTransaction $transaction, $amount = null) + { + $request = new PixTransactionRefund($transaction, $amount); + $response = $this->client->send($request); + + return $this->buildTransaction($response); + } + /** * @param BoletoTransaction $transaction * @return BoletoTransaction From fb2c8d42e405a97292709cfdee94bd6f67a56d67 Mon Sep 17 00:00:00 2001 From: Matheus-Maciel Date: Tue, 24 Nov 2020 14:31:39 -0300 Subject: [PATCH 14/26] fix/bulkAnticipation-tests Removed line 109 "assertEquals($this->anticipation->getPaymentDate(), $this->expectedPaymentDate);" from "PagarMe\Acceptance\BulkAnticipationContext::mustAnticipationContainSameData()" because UTC makes test fail. --- tests/acceptance/BulkAnticipationContext.php | 1 - tests/acceptance/features/bulk_anticipation.feature | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/tests/acceptance/BulkAnticipationContext.php b/tests/acceptance/BulkAnticipationContext.php index 114907a..1351d06 100644 --- a/tests/acceptance/BulkAnticipationContext.php +++ b/tests/acceptance/BulkAnticipationContext.php @@ -106,7 +106,6 @@ public function aAnticipationMustBeCreated() */ public function mustAnticipationContainSameData() { - assertEquals($this->anticipation->getPaymentDate(), $this->expectedPaymentDate); assertEquals($this->anticipation->getTimeframe(), $this->expectedTimeframe); assertEquals($this->anticipation->getStatus(), $this->expectedStatus); diff --git a/tests/acceptance/features/bulk_anticipation.feature b/tests/acceptance/features/bulk_anticipation.feature index ce816c3..7b20271 100644 --- a/tests/acceptance/features/bulk_anticipation.feature +++ b/tests/acceptance/features/bulk_anticipation.feature @@ -11,8 +11,8 @@ Feature: Bulk Anticipation And must anticipation contain same data Examples: | payment_date | timeframe | requested_amount | build | - | +5 days | start | 1000 | true | - | +6 days | start | 1000 | false | + | +7 days | start | 1000 | true | + | +7 days | start | 1000 | false | Scenario Outline: Deleting Bulk Anticipation Given a recipient with anticipatable volume @@ -23,4 +23,4 @@ Feature: Bulk Anticipation Then the Anticipation should no longer exist Examples: | payment_date | timeframe | requested_amount | build | - | +5 days | start | 1000 | true | + | +7 days | start | 1000 | true | From 9fbef7a32547786fdac9e0ef1ac314a6ae4c985f Mon Sep 17 00:00:00 2001 From: Matheus-Maciel Date: Tue, 24 Nov 2020 15:13:47 -0300 Subject: [PATCH 15/26] fix/refundTransaction-tests Changed refund amount because new rule of refunds make impossible old refund value --- tests/acceptance/features/transaction.feature | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/acceptance/features/transaction.feature b/tests/acceptance/features/transaction.feature index 91cac30..4125751 100644 --- a/tests/acceptance/features/transaction.feature +++ b/tests/acceptance/features/transaction.feature @@ -27,8 +27,8 @@ Feature: Transaction | number | holder | expiration | amount | installments | | 4539225249511077 | João Silva | 0623 | 1000 | 3 | | 5326284789092430 | Maria Silva | 0623 | 1300 | 7 | - | 36016500807288 | Pedro Silva | 0623 | 1500 | 1 | - | 377255656605321 | Cesar Silva | 0623 | 2100 | 12 | + | 36016500807288 | Pedro Silva | 0623 | 500 | 1 | + | 377255656605321 | Cesar Silva | 0623 | 210 | 2 | | 6062820984030620 | Carla Silva | 0623 | 4000 | 10 | | 5041754009357643 | Marta Silva | 0623 | 5000 | 1 | From 726c037f696a6a81afac90f3f4e2a6c9b84420d9 Mon Sep 17 00:00:00 2001 From: Matheus-Maciel Date: Tue, 24 Nov 2020 16:48:49 -0300 Subject: [PATCH 16/26] fix/bulkAnticipation-tests --- tests/acceptance/BulkAnticipationContext.php | 7 ++++--- tests/acceptance/features/transaction.feature | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/acceptance/BulkAnticipationContext.php b/tests/acceptance/BulkAnticipationContext.php index 1351d06..2f0386c 100644 --- a/tests/acceptance/BulkAnticipationContext.php +++ b/tests/acceptance/BulkAnticipationContext.php @@ -74,7 +74,7 @@ public function registerAAnticipationWith($paymentDate, $timeframe, $requestedAm $paymentDate = new \Datetime('+3 days'); } - $paymentDate->setTime(0, 0, 0); + $paymentDate->setTime(3, 0, 0); $this->expectedPaymentDate = $paymentDate; $this->expectedTimeframe = $timeframe; @@ -106,9 +106,10 @@ public function aAnticipationMustBeCreated() */ public function mustAnticipationContainSameData() { - assertEquals($this->anticipation->getTimeframe(), $this->expectedTimeframe); + assertEquals($this->expectedPaymentDate, $this->anticipation->getPaymentDate()); + assertEquals($this->expectedTimeframe, $this->anticipation->getTimeframe()); - assertEquals($this->anticipation->getStatus(), $this->expectedStatus); + assertEquals($this->expectedStatus, $this->anticipation->getStatus()); } /** diff --git a/tests/acceptance/features/transaction.feature b/tests/acceptance/features/transaction.feature index 4125751..8c72cfa 100644 --- a/tests/acceptance/features/transaction.feature +++ b/tests/acceptance/features/transaction.feature @@ -39,7 +39,7 @@ Feature: Transaction Then refund given "" the transaction And the transaction must be refunded with "" Examples: - | number | holder | expiration | amount | installments | value | + | number | holder | expiration | amount | installments | value | | 4539225249511077 | João Silva | 0623 | 1000 | 3 | 500 | | 5326284789092430 | Maria Silva | 0623 | 1300 | 7 | 700 | | 36016500807288 | Pedro Silva | 0623 | 1500 | 1 | 1300 | From 82a4cd6a4c7d68e9cd0a5899d1b411887a594ece Mon Sep 17 00:00:00 2001 From: Matheus-Maciel Date: Tue, 24 Nov 2020 18:34:24 -0300 Subject: [PATCH 17/26] fix/UTC-BulkAnticipations-tests --- tests/acceptance/BulkAnticipationContext.php | 4 ++-- tests/acceptance/features/bulk_anticipation.feature | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/acceptance/BulkAnticipationContext.php b/tests/acceptance/BulkAnticipationContext.php index 2f0386c..799e021 100644 --- a/tests/acceptance/BulkAnticipationContext.php +++ b/tests/acceptance/BulkAnticipationContext.php @@ -66,12 +66,12 @@ public function registerAAnticipationWith($paymentDate, $timeframe, $requestedAm { $build = filter_var($build, FILTER_VALIDATE_BOOLEAN); - $paymentDate = new \Datetime($paymentDate); + $paymentDate = new \Datetime($paymentDate, new \DateTimeZone('UTC')); $weekday = $paymentDate->format('w'); if (in_array($weekday, [0,6])) { - $paymentDate = new \Datetime('+3 days'); + $paymentDate = new \Datetime('+3 days', new \DateTimeZone('UTC')); } $paymentDate->setTime(3, 0, 0); diff --git a/tests/acceptance/features/bulk_anticipation.feature b/tests/acceptance/features/bulk_anticipation.feature index 7b20271..ce816c3 100644 --- a/tests/acceptance/features/bulk_anticipation.feature +++ b/tests/acceptance/features/bulk_anticipation.feature @@ -11,8 +11,8 @@ Feature: Bulk Anticipation And must anticipation contain same data Examples: | payment_date | timeframe | requested_amount | build | - | +7 days | start | 1000 | true | - | +7 days | start | 1000 | false | + | +5 days | start | 1000 | true | + | +6 days | start | 1000 | false | Scenario Outline: Deleting Bulk Anticipation Given a recipient with anticipatable volume @@ -23,4 +23,4 @@ Feature: Bulk Anticipation Then the Anticipation should no longer exist Examples: | payment_date | timeframe | requested_amount | build | - | +7 days | start | 1000 | true | + | +5 days | start | 1000 | true | From 1b7b7e4ec4facb814c00d5d93af0e8f40400920d Mon Sep 17 00:00:00 2001 From: Feijao Costa Date: Fri, 4 Dec 2020 15:14:20 -0300 Subject: [PATCH 18/26] Update CaseConverter.php --- lib/CaseConverter.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/CaseConverter.php b/lib/CaseConverter.php index e233520..adad2c7 100644 --- a/lib/CaseConverter.php +++ b/lib/CaseConverter.php @@ -4,8 +4,6 @@ trait CaseConverter { - use CaseConverter; - /** * @param string $sentence * @return string From 64f4656cfe728a0a32995223ee2e0b9cd70a018c Mon Sep 17 00:00:00 2001 From: Feijao Costa Date: Fri, 4 Dec 2020 15:22:40 -0300 Subject: [PATCH 19/26] Update composer.json --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 862dec5..0551e9f 100644 --- a/composer.json +++ b/composer.json @@ -1,5 +1,5 @@ { - "name": "pagarme/pagarme-php", + "name": "liveecommerce/pagarme-php", "description": "Pagar.Me PHP Library", "type": "lib", "keywords": [ From a7886ff9af9fa09970a0baeb5cdab958a84b55af Mon Sep 17 00:00:00 2001 From: willian-soaresferreira Date: Mon, 14 Dec 2020 11:43:34 -0300 Subject: [PATCH 20/26] bump version to 3.9.0 --- lib/PagarMe.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/PagarMe.php b/lib/PagarMe.php index ece8b32..288e698 100644 --- a/lib/PagarMe.php +++ b/lib/PagarMe.php @@ -26,7 +26,7 @@ class PagarMe { - const VERSION = '3.8.2'; + const VERSION = '3.9.0'; /** * @param Client From b94472b4c72ed666a72ead611195dcf326d14f87 Mon Sep 17 00:00:00 2001 From: willian-soaresferreira Date: Mon, 14 Dec 2020 16:19:45 -0300 Subject: [PATCH 21/26] fix: refund tests intermittency --- tests/acceptance/TransactionContext.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/acceptance/TransactionContext.php b/tests/acceptance/TransactionContext.php index 922d31f..05da947 100644 --- a/tests/acceptance/TransactionContext.php +++ b/tests/acceptance/TransactionContext.php @@ -299,6 +299,8 @@ public function aPaidTransactionMustBeCreatedWithPaidAmount($amount) */ public function fullRefundTheTransaction() { + sleep(5); + $this->transaction = $transaction = self::getPagarMe() ->transaction() ->creditCardRefund($this->transaction); @@ -318,6 +320,8 @@ public function theTransactionMustBeRefunded() */ public function refundGivenTheTransaction($amount) { + sleep(5); + $this->transaction = $transaction = self::getPagarMe() ->transaction() ->creditCardRefund($this->transaction, $amount); From c1d34ba7b2dfe48b51aeca1fb72c917d2094fa20 Mon Sep 17 00:00:00 2001 From: Feijao Costa Date: Fri, 30 Apr 2021 16:12:01 -0300 Subject: [PATCH 22/26] Update composer.json --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 0551e9f..a39c7d2 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ "license": "MIT", "require": { "php": ">=5.4.0", - "guzzlehttp/guzzle": "5.3.4" + "guzzlehttp/guzzle": ">=5.3.4" }, "require-dev": { "ext-mbstring": "*", From 5e959990ee05225e14c8882da93566d149e05cef Mon Sep 17 00:00:00 2001 From: Feijao Costa Date: Fri, 30 Apr 2021 16:14:42 -0300 Subject: [PATCH 23/26] Update PagarMe.php --- lib/PagarMe.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/PagarMe.php b/lib/PagarMe.php index 288e698..6f2e5d9 100644 --- a/lib/PagarMe.php +++ b/lib/PagarMe.php @@ -26,7 +26,7 @@ class PagarMe { - const VERSION = '3.9.0'; + const VERSION = '3.9.1'; /** * @param Client From 2198dcdcaa4044d1320dadc8d6df0820ba0a2971 Mon Sep 17 00:00:00 2001 From: Feijao Costa Date: Fri, 30 Apr 2021 18:35:42 -0300 Subject: [PATCH 24/26] Update TransactionHandler.php --- lib/Transaction/TransactionHandler.php | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/lib/Transaction/TransactionHandler.php b/lib/Transaction/TransactionHandler.php index 40037df..b4a6541 100644 --- a/lib/Transaction/TransactionHandler.php +++ b/lib/Transaction/TransactionHandler.php @@ -137,9 +137,14 @@ public function pixTransaction( $request = new PixTransactionCreate($transaction); - $response = $this->client->send($request); - - return $this->buildTransaction($response); + try { + $response = $this->client->send($request); + return $this->buildTransaction($response); + } catch (Exception $e) { + $message = $e->getMessage(); + $code = $e->getCode(); + throw new Exception($message, $code); + } } /** From 3ecf9ef6504b7eabb1ac2b9e419b7f9aa627e725 Mon Sep 17 00:00:00 2001 From: Feijao Costa Date: Fri, 30 Apr 2021 18:36:29 -0300 Subject: [PATCH 25/26] Update PagarMe.php --- lib/PagarMe.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/PagarMe.php b/lib/PagarMe.php index 6f2e5d9..0ec812e 100644 --- a/lib/PagarMe.php +++ b/lib/PagarMe.php @@ -26,7 +26,7 @@ class PagarMe { - const VERSION = '3.9.1'; + const VERSION = '3.9.2'; /** * @param Client From 41a868fb832438b38776719ae4765c60501ac50e Mon Sep 17 00:00:00 2001 From: Thais Sandim Date: Thu, 29 Aug 2024 22:56:58 -0300 Subject: [PATCH 26/26] melhorias send request --- composer.json | 2 +- lib/Client.php | 47 +++++++++-------------------------------------- 2 files changed, 10 insertions(+), 39 deletions(-) diff --git a/composer.json b/composer.json index a39c7d2..6b9f76d 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ "license": "MIT", "require": { "php": ">=5.4.0", - "guzzlehttp/guzzle": ">=5.3.4" + "guzzlehttp/guzzle": "7.5.*" }, "require-dev": { "ext-mbstring": "*", diff --git a/lib/Client.php b/lib/Client.php index bc73437..7486e54 100644 --- a/lib/Client.php +++ b/lib/Client.php @@ -53,15 +53,16 @@ public function __construct( */ public function send(RequestInterface $apiRequest) { - $request = $this->buildRequest($apiRequest); + $options = array_merge($this->requestOptions, [ + 'body' => json_encode($this->buildBody($apiRequest)), + 'headers' => [ + 'Content-Type' => 'application/json', + 'ServiceRefererName' => '62fa7b926ae07600199d7dfc' + ] + ]); try { - $response = $this->client->send( - $request, - $this->requestOptions - ); - - return json_decode($response->getBody()->getContents()); + $response = $this->client->request($apiRequest->getMethod(), $apiRequest->getPath(), $options); } catch (\GuzzleHttp\Exception\ClientException $exception) { $message = $exception->getResponse()->getBody()->getContents(); $code = $exception->getResponse()->getStatusCode(); @@ -72,38 +73,8 @@ public function send(RequestInterface $apiRequest) $exception->getCode() ); } - } - - /** - * @param RequestInterface $apiRequest - * @return mixed - */ - private function buildRequest($apiRequest) - { - if (class_exists('\\GuzzleHttp\\Psr7\\Request')) { - return new \GuzzleHttp\Psr7\Request( - $apiRequest->getMethod(), - $apiRequest->getPath(), - ['Content-Type' => 'application/json'], - json_encode($this->buildBody($apiRequest)) - ); - } - - if (class_exists('\\GuzzleHttp\\Message\\Request') - && method_exists($this->client, 'createRequest') - ) { - $options = array_merge( - $this->requestOptions, - ['json' => $this->buildBody($apiRequest)] - ); - return $this->client->createRequest( - $apiRequest->getMethod(), - $apiRequest->getPath(), - $options - ); - } - throw new \Exception("Can't build request"); + return json_decode($response->getBody()->getContents()); } /**