PagarmePaymentService.php 26 KB

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