Explorar el Código

refactor: altera service de customer integrado ao pagarme para utilizar a facade http ao inves do sdk do pagarme

Gustavo Mantovani hace 3 semanas
padre
commit
d97d0dff87

+ 17 - 17
app/Http/Requests/RegisterClientRequest.php

@@ -9,24 +9,24 @@ class RegisterClientRequest extends FormRequest
   public function rules(): array
   {
     return [
-      'email'         => 'sometimes|email|nullable',
-      'phone'         => 'sometimes|string|nullable',
-      'name'          => 'sometimes|string|max:255|nullable',
-      'code'          => 'required|string|max:6',
-      'document'      => 'sometimes|string|nullable',
-      'zip_code'      => 'sometimes|string|max:20|nullable',
-      'address'       => 'sometimes|string|max:255|nullable',
-      'number'        => 'sometimes|string|max:20|nullable',
-      'district'      => 'sometimes|string|max:255|nullable',
-      'complement'    => 'sometimes|string|max:255|nullable',
+      'email'          => 'sometimes|email|nullable',
+      'phone'          => 'sometimes|string|nullable',
+      'name'           => 'sometimes|string|max:255|nullable',
+      'code'           => 'required|string|max:6',
+      'document'       => 'sometimes|string|nullable',
+      'zip_code'       => 'sometimes|string|max:20|nullable',
+      'address'        => 'sometimes|string|max:255|nullable',
+      'number'         => 'sometimes|string|max:20|nullable',
+      'district'       => 'sometimes|string|max:255|nullable',
+      'complement'     => 'sometimes|string|max:255|nullable',
       'has_complement' => 'sometimes|boolean|nullable',
-      'nickname'      => 'sometimes|string|max:255|nullable',
-      'instructions'  => 'sometimes|string|max:500|nullable',
-      'address_type'  => 'sometimes|string|in:home,commercial,other|nullable',
-      'city'          => 'sometimes|string|max:255|nullable',
-      'state'         => 'sometimes|string|max:10|nullable',
-      'latitude'      => 'sometimes|numeric|nullable',
-      'longitude'     => 'sometimes|numeric|nullable',
+      'nickname'       => 'sometimes|string|max:255|nullable',
+      'instructions'   => 'sometimes|string|max:500|nullable',
+      'address_type'   => 'sometimes|string|in:home,commercial,other|nullable',
+      'city'           => 'sometimes|string|max:255|nullable',
+      'state'          => 'sometimes|string|max:10|nullable',
+      'latitude'       => 'sometimes|numeric|nullable',
+      'longitude'      => 'sometimes|numeric|nullable',
     ];
   }
 }

+ 121 - 101
app/Services/Pagarme/PagarmeCustomerService.php

@@ -3,21 +3,11 @@
 namespace App\Services\Pagarme;
 
 use App\Models\Client;
+use Illuminate\Support\Facades\Http;
 use Illuminate\Support\Facades\Log;
