PagarmePaymentService.php 27 KB

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