PagarmePaymentService.php 27 KB

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