PagarmePaymentService.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. <?php
  2. namespace App\Services\Pagarme;
  3. use App\Data\Pagarme\Customer\CustomerRequestData;
  4. use App\Data\Pagarme\Customer\Parts\Request\AddressData;
  5. use App\Data\Pagarme\Customer\Parts\Request\PhoneData;
  6. use App\Data\Pagarme\Customer\Parts\Request\PhonesData;
  7. use App\Data\Pagarme\Order\OrderRequestData;
  8. use App\Data\Pagarme\Order\OrderResponseData;
  9. use App\Data\Pagarme\Order\Parts\Request\CreditCardData;
  10. use App\Data\Pagarme\Order\Parts\Request\ItemData;
  11. use App\Data\Pagarme\Order\Parts\Request\PaymentData;
  12. use App\Data\Pagarme\Order\Parts\Request\PixAdditionalInformationData;
  13. use App\Data\Pagarme\Order\Parts\Request\PixData;
  14. use App\Data\Pagarme\Order\Parts\Request\SplitData;
  15. use App\Data\Pagarme\Order\Parts\Request\SplitOptionsData;
  16. use App\Enums\PaymentSplitStatusEnum;
  17. use App\Enums\PaymentStatusEnum;
  18. use App\Models\Address;
  19. use App\Models\Cart;
  20. use App\Models\Client;
  21. use App\Models\Payment;
  22. use App\Models\PaymentSplit;
  23. use App\Models\Schedule;
  24. use App\Services\Pagarme\Concerns\FormatsPagarmeData;
  25. use App\Services\Pagarme\Concerns\MocksPagarmeRequests;
  26. use App\Services\Pagarme\Concerns\SendsPagarmeRequests;
  27. use Illuminate\Support\Facades\Log;
  28. use Illuminate\Support\Str;
  29. class PagarmePaymentService
  30. {
  31. use FormatsPagarmeData;
  32. use MocksPagarmeRequests;
  33. use SendsPagarmeRequests;
  34. public function calculatePaymentAmounts(float $serviceAmount, string $paymentMethod, ?Schedule $schedule = null): array
  35. {
  36. if ($serviceAmount <= 0) {
  37. throw new \InvalidArgumentException('Valor do servico precisa ser maior que zero.');
  38. }
  39. if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
  40. throw new \InvalidArgumentException('Forma de pagamento invalida.');
  41. }
  42. $platformFeeRate = $this->platformFeeRate($paymentMethod, $schedule);
  43. $platformFee = round($serviceAmount * $platformFeeRate, 2);
  44. $grossAmount = round($serviceAmount + $platformFee, 2);
  45. if ($platformFee > 0 && empty(config('services.pagarme.platform_recipient_id'))) {
  46. throw new \InvalidArgumentException('PAGARME_PLATFORM_RECIPIENT_ID precisa estar configurado para receber a taxa da plataforma no split.');
  47. }
  48. return [
  49. 'service_amount' => round($serviceAmount, 2),
  50. 'platform_fee_amount' => $platformFee,
  51. 'gross_amount' => $grossAmount,
  52. ];
  53. }
  54. private function platformFeeRate(string $paymentMethod, ?Schedule $schedule = null): float
  55. {
  56. if ($schedule && $this->scheduleBelongsToCartWithAtLeastThreeItems($schedule)) {
  57. return (float) config('services.pagarme.platform_cart_min_3_schedules_fee_rate');
  58. }
  59. return $paymentMethod === 'credit_card'
  60. ? (float) config('services.pagarme.platform_credit_card_fee_rate')
  61. : (float) config('services.pagarme.platform_pix_fee_rate');
  62. }
  63. public function platformFeeRates(): array
  64. {
  65. return [
  66. 'pix' => (float) config('services.pagarme.platform_pix_fee_rate'),
  67. 'credit_card' => (float) config('services.pagarme.platform_credit_card_fee_rate'),
  68. 'cart_min_3_schedules' => (float) config('services.pagarme.platform_cart_min_3_schedules_fee_rate'),
  69. ];
  70. }
  71. public function processPayment(
  72. Payment $payment,
  73. Schedule $schedule,
  74. string $paymentMethod,
  75. ?string $cardId = null,
  76. array $options = [],
  77. ): array {
  78. $grossAmount = (float) $payment->gross_amount;
  79. $items = $this->buildOrderItems($schedule, $grossAmount);
  80. $customer = $this->buildCustomer($schedule, $options);
  81. $split = $this->buildSplit($payment, $options);
  82. $pixOptions = config('services.pagarme.pix_disable_split')
  83. ? []
  84. : ['split' => $split];
  85. $orderOptions = array_merge(['split' => $split], $pixOptions);
  86. if ($paymentMethod === 'credit_card') {
  87. $creditCard = new CreditCardData(
  88. cardId: $cardId,
  89. installments: $payment->installments,
  90. statementDescriptor: Str::limit((string) config('app.name', 'SOFTPAR'), 13, ''),
  91. operationType: 'auth_and_capture',
  92. );
  93. $result = $this->createOrderWithCreditCard(
  94. payment: $payment,
  95. items: $items,
  96. customer: $customer,
  97. creditCard: $creditCard,
  98. options: $orderOptions,
  99. );
  100. $this->logCreditCardOrderResult($payment, $result, 'create_order');
  101. $orderStatus = OrderResponseData::fromArray($result)->paymentStatus();
  102. if (! in_array($orderStatus, [PaymentStatusEnum::PAID, PaymentStatusEnum::AUTHORIZED], true)) {
  103. return $result;
  104. }
  105. return $result;
  106. }
  107. $pixData = new PixData(
  108. expiresIn: 1800,
  109. additionalInformation: [
  110. new PixAdditionalInformationData(
  111. name: 'Agendamento',
  112. value: (string) $schedule->id,
  113. ),
  114. ],
  115. );
  116. return $this->createOrderWithPix(
  117. payment: $payment,
  118. items: $items,
  119. customer: $customer,
  120. pix: $pixData,
  121. options: $pixOptions,
  122. );
  123. }
  124. //
  125. public function createOrderWithCreditCard(
  126. Payment $payment,
  127. array $items,
  128. CustomerRequestData $customer,
  129. CreditCardData $creditCard,
  130. array $options = []
  131. ): array {
  132. return $this->createOrder(
  133. payment: $payment,
  134. items: $items,
  135. customer: $customer,
  136. paymentMethod: OrderRequestData::creditCardPaymentMethod(
  137. creditCard: $creditCard,
  138. split: is_array($options['split'] ?? null) ? $options['split'] : null,
  139. ),
  140. options: $options,
  141. );
  142. }
  143. public function createOrderWithPix(
  144. Payment $payment,
  145. array $items,
  146. CustomerRequestData $customer,
  147. PixData $pix,
  148. array $options = []
  149. ): array {
  150. return $this->createOrder(
  151. payment: $payment,
  152. items: $items,
  153. customer: $customer,
  154. paymentMethod: OrderRequestData::pixPaymentMethod(
  155. pix: $pix,
  156. split: is_array($options['split'] ?? null) ? $options['split'] : null,
  157. ),
  158. options: $options,
  159. );
  160. }
  161. public function createOrder(
  162. Payment $payment,
  163. array $items,
  164. CustomerRequestData $customer,
  165. PaymentData $paymentMethod,
  166. array $options = []
  167. ): array {
  168. $metadata = array_filter([
  169. 'payment_id' => (string) $payment->id,
  170. 'schedule_id' => $payment->schedule_id ? (string) $payment->schedule_id : null,
  171. 'client_id' => (string) $payment->client_id,
  172. 'provider_id' => $payment->provider_id ? (string) $payment->provider_id : null,
  173. ], fn ($value) => $value !== null);
  174. $metadata = array_merge($metadata, $options['metadata'] ?? []);
  175. $requestData = new OrderRequestData(
  176. code: $payment->ensureGatewayCode(),
  177. items: $items,
  178. payments: [$paymentMethod],
  179. metadata: $metadata,
  180. customer: $customer,
  181. customerId: $options['customer_id'] ?? null,
  182. closed: $options['closed'] ?? true,
  183. channel: $options['channel'] ?? null,
  184. );
  185. if ($this->shouldMockPagarmeRequest()) {
  186. $order = OrderResponseData::fromArray(
  187. $this->mockOrderResponse($payment, $requestData, $paymentMethod),
  188. );
  189. $order->requireId();
  190. $this->saveExternalCustomerId($payment, $order);
  191. return $order->toArray();
  192. }
  193. $order = OrderResponseData::fromArray($this->pagarmeRequest(
  194. method: 'POST',
  195. path: '/orders',
  196. payload: $requestData,
  197. idempotencyKey: $this->idempotencyKey($payment),
  198. errorMessage: 'Erro ao criar pedido de pagamento no Pagar.me.',
  199. ));
  200. $order->requireId();
  201. $this->saveExternalCustomerId($payment, $order);
  202. return $order->toArray();
  203. }
  204. //
  205. public function applyGatewayResponseToPayment(Payment $payment, array $orderResponse): Payment
  206. {
  207. $order = OrderResponseData::fromArray($orderResponse);
  208. $newStatus = $order->paymentStatus();
  209. $failureCode = null;
  210. $failureMessage = null;
  211. if ($newStatus === PaymentStatusEnum::FAILED) {
  212. $failureCode = $order->failureCode();
  213. $failureMessage = $order->failureMessage();
  214. $this->logCreditCardOrderResult($payment, $orderResponse, 'webhook_failed');
  215. }
  216. $gatewayFeeCents = $order->lastTransaction()?->cost ?? 0;
  217. $gatewayFee = $gatewayFeeCents > 0 ? round($gatewayFeeCents / 100, 2) : 0;
  218. $gatewayPayload = $newStatus === PaymentStatusEnum::FAILED
  219. ? $this->normalizeFailedGatewayPayload($orderResponse, $failureCode, $failureMessage)
  220. : $orderResponse;
  221. $payment->forceFill([
  222. 'gateway_provider' => 'pagarme',
  223. 'gateway_entity_reference' => $order->gatewayEntityReference(),
  224. 'gateway_entity_label' => $order->gatewayEntityLabel(),
  225. 'gateway_operation_reference' => $order->gatewayOperationReference(),
  226. 'gateway_operation_label' => $order->gatewayOperationLabel(),
  227. 'status' => $newStatus,
  228. 'paid_at' => $order->paidAt(),
  229. 'authorized_at' => $order->authorizedAt(),
  230. 'gateway_payload' => $gatewayPayload,
  231. 'gateway_fee_amount' => $gatewayFee,
  232. 'failure_code' => $failureCode,
  233. 'failure_message' => $failureMessage,
  234. ])->save();
  235. $splitStatus = match ($newStatus) {
  236. PaymentStatusEnum::PAID => PaymentSplitStatusEnum::TRANSFERRED,
  237. PaymentStatusEnum::FAILED => PaymentSplitStatusEnum::FAILED,
  238. PaymentStatusEnum::CANCELLED => PaymentSplitStatusEnum::CANCELLED,
  239. PaymentStatusEnum::AUTHORIZED => PaymentSplitStatusEnum::PROCESSING,
  240. default => PaymentSplitStatusEnum::PENDING,
  241. };
  242. PaymentSplit::query()
  243. ->where('payment_id', $payment->id)
  244. ->update(['status' => $splitStatus]);
  245. return $payment->fresh();
  246. }
  247. //
  248. private function scheduleBelongsToCartWithAtLeastThreeItems(Schedule $schedule): bool
  249. {
  250. return Cart::query()
  251. ->whereHas('items', fn ($query) => $query->where('schedule_id', $schedule->id))
  252. ->whereHas('items', null, '>=', 3)
  253. ->exists();
  254. }
  255. //
  256. private function mockCustomerResponse(OrderRequestData $requestData): array
  257. {
  258. $customer = $requestData->customer?->toArray() ?? [];
  259. return array_merge($customer, [
  260. 'id' => $requestData->customerId ?: $this->mockPagarmeId('cus', $customer['code'] ?? $requestData->code),
  261. 'delinquent' => false,
  262. ]);
  263. }
  264. private function mockOrderResponse(
  265. Payment $payment, OrderRequestData $requestData, PaymentData $paymentMethod,
  266. ): array {
  267. $payload = $requestData->toArray();
  268. $now = now()->toISOString();
  269. $orderId = $this->mockPagarmeId('or', $payment->id);
  270. $chargeId = $this->mockPagarmeId('ch', $payment->id);
  271. $transactionId = $this->mockPagarmeId('tran', $payment->id);
  272. $amount = array_sum(array_map(
  273. static fn (array $item): int => ((int) ($item['amount'] ?? 0)) * ((int) ($item['quantity'] ?? 1)),
  274. $payload['items'] ?? [],
  275. ));
  276. $isCreditCard = $paymentMethod->paymentMethod === 'credit_card';
  277. $chargeStatus = $isCreditCard ? 'paid' : 'pending';
  278. $transactionStatus = $isCreditCard ? 'captured' : 'waiting_payment';
  279. $transaction = [
  280. 'id' => $transactionId,
  281. 'status' => $transactionStatus,
  282. 'amount' => $amount,
  283. 'cost' => 0,
  284. 'created_at' => $now,
  285. 'acquirer_message' => $isCreditCard ? 'Transacao mockada aprovada.' : null,
  286. 'gateway_response' => [
  287. 'code' => $isCreditCard ? '00' : 'mock_waiting_payment',
  288. 'message' => 'Pagar.me mock local.',
  289. ],
  290. ];
  291. if (! $isCreditCard) {
  292. $transaction['qr_code'] = '00020101021226880014br.gov.bcb.pix2566mock.local/pix/'.$payment->id;
  293. $transaction['qr_code_url'] = url("/mock/pix/{$payment->id}");
  294. $transaction['expires_at'] = now()->addMinutes(30)->toISOString();
  295. }
  296. return [
  297. 'id' => $orderId,
  298. 'code' => $requestData->code,
  299. 'amount' => $amount,
  300. 'currency' => 'BRL',
  301. 'closed' => true,
  302. 'status' => $chargeStatus,
  303. 'items' => $payload['items'] ?? [],
  304. 'customer' => $this->mockCustomerResponse($requestData),
  305. 'charges' => [[
  306. 'id' => $chargeId,
  307. 'status' => $chargeStatus,
  308. 'amount' => $amount,
  309. 'currency' => 'BRL',
  310. 'paid_at' => $isCreditCard ? $now : null,
  311. 'created_at' => $now,
  312. 'expires_at' => $isCreditCard ? null : now()->addMinutes(30)->toISOString(),
  313. 'last_transaction' => $transaction,
  314. ]],
  315. 'checkouts' => [],
  316. 'metadata' => array_merge($requestData->metadata, ['mocked' => true]),
  317. 'created_at' => $now,
  318. 'updated_at' => $now,
  319. 'closed_at' => $now,
  320. ];
  321. }
  322. //
  323. private function buildCustomer(Schedule $schedule, array $options = []): CustomerRequestData
  324. {
  325. $client = $schedule->client;
  326. $user = $client->user()->first(['id', 'name', 'email', 'phone']);
  327. $address = Address::with(['city.state', 'state'])->find($schedule->address_id);
  328. foreach ([
  329. 'nome' => $user?->name,
  330. 'email' => $user?->email,
  331. 'documento' => $client->document,
  332. ] as $field => $value) {
  333. if ($value === null || $value === '') {
  334. throw new \InvalidArgumentException("Cliente precisa ter {$field} para criar pedido no Pagar.me.");
  335. }
  336. }
  337. if (! $address) {
  338. throw new \InvalidArgumentException('Endereco do agendamento nao encontrado para criar pedido no Pagar.me.');
  339. }
  340. $document = $this->customerDocument($client->document);
  341. $documentType = $this->customerDocumentType($document);
  342. $phone = $this->buildPhonePayload($user->phone)
  343. ?: $this->buildPhonePayload($options['phone'] ?? null);
  344. $state = $address->state?->code ?? $address->city?->state?->code;
  345. $city = $address->city?->name;
  346. $zipCode = $this->digits($address->zip_code);
  347. $line1 = implode(', ', array_filter([
  348. $address->number ?: 'S/N',
  349. $address->address,
  350. $address->district,
  351. ]));
  352. foreach ([
  353. 'documento' => $document,
  354. 'estado' => $state,
  355. 'cidade' => $city,
  356. 'cep' => $zipCode,
  357. 'endereco' => $line1,
  358. 'telefone' => $phone,
  359. ] as $field => $value) {
  360. if ($value === null || $value === '' || $value === []) {
  361. throw new \InvalidArgumentException("Cliente precisa ter {$field} valido para criar pedido no Pagar.me.");
  362. }
  363. }
  364. $customerAddress = new AddressData(
  365. line1: $line1,
  366. line2: $address->complement ?: $address->instructions,
  367. zipCode: $zipCode,
  368. city: $city,
  369. state: $state,
  370. country: 'BR',
  371. );
  372. $customerPhones = null;
  373. if ($phone) {
  374. $customerPhones = new PhonesData(
  375. mobilePhone: new PhoneData(
  376. countryCode: $phone['country_code'],
  377. areaCode: $phone['area_code'],
  378. number: $phone['number'],
  379. ),
  380. );
  381. }
  382. return new CustomerRequestData(
  383. name: $user->name,
  384. email: $user->email,
  385. document: $document,
  386. type: $documentType === 'CNPJ' ? 'company' : 'individual',
  387. documentType: $documentType,
  388. code: $client->ensureGatewayCode(),
  389. address: $customerAddress,
  390. phones: $customerPhones,
  391. );
  392. }
  393. private function buildOrderItems(Schedule $schedule, float $grossAmount): array
  394. {
  395. return [$this->buildOrderItem($schedule, $grossAmount)];
  396. }
  397. private function buildOrderItem(Schedule $schedule, float $grossAmount): ItemData
  398. {
  399. $description = $schedule->customSchedule?->serviceType?->description
  400. ?? "Servico {$schedule->id}";
  401. return new ItemData(
  402. code: "schedule-{$schedule->id}",
  403. amount: OrderRequestData::amountInCents($grossAmount),
  404. quantity: 1,
  405. description: $description,
  406. );
  407. }
  408. private function buildPhonePayload(?string $phone): ?array
  409. {
  410. $digits = $this->digits($phone);
  411. if (strlen($digits) < 10) {
  412. return null;
  413. }
  414. if (str_starts_with($digits, '55')) {
  415. $digits = substr($digits, 2);
  416. }
  417. return [
  418. 'country_code' => '55',
  419. 'area_code' => substr($digits, 0, 2),
  420. 'number' => substr($digits, 2),
  421. ];
  422. }
  423. private function buildSplit(Payment $payment, array $options): array
  424. {
  425. $transfers = PaymentSplit::query()
  426. ->where('payment_id', $payment->id)
  427. ->get();
  428. $split = OrderRequestData::splitFromTransfers($transfers);
  429. $platformRecipientId = config('services.pagarme.platform_recipient_id');
  430. if (empty($platformRecipientId)) {
  431. return $split;
  432. }
  433. $orderAmountCents = OrderRequestData::amountInCents((float) $payment->gross_amount);
  434. $providerTotalCents = array_sum(array_map(
  435. static fn (SplitData $s) => $s->amount,
  436. $split,
  437. ));
  438. $platformAmountCents = $orderAmountCents - $providerTotalCents;
  439. if ($platformAmountCents > 0) {
  440. $split[] = new SplitData(
  441. amount: $platformAmountCents,
  442. recipientId: $platformRecipientId,
  443. type: 'flat',
  444. options: new SplitOptionsData(
  445. chargeProcessingFee: true,
  446. chargeRemainderFee: true,
  447. liable: true,
  448. ),
  449. );
  450. }
  451. return $split;
  452. }
  453. //
  454. private function isMisleadingGatewayCode(mixed $code): bool
  455. {
  456. if ($code === null || $code === '') {
  457. return false;
  458. }
  459. $code = mb_strtolower((string) $code);
  460. return preg_match('/^[1-2]\d{2}$/', $code) === 1
  461. || in_array($code, ['00', '0', 'approved', 'success'], true);
  462. }
  463. private function logCreditCardOrderResult(Payment $payment, array $orderResponse, string $source): void
  464. {
  465. $order = OrderResponseData::fromArray($orderResponse);
  466. $charge = $order->firstCharge();
  467. $transaction = $order->lastTransaction();
  468. $failureCode = $order->failureCode();
  469. Log::channel('pagarme')->info('Pagar.me credit card order result', [
  470. 'source' => $source,
  471. 'payment_id' => $payment->id,
  472. 'provider_id' => $payment->provider_id,
  473. 'order_id' => $order->id,
  474. 'order_status' => $order->status,
  475. 'charge_id' => $charge?->id,
  476. 'charge_status' => $charge?->status,
  477. 'transaction_id' => $transaction?->id,
  478. 'transaction_status' => $transaction?->status,
  479. 'failure_code' => $failureCode,
  480. 'failure_message' => $order->failureMessage(),
  481. 'acquirer_message' => $transaction?->acquirerMessage,
  482. 'gateway_response' => $this->normalizeGatewayResponseForFailure(
  483. $transaction?->gatewayResponse ?? [],
  484. $failureCode,
  485. ),
  486. ]);
  487. }
  488. private function normalizeFailedGatewayPayload(array $payload, ?string $failureCode, ?string $failureMessage): array
  489. {
  490. $payload['failure_code'] = $failureCode;
  491. $payload['failure_message'] = $failureMessage;
  492. if (isset($payload['charges'][0]['last_transaction']['gateway_response'])
  493. && is_array($payload['charges'][0]['last_transaction']['gateway_response'])) {
  494. $payload['charges'][0]['last_transaction']['gateway_response'] = $this->normalizeGatewayResponseForFailure(
  495. $payload['charges'][0]['last_transaction']['gateway_response'],
  496. $failureCode,
  497. );
  498. }
  499. return $payload;
  500. }
  501. private function normalizeGatewayResponseForFailure(array $gatewayResponse, ?string $failureCode): array
  502. {
  503. $code = $gatewayResponse['code'] ?? null;
  504. if (! $failureCode || ! $this->isMisleadingGatewayCode($code)) {
  505. return $gatewayResponse;
  506. }
  507. $gatewayResponse['raw_code'] = $code;
  508. $gatewayResponse['code'] = $failureCode;
  509. return $gatewayResponse;
  510. }
  511. private function roundMoneyUp(float $amount): float
  512. {
  513. return ceil($amount * 100) / 100;
  514. }
  515. // evita criacao duplicada de payment
  516. private function idempotencyKey(Payment $payment): string
  517. {
  518. if (! empty($payment->idempotency_key)) {
  519. return $payment->idempotency_key;
  520. }
  521. $payment->loadMissing(['client.user', 'provider.user', 'schedule']);
  522. $amountCents = (int) round((float) $payment->gross_amount * 100);
  523. $key = $this->pagarmeIdempotencyKey('order', [
  524. "schedule-{$payment->schedule_id}",
  525. $payment->client?->user?->name ?: "client-{$payment->client_id}",
  526. $payment->provider?->user?->name ?: ($payment->provider_id ? "provider-{$payment->provider_id}" : 'provider-none'),
  527. $payment->payment_method,
  528. "amount-{$amountCents}",
  529. ]);
  530. $payment->forceFill(['idempotency_key' => $key])->save();
  531. return $key;
  532. }
  533. // salva o gateway_customer_id do Pagar.me no Client apos criacao de ordem
  534. private function saveExternalCustomerId(Payment $payment, OrderResponseData $order): void
  535. {
  536. $customerId = $order->customer?->id;
  537. $customerCode = $order->customer?->code;
  538. if (! $customerId && ! $customerCode) {
  539. return;
  540. }
  541. $client = Client::find($payment->client_id);
  542. if (! $client) {
  543. return;
  544. }
  545. $updated = false;
  546. if (! $client->gateway_customer_id && $customerId) {
  547. $client->gateway_customer_id = $customerId;
  548. $updated = true;
  549. }
  550. if (! $client->gateway_customer_code && $customerCode) {
  551. $client->gateway_customer_code = $customerCode;
  552. $updated = true;
  553. }
  554. if ($updated) {
  555. $client->save();
  556. }
  557. }
  558. }