PaymentService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. } elseif ($this->isExpiredPixPayment($existingPayment)) {
  93. $existingPayment->forceFill([
  94. 'status' => PaymentStatusEnum::FAILED,
  95. 'failed_at' => now(),
  96. 'failure_message' => 'Pagamento Pix expirado.',
  97. ])->save();
  98. PaymentSplit::query()
  99. ->where('payment_id', $existingPayment->id)
  100. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  101. } else {
  102. if ($existingPayment->payment_method !== $paymentMethod && $existingPayment->status !== PaymentStatusEnum::PAID) {
  103. throw new \InvalidArgumentException('Ja existe um pagamento em andamento para este agendamento.');
  104. }
  105. $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
  106. return $existingPayment;
  107. }
  108. }
  109. $clientPaymentMethod = null;
  110. $cardId = null;
  111. if ($paymentMethod === 'credit_card') {
  112. if (! $clientPaymentMethodId && empty($options['card_id'])) {
  113. throw new \InvalidArgumentException('Cartao de pagamento ou card_id e obrigatorio.');
  114. }
  115. if ($clientPaymentMethodId) {
  116. $clientPaymentMethod = ClientPaymentMethod::query()
  117. ->where('client_id', $schedule->client_id)
  118. ->where('id', $clientPaymentMethodId)
  119. ->where('is_active', true)
  120. ->first();
  121. if (! $clientPaymentMethod) {
  122. throw new \InvalidArgumentException('Cartao de pagamento nao encontrado ou inativo para este cliente.');
  123. }
  124. }
  125. $cardId = $options['card_id'] ?? $clientPaymentMethod?->gateway_card_id ?? null;
  126. if (empty($cardId)) {
  127. throw new \InvalidArgumentException('Cartao de pagamento invalido ou sem gateway_card_id do Pagar.me.');
  128. }
  129. }
  130. $serviceAmount = (float) $schedule->total_amount;
  131. $amounts = $this->pagarmePaymentService->calculatePaymentAmounts(
  132. serviceAmount: $serviceAmount,
  133. paymentMethod: $paymentMethod,
  134. );
  135. $payment = Payment::create([
  136. 'schedule_id' => $schedule->id,
  137. 'client_id' => $schedule->client_id,
  138. 'provider_id' => $schedule->provider_id,
  139. 'client_payment_method_id' => $paymentMethod === 'credit_card' ? ($clientPaymentMethod?->id ?? null) : null,
  140. 'gateway_provider' => 'pagarme',
  141. 'gateway_code' => 'payment-'.(string) Str::uuid(),
  142. 'payment_method' => $paymentMethod,
  143. 'status' => PaymentStatusEnum::PENDING,
  144. 'gross_amount' => $amounts['gross_amount'],
  145. 'gateway_fee_amount' => 0,
  146. 'platform_fee_amount' => $amounts['platform_fee_amount'],
  147. 'net_amount' => $amounts['gross_amount'],
  148. 'currency' => 'BRL',
  149. 'installments' => 1,
  150. 'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
  151. 'metadata' => [
  152. 'service_amount' => number_format($amounts['service_amount'], 2, '.', ''),
  153. 'platform_fee' => number_format($amounts['platform_fee_amount'], 2, '.', ''),
  154. 'anticipation_fee' => number_format($amounts['anticipation_fee_amount'], 2, '.', ''),
  155. ],
  156. ]);
  157. PaymentSplit::create([
  158. 'payment_id' => $payment->id,
  159. 'provider_id' => $schedule->provider_id,
  160. 'gateway_provider' => 'pagarme',
  161. 'gateway_transfer_target_reference' => $schedule->provider->recipient_id,
  162. 'gateway_transfer_target_label' => 'recipient',
  163. 'status' => PaymentSplitStatusEnum::PENDING,
  164. 'gross_amount' => $serviceAmount,
  165. 'gateway_fee_amount' => 0,
  166. 'net_amount' => $serviceAmount,
  167. 'metadata' => [
  168. 'schedule_id' => (string) $schedule->id,
  169. ],
  170. ]);
  171. $schedule->ensureCustomerPhone($options['phone'] ?? null);
  172. try {
  173. $orderResponse = $this->pagarmePaymentService->processPayment(
  174. payment: $payment,
  175. schedule: $schedule,
  176. paymentMethod: $paymentMethod,
  177. cardId: $cardId,
  178. options: $options,
  179. );
  180. } catch (\Throwable $e) {
  181. $payment->forceFill([
  182. 'status' => PaymentStatusEnum::FAILED,
  183. 'failed_at' => now(),
  184. 'failure_message' => $e->getMessage(),
  185. ])->save();
  186. PaymentSplit::query()
  187. ->where('payment_id', $payment->id)
  188. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  189. throw $e;
  190. }
  191. $payment = $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
  192. $this->syncScheduleStatusAfterPayment($schedule, $payment);
  193. return $payment;
  194. }
  195. public function getOrCreatePixPayment(Schedule $schedule): Payment
  196. {
  197. $existingPayment = Payment::query()
  198. ->where('schedule_id', $schedule->id)
  199. ->where('payment_method', 'pix')
  200. ->whereIn('status', [
  201. PaymentStatusEnum::PENDING->value,
  202. PaymentStatusEnum::PROCESSING->value,
  203. PaymentStatusEnum::AUTHORIZED->value,
  204. PaymentStatusEnum::PAID->value,
  205. ])
  206. ->latest('id')
  207. ->first();
  208. if ($existingPayment && $this->isExpiredPixPayment($existingPayment)) {
  209. $existingPayment->forceFill([
  210. 'status' => PaymentStatusEnum::FAILED,
  211. 'failed_at' => Carbon::now(),
  212. 'failure_message' => 'Pagamento Pix expirado.',
  213. ])->save();
  214. PaymentSplit::query()
  215. ->where('payment_id', $existingPayment->id)
  216. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  217. $existingPayment = null;
  218. }
  219. if ($existingPayment) {
  220. if ($this->isIncompleteGatewayPayment($existingPayment)) {
  221. $existingPayment->forceFill([
  222. 'status' => PaymentStatusEnum::FAILED,
  223. 'failed_at' => Carbon::now(),
  224. 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
  225. ])->save();
  226. PaymentSplit::query()
  227. ->where('payment_id', $existingPayment->id)
  228. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  229. } else {
  230. $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
  231. return $existingPayment;
  232. }
  233. }
  234. return $this->payAcceptedSchedule(
  235. schedule: $schedule,
  236. paymentMethod: 'pix',
  237. );
  238. }
  239. //
  240. private function isExpiredPixPayment(Payment $payment): bool
  241. {
  242. if ($payment->payment_method !== 'pix') {
  243. return false;
  244. }
  245. if ($payment->status === PaymentStatusEnum::PAID) {
  246. return false;
  247. }
  248. return $payment->expires_at !== null
  249. && $payment->expires_at->isPast();
  250. }
  251. private function isIncompleteGatewayPayment(Payment $payment): bool
  252. {
  253. return $payment->status === PaymentStatusEnum::PENDING
  254. && empty($payment->gateway_entity_reference)
  255. && empty($payment->gateway_operation_reference)
  256. && empty($payment->gateway_payload);
  257. }
  258. public function syncScheduleStatusAfterPayment(Schedule $schedule, Payment $payment): void
  259. {
  260. if ($payment->status !== PaymentStatusEnum::PAID || $schedule->status === 'paid') {
  261. return;
  262. }
  263. $schedule->update(['status' => 'paid']);
  264. }
  265. }