PaymentService.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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\Str;
  12. class PaymentService
  13. {
  14. public function __construct(
  15. private readonly PagarmePaymentService $pagarmePaymentService,
  16. ) {}
  17. public function getAll(): Collection
  18. {
  19. return Payment::query()
  20. ->orderBy('created_at', 'desc')
  21. ->get();
  22. }
  23. public function findById(int $id): ?Payment
  24. {
  25. return Payment::find($id);
  26. }
  27. public function create(array $data): Payment
  28. {
  29. return Payment::create($data);
  30. }
  31. public function update(int $id, array $data): ?Payment
  32. {
  33. $model = $this->findById($id);
  34. if (! $model) {
  35. return null;
  36. }
  37. $model->update($data);
  38. return $model->fresh();
  39. }
  40. public function delete(int $id): bool
  41. {
  42. $model = $this->findById($id);
  43. if (! $model) {
  44. return false;
  45. }
  46. return $model->delete();
  47. }
  48. public function createPagarmeOrderForAcceptedSchedule(Schedule $schedule): Payment
  49. {
  50. $schedule->loadMissing(['client', 'provider', 'customSchedule.serviceType']);
  51. if (! $schedule->provider_id || ! $schedule->provider) {
  52. throw new \InvalidArgumentException('Agendamento precisa ter prestador confirmado para gerar pagamento.');
  53. }
  54. if ((float) $schedule->total_amount <= 0) {
  55. throw new \InvalidArgumentException('Agendamento precisa ter valor maior que zero para gerar pagamento.');
  56. }
  57. if (empty($schedule->provider->recipient_id)) {
  58. throw new \InvalidArgumentException('Prestador precisa ter recipient_id do Pagar.me para receber split.');
  59. }
  60. $existingPayment = Payment::query()
  61. ->where('schedule_id', $schedule->id)
  62. ->whereIn('status', ['pending', 'processing', 'authorized', 'paid'])
  63. ->latest('id')
  64. ->first();
  65. if ($existingPayment) {
  66. return $existingPayment;
  67. }
  68. $clientPaymentMethod = ClientPaymentMethod::query()
  69. ->where('client_id', $schedule->client_id)
  70. ->where('is_active', true)
  71. ->latest('id')
  72. ->first();
  73. $paymentMethod = $clientPaymentMethod?->token ? 'credit_card' : 'pix';
  74. $serviceAmount = (float) $schedule->total_amount;
  75. $platformFee = round($serviceAmount * 0.11, 2);
  76. $grossAmount = round($serviceAmount + $platformFee, 2);
  77. $payment = Payment::create([
  78. 'schedule_id' => $schedule->id,
  79. 'client_id' => $schedule->client_id,
  80. 'provider_id' => $schedule->provider_id,
  81. 'client_payment_method_id' => $paymentMethod === 'credit_card' ? $clientPaymentMethod->id : null,
  82. 'gateway_provider' => 'pagarme',
  83. 'payment_method' => $paymentMethod,
  84. 'status' => 'pending',
  85. 'gross_amount' => $grossAmount,
  86. 'gateway_fee_amount' => 0,
  87. 'platform_fee_amount' => $platformFee,
  88. 'net_amount' => $grossAmount,
  89. 'currency' => 'BRL',
  90. 'installments' => 1,
  91. 'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
  92. 'metadata' => [
  93. 'service_amount' => number_format($serviceAmount, 2, '.', ''),
  94. 'platform_fee' => number_format($platformFee, 2, '.', ''),
  95. ],
  96. ]);
  97. $transfer = PaymentTransfer::create([
  98. 'payment_id' => $payment->id,
  99. 'provider_id' => $schedule->provider_id,
  100. 'gateway_provider' => 'pagarme',
  101. 'gateway_transfer_target_reference' => $schedule->provider->recipient_id,
  102. 'gateway_transfer_target_label' => 'recipient',
  103. 'status' => 'pending',
  104. 'gross_amount' => $serviceAmount,
  105. 'gateway_fee_amount' => 0,
  106. 'net_amount' => $serviceAmount,
  107. 'metadata' => [
  108. 'schedule_id' => (string) $schedule->id,
  109. ],
  110. ]);
  111. $items = $this->buildOrderItems($schedule, $grossAmount);
  112. $customer = $this->buildCustomerPayload($schedule);
  113. $split = $this->pagarmePaymentService->buildSplitFromTransfers(collect([$transfer]));
  114. $orderResponse = $paymentMethod === 'credit_card'
  115. ? $this->pagarmePaymentService->createOrderWithCreditCard(
  116. payment: $payment,
  117. items: $items,
  118. customer: $customer,
  119. creditCard: [
  120. 'installments' => 1,
  121. 'statement_descriptor' => Str::limit((string) config('app.name', 'SOFTPAR'), 13, ''),
  122. 'operation_type' => 'auth_and_capture',
  123. 'card_token' => $clientPaymentMethod->token,
  124. ],
  125. options: ['split' => $split],
  126. )
  127. : $this->pagarmePaymentService->createOrderWithPix(
  128. payment: $payment,
  129. items: $items,
  130. customer: $customer,
  131. pix: [
  132. 'expires_at' => $payment->expires_at?->toISOString(),
  133. ],
  134. options: ['split' => $split],
  135. );
  136. return $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
  137. }
  138. /**
  139. * @return array<int, array<string, mixed>>
  140. */
  141. private function buildOrderItems(Schedule $schedule, float $grossAmount): array
  142. {
  143. $description = $schedule->customSchedule?->serviceType?->description
  144. ?? "Servico {$schedule->id}";
  145. return [[
  146. 'amount' => $this->pagarmePaymentService->toGatewayAmountInCents($grossAmount),
  147. 'description' => $description,
  148. 'quantity' => 1,
  149. 'code' => "schedule-{$schedule->id}",
  150. ]];
  151. }
  152. /**
  153. * @return array<string, mixed>
  154. */
  155. private function buildCustomerPayload(Schedule $schedule): array
  156. {
  157. $client = $schedule->client;
  158. $user = $client->user()->first(['id', 'name', 'email', 'phone']);
  159. $address = Address::with(['city.state', 'state'])->find($schedule->address_id);
  160. if (! $user?->name || ! $user?->email || ! $client->document) {
  161. throw new \InvalidArgumentException('Cliente precisa ter nome, email e documento para criar pedido no Pagar.me.');
  162. }
  163. if (! $address) {
  164. throw new \InvalidArgumentException('Endereco do agendamento nao encontrado para criar pedido no Pagar.me.');
  165. }
  166. $document = $this->digits($client->document);
  167. $phone = $this->buildPhonePayload($user->phone);
  168. $state = $address->state?->code ?? $address->city?->state?->code;
  169. $city = $address->city?->name;
  170. $zipCode = $this->digits($address->zip_code);
  171. $line1 = implode(', ', array_filter([
  172. $address->number ?: 'S/N',
  173. $address->address,
  174. $address->district,
  175. ]));
  176. foreach ([
  177. 'documento' => $document,
  178. 'telefone' => $phone,
  179. 'estado' => $state,
  180. 'cidade' => $city,
  181. 'cep' => $zipCode,
  182. 'endereco' => $line1,
  183. ] as $field => $value) {
  184. if ($value === null || $value === '' || $value === []) {
  185. throw new \InvalidArgumentException("Cliente precisa ter {$field} valido para criar pedido no Pagar.me.");
  186. }
  187. }
  188. return [
  189. 'name' => $user->name,
  190. 'email' => $user->email,
  191. 'code' => "client-{$client->id}",
  192. 'document' => $document,
  193. 'document_type' => strlen($document) === 14 ? 'CNPJ' : 'CPF',
  194. 'type' => strlen($document) === 14 ? 'company' : 'individual',
  195. 'address' => [
  196. 'country' => 'BR',
  197. 'state' => $state,
  198. 'city' => $city,
  199. 'zip_code' => $zipCode,
  200. 'line_1' => $line1,
  201. 'line_2' => $address->complement ?: $address->instructions,
  202. ],
  203. 'phones' => ['mobile_phone' => $phone],
  204. ];
  205. }
  206. /**
  207. * @return array<string, string>|null
  208. */
  209. private function buildPhonePayload(?string $phone): ?array
  210. {
  211. $digits = $this->digits($phone);
  212. if (strlen($digits) < 10) {
  213. return null;
  214. }
  215. if (str_starts_with($digits, '55')) {
  216. $digits = substr($digits, 2);
  217. }
  218. return [
  219. 'country_code' => '55',
  220. 'area_code' => substr($digits, 0, 2),
  221. 'number' => substr($digits, 2),
  222. ];
  223. }
  224. private function digits(?string $value): string
  225. {
  226. return preg_replace('/\D+/', '', (string) $value) ?? '';
  227. }
  228. }