PaymentService.php 11 KB

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