PagarmePaymentService.php 19 KB

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