PagarmePaymentService.php 24 KB

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