PagarmePaymentService.php 16 KB

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