PaymentService.php 15 KB

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