PaymentService.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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\Database\Eloquent\Collection;
  12. use Illuminate\Support\Str;
  13. class PaymentService
  14. {
  15. public function __construct(
  16. private readonly PagarmePaymentService $pagarmePaymentService,
  17. ) {}
  18. public function getAll(): Collection
  19. {
  20. return Payment::query()
  21. ->with(['client.user', 'provider.user'])
  22. ->orderBy('created_at', 'desc')
  23. ->get();
  24. }
  25. public function findById(int $id): ?Payment
  26. {
  27. return Payment::query()
  28. ->with(['client.user', 'provider.user'])
  29. ->find($id);
  30. }
  31. public function create(array $data): Payment
  32. {
  33. return Payment::create($data);
  34. }
  35. public function update(int $id, array $data): ?Payment
  36. {
  37. $model = $this->findById($id);
  38. if (! $model) {
  39. return null;
  40. }
  41. $model->update($data);
  42. return $model->fresh();
  43. }
  44. public function delete(int $id): bool
  45. {
  46. $model = $this->findById($id);
  47. if (! $model) {
  48. return false;
  49. }
  50. return $model->delete();
  51. }
  52. //
  53. public function payAcceptedSchedule(
  54. Schedule $schedule,
  55. string $paymentMethod,
  56. ?int $clientPaymentMethodId = null,
  57. array $options = []
  58. ): Payment {
  59. $schedule->loadMissing(['client', 'provider', 'customSchedule.serviceType']);
  60. if ($schedule->status !== 'accepted') {
  61. throw new \InvalidArgumentException('Agendamento precisa estar aceito para ser pago.');
  62. }
  63. if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
  64. throw new \InvalidArgumentException('Forma de pagamento invalida.');
  65. }
  66. if (! $schedule->provider_id || ! $schedule->provider) {
  67. throw new \InvalidArgumentException('Agendamento precisa ter prestador confirmado para gerar pagamento.');
  68. }
  69. if ((float) $schedule->total_amount <= 0) {
  70. throw new \InvalidArgumentException('Agendamento precisa ter valor maior que zero para gerar pagamento.');
  71. }
  72. if (empty($schedule->provider->recipient_id)) {
  73. throw new \InvalidArgumentException('Prestador precisa ter recipient_id do Pagar.me para receber split.');
  74. }
  75. $existingPayment = Payment::query()
  76. ->where('schedule_id', $schedule->id)
  77. ->whereIn('status', [
  78. PaymentStatusEnum::PENDING->value,
  79. PaymentStatusEnum::PROCESSING->value,
  80. PaymentStatusEnum::AUTHORIZED->value,
  81. PaymentStatusEnum::PAID->value,
  82. ])
  83. ->latest('id')
  84. ->first();
  85. if ($existingPayment) {
  86. if ($this->isIncompleteGatewayPayment($existingPayment)) {
  87. $existingPayment->forceFill([
  88. 'status' => PaymentStatusEnum::FAILED,
  89. 'failed_at' => now(),
  90. 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
  91. ])->save();
  92. } else {
  93. if ($existingPayment->payment_method !== $paymentMethod && $existingPayment->status !== PaymentStatusEnum::PAID) {
  94. throw new \InvalidArgumentException('Ja existe um pagamento em andamento para este agendamento.');
  95. }
  96. $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
  97. return $existingPayment;
  98. }
  99. }
  100. $clientPaymentMethod = null;
  101. $cardId = null;
  102. if ($paymentMethod === 'credit_card') {
  103. if (! $clientPaymentMethodId && empty($options['card_id'])) {
  104. throw new \InvalidArgumentException('Cartao de pagamento ou card_id e obrigatorio.');
  105. }
  106. if ($clientPaymentMethodId) {
  107. $clientPaymentMethod = ClientPaymentMethod::query()
  108. ->where('client_id', $schedule->client_id)
  109. ->where('id', $clientPaymentMethodId)
  110. ->where('is_active', true)
  111. ->first();
  112. if (! $clientPaymentMethod) {
  113. throw new \InvalidArgumentException('Cartao de pagamento nao encontrado ou inativo para este cliente.');
  114. }
  115. }
  116. $cardId = $options['card_id'] ?? $clientPaymentMethod?->gateway_card_id ?? null;
  117. if (empty($cardId)) {
  118. throw new \InvalidArgumentException('Cartao de pagamento invalido ou sem gateway_card_id do Pagar.me.');
  119. }
  120. }
  121. $serviceAmount = (float) $schedule->total_amount;
  122. $platformFee = round($serviceAmount * 0.11, 2);
  123. $grossAmount = round($serviceAmount + $platformFee, 2);
  124. $platformRecipientId = config('services.pagarme.platform_recipient_id');
  125. if ($platformFee > 0 && empty($platformRecipientId)) {
  126. throw new \InvalidArgumentException('PAGARME_PLATFORM_RECIPIENT_ID precisa estar configurado para receber a taxa da plataforma no split.');
  127. }
  128. $payment = Payment::create([
  129. 'schedule_id' => $schedule->id,
  130. 'client_id' => $schedule->client_id,
  131. 'provider_id' => $schedule->provider_id,
  132. 'client_payment_method_id' => $paymentMethod === 'credit_card' ? ($clientPaymentMethod?->id ?? null) : null,
  133. 'gateway_provider' => 'pagarme',
  134. 'gateway_code' => 'payment-'.(string) Str::uuid(),
  135. 'payment_method' => $paymentMethod,
  136. 'status' => PaymentStatusEnum::PENDING,
  137. 'gross_amount' => $grossAmount,
  138. 'gateway_fee_amount' => 0,
  139. 'platform_fee_amount' => $platformFee,
  140. 'net_amount' => $grossAmount,
  141. 'currency' => 'BRL',
  142. 'installments' => 1,
  143. 'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
  144. 'metadata' => [
  145. 'service_amount' => number_format($serviceAmount, 2, '.', ''),
  146. 'platform_fee' => number_format($platformFee, 2, '.', ''),
  147. ],
  148. ]);
  149. PaymentSplit::create([
  150. 'payment_id' => $payment->id,
  151. 'provider_id' => $schedule->provider_id,
  152. 'gateway_provider' => 'pagarme',
  153. 'gateway_transfer_target_reference' => $schedule->provider->recipient_id,
  154. 'gateway_transfer_target_label' => 'recipient',
  155. 'status' => PaymentSplitStatusEnum::PENDING,
  156. 'gross_amount' => $serviceAmount,
  157. 'gateway_fee_amount' => 0,
  158. 'net_amount' => $serviceAmount,
  159. 'metadata' => [
  160. 'schedule_id' => (string) $schedule->id,
  161. ],
  162. ]);
  163. $this->pagarmePaymentService->ensureCustomerPhone($schedule, $options);
  164. try {
  165. $orderResponse = $this->pagarmePaymentService->processPayment(
  166. payment: $payment,
  167. schedule: $schedule,
  168. paymentMethod: $paymentMethod,
  169. cardId: $cardId,
  170. options: $options,
  171. );
  172. } catch (\Throwable $e) {
  173. $payment->forceFill([
  174. 'status' => PaymentStatusEnum::FAILED,
  175. 'failed_at' => now(),
  176. 'failure_message' => $e->getMessage(),
  177. ])->save();
  178. PaymentSplit::query()
  179. ->where('payment_id', $payment->id)
  180. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  181. throw $e;
  182. }
  183. $payment = $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
  184. $this->syncScheduleStatusAfterPayment($schedule, $payment);
  185. return $payment;
  186. }
  187. //
  188. private function isIncompleteGatewayPayment(Payment $payment): bool
  189. {
  190. return $payment->status === PaymentStatusEnum::PENDING
  191. && empty($payment->gateway_entity_reference)
  192. && empty($payment->gateway_operation_reference)
  193. && empty($payment->gateway_payload);
  194. }
  195. public function syncScheduleStatusAfterPayment(Schedule $schedule, Payment $payment): void
  196. {
  197. if ($payment->status !== PaymentStatusEnum::PAID || $schedule->status === 'paid') {
  198. return;
  199. }
  200. $schedule->update(['status' => 'paid']);
  201. }
  202. }