-use PagarmeApiSDKLib\Authentication\BasicAuthCredentialsBuilder;
-use PagarmeApiSDKLib\Models\CreateAddressRequest;
-use PagarmeApiSDKLib\Models\CreatePhonesRequest;
-use PagarmeApiSDKLib\Models\Builders\CreateAddressRequestBuilder;
-use PagarmeApiSDKLib\Models\Builders\CreateCustomerRequestBuilder;
-use PagarmeApiSDKLib\Models\Builders\CreatePhoneRequestBuilder;
-use PagarmeApiSDKLib\Models\Builders\CreatePhonesRequestBuilder;
-use PagarmeApiSDKLib\PagarmeApiSDKClient;
-use PagarmeApiSDKLib\PagarmeApiSDKClientBuilder;
 
 class PagarmeCustomerService
 {
-    private ?PagarmeApiSDKClient $client = null;
-
     public function createCustomerForClient(Client $client, array $data): ?string
     {
         if (!empty($client->external_customer_id)) {
@@ -26,120 +16,158 @@ class PagarmeCustomerService
 
         $client->loadMissing('user');
 
-        $name = $client->user?->name ?? $data['name'] ?? 'Cliente';
-        $email = $client->user?->email ?? $data['email'] ?? null;
+        $name     = $client->user?->name ?? $data['name'] ?? 'Cliente';
+        $email    = $client->user?->email ?? $data['email'] ?? null;
         $document = $this->sanitizeDigits($client->document ?? $data['document'] ?? null);
 
         if (empty($email) || empty($document)) {
-            Log::warning('Skipping customer creation because the client is missing email or document.', [
-                'client_id' => $client->id,
-                'user_id' => $client->user_id,
-            ]);
+            Log::channel('pagarme')->warning(
+                'Skipping customer creation because the client is missing email or document.',
+                [
+                    'client_id' => $client->id,
+                    'user_id'   => $client->user_id,
+                ]
+            );
 
             return null;
         }
 
         $address = $this->buildAddress($data);
-        $phones = $this->buildPhones($client->user?->phone ?? $data['phone'] ?? null);
-        $code = $client->external_customer_code ?? "client-{$client->id}";
-
-        $customerRequest = CreateCustomerRequestBuilder::init(
-            $name,
-            $email,
-            $document,
-            $this->personType($document),
-            $address,
-            [
+        $phones  = $this->buildPhones($client->user?->phone ?? $data['phone'] ?? null);
+        $code    = $client->external_customer_code ?? "client-{$client->id}";
+
+        $payload = [
+            'name'        => $name,
+            'email'       => $email,
+            'document'    => $document,
+            'type'        => $this->personType($document),
+            'document_type' => $this->documentType($document),
+            'code'        => $code,
+
+            'address' => $address,
+
+            'phones' => $phones,
+
+            'metadata' => [
                 'client_id' => (string) $client->id,
-                'user_id' => (string) ($client->user_id ?? ''),
+                'user_id'   => (string) ($client->user_id ?? ''),
             ],
-            $phones,
-            $code
-        )
-            ->documentType($this->documentType($document))
-            ->build();
-
-        $customer = $this->client()->getCustomersController()->createCustomer(
-            $customerRequest,
-            $this->idempotencyKey($client->id)
-        );
-
-        $customerId = $customer->getId();
+        ];
+
+        $response = $this->pagarmeRequest($client->id)
+            ->post($this->pagarmeUrl('/customers'), $payload);
+
+        if ($response->failed()) {
+            Log::channel('pagarme')->error('Pagar.me customer creation failed', [
+                'status' => $response->status(),
+                'body'   => $response->json() ?? $response->body(),
+                'client' => [
+                    'id'       => $client->id,
+                    'email'    => $email,
+                    'document' => $document,
+                ],
+            ]);
+
+            throw new \RuntimeException('Erro ao criar cliente no Pagar.me.');
+        }
+
+        $customerData = $response->json();
+        $customerId   = $customerData['id'] ?? null;
+
         if (!$customerId) {
+            Log::channel('pagarme')->error('Customer creation returned an empty id.', [
+                'client_id' => $client->id,
+                'response'  => $customerData,
+            ]);
+
             throw new \RuntimeException('Customer creation returned an empty id.');
         }
 
         $client->forceFill([
-            'external_customer_id' => $customerId,
+            'external_customer_id'   => $customerId,
             'external_customer_code' => $code,
         ])->save();
 
         return $customerId;
     }
 
-    private function buildAddress(array $data): CreateAddressRequest
+    //
+
+    private function pagarmeUrl(string $path): string
     {
-        $zipCode = $this->sanitizeDigits($data['zip_code'] ?? null);
-        $street = (string) ($data['address'] ?? '');
-        $number = (string) ($data['number'] ?? '0');
+        return rtrim(config('services.pagarme.base_url'), '/') . '/' . ltrim($path, '/');
+    }
+
+    private function idempotencyKey(int $clientId): string
+    {
+        return "client-{$clientId}-customer";
+    }
+
+    //
+
+    private function buildAddress(array $data): array
+    {
+        $zipCode      = $this->sanitizeDigits($data['zip_code'] ?? null);
+        $street       = (string) ($data['address'] ?? '');
+        $number       = (string) ($data['number'] ?? '0');
         $neighborhood = (string) ($data['district'] ?? '');
-        $city = (string) ($data['city'] ?? '');
-        $state = (string) ($data['state'] ?? '');
-        $country = (string) ($data['country'] ?? 'BR');
-        $complement = (string) ($data['complement'] ?? '');
+        $city         = (string) ($data['city'] ?? '');
+        $state        = (string) ($data['state'] ?? '');
+        $country      = (string) ($data['country'] ?? 'BR');
+        $complement   = (string) ($data['complement'] ?? '');
 
         $line1Parts = array_filter([$number, $street, $neighborhood], static fn ($value) => $value !== '');
+
         $line1 = implode(', ', $line1Parts);
         $line2 = $complement ?: (string) ($data['instructions'] ?? '');
 
-        return CreateAddressRequestBuilder::init(
-            $street,
-            $number,
-            $zipCode,
-            $neighborhood,
-            $city,
-            $state,
-            $country,
-            $complement,
-            $line1,
-            $line2
-        )
-            ->metadata([
+        return [
+            'street'       => $street,
+            'number'       => $number,
+            'zip_code'     => $zipCode,
+            'neighborhood' => $neighborhood,
+            'city'         => $city,
+            'state'        => $state,
+            'country'      => $country,
+            'complement'   => $complement,
+            'line_1'       => $line1,
+            'line_2'       => $line2,
+
+            'metadata' => [
                 'source' => 'register-client',
-            ])
-            ->build();
+            ],
+        ];
     }
 
-    private function buildPhones(?string $phone): CreatePhonesRequest
+    private function buildPhones(?string $phone): array
     {
         $digits = $this->sanitizeDigits($phone);
-        $phonesBuilder = CreatePhonesRequestBuilder::init();
 
         if (empty($digits)) {
-            return $phonesBuilder->build();
+            return [];
         }
 
         $countryCode = '55';
-        $areaCode = substr($digits, 0, 2);
-        $number = substr($digits, 2);
+        $areaCode    = substr($digits, 0, 2);
+        $number      = substr($digits, 2);
 
         if (strlen($digits) <= 2) {
             $areaCode = '';
-            $number = $digits;
+            $number   = $digits;
         }
 
-        $mobilePhone = CreatePhoneRequestBuilder::init()
-            ->countryCode($countryCode)
-            ->areaCode($areaCode)
-            ->number($number)
-            ->type('mobile')
-            ->build();
-
-        return $phonesBuilder
-            ->mobilePhone($mobilePhone)
-            ->build();
+        return [
+            'mobile_phone' => [
+                'country_code' => $countryCode,
+                'area_code'    => $areaCode,
+                'number'       => $number,
+                'type'         => 'mobile',
+            ],
+        ];
     }
 
+    //
+
     private function documentType(string $document): string
     {
         return strlen($document) === 14 ? 'CNPJ' : 'CPF';
@@ -155,31 +183,23 @@ class PagarmeCustomerService
         return preg_replace('/\D+/', '', (string) $value) ?? '';
     }
 
-    private function client(): PagarmeApiSDKClient
-    {
-        if ($this->client) {
-            return $this->client;
-        }
+    //
 
+    private function pagarmeRequest(int $clientId)
+    {
         $secretKey = config('services.pagarme.secret_key');
+
         if (empty($secretKey)) {
+            Log::channel('pagarme')->error('PAGARME_SECRET_KEY is not configured.');
+
             throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
         }
 
-        $serviceRefererName = (string) config('services.pagarme.service_referer_name', config('app.name'));
-
-        $this->client = PagarmeApiSDKClientBuilder::init()
-            ->basicAuthCredentials(
-                BasicAuthCredentialsBuilder::init($secretKey, '')
-            )
-            ->serviceRefererName($serviceRefererName)
-            ->build();
-
-        return $this->client;
-    }
-
-    private function idempotencyKey(int $clientId): string
-    {
-        return "client-{$clientId}-customer";
+        return Http::withBasicAuth($secretKey, '')
+            ->withHeaders([
+                'Idempotency-Key' => $this->idempotencyKey($clientId),
+                'Content-Type'    => 'application/json',
+                'Accept'          => 'application/json',
+            ]);
     }
-}
+}

+ 1 - 2
composer.json

@@ -12,8 +12,7 @@
         "kalnoy/nestedset": "^6.0",
         "laravel/framework": "^12.0",
         "laravel/sanctum": "^4.0",
-        "laravel/tinker": "^2.9",
-        "pagarme/pagarme-php-sdk": "^6.8"
+        "laravel/tinker": "^2.9"
     },
     "require-dev": {
         "barryvdh/laravel-ide-helper": "^3.6",

+ 1 - 330
composer.lock

@@ -4,225 +4,8 @@
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
         "This file is @generated automatically"
     ],
-    "content-hash": "0b19352c401e0079ba79bdf74477b3fb",
+    "content-hash": "40404f977a56fc05d7f7679557905a6b",
     "packages": [
-        {
-            "name": "apimatic/core",
-            "version": "0.3.17",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/apimatic/core-lib-php.git",
-                "reference": "a48a583f686ee3786432b976c795a2817ec095b3"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/apimatic/core-lib-php/zipball/a48a583f686ee3786432b976c795a2817ec095b3",
-                "reference": "a48a583f686ee3786432b976c795a2817ec095b3",
-                "shasum": ""
-            },
-            "require": {
-                "apimatic/core-interfaces": "~0.1.5",
-                "apimatic/jsonmapper": "^3.1.1",
-                "ext-curl": "*",
-                "ext-dom": "*",
-                "ext-json": "*",
-                "ext-libxml": "*",
-                "php": "^7.2 || ^8.0",
-                "php-jsonpointer/php-jsonpointer": "^3.0.2",
-                "psr/log": "^1.1.4 || ^2.0.0 || ^3.0.0",
-                "symfony/http-foundation": "^5.4 || ^6.0 || ^7.0 || ^8.0"
-            },
-            "require-dev": {
-                "phan/phan": "5.4.5",
-                "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5",
-                "squizlabs/php_codesniffer": "^3.5"
-            },
-            "type": "library",
-            "autoload": {
-                "psr-4": {
-                    "Core\\": "src/"
-                }
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "MIT"
-            ],
-            "description": "Core logic and the utilities for the Apimatic's PHP SDK",
-            "homepage": "https://github.com/apimatic/core-lib-php",
-            "keywords": [
-                "apimatic",
-                "core",
-                "corelib",
-                "php"
-            ],
-            "support": {
-                "issues": "https://github.com/apimatic/core-lib-php/issues",
-                "source": "https://github.com/apimatic/core-lib-php/tree/0.3.17"
-            },
-            "time": "2026-01-27T05:14:10+00:00"
-        },
-        {
-            "name": "apimatic/core-interfaces",
-            "version": "0.1.5",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/apimatic/core-interfaces-php.git",
-                "reference": "b4f1bffc8be79584836f70af33c65e097eec155c"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/apimatic/core-interfaces-php/zipball/b4f1bffc8be79584836f70af33c65e097eec155c",
-                "reference": "b4f1bffc8be79584836f70af33c65e097eec155c",
-                "shasum": ""
-            },
-            "require": {
-                "php": "^7.2 || ^8.0"
-            },
-            "type": "library",
-            "autoload": {
-                "psr-4": {
-                    "CoreInterfaces\\": "src/"
-                }
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "MIT"
-            ],
-            "description": "Definition of the behavior of apimatic/core, apimatic/unirest-php and Apimatic's PHP SDK",
-            "homepage": "https://github.com/apimatic/core-interfaces-php",
-            "keywords": [
-                "apimatic",
-                "core",
-                "corelib",
-                "interface",
-                "php",
-                "unirest"
-            ],
-            "support": {
-                "issues": "https://github.com/apimatic/core-interfaces-php/issues",
-                "source": "https://github.com/apimatic/core-interfaces-php/tree/0.1.5"
-            },
-            "time": "2024-05-09T06:32:07+00:00"
-        },
-        {
-            "name": "apimatic/jsonmapper",
-            "version": "3.1.7",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/apimatic/jsonmapper.git",
-                "reference": "61e45f6021e4a4e07497be596b4787c3c6b39bea"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/apimatic/jsonmapper/zipball/61e45f6021e4a4e07497be596b4787c3c6b39bea",
-                "reference": "61e45f6021e4a4e07497be596b4787c3c6b39bea",
-                "shasum": ""
-            },
-            "require": {
-                "ext-json": "*",
-                "php": "^5.6 || ^7.0 || ^8.0"
-            },
-            "require-dev": {
-                "phpunit/phpunit": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 || ^9.0.0",
-                "squizlabs/php_codesniffer": "^3.0.0"
-            },
-            "type": "library",
-            "autoload": {
-                "psr-4": {
-                    "apimatic\\jsonmapper\\": "src/"
-                }
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "OSL-3.0"
-            ],
-            "authors": [
-                {
-                    "name": "Christian Weiske",
-                    "email": "christian.weiske@netresearch.de",
-                    "homepage": "http://www.netresearch.de/",
-                    "role": "Developer"
-                },
-                {
-                    "name": "Mehdi Jaffery",
-                    "email": "mehdi.jaffery@apimatic.io",
-                    "homepage": "http://apimatic.io/",
-                    "role": "Developer"
-                }
-            ],
-            "description": "Map nested JSON structures onto PHP classes",
-            "support": {
-                "email": "mehdi.jaffery@apimatic.io",
-                "issues": "https://github.com/apimatic/jsonmapper/issues",
-                "source": "https://github.com/apimatic/jsonmapper/tree/3.1.7"
-            },
-            "time": "2025-11-06T14:43:04+00:00"
-        },
-        {
-            "name": "apimatic/unirest-php",
-            "version": "4.0.7",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/apimatic/unirest-php.git",
-                "reference": "bdfd5f27c105772682c88ed671683f1bd93f4a3c"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/apimatic/unirest-php/zipball/bdfd5f27c105772682c88ed671683f1bd93f4a3c",
-                "reference": "bdfd5f27c105772682c88ed671683f1bd93f4a3c",
-                "shasum": ""
-            },
-            "require": {
-                "apimatic/core-interfaces": "^0.1.0",
-                "ext-curl": "*",
-                "ext-json": "*",
-                "php": "^7.2 || ^8.0"
-            },
-            "require-dev": {
-                "phan/phan": "5.4.2",
-                "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5",
-                "squizlabs/php_codesniffer": "^3.5"
-            },
-            "type": "library",
-            "autoload": {
-                "psr-4": {
-                    "Unirest\\": "src/"
-                }
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "MIT"
-            ],
-            "authors": [
-                {
-                    "name": "Mashape",
-                    "email": "opensource@mashape.com",
-                    "homepage": "https://www.mashape.com",
-                    "role": "Developer"
-                },
-                {
-                    "name": "APIMATIC",
-                    "email": "opensource@apimatic.io",
-                    "homepage": "https://www.apimatic.io",
-                    "role": "Developer"
-                }
-            ],
-            "description": "Unirest PHP",
-            "homepage": "https://github.com/apimatic/unirest-php",
-            "keywords": [
-                "client",
-                "curl",
-                "http",
-                "https",
-                "rest"
-            ],
-            "support": {
-                "email": "opensource@apimatic.io",
-                "issues": "https://github.com/apimatic/unirest-php/issues",
-                "source": "https://github.com/apimatic/unirest-php/tree/4.0.7"
-            },
-            "time": "2025-06-17T09:09:48+00:00"
-        },
         {
             "name": "brick/math",
             "version": "0.13.1",
@@ -2851,118 +2634,6 @@
             ],
             "time": "2025-05-08T08:14:37+00:00"
         },
