PaymentService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. <?php
  2. namespace App\Services;
  3. use App\Data\Pagarme\Request\PagarmeOrderRequestData\PagarmeOrderRequestData;
  4. use App\Enums\PaymentSplitStatusEnum;
  5. use App\Enums\PaymentStatusEnum;
  6. use App\Models\Address;
  7. use App\Models\ClientPaymentMethod;
  8. use App\Models\Payment;
  9. use App\Models\PaymentSplit;
  10. use App\Models\Schedule;
  11. use App\Services\Pagarme\PagarmePaymentService;
  12. use Carbon\Carbon;
  13. use Illuminate\Database\Eloquent\Collection;
  14. use Illuminate\Support\Str;
  15. class PaymentService
  16. {
  17. public function __construct(
  18. private readonly PagarmePaymentService $pagarmePaymentService,
  19. ) {}
  20. public function getAll(): Collection
  21. {
  22. return Payment::query()
  23. ->with(['client.user', 'provider.user'])
  24. ->orderBy('created_at', 'desc')
  25. ->get();
  26. }
  27. public function findById(int $id): ?Payment
  28. {
  29. return Payment::query()
  30. ->with(['client.user', 'provider.user'])
  31. ->find($id);
  32. }
  33. public function create(array $data): Payment
  34. {
  35. return Payment::create($data);
  36. }
  37. public function update(int $id, array $data): ?Payment
  38. {
  39. $model = $this->findById($id);
  40. if (! $model) {
  41. return null;
  42. }
  43. $model->update($data);
  44. return $model->fresh();
  45. }
  46. public function delete(int $id): bool
  47. {
  48. $model = $this->findById($id);
  49. if (! $model) {
  50. return false;
  51. }
  52. return $model->delete();
  53. }
  54. //
  55. public function payAcceptedSchedule(
  56. Schedule $schedule,
  57. string $paymentMethod,
  58. ?int $clientPaymentMethodId = null,
  59. array $options = []
  60. ): Payment {
  61. $schedule->loadMissing(['client', 'provider', 'customSchedule.serviceType']);
  62. if ($schedule->status !== 'accepted') {
  63. throw new \InvalidArgumentException('Agendamento precisa estar aceito para ser pago.');
  64. }
  65. if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
  66. throw new \InvalidArgumentException('Forma de pagamento invalida.');
  67. }
  68. if (! $schedule->provider_id || ! $schedule->provider) {
  69. throw new \InvalidArgumentException('Agendamento precisa ter prestador confirmado para gerar pagamento.');
  70. }
  71. if ((float) $schedule->total_amount <= 0) {
  72. throw new \InvalidArgumentException('Agendamento precisa ter valor maior que zero para gerar pagamento.');
  73. }
  74. if (empty($schedule->provider->recipient_id)) {
  75. throw new \InvalidArgumentException('Prestador precisa ter recipient_id do Pagar.me para receber split.');
  76. }
  77. $existingPayment = Payment::query()
  78. ->where('schedule_id', $schedule->id)
  79. ->whereIn('status', [
  80. PaymentStatusEnum::PENDING->value,
  81. PaymentStatusEnum::PROCESSING->value,
  82. PaymentStatusEnum::AUTHORIZED->value,
  83. PaymentStatusEnum::PAID->value,
  84. ])
  85. ->latest('id')
  86. ->first();
  87. if ($existingPayment) {
  88. if ($this->isIncompleteGatewayPayment($existingPayment)) {
  89. $existingPayment->forceFill([
  90. 'status' => PaymentStatusEnum::FAILED,
  91. 'failed_at' => now(),
  92. 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
  93. ])->save();
  94. } else {
  95. if ($existingPayment->payment_method !== $paymentMethod && $existingPayment->status !== PaymentStatusEnum::PAID) {
  96. throw new \InvalidArgumentException('Ja existe um pagamento em andamento para este agendamento.');
  97. }
  98. $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
  99. return $existingPayment;
  100. }
  101. }
  102. $clientPaymentMethod = null;
  103. if ($paymentMethod === 'credit_card') {
  104. if (! $clientPaymentMethodId && empty($options['card_id'])) {
  105. throw new \InvalidArgumentException('Cartao de pagamento ou card_id e obrigatorio.');
  106. }
  107. if ($clientPaymentMethodId) {
  108. $clientPaymentMethod = ClientPaymentMethod::query()
  109. ->where('client_id', $schedule->client_id)
  110. ->where('id', $clientPaymentMethodId)
  111. ->where('is_active', true)
  112. ->first();
  113. if (! $clientPaymentMethod) {
  114. throw new \InvalidArgumentException('Cartao de pagamento nao encontrado ou inativo para este cliente.');
  115. }
  116. }
  117. if (
  118. empty($clientPaymentMethod?->gateway_card_id)
  119. && empty($options['card_id'])
  120. ) {
  121. throw new \InvalidArgumentException('Cartao de pagamento invalido ou sem gateway_card_id do Pagar.me.');
  122. }
  123. }
  124. $serviceAmount = (float) $schedule->total_amount;
  125. $platformFee = round($serviceAmount * 0.11, 2);
  126. $grossAmount = round($serviceAmount + $platformFee, 2);
  127. $items = $this->buildOrderItems($schedule, $grossAmount);
  128. $this->ensureCustomerPhoneForPayment($schedule, $options);
  129. $customer = $this->buildCustomerPayload(schedule: $schedule, options: $options, requirePhone: true);
  130. $platformRecipientId = config('services.pagarme.platform_recipient_id');
  131. if ($platformFee > 0 && empty($platformRecipientId)) {
  132. throw new \InvalidArgumentException('PAGARME_PLATFORM_RECIPIENT_ID precisa estar configurado para receber a taxa da plataforma no split.');
  133. }
  134. $payment = Payment::create([
  135. 'schedule_id' => $schedule->id,
  136. 'client_id' => $schedule->client_id,
  137. 'provider_id' => $schedule->provider_id,
  138. 'client_payment_method_id' => $paymentMethod === 'credit_card' ? $clientPaymentMethod->id : null,
  139. 'gateway_provider' => 'pagarme',
  140. 'gateway_code' => 'payment-'.(string) Str::uuid(),
  141. 'payment_method' => $paymentMethod,
  142. 'status' => PaymentStatusEnum::PENDING,
  143. 'gross_amount' => $grossAmount,
  144. 'gateway_fee_amount' => 0,
  145. 'platform_fee_amount' => $platformFee,
  146. 'net_amount' => $grossAmount,
  147. 'currency' => 'BRL',
  148. 'installments' => 1,
  149. 'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
  150. 'metadata' => [
  151. 'service_amount' => number_format($serviceAmount, 2, '.', ''),
  152. 'platform_fee' => number_format($platformFee, 2, '.', ''),
  153. ],
  154. ]);
  155. $transfer = PaymentSplit::create([
  156. 'payment_id' => $payment->id,
  157. 'provider_id' => $schedule->provider_id,
  158. 'gateway_provider' => 'pagarme',
  159. 'gateway_transfer_target_reference' => $schedule->provider->recipient_id,
  160. 'gateway_transfer_target_label' => 'recipient',
  161. 'status' => PaymentSplitStatusEnum::PENDING,
  162. 'gross_amount' => $serviceAmount,
  163. 'gateway_fee_amount' => 0,
  164. 'net_amount' => $serviceAmount,
  165. 'metadata' => [
  166. 'schedule_id' => (string) $schedule->id,
  167. ],
  168. ]);
  169. $split = PagarmeOrderRequestData::splitFromTransfers(collect([$transfer]));
  170. if ($platformFee > 0) {
  171. $split[] = [
  172. 'amount' => PagarmeOrderRequestData::amountInCents($platformFee),
  173. 'recipient_id' => $platformRecipientId,
  174. 'type' => 'flat',
  175. 'options' => [
  176. 'charge_processing_fee' => true,
  177. 'charge_remainder_fee' => true,
  178. 'liable' => true,
  179. ],
  180. ];
  181. }
  182. $pixOptions = config('services.pagarme.pix_disable_split')
  183. ? []
  184. : ['split' => $split];
  185. try {
  186. $creditCardReference = $paymentMethod === 'credit_card'
  187. ? $this->resolveCreditCardReference($clientPaymentMethod, $options)
  188. : [];
  189. $orderResponse = $paymentMethod === 'credit_card'
  190. ? $this->pagarmePaymentService->createOrderWithCreditCard(
  191. payment: $payment,
  192. items: $items,
  193. customer: $customer,
  194. creditCard: [
  195. 'installments' => 1,
  196. 'statement_descriptor' => Str::limit((string) config('app.name', 'SOFTPAR'), 13, ''),
  197. 'operation_type' => 'auth_and_capture',
  198. ] + $creditCardReference,
  199. options: [
  200. 'split' => $split,
  201. ],
  202. )
  203. : $this->pagarmePaymentService->createOrderWithPix(
  204. payment: $payment,
  205. items: $items,
  206. customer: $customer,
  207. pix: [
  208. 'expires_in' => '1800',
  209. 'additional_information' => [
  210. [
  211. 'name' => 'Agendamento',
  212. 'value' => (string) $schedule->id,
  213. ],
  214. ],
  215. ],
  216. options: $pixOptions,
  217. );
  218. } catch (\Throwable $e) {
  219. $payment->forceFill([
  220. 'status' => PaymentStatusEnum::FAILED,
  221. 'failed_at' => now(),
  222. 'failure_message' => $e->getMessage(),
  223. ])->save();
  224. $transfer->update(['status' => PaymentSplitStatusEnum::FAILED]);
  225. throw $e;
  226. }
  227. $payment = $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
  228. $this->syncScheduleStatusAfterPayment($schedule, $payment);
  229. return $payment;
  230. }
  231. //
  232. private function buildOrderItems(Schedule $schedule, float $grossAmount): array
  233. {
  234. $description = $schedule->customSchedule?->serviceType?->description
  235. ?? "Servico {$schedule->id}";
  236. return [[
  237. 'amount' => PagarmeOrderRequestData::amountInCents($grossAmount),
  238. 'description' => $description,
  239. 'quantity' => 1,
  240. 'code' => "schedule-{$schedule->id}",
  241. ]];
  242. }
  243. private function buildCustomerPayload(
  244. Schedule $schedule,
  245. array $options = [],
  246. bool $requirePhone = true
  247. ): array {
  248. $client = $schedule->client;
  249. $user = $client->user()->first(['id', 'name', 'email', 'phone']);
  250. $address = Address::with(['city.state', 'state'])->find($schedule->address_id);
  251. foreach ([
  252. 'nome' => $user?->name,
  253. 'email' => $user?->email,
  254. 'documento' => $client->document,
  255. ] as $field => $value) {
  256. if ($value === null || $value === '') {
  257. throw new \InvalidArgumentException("Cliente precisa ter {$field} para criar pedido no Pagar.me.");
  258. }
  259. }
  260. if (! $address) {
  261. throw new \InvalidArgumentException('Endereco do agendamento nao encontrado para criar pedido no Pagar.me.');
  262. }
  263. $document = $this->digits($client->document);
  264. $phone = $this->buildPhonePayload($user->phone)
  265. ?: $this->buildPhonePayload($options['phone'] ?? null);
  266. $state = $address->state?->code ?? $address->city?->state?->code;
  267. $city = $address->city?->name;
  268. $zipCode = $this->digits($address->zip_code);
  269. $line1 = implode(', ', array_filter([
  270. $address->number ?: 'S/N',
  271. $address->address,
  272. $address->district,
  273. ]));
  274. $requiredFields = [
  275. 'documento' => $document,
  276. 'estado' => $state,
  277. 'cidade' => $city,
  278. 'cep' => $zipCode,
  279. 'endereco' => $line1,
  280. ];
  281. if ($requirePhone) {
  282. $requiredFields['telefone'] = $phone;
  283. }
  284. foreach ($requiredFields as $field => $value) {
  285. if ($value === null || $value === '' || $value === []) {
  286. throw new \InvalidArgumentException("Cliente precisa ter {$field} valido para criar pedido no Pagar.me.");
  287. }
  288. }
  289. return [
  290. 'name' => $user->name,
  291. 'email' => $user->email,
  292. 'code' => "client-{$client->id}",
  293. 'document' => $document,
  294. 'document_type' => strlen($document) === 14 ? 'CNPJ' : 'CPF',
  295. 'type' => strlen($document) === 14 ? 'company' : 'individual',
  296. 'address' => [
  297. 'country' => 'BR',
  298. 'state' => $state,
  299. 'city' => $city,
  300. 'zip_code' => $zipCode,
  301. 'line_1' => $line1,
  302. 'line_2' => $address->complement ?: $address->instructions,
  303. ],
  304. 'phones' => $phone ? ['mobile_phone' => $phone] : null,
  305. ];
  306. }
  307. private function buildPhonePayload(?string $phone): ?array
  308. {
  309. $digits = $this->digits($phone);
  310. if (strlen($digits) < 10) {
  311. return null;
  312. }
  313. if (str_starts_with($digits, '55')) {
  314. $digits = substr($digits, 2);
  315. }
  316. return [
  317. 'country_code' => '55',
  318. 'area_code' => substr($digits, 0, 2),
  319. 'number' => substr($digits, 2),
  320. ];
  321. }
  322. private function ensureCustomerPhoneForPayment(Schedule $schedule, array $options = []): void
  323. {
  324. $userPhone = $schedule->client?->user?->phone;
  325. $phone = $this->buildPhonePayload($userPhone)
  326. ?: $this->buildPhonePayload($options['phone'] ?? null);
  327. if ($phone) {
  328. return;
  329. }
  330. throw new \InvalidArgumentException(
  331. 'Voce precisa cadastrar um numero de celular valido no seu perfil para concluir o pagamento.'
  332. );
  333. }
  334. private function digits(?string $value): string
  335. {
  336. return preg_replace('/\D+/', '', (string) $value) ?? '';
  337. }
  338. private function isIncompleteGatewayPayment(Payment $payment): bool
  339. {
  340. return $payment->status === PaymentStatusEnum::PENDING
  341. && empty($payment->gateway_entity_reference)
  342. && empty($payment->gateway_operation_reference)
  343. && empty($payment->gateway_payload);
  344. }
  345. private function resolveCreditCardReference(?ClientPaymentMethod $clientPaymentMethod, array $options): array
  346. {
  347. if (! empty($options['card_id'])) {
  348. return ['card_id' => $options['card_id']];
  349. }
  350. if (! empty($clientPaymentMethod?->gateway_card_id)) {
  351. return ['card_id' => $clientPaymentMethod->gateway_card_id];
  352. }
  353. throw new \InvalidArgumentException('Cartao de pagamento precisa ter gateway_card_id do Pagar.me.');
  354. }
  355. public function syncScheduleStatusAfterPayment(Schedule $schedule, Payment $payment): void
  356. {
  357. if ($payment->status !== PaymentStatusEnum::PAID || $schedule->status === 'paid') {
  358. return;
  359. }
  360. $schedule->update(['status' => 'paid']);
  361. }
  362. }