PagarmePaymentService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. <?php
  2. namespace App\Services\Pagarme;
  3. use App\Data\Pagarme\Customer\CustomerRequestData;
  4. use App\Data\Pagarme\Customer\Parts\Request\AddressData;
  5. use App\Data\Pagarme\Customer\Parts\Request\PhoneData;
  6. use App\Data\Pagarme\Customer\Parts\Request\PhonesData;
  7. use App\Data\Pagarme\Order\OrderRequestData;
  8. use App\Data\Pagarme\Order\OrderResponseData;
  9. use App\Data\Pagarme\Order\Parts\Request\CreditCardData;
  10. use App\Data\Pagarme\Order\Parts\Request\ItemData;
  11. use App\Data\Pagarme\Order\Parts\Request\PaymentData;
  12. use App\Data\Pagarme\Order\Parts\Request\PixAdditionalInformationData;
  13. use App\Data\Pagarme\Order\Parts\Request\PixData;
  14. use App\Data\Pagarme\Order\Parts\Request\SplitData;
  15. use App\Data\Pagarme\Order\Parts\Request\SplitOptionsData;
  16. use App\Enums\PaymentSplitStatusEnum;
  17. use App\Enums\PaymentStatusEnum;
  18. use App\Models\Address;
  19. use App\Models\Client;
  20. use App\Models\Payment;
  21. use App\Models\PaymentSplit;
  22. use App\Models\Schedule;
  23. use App\Services\Pagarme\Concerns\FormatsPagarmeData;
  24. use App\Services\Pagarme\Concerns\SendsPagarmeRequests;
  25. use Illuminate\Support\Collection;
  26. use Illuminate\Support\Facades\Log;
  27. use Illuminate\Support\Str;
  28. class PagarmePaymentService
  29. {
  30. use FormatsPagarmeData;
  31. use SendsPagarmeRequests;
  32. public function calculatePaymentAmounts(float $serviceAmount, string $paymentMethod): array
  33. {
  34. if ($serviceAmount <= 0) {
  35. throw new \InvalidArgumentException('Valor do servico precisa ser maior que zero.');
  36. }
  37. if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
  38. throw new \InvalidArgumentException('Forma de pagamento invalida.');
  39. }
  40. $platformFeeRate = $paymentMethod === 'credit_card'
  41. ? (float) config('services.pagarme.platform_credit_card_fee_rate')
  42. : (float) config('services.pagarme.platform_pix_fee_rate');
  43. $platformFee = round($serviceAmount * $platformFeeRate, 2);
  44. $grossAmount = round($serviceAmount + $platformFee, 2);
  45. if ($platformFee > 0 && empty(config('services.pagarme.platform_recipient_id'))) {
  46. throw new \InvalidArgumentException('PAGARME_PLATFORM_RECIPIENT_ID precisa estar configurado para receber a taxa da plataforma no split.');
  47. }
  48. return [
  49. 'service_amount' => round($serviceAmount, 2),
  50. 'platform_fee_amount' => $platformFee,
  51. 'gross_amount' => $grossAmount,
  52. ];
  53. }
  54. public function platformFeeRates(): array
  55. {
  56. return [
  57. 'pix' => (float) config('services.pagarme.platform_pix_fee_rate'),
  58. 'credit_card' => (float) config('services.pagarme.platform_credit_card_fee_rate'),
  59. ];
  60. }
  61. public function processPayment(
  62. Payment $payment,
  63. Schedule $schedule,
  64. string $paymentMethod,
  65. ?string $cardId = null,
  66. array $options = [],
  67. ): array {
  68. $grossAmount = (float) $payment->gross_amount;
  69. $items = $this->buildOrderItems($schedule, $grossAmount);
  70. $customer = $this->buildCustomer($schedule, $options);
  71. $split = $this->buildSplit($payment, $options);
  72. $pixOptions = config('services.pagarme.pix_disable_split')
  73. ? []
  74. : ['split' => $split];
  75. $orderOptions = array_merge(['split' => $split], $pixOptions);
  76. if ($paymentMethod === 'credit_card') {
  77. $creditCard = new CreditCardData(
  78. cardId: $cardId,
  79. installments: $payment->installments,
  80. statementDescriptor: Str::limit((string) config('app.name', 'SOFTPAR'), 13, ''),
  81. operationType: 'auth_and_capture',
  82. );
  83. $result = $this->createOrderWithCreditCard(
  84. payment: $payment,
  85. items: $items,
  86. customer: $customer,
  87. creditCard: $creditCard,
  88. options: $orderOptions,
  89. );
  90. $this->logCreditCardOrderResult($payment, $result, 'create_order');
  91. $orderStatus = OrderResponseData::fromArray($result)->paymentStatus();
  92. if (! in_array($orderStatus, [PaymentStatusEnum::PAID, PaymentStatusEnum::AUTHORIZED], true)) {
  93. return $result;
  94. }
  95. return $result;
  96. }
  97. $pixData = new PixData(
  98. expiresIn: 1800,
  99. additionalInformation: [
  100. new PixAdditionalInformationData(
  101. name: 'Agendamento',
  102. value: (string) $schedule->id,
  103. ),
  104. ],
  105. );
  106. return $this->createOrderWithPix(
  107. payment: $payment,
  108. items: $items,
  109. customer: $customer,
  110. pix: $pixData,
  111. options: $pixOptions,
  112. );
  113. }
  114. public function processCartPayment(
  115. Payment $payment,
  116. Collection $schedules,
  117. string $paymentMethod,
  118. ?string $cardId = null,
  119. array $options = [],
  120. ): array {
  121. $firstSchedule = $schedules->first();
  122. if (! $firstSchedule) {
  123. throw new \InvalidArgumentException('Carrinho precisa ter ao menos um agendamento.');
  124. }
  125. $items = $schedules
  126. ->map(fn (Schedule $schedule) => $this->buildOrderItem(
  127. schedule: $schedule,
  128. grossAmount: (float) data_get($schedule, 'payment_gross_amount', $schedule->total_amount),
  129. ))
  130. ->values()
  131. ->all();
  132. $customer = $this->buildCustomer($firstSchedule, $options);
  133. $split = $this->buildSplit($payment, $options);
  134. $metadataOptions = [
  135. 'metadata' => [
  136. 'schedule_ids' => $schedules->pluck('id')->implode(','),
  137. ],
  138. ];
  139. $splitOptions = ['split' => $split];
  140. $pixOptions = config('services.pagarme.pix_disable_split')
  141. ? $metadataOptions
  142. : array_merge($metadataOptions, $splitOptions);
  143. $creditCardOptions = array_merge($metadataOptions, $splitOptions);
  144. if ($paymentMethod === 'credit_card') {
  145. $creditCard = new CreditCardData(
  146. cardId: $cardId,
  147. installments: $payment->installments,
  148. statementDescriptor: Str::limit((string) config('app.name', 'SOFTPAR'), 13, ''),
  149. operationType: 'auth_and_capture',
  150. );
  151. $result = $this->createOrderWithCreditCard(
  152. payment: $payment,
  153. items: $items,
  154. customer: $customer,
  155. creditCard: $creditCard,
  156. options: $creditCardOptions,
  157. );
  158. $this->logCreditCardOrderResult($payment, $result, 'create_cart_order');
  159. return $result;
  160. }
  161. $pixData = new PixData(
  162. expiresIn: 1800,
  163. additionalInformation: [
  164. new PixAdditionalInformationData(
  165. name: 'Agendamentos',
  166. value: $schedules->pluck('id')->implode(','),
  167. ),
  168. ],
  169. );
  170. return $this->createOrderWithPix(
  171. payment: $payment,
  172. items: $items,
  173. customer: $customer,
  174. pix: $pixData,
  175. options: $pixOptions,
  176. );
  177. }
  178. public function createOrderWithCreditCard(
  179. Payment $payment,
  180. array $items,
  181. CustomerRequestData $customer,
  182. CreditCardData $creditCard,
  183. array $options = []
  184. ): array {
  185. return $this->createOrder(
  186. payment: $payment,
  187. items: $items,
  188. customer: $customer,
  189. paymentMethod: OrderRequestData::creditCardPaymentMethod(
  190. creditCard: $creditCard,
  191. split: is_array($options['split'] ?? null) ? $options['split'] : null,
  192. ),
  193. options: $options,
  194. );
  195. }
  196. public function createOrderWithPix(
  197. Payment $payment,
  198. array $items,
  199. CustomerRequestData $customer,
  200. PixData $pix,
  201. array $options = []
  202. ): array {
  203. return $this->createOrder(
  204. payment: $payment,
  205. items: $items,
  206. customer: $customer,
  207. paymentMethod: OrderRequestData::pixPaymentMethod(
  208. pix: $pix,
  209. split: is_array($options['split'] ?? null) ? $options['split'] : null,
  210. ),
  211. options: $options,
  212. );
  213. }
  214. public function createOrder(
  215. Payment $payment,
  216. array $items,
  217. CustomerRequestData $customer,
  218. PaymentData $paymentMethod,
  219. array $options = []
  220. ): array {
  221. $metadata = array_filter([
  222. 'payment_id' => (string) $payment->id,
  223. 'schedule_id' => $payment->schedule_id ? (string) $payment->schedule_id : null,
  224. 'client_id' => (string) $payment->client_id,
  225. 'provider_id' => $payment->provider_id ? (string) $payment->provider_id : null,
  226. ], fn ($value) => $value !== null);
  227. $metadata = array_merge($metadata, $options['metadata'] ?? []);
  228. $requestData = new OrderRequestData(
  229. code: $payment->ensureGatewayCode(),
  230. items: $items,
  231. payments: [$paymentMethod],
  232. metadata: $metadata,
  233. customer: $customer,
  234. customerId: $options['customer_id'] ?? null,
  235. closed: $options['closed'] ?? true,
  236. channel: $options['channel'] ?? null,
  237. );
  238. $order = OrderResponseData::fromArray($this->pagarmeRequest(
  239. method: 'POST',
  240. path: '/orders',
  241. payload: $requestData,
  242. idempotencyKey: $this->idempotencyKey($payment),
  243. errorMessage: 'Erro ao criar pedido de pagamento no Pagar.me.',
  244. ));
  245. $order->requireId();
  246. $this->saveExternalCustomerId($payment, $order);
  247. return $order->toArray();
  248. }
  249. //
  250. public function applyGatewayResponseToPayment(Payment $payment, array $orderResponse): Payment
  251. {
  252. $order = OrderResponseData::fromArray($orderResponse);
  253. $newStatus = $order->paymentStatus();
  254. $failureCode = null;
  255. $failureMessage = null;
  256. if ($newStatus === PaymentStatusEnum::FAILED) {
  257. $failureCode = $order->failureCode();
  258. $failureMessage = $order->failureMessage();
  259. $this->logCreditCardOrderResult($payment, $orderResponse, 'webhook_failed');
  260. }
  261. $gatewayFeeCents = $order->lastTransaction()?->cost ?? 0;
  262. $gatewayFee = $gatewayFeeCents > 0 ? round($gatewayFeeCents / 100, 2) : 0;
  263. $gatewayPayload = $newStatus === PaymentStatusEnum::FAILED
  264. ? $this->normalizeFailedGatewayPayload($orderResponse, $failureCode, $failureMessage)
  265. : $orderResponse;
  266. $payment->forceFill([
  267. 'gateway_provider' => 'pagarme',
  268. 'gateway_entity_reference' => $order->gatewayEntityReference(),
  269. 'gateway_entity_label' => $order->gatewayEntityLabel(),
  270. 'gateway_operation_reference' => $order->gatewayOperationReference(),
  271. 'gateway_operation_label' => $order->gatewayOperationLabel(),
  272. 'status' => $newStatus,
  273. 'paid_at' => $order->paidAt(),
  274. 'authorized_at' => $order->authorizedAt(),
  275. 'gateway_payload' => $gatewayPayload,
  276. 'gateway_fee_amount' => $gatewayFee,
  277. 'failure_code' => $failureCode,
  278. 'failure_message' => $failureMessage,
  279. ])->save();
  280. $splitStatus = match ($newStatus) {
  281. PaymentStatusEnum::PAID => PaymentSplitStatusEnum::TRANSFERRED,
  282. PaymentStatusEnum::FAILED => PaymentSplitStatusEnum::FAILED,
  283. PaymentStatusEnum::CANCELLED => PaymentSplitStatusEnum::CANCELLED,
  284. PaymentStatusEnum::AUTHORIZED => PaymentSplitStatusEnum::PROCESSING,
  285. default => PaymentSplitStatusEnum::PENDING,
  286. };
  287. PaymentSplit::query()
  288. ->where('payment_id', $payment->id)
  289. ->update(['status' => $splitStatus]);
  290. return $payment->fresh();
  291. }
  292. //
  293. private function buildCustomer(Schedule $schedule, array $options = []): CustomerRequestData
  294. {
  295. $client = $schedule->client;
  296. $user = $client->user()->first(['id', 'name', 'email', 'phone']);
  297. $address = Address::with(['city.state', 'state'])->find($schedule->address_id);
  298. foreach ([
  299. 'nome' => $user?->name,
  300. 'email' => $user?->email,
  301. 'documento' => $client->document,
  302. ] as $field => $value) {
  303. if ($value === null || $value === '') {
  304. throw new \InvalidArgumentException("Cliente precisa ter {$field} para criar pedido no Pagar.me.");
  305. }
  306. }
  307. if (! $address) {
  308. throw new \InvalidArgumentException('Endereco do agendamento nao encontrado para criar pedido no Pagar.me.');
  309. }
  310. $document = $this->digits($client->document);
  311. $phone = $this->buildPhonePayload($user->phone)
  312. ?: $this->buildPhonePayload($options['phone'] ?? null);
  313. $state = $address->state?->code ?? $address->city?->state?->code;
  314. $city = $address->city?->name;
  315. $zipCode = $this->digits($address->zip_code);
  316. $line1 = implode(', ', array_filter([
  317. $address->number ?: 'S/N',
  318. $address->address,
  319. $address->district,
  320. ]));
  321. foreach ([
  322. 'documento' => $document,
  323. 'estado' => $state,
  324. 'cidade' => $city,
  325. 'cep' => $zipCode,
  326. 'endereco' => $line1,
  327. 'telefone' => $phone,
  328. ] as $field => $value) {
  329. if ($value === null || $value === '' || $value === []) {
  330. throw new \InvalidArgumentException("Cliente precisa ter {$field} valido para criar pedido no Pagar.me.");
  331. }
  332. }
  333. $customerAddress = new AddressData(
  334. line1: $line1,
  335. line2: $address->complement ?: $address->instructions,
  336. zipCode: $zipCode,
  337. city: $city,
  338. state: $state,
  339. country: 'BR',
  340. );
  341. $customerPhones = null;
  342. if ($phone) {
  343. $customerPhones = new PhonesData(
  344. mobilePhone: new PhoneData(
  345. countryCode: $phone['country_code'],
  346. areaCode: $phone['area_code'],
  347. number: $phone['number'],
  348. ),
  349. );
  350. }
  351. return new CustomerRequestData(
  352. name: $user->name,
  353. email: $user->email,
  354. document: $document,
  355. type: strlen($document) === 14 ? 'company' : 'individual',
  356. documentType: strlen($document) === 14 ? 'CNPJ' : 'CPF',
  357. code: $client->ensureGatewayCode(),
  358. address: $customerAddress,
  359. phones: $customerPhones,
  360. );
  361. }
  362. private function buildOrderItems(Schedule $schedule, float $grossAmount): array
  363. {
  364. return [$this->buildOrderItem($schedule, $grossAmount)];
  365. }
  366. private function buildOrderItem(Schedule $schedule, float $grossAmount): ItemData
  367. {
  368. $description = $schedule->customSchedule?->serviceType?->description
  369. ?? "Servico {$schedule->id}";
  370. return new ItemData(
  371. code: "schedule-{$schedule->id}",
  372. amount: OrderRequestData::amountInCents($grossAmount),
  373. quantity: 1,
  374. description: $description,
  375. );
  376. }
  377. private function logCreditCardOrderResult(Payment $payment, array $orderResponse, string $source): void
  378. {
  379. $order = OrderResponseData::fromArray($orderResponse);
  380. $charge = $order->firstCharge();
  381. $transaction = $order->lastTransaction();
  382. $failureCode = $order->failureCode();
  383. Log::channel('pagarme')->info('Pagar.me credit card order result', [
  384. 'source' => $source,
  385. 'payment_id' => $payment->id,
  386. 'provider_id' => $payment->provider_id,
  387. 'order_id' => $order->id,
  388. 'order_status' => $order->status,
  389. 'charge_id' => $charge?->id,
  390. 'charge_status' => $charge?->status,
  391. 'transaction_id' => $transaction?->id,
  392. 'transaction_status' => $transaction?->status,
  393. 'failure_code' => $failureCode,
  394. 'failure_message' => $order->failureMessage(),
  395. 'acquirer_message' => $transaction?->acquirerMessage,
  396. 'gateway_response' => $this->normalizeGatewayResponseForFailure(
  397. $transaction?->gatewayResponse ?? [],
  398. $failureCode,
  399. ),
  400. ]);
  401. }
  402. private function normalizeFailedGatewayPayload(array $payload, ?string $failureCode, ?string $failureMessage): array
  403. {
  404. $payload['failure_code'] = $failureCode;
  405. $payload['failure_message'] = $failureMessage;
  406. if (isset($payload['charges'][0]['last_transaction']['gateway_response'])
  407. && is_array($payload['charges'][0]['last_transaction']['gateway_response'])) {
  408. $payload['charges'][0]['last_transaction']['gateway_response'] = $this->normalizeGatewayResponseForFailure(
  409. $payload['charges'][0]['last_transaction']['gateway_response'],
  410. $failureCode,
  411. );
  412. }
  413. return $payload;
  414. }
  415. private function normalizeGatewayResponseForFailure(array $gatewayResponse, ?string $failureCode): array
  416. {
  417. $code = $gatewayResponse['code'] ?? null;
  418. if (! $failureCode || ! $this->isMisleadingGatewayCode($code)) {
  419. return $gatewayResponse;
  420. }
  421. $gatewayResponse['raw_code'] = $code;
  422. $gatewayResponse['code'] = $failureCode;
  423. return $gatewayResponse;
  424. }
  425. private function isMisleadingGatewayCode(mixed $code): bool
  426. {
  427. if ($code === null || $code === '') {
  428. return false;
  429. }
  430. $code = mb_strtolower((string) $code);
  431. return preg_match('/^[1-2]\d{2}$/', $code) === 1
  432. || in_array($code, ['00', '0', 'approved', 'success'], true);
  433. }
  434. private function buildPhonePayload(?string $phone): ?array
  435. {
  436. $digits = $this->digits($phone);
  437. if (strlen($digits) < 10) {
  438. return null;
  439. }
  440. if (str_starts_with($digits, '55')) {
  441. $digits = substr($digits, 2);
  442. }
  443. return [
  444. 'country_code' => '55',
  445. 'area_code' => substr($digits, 0, 2),
  446. 'number' => substr($digits, 2),
  447. ];
  448. }
  449. private function roundMoneyUp(float $amount): float
  450. {
  451. return ceil($amount * 100) / 100;
  452. }
  453. private function buildSplit(Payment $payment, array $options): array
  454. {
  455. $transfers = PaymentSplit::query()
  456. ->where('payment_id', $payment->id)
  457. ->get();
  458. $split = OrderRequestData::splitFromTransfers($transfers);
  459. $platformRecipientId = config('services.pagarme.platform_recipient_id');
  460. if (empty($platformRecipientId)) {
  461. return $split;
  462. }
  463. $orderAmountCents = OrderRequestData::amountInCents((float) $payment->gross_amount);
  464. $providerTotalCents = array_sum(array_map(
  465. static fn (SplitData $s) => $s->amount,
  466. $split,
  467. ));
  468. $platformAmountCents = $orderAmountCents - $providerTotalCents;
  469. if ($platformAmountCents > 0) {
  470. $split[] = new SplitData(
  471. amount: $platformAmountCents,
  472. recipientId: $platformRecipientId,
  473. type: 'flat',
  474. options: new SplitOptionsData(
  475. chargeProcessingFee: true,
  476. chargeRemainderFee: true,
  477. liable: true,
  478. ),
  479. );
  480. }
  481. return $split;
  482. }
  483. // evita criacao duplicada de payment
  484. private function idempotencyKey(Payment $payment): string
  485. {
  486. if (! empty($payment->idempotency_key)) {
  487. return $payment->idempotency_key;
  488. }
  489. $key = 'order-'.(string) \Illuminate\Support\Str::uuid();
  490. $payment->forceFill(['idempotency_key' => $key])->save();
  491. return $key;
  492. }
  493. // salva o gateway_customer_id do Pagar.me no Client apos criacao de ordem
  494. private function saveExternalCustomerId(Payment $payment, OrderResponseData $order): void
  495. {
  496. $customerId = $order->customer?->id;
  497. $customerCode = $order->customer?->code;
  498. if (! $customerId && ! $customerCode) {
  499. return;
  500. }
  501. $client = Client::find($payment->client_id);
  502. if (! $client) {
  503. return;
  504. }
  505. $updated = false;
  506. if (! $client->gateway_customer_id && $customerId) {
  507. $client->gateway_customer_id = $customerId;
  508. $updated = true;
  509. }
  510. if (! $client->gateway_customer_code && $customerCode) {
  511. $client->gateway_customer_code = $customerCode;
  512. $updated = true;
  513. }
  514. if ($updated) {
  515. $client->save();
  516. }
  517. }
  518. }