PagarmePaymentService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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->customerDocument($client->document);
  245. $documentType = $this->customerDocumentType($document);
  246. $phone = $this->buildPhonePayload($user->phone)
  247. ?: $this->buildPhonePayload($options['phone'] ?? null);
  248. $state = $address->state?->code ?? $address->city?->state?->code;
  249. $city = $address->city?->name;
  250. $zipCode = $this->digits($address->zip_code);
  251. $line1 = implode(', ', array_filter([
  252. $address->number ?: 'S/N',
  253. $address->address,
  254. $address->district,
  255. ]));
  256. foreach ([
  257. 'documento' => $document,
  258. 'estado' => $state,
  259. 'cidade' => $city,
  260. 'cep' => $zipCode,
  261. 'endereco' => $line1,
  262. 'telefone' => $phone,
  263. ] as $field => $value) {
  264. if ($value === null || $value === '' || $value === []) {
  265. throw new \InvalidArgumentException("Cliente precisa ter {$field} valido para criar pedido no Pagar.me.");
  266. }
  267. }
  268. $customerAddress = new AddressData(
  269. line1: $line1,
  270. line2: $address->complement ?: $address->instructions,
  271. zipCode: $zipCode,
  272. city: $city,
  273. state: $state,
  274. country: 'BR',
  275. );
  276. $customerPhones = null;
  277. if ($phone) {
  278. $customerPhones = new PhonesData(
  279. mobilePhone: new PhoneData(
  280. countryCode: $phone['country_code'],
  281. areaCode: $phone['area_code'],
  282. number: $phone['number'],
  283. ),
  284. );
  285. }
  286. return new CustomerRequestData(
  287. name: $user->name,
  288. email: $user->email,
  289. document: $document,
  290. type: $documentType === 'CNPJ' ? 'company' : 'individual',
  291. documentType: $documentType,
  292. code: $client->ensureGatewayCode(),
  293. address: $customerAddress,
  294. phones: $customerPhones,
  295. );
  296. }
  297. private function buildOrderItems(Schedule $schedule, float $grossAmount): array
  298. {
  299. $description = $schedule->customSchedule?->serviceType?->description
  300. ?? "Servico {$schedule->id}";
  301. return [new ItemData(
  302. code: "schedule-{$schedule->id}",
  303. amount: OrderRequestData::amountInCents($grossAmount),
  304. quantity: 1,
  305. description: $description,
  306. )];
  307. }
  308. private function logCreditCardOrderResult(Payment $payment, array $orderResponse, string $source): void
  309. {
  310. $order = OrderResponseData::fromArray($orderResponse);
  311. $charge = $order->firstCharge();
  312. $transaction = $order->lastTransaction();
  313. $failureCode = $order->failureCode();
  314. Log::channel('pagarme')->info('Pagar.me credit card order result', [
  315. 'source' => $source,
  316. 'payment_id' => $payment->id,
  317. 'provider_id' => $payment->provider_id,
  318. 'order_id' => $order->id,
  319. 'order_status' => $order->status,
  320. 'charge_id' => $charge?->id,
  321. 'charge_status' => $charge?->status,
  322. 'transaction_id' => $transaction?->id,
  323. 'transaction_status' => $transaction?->status,
  324. 'failure_code' => $failureCode,
  325. 'failure_message' => $order->failureMessage(),
  326. 'acquirer_message' => $transaction?->acquirerMessage,
  327. 'gateway_response' => $this->normalizeGatewayResponseForFailure(
  328. $transaction?->gatewayResponse ?? [],
  329. $failureCode,
  330. ),
  331. ]);
  332. }
  333. private function normalizeFailedGatewayPayload(array $payload, ?string $failureCode, ?string $failureMessage): array
  334. {
  335. $payload['failure_code'] = $failureCode;
  336. $payload['failure_message'] = $failureMessage;
  337. if (isset($payload['charges'][0]['last_transaction']['gateway_response'])
  338. && is_array($payload['charges'][0]['last_transaction']['gateway_response'])) {
  339. $payload['charges'][0]['last_transaction']['gateway_response'] = $this->normalizeGatewayResponseForFailure(
  340. $payload['charges'][0]['last_transaction']['gateway_response'],
  341. $failureCode,
  342. );
  343. }
  344. return $payload;
  345. }
  346. private function normalizeGatewayResponseForFailure(array $gatewayResponse, ?string $failureCode): array
  347. {
  348. $code = $gatewayResponse['code'] ?? null;
  349. if (! $failureCode || ! $this->isMisleadingGatewayCode($code)) {
  350. return $gatewayResponse;
  351. }
  352. $gatewayResponse['raw_code'] = $code;
  353. $gatewayResponse['code'] = $failureCode;
  354. return $gatewayResponse;
  355. }
  356. private function isMisleadingGatewayCode(mixed $code): bool
  357. {
  358. if ($code === null || $code === '') {
  359. return false;
  360. }
  361. $code = mb_strtolower((string) $code);
  362. return preg_match('/^[1-2]\d{2}$/', $code) === 1
  363. || in_array($code, ['00', '0', 'approved', 'success'], true);
  364. }
  365. private function buildPhonePayload(?string $phone): ?array
  366. {
  367. $digits = $this->digits($phone);
  368. if (strlen($digits) < 10) {
  369. return null;
  370. }
  371. if (str_starts_with($digits, '55')) {
  372. $digits = substr($digits, 2);
  373. }
  374. return [
  375. 'country_code' => '55',
  376. 'area_code' => substr($digits, 0, 2),
  377. 'number' => substr($digits, 2),
  378. ];
  379. }
  380. private function roundMoneyUp(float $amount): float
  381. {
  382. return ceil($amount * 100) / 100;
  383. }
  384. private function buildSplit(Payment $payment, array $options): array
  385. {
  386. $transfers = PaymentSplit::query()
  387. ->where('payment_id', $payment->id)
  388. ->get();
  389. $split = OrderRequestData::splitFromTransfers($transfers);
  390. $platformRecipientId = config('services.pagarme.platform_recipient_id');
  391. if (empty($platformRecipientId)) {
  392. return $split;
  393. }
  394. $orderAmountCents = OrderRequestData::amountInCents((float) $payment->gross_amount);
  395. $providerTotalCents = array_sum(array_map(
  396. static fn (SplitData $s) => $s->amount,
  397. $split,
  398. ));
  399. $platformAmountCents = $orderAmountCents - $providerTotalCents;
  400. if ($platformAmountCents > 0) {
  401. $split[] = new SplitData(
  402. amount: $platformAmountCents,
  403. recipientId: $platformRecipientId,
  404. type: 'flat',
  405. options: new SplitOptionsData(
  406. chargeProcessingFee: true,
  407. chargeRemainderFee: true,
  408. liable: true,
  409. ),
  410. );
  411. }
  412. return $split;
  413. }
  414. // evita criacao duplicada de payment
  415. private function idempotencyKey(Payment $payment): string
  416. {
  417. if (! empty($payment->idempotency_key)) {
  418. return $payment->idempotency_key;
  419. }
  420. $key = 'order-'.(string) \Illuminate\Support\Str::uuid();
  421. $payment->forceFill(['idempotency_key' => $key])->save();
  422. return $key;
  423. }
  424. // salva o gateway_customer_id do Pagar.me no Client apos criacao de ordem
  425. private function saveExternalCustomerId(Payment $payment, OrderResponseData $order): void
  426. {
  427. $customerId = $order->customer?->id;
  428. $customerCode = $order->customer?->code;
  429. if (! $customerId && ! $customerCode) {
  430. return;
  431. }
  432. $client = Client::find($payment->client_id);
  433. if (! $client) {
  434. return;
  435. }
  436. $updated = false;
  437. if (! $client->gateway_customer_id && $customerId) {
  438. $client->gateway_customer_id = $customerId;
  439. $updated = true;
  440. }
  441. if (! $client->gateway_customer_code && $customerCode) {
  442. $client->gateway_customer_code = $customerCode;
  443. $updated = true;
  444. }
  445. if ($updated) {
  446. $client->save();
  447. }
  448. }
  449. }