PagarmePaymentService.php 27 KB

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