PagarmePaymentService.php 16 KB

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