PagarmePaymentService.php 17 KB

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