PaymentService.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\PaymentSplitStatusEnum;
  4. use App\Enums\PaymentStatusEnum;
  5. use App\Models\ClientPaymentMethod;
  6. use App\Models\Payment;
  7. use App\Models\PaymentSplit;
  8. use App\Models\Schedule;
  9. use App\Services\Pagarme\PagarmePaymentService;
  10. use Carbon\Carbon;
  11. use Illuminate\Auth\Access\AuthorizationException;
  12. use Illuminate\Database\Eloquent\Collection;
  13. use Illuminate\Support\Collection as SupportCollection;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Str;
  16. class PaymentService
  17. {
  18. public function __construct(
  19. private readonly PagarmePaymentService $pagarmePaymentService,
  20. ) {}
  21. public function getAll(): Collection
  22. {
  23. return Payment::query()
  24. ->with(['client.user', 'provider.user'])
  25. ->orderBy('created_at', 'desc')
  26. ->get();
  27. }
  28. public function findById(int $id): ?Payment
  29. {
  30. return Payment::query()
  31. ->with(['client.user', 'provider.user'])
  32. ->find($id);
  33. }
  34. public function create(array $data): Payment
  35. {
  36. return Payment::create($data);
  37. }
  38. public function update(int $id, array $data): ?Payment
  39. {
  40. $model = $this->findById($id);
  41. if (! $model) {
  42. return null;
  43. }
  44. $model->update($data);
  45. return $model->fresh();
  46. }
  47. public function delete(int $id): bool
  48. {
  49. $model = $this->findById($id);
  50. if (! $model) {
  51. return false;
  52. }
  53. return $model->delete();
  54. }
  55. //
  56. public function platformFees(): array
  57. {
  58. return $this->pagarmePaymentService->platformFeeRates();
  59. }
  60. //
  61. public function payAcceptedSchedule(
  62. Schedule $schedule,
  63. string $paymentMethod,
  64. ?int $clientPaymentMethodId = null, array $options = []
  65. ): Payment {
  66. $schedule->loadMissing(['client', 'provider', 'customSchedule.serviceType']);
  67. if ($schedule->status !== 'accepted') {
  68. throw new \InvalidArgumentException('Agendamento precisa estar aceito para ser pago.');
  69. }
  70. if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
  71. throw new \InvalidArgumentException('Forma de pagamento invalida.');
  72. }
  73. if (! $schedule->provider_id || ! $schedule->provider) {
  74. throw new \InvalidArgumentException('Agendamento precisa ter prestador confirmado para gerar pagamento.');
  75. }
  76. if ((float) $schedule->total_amount <= 0) {
  77. throw new \InvalidArgumentException('Agendamento precisa ter valor maior que zero para gerar pagamento.');
  78. }
  79. if (empty($schedule->provider->recipient_id)) {
  80. throw new \InvalidArgumentException('Prestador precisa ter recipient_id do Pagar.me para receber split.');
  81. }
  82. $existingPayment = Payment::query()
  83. ->where('schedule_id', $schedule->id)
  84. ->whereIn('status', [
  85. PaymentStatusEnum::PENDING->value,
  86. PaymentStatusEnum::PROCESSING->value,
  87. PaymentStatusEnum::AUTHORIZED->value,
  88. PaymentStatusEnum::PAID->value,
  89. ])
  90. ->latest('id')
  91. ->first();
  92. if ($existingPayment) {
  93. if ($this->isIncompleteGatewayPayment($existingPayment)) {
  94. $existingPayment->forceFill([
  95. 'status' => PaymentStatusEnum::FAILED,
  96. 'failed_at' => now(),
  97. 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
  98. ])->save();
  99. }
  100. elseif ($this->isExpiredPixPayment($existingPayment)) {
  101. $existingPayment->forceFill([
  102. 'status' => PaymentStatusEnum::FAILED,
  103. 'failed_at' => now(),
  104. 'failure_message' => 'Pagamento Pix expirado.',
  105. ])->save();
  106. PaymentSplit::query()
  107. ->where('payment_id', $existingPayment->id)
  108. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  109. }
  110. else {
  111. if ($existingPayment->payment_method !== $paymentMethod && $existingPayment->status !== PaymentStatusEnum::PAID) {
  112. throw new \InvalidArgumentException('Ja existe um pagamento em andamento para este agendamento.');
  113. }
  114. $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
  115. return $existingPayment;
  116. }
  117. }
  118. $clientPaymentMethod = null;
  119. $cardId = null;
  120. if ($paymentMethod === 'credit_card') {
  121. if (! $clientPaymentMethodId && empty($options['card_id'])) {
  122. throw new \InvalidArgumentException('Cartao de pagamento ou card_id e obrigatorio.');
  123. }
  124. if ($clientPaymentMethodId) {
  125. $clientPaymentMethod = ClientPaymentMethod::query()
  126. ->where('client_id', $schedule->client_id)
  127. ->where('id', $clientPaymentMethodId)
  128. ->where('is_active', true)
  129. ->first();
  130. if (! $clientPaymentMethod) {
  131. throw new \InvalidArgumentException('Cartao de pagamento nao encontrado ou inativo para este cliente.');
  132. }
  133. }
  134. $cardId = $options['card_id'] ?? $clientPaymentMethod?->gateway_card_id ?? null;
  135. if (empty($cardId)) {
  136. throw new \InvalidArgumentException('Cartao de pagamento invalido ou sem gateway_card_id do Pagar.me.');
  137. }
  138. }
  139. $serviceAmount = (float) $schedule->total_amount;
  140. $amounts = $this->pagarmePaymentService->calculatePaymentAmounts(
  141. serviceAmount: $serviceAmount,
  142. paymentMethod: $paymentMethod,
  143. );
  144. $payment = Payment::create([
  145. 'schedule_id' => $schedule->id,
  146. 'client_id' => $schedule->client_id,
  147. 'provider_id' => $schedule->provider_id,
  148. 'client_payment_method_id' => $paymentMethod === 'credit_card' ? ($clientPaymentMethod?->id ?? null) : null,
  149. 'gateway_provider' => 'pagarme',
  150. 'gateway_code' => 'payment-'.(string) Str::uuid(),
  151. 'payment_method' => $paymentMethod,
  152. 'status' => PaymentStatusEnum::PENDING,
  153. 'gross_amount' => $amounts['gross_amount'],
  154. 'gateway_fee_amount' => 0,
  155. 'platform_fee_amount' => $amounts['platform_fee_amount'],
  156. 'net_amount' => $amounts['gross_amount'],
  157. 'currency' => 'BRL',
  158. 'installments' => 1,
  159. 'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
  160. 'metadata' => [
  161. 'service_amount' => number_format($amounts['service_amount'], 2, '.', ''),
  162. 'platform_fee' => number_format($amounts['platform_fee_amount'], 2, '.', ''),
  163. ],
  164. ]);
  165. PaymentSplit::create([
  166. 'payment_id' => $payment->id,
  167. 'provider_id' => $schedule->provider_id,
  168. 'gateway_provider' => 'pagarme',
  169. 'gateway_transfer_target_reference' => $schedule->provider->recipient_id,
  170. 'gateway_transfer_target_label' => 'recipient',
  171. 'status' => PaymentSplitStatusEnum::PENDING,
  172. 'gross_amount' => $serviceAmount,
  173. 'gateway_fee_amount' => 0,
  174. 'net_amount' => $serviceAmount,
  175. 'metadata' => [
  176. 'schedule_id' => (string) $schedule->id,
  177. ],
  178. ]);
  179. $schedule->ensureCustomerPhone($options['phone'] ?? null);
  180. try {
  181. $orderResponse = $this->pagarmePaymentService->processPayment(
  182. payment: $payment,
  183. schedule: $schedule,
  184. paymentMethod: $paymentMethod,
  185. cardId: $cardId,
  186. options: $options,
  187. );
  188. } catch (\Throwable $e) {
  189. $payment->forceFill([
  190. 'status' => PaymentStatusEnum::FAILED,
  191. 'failed_at' => now(),
  192. 'failure_message' => $e->getMessage(),
  193. ])->save();
  194. PaymentSplit::query()
  195. ->where('payment_id', $payment->id)
  196. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  197. throw $e;
  198. }
  199. $payment = $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
  200. $this->syncScheduleStatusAfterPayment($schedule, $payment);
  201. return $payment;
  202. }
  203. public function payAcceptedSchedules(
  204. array|SupportCollection $schedules, string $paymentMethod,
  205. ?int $clientPaymentMethodId = null, array $options = []
  206. ): Payment {
  207. $schedules = collect($schedules)
  208. ->map(fn (Schedule|int $schedule) => $schedule instanceof Schedule ? $schedule : Schedule::findOrFail($schedule))
  209. ->values();
  210. $this->validateCartSchedules($schedules, $paymentMethod);
  211. $firstSchedule = $schedules->first();
  212. if (! $firstSchedule) {
  213. throw new \InvalidArgumentException('Carrinho precisa ter ao menos um agendamento.');
  214. }
  215. $clientPaymentMethod = null;
  216. $cardId = null;
  217. if ($paymentMethod === 'credit_card') {
  218. if (! $clientPaymentMethodId && empty($options['card_id'])) {
  219. throw new \InvalidArgumentException('Cartao de pagamento ou card_id e obrigatorio.');
  220. }
  221. if ($clientPaymentMethodId) {
  222. $clientPaymentMethod = ClientPaymentMethod::query()
  223. ->where('client_id', $firstSchedule->client_id)
  224. ->where('id', $clientPaymentMethodId)
  225. ->where('is_active', true)
  226. ->first();
  227. if (! $clientPaymentMethod) {
  228. throw new \InvalidArgumentException('Cartao de pagamento nao encontrado ou inativo para este cliente.');
  229. }
  230. }
  231. $cardId = $options['card_id'] ?? $clientPaymentMethod?->gateway_card_id ?? null;
  232. if (empty($cardId)) {
  233. throw new \InvalidArgumentException('Cartao de pagamento invalido ou sem gateway_card_id do Pagar.me.');
  234. }
  235. }
  236. $payment = DB::transaction(function () use ($schedules, $paymentMethod, $clientPaymentMethod, $firstSchedule) {
  237. $totals = $this->cartPaymentTotals($schedules, $paymentMethod);
  238. $providerIds = $schedules->pluck('provider_id')->unique()->values();
  239. $payment = Payment::create([
  240. 'schedule_id' => null,
  241. 'client_id' => $firstSchedule->client_id,
  242. 'provider_id' => $providerIds->count() === 1 ? $providerIds->first() : null,
  243. 'client_payment_method_id' => $paymentMethod === 'credit_card' ? ($clientPaymentMethod?->id ?? null) : null,
  244. 'gateway_provider' => 'pagarme',
  245. 'gateway_code' => 'payment-'.(string) Str::uuid(),
  246. 'payment_method' => $paymentMethod,
  247. 'status' => PaymentStatusEnum::PENDING,
  248. 'gross_amount' => $totals['gross_amount'],
  249. 'gateway_fee_amount' => 0,
  250. 'platform_fee_amount' => $totals['platform_fee_amount'],
  251. 'net_amount' => $totals['gross_amount'],
  252. 'currency' => 'BRL',
  253. 'installments' => 1,
  254. 'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
  255. 'metadata' => [
  256. 'service_amount' => number_format($totals['service_amount'], 2, '.', ''),
  257. 'platform_fee' => number_format($totals['platform_fee_amount'], 2, '.', ''),
  258. 'schedule_ids' => $schedules->pluck('id')->map(fn ($id) => (string) $id)->all(),
  259. ],
  260. ]);
  261. foreach ($schedules as $schedule) {
  262. $amounts = $this->pagarmePaymentService->calculatePaymentAmounts(
  263. serviceAmount: (float) $schedule->total_amount,
  264. paymentMethod: $paymentMethod,
  265. );
  266. $schedule->setAttribute('payment_gross_amount', $amounts['gross_amount']);
  267. $payment->schedules()->attach($schedule->id);
  268. PaymentSplit::create([
  269. 'payment_id' => $payment->id,
  270. 'provider_id' => $schedule->provider_id,
  271. 'gateway_provider' => 'pagarme',
  272. 'gateway_transfer_target_reference' => $schedule->provider->recipient_id,
  273. 'gateway_transfer_target_label' => 'recipient',
  274. 'status' => PaymentSplitStatusEnum::PENDING,
  275. 'gross_amount' => (float) $schedule->total_amount,
  276. 'gateway_fee_amount' => 0,
  277. 'net_amount' => (float) $schedule->total_amount,
  278. 'metadata' => [
  279. 'schedule_id' => (string) $schedule->id,
  280. ],
  281. ]);
  282. }
  283. return $payment;
  284. });
  285. $firstSchedule->ensureCustomerPhone($options['phone'] ?? null);
  286. try {
  287. $orderResponse = $this->pagarmePaymentService->processCartPayment(
  288. payment: $payment,
  289. schedules: $schedules,
  290. paymentMethod: $paymentMethod,
  291. cardId: $cardId,
  292. options: $options,
  293. );
  294. } catch (\Throwable $e) {
  295. $payment->forceFill([
  296. 'status' => PaymentStatusEnum::FAILED,
  297. 'failed_at' => now(),
  298. 'failure_message' => $e->getMessage(),
  299. ])->save();
  300. PaymentSplit::query()
  301. ->where('payment_id', $payment->id)
  302. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  303. throw $e;
  304. }
  305. $payment = $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
  306. $this->syncSchedulesStatusAfterPayment($payment);
  307. return $payment->fresh(['client.user', 'provider.user', 'schedules']);
  308. }
  309. public function payCart(array $data, int $userId): Payment
  310. {
  311. $schedules = $this->cartSchedules($data['schedule_ids']);
  312. if ($schedules->contains(fn (Schedule $schedule) => $schedule->client?->user_id !== $userId)) {
  313. throw new AuthorizationException;
  314. }
  315. return $this->payAcceptedSchedules(
  316. schedules: $schedules,
  317. paymentMethod: $data['payment_method'],
  318. clientPaymentMethodId: $data['client_payment_method_id'] ?? null,
  319. options: [
  320. 'phone' => $data['phone'] ?? null,
  321. 'card_id' => $data['card_id'] ?? null,
  322. ],
  323. );
  324. }
  325. public function getOrCreatePixPayment(Schedule $schedule): Payment
  326. {
  327. $existingPayment = Payment::query()
  328. ->where('schedule_id', $schedule->id)
  329. ->where('payment_method', 'pix')
  330. ->whereIn('status', [
  331. PaymentStatusEnum::PENDING->value,
  332. PaymentStatusEnum::PROCESSING->value,
  333. PaymentStatusEnum::AUTHORIZED->value,
  334. PaymentStatusEnum::PAID->value,
  335. ])
  336. ->latest('id')
  337. ->first();
  338. if ($existingPayment && $this->isExpiredPixPayment($existingPayment)) {
  339. $existingPayment->forceFill([
  340. 'status' => PaymentStatusEnum::FAILED,
  341. 'failed_at' => Carbon::now(),
  342. 'failure_message' => 'Pagamento Pix expirado.',
  343. ])->save();
  344. PaymentSplit::query()
  345. ->where('payment_id', $existingPayment->id)
  346. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  347. $existingPayment = null;
  348. }
  349. if ($existingPayment) {
  350. if ($this->isIncompleteGatewayPayment($existingPayment)) {
  351. $existingPayment->forceFill([
  352. 'status' => PaymentStatusEnum::FAILED,
  353. 'failed_at' => Carbon::now(),
  354. 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
  355. ])->save();
  356. PaymentSplit::query()
  357. ->where('payment_id', $existingPayment->id)
  358. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  359. } else {
  360. $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
  361. return $existingPayment;
  362. }
  363. }
  364. return $this->payAcceptedSchedule(
  365. schedule: $schedule,
  366. paymentMethod: 'pix',
  367. );
  368. }
  369. //
  370. private function isExpiredPixPayment(Payment $payment): bool
  371. {
  372. if ($payment->payment_method !== 'pix') {
  373. return false;
  374. }
  375. if ($payment->status === PaymentStatusEnum::PAID) {
  376. return false;
  377. }
  378. return $payment->expires_at !== null
  379. && $payment->expires_at->isPast();
  380. }
  381. private function isIncompleteGatewayPayment(Payment $payment): bool
  382. {
  383. return $payment->status === PaymentStatusEnum::PENDING
  384. && empty($payment->gateway_entity_reference)
  385. && empty($payment->gateway_operation_reference)
  386. && empty($payment->gateway_payload);
  387. }
  388. public function syncScheduleStatusAfterPayment(Schedule $schedule, Payment $payment): void
  389. {
  390. if ($payment->status !== PaymentStatusEnum::PAID || $schedule->status === 'paid') {
  391. return;
  392. }
  393. $schedule->update(['status' => 'paid']);
  394. }
  395. public function syncSchedulesStatusAfterPayment(Payment $payment): void
  396. {
  397. $payment->loadMissing('schedules');
  398. if ($payment->schedules->isEmpty()) {
  399. if ($payment->schedule) {
  400. $this->syncScheduleStatusAfterPayment($payment->schedule, $payment);
  401. }
  402. return;
  403. }
  404. $payment->schedules->each(fn (Schedule $schedule) => $this->syncScheduleStatusAfterPayment($schedule, $payment));
  405. }
  406. private function validateCartSchedules(SupportCollection $schedules, string $paymentMethod): void
  407. {
  408. if ($schedules->isEmpty()) {
  409. throw new \InvalidArgumentException('Carrinho precisa ter ao menos um agendamento.');
  410. }
  411. if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
  412. throw new \InvalidArgumentException('Forma de pagamento invalida.');
  413. }
  414. $clientIds = $schedules->pluck('client_id')->unique()->values();
  415. if ($clientIds->count() !== 1) {
  416. throw new \InvalidArgumentException('Todos os agendamentos do carrinho precisam ser do mesmo cliente.');
  417. }
  418. $schedules->each(function (Schedule $schedule): void {
  419. $schedule->loadMissing(['client', 'provider', 'customSchedule.serviceType']);
  420. if ($schedule->status !== 'accepted') {
  421. throw new \InvalidArgumentException("Agendamento {$schedule->id} precisa estar aceito para ser pago.");
  422. }
  423. if (! $schedule->provider_id || ! $schedule->provider) {
  424. throw new \InvalidArgumentException("Agendamento {$schedule->id} precisa ter prestador confirmado para gerar pagamento.");
  425. }
  426. if ((float) $schedule->total_amount <= 0) {
  427. throw new \InvalidArgumentException("Agendamento {$schedule->id} precisa ter valor maior que zero para gerar pagamento.");
  428. }
  429. if (empty($schedule->provider->recipient_id)) {
  430. throw new \InvalidArgumentException("Prestador do agendamento {$schedule->id} precisa ter recipient_id do Pagar.me para receber split.");
  431. }
  432. $existingPayment = Payment::query()
  433. ->where(function ($query) use ($schedule) {
  434. $query->where('schedule_id', $schedule->id)
  435. ->orWhereHas('schedules', fn ($query) => $query->where('schedules.id', $schedule->id));
  436. })
  437. ->whereIn('status', [
  438. PaymentStatusEnum::PENDING->value,
  439. PaymentStatusEnum::PROCESSING->value,
  440. PaymentStatusEnum::AUTHORIZED->value,
  441. PaymentStatusEnum::PAID->value,
  442. ])
  443. ->latest('id')
  444. ->first();
  445. if ($existingPayment) {
  446. throw new \InvalidArgumentException("Ja existe um pagamento em andamento para o agendamento {$schedule->id}.");
  447. }
  448. });
  449. }
  450. //
  451. private function cartSchedules(array $scheduleIds): SupportCollection
  452. {
  453. $schedules = Schedule::query()
  454. ->with(['client', 'provider', 'customSchedule.serviceType'])
  455. ->whereIn('id', $scheduleIds)
  456. ->get()
  457. ->sortBy(fn (Schedule $schedule) => array_search($schedule->id, $scheduleIds, true))
  458. ->values();
  459. if ($schedules->count() !== count($scheduleIds)) {
  460. throw new \InvalidArgumentException('Um ou mais agendamentos nao foram encontrados.');
  461. }
  462. return $schedules;
  463. }
  464. private function cartPaymentTotals(SupportCollection $schedules, string $paymentMethod): array
  465. {
  466. return $schedules->reduce(function (array $totals, Schedule $schedule) use ($paymentMethod) {
  467. $amounts = $this->pagarmePaymentService->calculatePaymentAmounts(
  468. serviceAmount: (float) $schedule->total_amount,
  469. paymentMethod: $paymentMethod,
  470. );
  471. return [
  472. 'service_amount' => $totals['service_amount'] + $amounts['service_amount'],
  473. 'platform_fee_amount' => $totals['platform_fee_amount'] + $amounts['platform_fee_amount'],
  474. 'gross_amount' => $totals['gross_amount'] + $amounts['gross_amount'],
  475. ];
  476. }, [
  477. 'service_amount' => 0,
  478. 'platform_fee_amount' => 0,
  479. 'gross_amount' => 0,
  480. ]);
  481. }
  482. }