PagarmePaymentService.php 16 KB

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