PagarmePaymentService.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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\Collection;
  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. private function platformFeeRate(string $paymentMethod, ?Schedule $schedule = null): float
  56. {
  57. if ($schedule && $this->scheduleBelongsToCartWithAtLeastThreeItems($schedule)) {
  58. return $this->configuredPlatformFeeRate('platform_cart_min_3_schedules_fee_rate');
  59. }
  60. return $paymentMethod === 'credit_card'
  61. ? $this->configuredPlatformFeeRate('platform_credit_card_fee_rate')
  62. : $this->configuredPlatformFeeRate('platform_pix_fee_rate');
  63. }
  64. public function platformFeeRates(): array
  65. {
  66. return [
  67. 'pix' => $this->configuredPlatformFeeRate('platform_pix_fee_rate'),
  68. 'credit_card' => $this->configuredPlatformFeeRate('platform_credit_card_fee_rate'),
  69. 'cart_min_3_schedules' => $this->configuredPlatformFeeRate('platform_cart_min_3_schedules_fee_rate'),
  70. ];
  71. }
  72. private function configuredPlatformFeeRate(string $key): float
  73. {
  74. $rate = config("services.pagarme.{$key}", 0);
  75. if (is_string($rate)) {
  76. $rate = str_replace(',', '.', trim($rate));
  77. }
  78. $rate = (float) $rate;
  79. return $rate > 1 ? $rate / 100 : $rate;
  80. }
  81. public function processPayment(
  82. Payment $payment,
  83. Schedule $schedule,
  84. string $paymentMethod,
  85. ?string $cardId = null,
  86. array $options = [],
  87. ): array {
  88. $grossAmount = (float) $payment->gross_amount;
  89. $items = $this->buildOrderItems($schedule, $grossAmount);
  90. $customer = $this->buildCustomer($schedule, $options);
  91. $split = $this->buildSplit($payment, $options);
  92. $pixOptions = config('services.pagarme.pix_disable_split')
  93. ? []
  94. : ['split' => $split];
  95. $orderOptions = array_merge(['split' => $split], $pixOptions);
  96. if ($paymentMethod === 'credit_card') {
  97. $creditCard = new CreditCardData(
  98. cardId: $cardId,
  99. installments: $payment->installments,
  100. statementDescriptor: Str::limit((string) config('app.name', 'SOFTPAR'), 13, ''),
  101. operationType: 'auth_and_capture',
  102. );
  103. $result = $this->createOrderWithCreditCard(
  104. payment: $payment,
  105. items: $items,
  106. customer: $customer,
  107. creditCard: $creditCard,
  108. options: $orderOptions,
  109. );
  110. $this->logCreditCardOrderResult($payment, $result, 'create_order');
  111. $orderStatus = OrderResponseData::fromArray($result)->paymentStatus();
  112. if (! in_array($orderStatus, [PaymentStatusEnum::PAID, PaymentStatusEnum::AUTHORIZED], true)) {
  113. return $result;
  114. }
  115. return $result;
  116. }
  117. $pixData = new PixData(
  118. expiresIn: 1800,
  119. additionalInformation: [
  120. new PixAdditionalInformationData(
  121. name: 'Agendamento',
  122. value: (string) $schedule->id,
  123. ),
  124. ],
  125. );
  126. return $this->createOrderWithPix(
  127. payment: $payment,
  128. items: $items,
  129. customer: $customer,
  130. pix: $pixData,
  131. options: $pixOptions,
  132. );
  133. }
  134. public function processCartPayment(
  135. Payment $payment,
  136. Collection $schedules,
  137. string $paymentMethod,
  138. ?string $cardId = null,
  139. array $options = [],
  140. ): array {
  141. $firstSchedule = $schedules->first();
  142. if (! $firstSchedule) {
  143. throw new \InvalidArgumentException('Carrinho precisa ter ao menos um agendamento.');
  144. }
  145. $items = $schedules
  146. ->map(fn (Schedule $schedule) => $this->buildOrderItem(
  147. $schedule,
  148. (float) $schedule->getAttribute('payment_gross_amount'),
  149. ))
  150. ->all();
  151. $customer = $this->buildCustomer($firstSchedule, $options);
  152. $split = $this->buildSplit($payment, $options);
  153. $paymentOptions = config('services.pagarme.pix_disable_split')
  154. ? []
  155. : ['split' => $split];
  156. $metadata = [
  157. 'cart_id' => (string) $payment->cart_id,
  158. 'schedule_ids' => $schedules->pluck('id')->implode(','),
  159. ];
  160. if ($paymentMethod === 'credit_card') {
  161. $creditCard = new CreditCardData(
  162. cardId: $cardId,
  163. installments: $payment->installments,
  164. statementDescriptor: Str::limit((string) config('app.name', 'SOFTPAR'), 13, ''),
  165. operationType: 'auth_and_capture',
  166. );
  167. $result = $this->createOrderWithCreditCard(
  168. payment: $payment,
  169. items: $items,
  170. customer: $customer,
  171. creditCard: $creditCard,
  172. options: ['split' => $split, 'metadata' => $metadata],
  173. );
  174. $this->logCreditCardOrderResult($payment, $result, 'create_cart_order');
  175. return $result;
  176. }
  177. $pixData = new PixData(
  178. expiresIn: 1800,
  179. additionalInformation: [
  180. new PixAdditionalInformationData(
  181. name: 'Agendamentos',
  182. value: $schedules->pluck('id')->implode(','),
  183. ),
  184. ],
  185. );
  186. return $this->createOrderWithPix(
  187. payment: $payment,
  188. items: $items,
  189. customer: $customer,
  190. pix: $pixData,
  191. options: [...$paymentOptions, 'metadata' => $metadata],
  192. );
  193. }
  194. //
  195. public function createOrderWithCreditCard(
  196. Payment $payment,
  197. array $items,
  198. CustomerRequestData $customer,
  199. CreditCardData $creditCard,
  200. array $options = []
  201. ): array {
  202. return $this->createOrder(
  203. payment: $payment,
  204. items: $items,
  205. customer: $customer,
  206. paymentMethod: OrderRequestData::creditCardPaymentMethod(
  207. creditCard: $creditCard,
  208. split: is_array($options['split'] ?? null) ? $options['split'] : null,
  209. ),
  210. options: $options,
  211. );
  212. }
  213. public function createOrderWithPix(
  214. Payment $payment,
  215. array $items,
  216. CustomerRequestData $customer,
  217. PixData $pix,
  218. array $options = []
  219. ): array {
  220. return $this->createOrder(
  221. payment: $payment,
  222. items: $items,
  223. customer: $customer,
  224. paymentMethod: OrderRequestData::pixPaymentMethod(
  225. pix: $pix,
  226. split: is_array($options['split'] ?? null) ? $options['split'] : null,
  227. ),
  228. options: $options,
  229. );
  230. }
  231. public function createOrder(
  232. Payment $payment,
  233. array $items,
  234. CustomerRequestData $customer,
  235. PaymentData $paymentMethod,
  236. array $options = []
  237. ): array {
  238. $metadata = array_filter([
  239. 'payment_id' => (string) $payment->id,
  240. 'schedule_id' => $payment->schedule_id ? (string) $payment->schedule_id : null,
  241. 'cart_id' => $payment->cart_id ? (string) $payment->cart_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 scheduleBelongsToCartWithAtLeastThreeItems(Schedule $schedule): bool
  320. {
  321. return Cart::query()
  322. ->whereHas('items', fn ($query) => $query->where('schedule_id', $schedule->id))
  323. ->whereHas('items', null, '>=', 3)
  324. ->exists();
  325. }
  326. //
  327. private function mockCustomerResponse(OrderRequestData $requestData): array
  328. {
  329. $customer = $requestData->customer?->toArray() ?? [];
  330. return array_merge($customer, [
  331. 'id' => $requestData->customerId ?: $this->mockPagarmeId('cus', $customer['code'] ?? $requestData->code),
  332. 'delinquent' => false,
  333. ]);
  334. }
  335. private function mockOrderResponse(
  336. Payment $payment, OrderRequestData $requestData, PaymentData $paymentMethod,
  337. ): array {
  338. $payload = $requestData->toArray();
  339. $now = now()->toISOString();
  340. $orderId = $this->mockPagarmeId('or', $payment->id);
  341. $chargeId = $this->mockPagarmeId('ch', $payment->id);
  342. $transactionId = $this->mockPagarmeId('tran', $payment->id);
  343. $amount = array_sum(array_map(
  344. static fn (array $item): int => ((int) ($item['amount'] ?? 0)) * ((int) ($item['quantity'] ?? 1)),
  345. $payload['items'] ?? [],
  346. ));
  347. $isCreditCard = $paymentMethod->paymentMethod === 'credit_card';
  348. $chargeStatus = $isCreditCard ? 'paid' : 'pending';
  349. $transactionStatus = $isCreditCard ? 'captured' : 'waiting_payment';
  350. $transaction = [
  351. 'id' => $transactionId,
  352. 'status' => $transactionStatus,
  353. 'amount' => $amount,
  354. 'cost' => 0,
  355. 'created_at' => $now,
  356. 'acquirer_message' => $isCreditCard ? 'Transacao mockada aprovada.' : null,
  357. 'gateway_response' => [
  358. 'code' => $isCreditCard ? '00' : 'mock_waiting_payment',
  359. 'message' => 'Pagar.me mock local.',
  360. ],
  361. ];
  362. if (! $isCreditCard) {
  363. $transaction['qr_code'] = '00020101021226880014br.gov.bcb.pix2566mock.local/pix/'.$payment->id;
  364. $transaction['qr_code_url'] = url("/mock/pix/{$payment->id}");
  365. $transaction['expires_at'] = now()->addMinutes(30)->toISOString();
  366. }
  367. return [
  368. 'id' => $orderId,
  369. 'code' => $requestData->code,
  370. 'amount' => $amount,
  371. 'currency' => 'BRL',
  372. 'closed' => true,
  373. 'status' => $chargeStatus,
  374. 'items' => $payload['items'] ?? [],
  375. 'customer' => $this->mockCustomerResponse($requestData),
  376. 'charges' => [[
  377. 'id' => $chargeId,
  378. 'status' => $chargeStatus,
  379. 'amount' => $amount,
  380. 'currency' => 'BRL',
  381. 'paid_at' => $isCreditCard ? $now : null,
  382. 'created_at' => $now,
  383. 'expires_at' => $isCreditCard ? null : now()->addMinutes(30)->toISOString(),
  384. 'last_transaction' => $transaction,
  385. ]],
  386. 'checkouts' => [],
  387. 'metadata' => array_merge($requestData->metadata, ['mocked' => true]),
  388. 'created_at' => $now,
  389. 'updated_at' => $now,
  390. 'closed_at' => $now,
  391. ];
  392. }
  393. //
  394. private function buildCustomer(Schedule $schedule, array $options = []): CustomerRequestData
  395. {
  396. $client = $schedule->client;
  397. $user = $client->user()->first(['id', 'name', 'email', 'phone']);
  398. $address = Address::with(['city.state', 'state'])->find($schedule->address_id);
  399. foreach ([
  400. 'nome' => $user?->name,
  401. 'email' => $user?->email,
  402. 'documento' => $client->document,
  403. ] as $field => $value) {
  404. if ($value === null || $value === '') {
  405. throw new \InvalidArgumentException("Cliente precisa ter {$field} para criar pedido no Pagar.me.");
  406. }
  407. }
  408. if (! $address) {
  409. throw new \InvalidArgumentException('Endereco do agendamento nao encontrado para criar pedido no Pagar.me.');
  410. }
  411. $document = $this->customerDocument($client->document);
  412. $documentType = $this->customerDocumentType($document);
  413. $phone = $this->buildPhonePayload($user->phone)
  414. ?: $this->buildPhonePayload($options['phone'] ?? null);
  415. $state = $address->state?->code ?? $address->city?->state?->code;
  416. $city = $address->city?->name;
  417. $zipCode = $this->digits($address->zip_code);
  418. $line1 = implode(', ', array_filter([
  419. $address->number ?: 'S/N',
  420. $address->address,
  421. $address->district,
  422. ]));
  423. foreach ([
  424. 'documento' => $document,
  425. 'estado' => $state,
  426. 'cidade' => $city,
  427. 'cep' => $zipCode,
  428. 'endereco' => $line1,
  429. 'telefone' => $phone,
  430. ] as $field => $value) {
  431. if ($value === null || $value === '' || $value === []) {
  432. throw new \InvalidArgumentException("Cliente precisa ter {$field} valido para criar pedido no Pagar.me.");
  433. }
  434. }
  435. $customerAddress = new AddressData(
  436. line1: $line1,
  437. line2: $address->complement ?: $address->instructions,
  438. zipCode: $zipCode,
  439. city: $city,
  440. state: $state,
  441. country: 'BR',
  442. );
  443. $customerPhones = null;
  444. if ($phone) {
  445. $customerPhones = new PhonesData(
  446. mobilePhone: new PhoneData(
  447. countryCode: $phone['country_code'],
  448. areaCode: $phone['area_code'],
  449. number: $phone['number'],
  450. ),
  451. );
  452. }
  453. return new CustomerRequestData(
  454. name: $user->name,
  455. email: $user->email,
  456. document: $document,
  457. type: $documentType === 'CNPJ' ? 'company' : 'individual',
  458. documentType: $documentType,
  459. code: $client->ensureGatewayCode(),
  460. address: $customerAddress,
  461. phones: $customerPhones,
  462. );
  463. }
  464. private function buildOrderItems(Schedule $schedule, float $grossAmount): array
  465. {
  466. return [$this->buildOrderItem($schedule, $grossAmount)];
  467. }
  468. private function buildOrderItem(Schedule $schedule, float $grossAmount): ItemData
  469. {
  470. $description = $schedule->customSchedule?->serviceType?->description
  471. ?? "Servico {$schedule->id}";
  472. return new ItemData(
  473. code: "schedule-{$schedule->id}",
  474. amount: OrderRequestData::amountInCents($grossAmount),
  475. quantity: 1,
  476. description: $description,
  477. );
  478. }
  479. private function buildPhonePayload(?string $phone): ?array
  480. {
  481. $digits = $this->digits($phone);
  482. if (strlen($digits) < 10) {
  483. return null;
  484. }
  485. if (str_starts_with($digits, '55')) {
  486. $digits = substr($digits, 2);
  487. }
  488. return [
  489. 'country_code' => '55',
  490. 'area_code' => substr($digits, 0, 2),
  491. 'number' => substr($digits, 2),
  492. ];
  493. }
  494. private function buildSplit(Payment $payment, array $options): array
  495. {
  496. $transfers = PaymentSplit::query()
  497. ->where('payment_id', $payment->id)
  498. ->get();
  499. $split = OrderRequestData::splitFromTransfers($transfers);
  500. $platformRecipientId = config('services.pagarme.platform_recipient_id');
  501. if (empty($platformRecipientId)) {
  502. return $split;
  503. }
  504. $orderAmountCents = OrderRequestData::amountInCents((float) $payment->gross_amount);
  505. $providerTotalCents = array_sum(array_map(
  506. static fn (SplitData $s) => $s->amount,
  507. $split,
  508. ));
  509. $platformAmountCents = $orderAmountCents - $providerTotalCents;
  510. if ($platformAmountCents > 0) {
  511. $split[] = new SplitData(
  512. amount: $platformAmountCents,
  513. recipientId: $platformRecipientId,
  514. type: 'flat',
  515. options: new SplitOptionsData(
  516. chargeProcessingFee: true,
  517. chargeRemainderFee: true,
  518. liable: true,
  519. ),
  520. );
  521. }
  522. return $split;
  523. }
  524. //
  525. private function isMisleadingGatewayCode(mixed $code): bool
  526. {
  527. if ($code === null || $code === '') {
  528. return false;
  529. }
  530. $code = mb_strtolower((string) $code);
  531. return preg_match('/^[1-2]\d{2}$/', $code) === 1
  532. || in_array($code, ['00', '0', 'approved', 'success'], true);
  533. }
  534. private function logCreditCardOrderResult(Payment $payment, array $orderResponse, string $source): void
  535. {
  536. $order = OrderResponseData::fromArray($orderResponse);
  537. $charge = $order->firstCharge();
  538. $transaction = $order->lastTransaction();
  539. $failureCode = $order->failureCode();
  540. Log::channel('pagarme')->info('Pagar.me credit card order result', [
  541. 'source' => $source,
  542. 'payment_id' => $payment->id,
  543. 'provider_id' => $payment->provider_id,
  544. 'order_id' => $order->id,
  545. 'order_status' => $order->status,
  546. 'charge_id' => $charge?->id,
  547. 'charge_status' => $charge?->status,
  548. 'transaction_id' => $transaction?->id,
  549. 'transaction_status' => $transaction?->status,
  550. 'failure_code' => $failureCode,
  551. 'failure_message' => $order->failureMessage(),
  552. 'acquirer_message' => $transaction?->acquirerMessage,
  553. 'gateway_response' => $this->normalizeGatewayResponseForFailure(
  554. $transaction?->gatewayResponse ?? [],
  555. $failureCode,
  556. ),
  557. ]);
  558. }
  559. private function normalizeFailedGatewayPayload(array $payload, ?string $failureCode, ?string $failureMessage): array
  560. {
  561. $payload['failure_code'] = $failureCode;
  562. $payload['failure_message'] = $failureMessage;
  563. if (isset($payload['charges'][0]['last_transaction']['gateway_response'])
  564. && is_array($payload['charges'][0]['last_transaction']['gateway_response'])) {
  565. $payload['charges'][0]['last_transaction']['gateway_response'] = $this->normalizeGatewayResponseForFailure(
  566. $payload['charges'][0]['last_transaction']['gateway_response'],
  567. $failureCode,
  568. );
  569. }
  570. return $payload;
  571. }
  572. private function normalizeGatewayResponseForFailure(array $gatewayResponse, ?string $failureCode): array
  573. {
  574. $code = $gatewayResponse['code'] ?? null;
  575. if (! $failureCode || ! $this->isMisleadingGatewayCode($code)) {
  576. return $gatewayResponse;
  577. }
  578. $gatewayResponse['raw_code'] = $code;
  579. $gatewayResponse['code'] = $failureCode;
  580. return $gatewayResponse;
  581. }
  582. private function roundMoneyUp(float $amount): float
  583. {
  584. return ceil($amount * 100) / 100;
  585. }
  586. // evita criacao duplicada de payment
  587. private function idempotencyKey(Payment $payment): string
  588. {
  589. if (! empty($payment->idempotency_key)) {
  590. return $payment->idempotency_key;
  591. }
  592. $payment->loadMissing(['client.user', 'provider.user', 'schedule', 'cart']);
  593. $amountCents = (int) round((float) $payment->gross_amount * 100);
  594. $key = $this->pagarmeIdempotencyKey('order', [
  595. "payment-{$payment->id}",
  596. $payment->cart_id ? "cart-{$payment->cart_id}" : "schedule-{$payment->schedule_id}",
  597. $payment->client?->user?->name ?: "client-{$payment->client_id}",
  598. $payment->provider?->user?->name ?: ($payment->provider_id ? "provider-{$payment->provider_id}" : 'provider-none'),
  599. $payment->payment_method,
  600. "amount-{$amountCents}",
  601. ]);
  602. $payment->forceFill(['idempotency_key' => $key])->save();
  603. return $key;
  604. }
  605. // salva o gateway_customer_id do Pagar.me no Client apos criacao de ordem
  606. private function saveExternalCustomerId(Payment $payment, OrderResponseData $order): void
  607. {
  608. $customerId = $order->customer?->id;
  609. $customerCode = $order->customer?->code;
  610. if (! $customerId && ! $customerCode) {
  611. return;
  612. }
  613. $client = Client::find($payment->client_id);
  614. if (! $client) {
  615. return;
  616. }
  617. $updated = false;
  618. if (! $client->gateway_customer_id && $customerId) {
  619. $client->gateway_customer_id = $customerId;
  620. $updated = true;
  621. }
  622. if (! $client->gateway_customer_code && $customerCode) {
  623. $client->gateway_customer_code = $customerCode;
  624. $updated = true;
  625. }
  626. if ($updated) {
  627. $client->save();
  628. }
  629. }
  630. }