PaymentService.php 15 KB

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