PaymentService.php 16 KB

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