PagarmePaymentService.php 27 KB

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