-        {
-            "name": "pagarme/pagarme-php-sdk",
-            "version": "6.8.17",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/pagarme/pagarme-php-sdk.git",
-                "reference": "b58c1105bc2afe803bcc083b236538d723d85997"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/pagarme/pagarme-php-sdk/zipball/b58c1105bc2afe803bcc083b236538d723d85997",
-                "reference": "b58c1105bc2afe803bcc083b236538d723d85997",
-                "shasum": ""
-            },
-            "require": {
-                "apimatic/core": "~0.3.13",
-                "apimatic/core-interfaces": "~0.1.5",
-                "apimatic/unirest-php": "^4.0.6",
-                "ext-curl": "*",
-                "ext-json": "*",
-                "php": "^7.2 || ^8.0"
-            },
-            "require-dev": {
-                "phan/phan": "5.4.5",
-                "squizlabs/php_codesniffer": "^3.5"
-            },
-            "type": "library",
-            "autoload": {
-                "psr-4": {
-                    "PagarmeApiSDKLib\\": "src/"
-                }
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "MIT"
-            ],
-            "authors": [
-                {
-                    "name": "Pagar.me Pagamentos S/A",
-                    "email": "suporte@pagar.me",
-                    "homepage": "https://github.com/pagarme/"
-                }
-            ],
-            "description": "Pagarme API",
-            "homepage": "https://github.com/pagarme/",
-            "keywords": [
-                "PagarmeApiSDK",
-                "api",
-                "sdk"
-            ],
-            "support": {
-                "issues": "https://github.com/pagarme/pagarme-php-sdk/issues",
-                "source": "https://github.com/pagarme/pagarme-php-sdk/tree/6.8.17"
-            },
-            "time": "2025-05-13T13:22:34+00:00"
-        },
-        {
-            "name": "php-jsonpointer/php-jsonpointer",
-            "version": "v3.0.2",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/raphaelstolt/php-jsonpointer.git",
-                "reference": "4428f86c6f23846e9faa5a420c4ef14e485b3afb"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/raphaelstolt/php-jsonpointer/zipball/4428f86c6f23846e9faa5a420c4ef14e485b3afb",
-                "reference": "4428f86c6f23846e9faa5a420c4ef14e485b3afb",
-                "shasum": ""
-            },
-            "require": {
-                "php": ">=5.4"
-            },
-            "require-dev": {
-                "friendsofphp/php-cs-fixer": "^1.11",
-                "phpunit/phpunit": "4.6.*"
-            },
-            "type": "library",
-            "extra": {
-                "branch-alias": {
-                    "dev-master": "2.0.x-dev"
-                }
-            },
-            "autoload": {
-                "psr-0": {
-                    "Rs\\Json": "src/"
-                }
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "MIT"
-            ],
-            "authors": [
-                {
-                    "name": "Raphael Stolt",
-                    "email": "raphael.stolt@gmail.com",
-                    "homepage": "http://raphaelstolt.blogspot.com/"
-                }
-            ],
-            "description": "Implementation of JSON Pointer (http://tools.ietf.org/html/rfc6901)",
-            "homepage": "https://github.com/raphaelstolt/php-jsonpointer",
-            "keywords": [
-                "json",
-                "json pointer",
-                "json traversal"
-            ],
-            "support": {
-                "issues": "https://github.com/raphaelstolt/php-jsonpointer/issues",
-                "source": "https://github.com/raphaelstolt/php-jsonpointer/tree/master"
-            },
-            "time": "2016-08-29T08:51:01+00:00"
-        },
         {
             "name": "phpoption/phpoption",
             "version": "1.9.3",