PaymentService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Address;
  4. use App\Models\Client;
  5. use App\Models\ClientPaymentMethod;
  6. use App\Models\Payment;
  7. use App\Models\PaymentTransfer;
  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\Facades\Log;
  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', ['pending', 'processing', 'authorized', 'paid'])
  76. ->latest('id')
  77. ->first();
  78. if ($existingPayment) {
  79. if ($this->isIncompleteGatewayPayment($existingPayment)) {
  80. $existingPayment->forceFill([
  81. 'status' => 'failed',
  82. 'failed_at' => now(),
  83. 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
  84. ])->save();
  85. } else {
  86. if ($existingPayment->payment_method !== $paymentMethod && $existingPayment->status !== 'paid') {
  87. throw new \InvalidArgumentException('Ja existe um pagamento em andamento para este agendamento.');
  88. }
  89. $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
  90. return $existingPayment;
  91. }
  92. }
  93. $clientPaymentMethod = null;
  94. if ($paymentMethod === 'credit_card') {
  95. if (! $clientPaymentMethodId && empty($options['card_id'])) {
  96. throw new \InvalidArgumentException('Cartao de pagamento ou card_id e obrigatorio.');
  97. }
  98. if ($clientPaymentMethodId) {
  99. $clientPaymentMethod = ClientPaymentMethod::query()
  100. ->where('client_id', $schedule->client_id)
  101. ->where('id', $clientPaymentMethodId)
  102. ->where('is_active', true)
  103. ->first();
  104. if (! $clientPaymentMethod) {
  105. throw new \InvalidArgumentException('Cartao de pagamento nao encontrado ou inativo para este cliente.');
  106. }
  107. }
  108. if (
  109. empty($clientPaymentMethod?->gateway_card_id)
  110. && empty($options['card_id'])
  111. ) {
  112. throw new \InvalidArgumentException('Cartao de pagamento invalido ou sem gateway_card_id do Pagar.me.');
  113. }
  114. }
  115. $serviceAmount = (float) $schedule->total_amount;
  116. $platformFee = round($serviceAmount * 0.11, 2);
  117. $grossAmount = round($serviceAmount + $platformFee, 2);
  118. $items = $this->buildOrderItems($schedule, $grossAmount);
  119. $client = Client::find($schedule->client_id);
  120. $customerId = $client?->external_customer_id;
  121. $customer = empty($customerId) ? $this->buildCustomerPayload($schedule, $options) : [];
  122. $platformRecipientId = config('services.pagarme.platform_recipient_id');
  123. if ($platformFee > 0 && empty($platformRecipientId)) {
  124. throw new \InvalidArgumentException('PAGARME_PLATFORM_RECIPIENT_ID precisa estar configurado para receber a taxa da plataforma no split.');
  125. }
  126. $payment = Payment::create([
  127. 'schedule_id' => $schedule->id,
  128. 'client_id' => $schedule->client_id,
  129. 'provider_id' => $schedule->provider_id,
  130. 'client_payment_method_id' => $paymentMethod === 'credit_card' ? $clientPaymentMethod->id : null,
  131. 'gateway_provider' => 'pagarme',
  132. 'payment_method' => $paymentMethod,
  133. 'status' => 'pending',
  134. 'gross_amount' => $grossAmount,
  135. 'gateway_fee_amount' => 0,
  136. 'platform_fee_amount' => $platformFee,
  137. 'net_amount' => $grossAmount,
  138. 'currency' => 'BRL',
  139. 'installments' => 1,
  140. 'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
  141. 'metadata' => [
  142. 'service_amount' => number_format($serviceAmount, 2, '.', ''),
  143. 'platform_fee' => number_format($platformFee, 2, '.', ''),
  144. ],
  145. ]);
  146. $transfer = PaymentTransfer::create([
  147. 'payment_id' => $payment->id,
  148. 'provider_id' => $schedule->provider_id,
  149. 'gateway_provider' => 'pagarme',
  150. 'gateway_transfer_target_reference' => $schedule->provider->recipient_id,
  151. 'gateway_transfer_target_label' => 'recipient',
  152. 'status' => 'pending',
  153. 'gross_amount' => $serviceAmount,
  154. 'gateway_fee_amount' => 0,
  155. 'net_amount' => $serviceAmount,
  156. 'metadata' => [
  157. 'schedule_id' => (string) $schedule->id,
  158. ],
  159. ]);
  160. $split = $this->pagarmePaymentService->buildSplitFromTransfers(collect([$transfer]));
  161. if ($platformFee > 0) {
  162. $split[] = [
  163. 'amount' => $this->pagarmePaymentService->toGatewayAmountInCents($platformFee),
  164. 'recipient_id' => $platformRecipientId,
  165. 'type' => 'flat',
  166. 'options' => [
  167. 'charge_processing_fee' => true,
  168. 'charge_remainder_fee' => true,
  169. 'liable' => true,
  170. ],
  171. ];
  172. }
  173. try {
  174. $creditCardReference = $paymentMethod === 'credit_card'
  175. ? $this->resolveCreditCardReference($clientPaymentMethod, $options)
  176. : [];
  177. if ($paymentMethod === 'credit_card') {
  178. Log::channel('pagarme')->info('Resolved credit card reference for payment', [
  179. 'payment_id' => $payment->id,
  180. 'client_payment_method_id' => $clientPaymentMethod?->id,
  181. 'reference_type' => array_key_first($creditCardReference),
  182. 'gateway_card_id' => $clientPaymentMethod?->gateway_card_id,
  183. ]);
  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. 'customer_id' => $customerId,
  198. ],
  199. )
  200. : $this->pagarmePaymentService->createOrderWithPix(
  201. payment: $payment,
  202. items: $items,
  203. customer: $customer,
  204. pix: [
  205. 'expires_at' => $payment->expires_at?->toISOString(),
  206. ],
  207. options: [
  208. 'split' => $split,
  209. 'customer_id' => $customerId,
  210. ],
  211. );
  212. } catch (\Throwable $e) {
  213. $payment->forceFill([
  214. 'status' => 'failed',
  215. 'failed_at' => now(),
  216. 'failure_message' => $e->getMessage(),
  217. ])->save();
  218. $transfer->update(['status' => 'failed']);
  219. throw $e;
  220. }
  221. $payment = $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
  222. $this->syncScheduleStatusAfterPayment($schedule, $payment);
  223. return $payment;
  224. }
  225. //
  226. private function buildOrderItems(Schedule $schedule, float $grossAmount): array
  227. {
  228. $description = $schedule->customSchedule?->serviceType?->description
  229. ?? "Servico {$schedule->id}";
  230. return [[
  231. 'amount' => $this->pagarmePaymentService->toGatewayAmountInCents($grossAmount),
  232. 'description' => $description,
  233. 'quantity' => 1,
  234. 'code' => "schedule-{$schedule->id}",
  235. ]];
  236. }
  237. private function buildCustomerPayload(Schedule $schedule, array $options = []): array
  238. {
  239. $client = $schedule->client;
  240. $user = $client->user()->first(['id', 'name', 'email', 'phone']);
  241. $address = Address::with(['city.state', 'state'])->find($schedule->address_id);
  242. foreach ([
  243. 'nome' => $user?->name,
  244. 'email' => $user?->email,
  245. 'documento' => $client->document,
  246. ] as $field => $value) {
  247. if ($value === null || $value === '') {
  248. throw new \InvalidArgumentException("Cliente precisa ter {$field} para criar pedido no Pagar.me.");
  249. }
  250. }
  251. if (! $address) {
  252. throw new \InvalidArgumentException('Endereco do agendamento nao encontrado para criar pedido no Pagar.me.');
  253. }
  254. $document = $this->digits($client->document);
  255. $phone = $this->buildPhonePayload($user->phone)
  256. ?: $this->buildPhonePayload($options['phone'] ?? null);
  257. $state = $address->state?->code ?? $address->city?->state?->code;
  258. $city = $address->city?->name;
  259. $zipCode = $this->digits($address->zip_code);
  260. $line1 = implode(', ', array_filter([
  261. $address->number ?: 'S/N',
  262. $address->address,
  263. $address->district,
  264. ]));
  265. foreach ([
  266. 'documento' => $document,
  267. 'telefone' => $phone,
  268. 'estado' => $state,
  269. 'cidade' => $city,
  270. 'cep' => $zipCode,
  271. 'endereco' => $line1,
  272. ] as $field => $value) {
  273. if ($value === null || $value === '' || $value === []) {
  274. throw new \InvalidArgumentException("Cliente precisa ter {$field} valido para criar pedido no Pagar.me.");
  275. }
  276. }
  277. return [
  278. 'name' => $user->name,
  279. 'email' => $user->email,
  280. 'code' => "client-{$client->id}",
  281. 'document' => $document,
  282. 'document_type' => strlen($document) === 14 ? 'CNPJ' : 'CPF',
  283. 'type' => strlen($document) === 14 ? 'company' : 'individual',
  284. 'address' => [
  285. 'country' => 'BR',
  286. 'state' => $state,
  287. 'city' => $city,
  288. 'zip_code' => $zipCode,
  289. 'line_1' => $line1,
  290. 'line_2' => $address->complement ?: $address->instructions,
  291. ],
  292. 'phones' => ['mobile_phone' => $phone],
  293. ];
  294. }
  295. private function buildPhonePayload(?string $phone): ?array
  296. {
  297. $digits = $this->digits($phone);
  298. if (strlen($digits) < 10) {
  299. return null;
  300. }
  301. if (str_starts_with($digits, '55')) {
  302. $digits = substr($digits, 2);
  303. }
  304. return [
  305. 'country_code' => '55',
  306. 'area_code' => substr($digits, 0, 2),
  307. 'number' => substr($digits, 2),
  308. ];
  309. }
  310. private function digits(?string $value): string
  311. {
  312. return preg_replace('/\D+/', '', (string) $value) ?? '';
  313. }
  314. private function isIncompleteGatewayPayment(Payment $payment): bool
  315. {
  316. return $payment->status === 'pending'
  317. && empty($payment->gateway_entity_reference)
  318. && empty($payment->gateway_operation_reference)
  319. && empty($payment->gateway_payload);
  320. }
  321. private function resolveCreditCardReference(?ClientPaymentMethod $clientPaymentMethod, array $options): array
  322. {
  323. if (! empty($options['card_id'])) {
  324. return ['card_id' => $options['card_id']];
  325. }
  326. if (! empty($clientPaymentMethod?->gateway_card_id)) {
  327. return ['card_id' => $clientPaymentMethod->gateway_card_id];
  328. }
  329. throw new \InvalidArgumentException('Cartao de pagamento precisa ter gateway_card_id do Pagar.me.');
  330. }
  331. public function syncScheduleStatusAfterPayment(Schedule $schedule, Payment $payment): void
  332. {
  333. if ($payment->status !== 'paid' || $schedule->status === 'paid') {
  334. return;
  335. }
  336. $schedule->update(['status' => 'paid']);
  337. }
  338. }