|
@@ -3,6 +3,7 @@
|
|
|
namespace App\Services;
|
|
namespace App\Services;
|
|
|
|
|
|
|
|
use App\Models\Address;
|
|
use App\Models\Address;
|
|
|
|
|
+use App\Models\Client;
|
|
|
use App\Models\ClientPaymentMethod;
|
|
use App\Models\ClientPaymentMethod;
|
|
|
use App\Models\Payment;
|
|
use App\Models\Payment;
|
|
|
use App\Models\PaymentTransfer;
|
|
use App\Models\PaymentTransfer;
|
|
@@ -10,6 +11,7 @@ use App\Models\Schedule;
|
|
|
use App\Services\Pagarme\PagarmePaymentService;
|
|
use App\Services\Pagarme\PagarmePaymentService;
|
|
|
use Carbon\Carbon;
|
|
use Carbon\Carbon;
|
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
|
|
|
+use Illuminate\Support\Facades\Log;
|
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Support\Str;
|
|
|
|
|
|
|
|
class PaymentService
|
|
class PaymentService
|
|
@@ -59,10 +61,24 @@ class PaymentService
|
|
|
return $model->delete();
|
|
return $model->delete();
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- public function createPagarmeOrderForAcceptedSchedule(Schedule $schedule): Payment
|
|
|
|
|
- {
|
|
|
|
|
|
|
+ //
|
|
|
|
|
+
|
|
|
|
|
+ public function payAcceptedSchedule(
|
|
|
|
|
+ Schedule $schedule,
|
|
|
|
|
+ string $paymentMethod,
|
|
|
|
|
+ ?int $clientPaymentMethodId = null,
|
|
|
|
|
+ array $options = []
|
|
|
|
|
+ ): Payment {
|
|
|
$schedule->loadMissing(['client', 'provider', 'customSchedule.serviceType']);
|
|
$schedule->loadMissing(['client', 'provider', 'customSchedule.serviceType']);
|
|
|
|
|
|
|
|
|
|
+ if ($schedule->status !== 'accepted') {
|
|
|
|
|
+ throw new \InvalidArgumentException('Agendamento precisa estar aceito para ser pago.');
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
|
|
|
|
|
+ throw new \InvalidArgumentException('Forma de pagamento invalida.');
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
if (! $schedule->provider_id || ! $schedule->provider) {
|
|
if (! $schedule->provider_id || ! $schedule->provider) {
|
|
|
throw new \InvalidArgumentException('Agendamento precisa ter prestador confirmado para gerar pagamento.');
|
|
throw new \InvalidArgumentException('Agendamento precisa ter prestador confirmado para gerar pagamento.');
|
|
|
}
|
|
}
|
|
@@ -82,19 +98,62 @@ class PaymentService
|
|
|
->first();
|
|
->first();
|
|
|
|
|
|
|
|
if ($existingPayment) {
|
|
if ($existingPayment) {
|
|
|
- return $existingPayment;
|
|
|
|
|
|
|
+ if ($this->isIncompleteGatewayPayment($existingPayment)) {
|
|
|
|
|
+ $existingPayment->forceFill([
|
|
|
|
|
+ 'status' => 'failed',
|
|
|
|
|
+ 'failed_at' => now(),
|
|
|
|
|
+ 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
|
|
|
|
|
+ ])->save();
|
|
|
|
|
+ } else {
|
|
|
|
|
+ if ($existingPayment->payment_method !== $paymentMethod && $existingPayment->status !== 'paid') {
|
|
|
|
|
+ throw new \InvalidArgumentException('Ja existe um pagamento em andamento para este agendamento.');
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
|
|
|
|
|
+
|
|
|
|
|
+ return $existingPayment;
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- $clientPaymentMethod = ClientPaymentMethod::query()
|
|
|
|
|
- ->where('client_id', $schedule->client_id)
|
|
|
|
|
- ->where('is_active', true)
|
|
|
|
|
- ->latest('id')
|
|
|
|
|
- ->first();
|
|
|
|
|
|
|
+ $clientPaymentMethod = null;
|
|
|
|
|
+
|
|
|
|
|
+ if ($paymentMethod === 'credit_card') {
|
|
|
|
|
+ if (! $clientPaymentMethodId && empty($options['card_id'])) {
|
|
|
|
|
+ throw new \InvalidArgumentException('Cartao de pagamento ou card_id e obrigatorio.');
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
- $paymentMethod = $clientPaymentMethod?->token ? 'credit_card' : 'pix';
|
|
|
|
|
- $serviceAmount = (float) $schedule->total_amount;
|
|
|
|
|
- $platformFee = round($serviceAmount * 0.11, 2);
|
|
|
|
|
- $grossAmount = round($serviceAmount + $platformFee, 2);
|
|
|
|
|
|
|
+ if ($clientPaymentMethodId) {
|
|
|
|
|
+ $clientPaymentMethod = ClientPaymentMethod::query()
|
|
|
|
|
+ ->where('client_id', $schedule->client_id)
|
|
|
|
|
+ ->where('id', $clientPaymentMethodId)
|
|
|
|
|
+ ->where('is_active', true)
|
|
|
|
|
+ ->first();
|
|
|
|
|
+
|
|
|
|
|
+ if (! $clientPaymentMethod) {
|
|
|
|
|
+ throw new \InvalidArgumentException('Cartao de pagamento nao encontrado ou inativo para este cliente.');
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (
|
|
|
|
|
+ empty($clientPaymentMethod?->gateway_card_id)
|
|
|
|
|
+ && empty($options['card_id'])
|
|
|
|
|
+ ) {
|
|
|
|
|
+ throw new \InvalidArgumentException('Cartao de pagamento invalido ou sem gateway_card_id do Pagar.me.');
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ $serviceAmount = (float) $schedule->total_amount;
|
|
|
|
|
+ $platformFee = round($serviceAmount * 0.11, 2);
|
|
|
|
|
+ $grossAmount = round($serviceAmount + $platformFee, 2);
|
|
|
|
|
+ $items = $this->buildOrderItems($schedule, $grossAmount);
|
|
|
|
|
+ $client = Client::find($schedule->client_id);
|
|
|
|
|
+ $customerId = $client?->external_customer_id;
|
|
|
|
|
+ $customer = empty($customerId) ? $this->buildCustomerPayload($schedule, $options) : [];
|
|
|
|
|
+ $platformRecipientId = config('services.pagarme.platform_recipient_id');
|
|
|
|
|
+
|
|
|
|
|
+ if ($platformFee > 0 && empty($platformRecipientId)) {
|
|
|
|
|
+ throw new \InvalidArgumentException('PAGARME_PLATFORM_RECIPIENT_ID precisa estar configurado para receber a taxa da plataforma no split.');
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
$payment = Payment::create([
|
|
$payment = Payment::create([
|
|
|
'schedule_id' => $schedule->id,
|
|
'schedule_id' => $schedule->id,
|
|
@@ -111,60 +170,107 @@ class PaymentService
|
|
|
'currency' => 'BRL',
|
|
'currency' => 'BRL',
|
|
|
'installments' => 1,
|
|
'installments' => 1,
|
|
|
'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
|
|
'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
|
|
|
- 'metadata' => [
|
|
|
|
|
|
|
+
|
|
|
|
|
+ 'metadata' => [
|
|
|
'service_amount' => number_format($serviceAmount, 2, '.', ''),
|
|
'service_amount' => number_format($serviceAmount, 2, '.', ''),
|
|
|
'platform_fee' => number_format($platformFee, 2, '.', ''),
|
|
'platform_fee' => number_format($platformFee, 2, '.', ''),
|
|
|
],
|
|
],
|
|
|
]);
|
|
]);
|
|
|
|
|
|
|
|
$transfer = PaymentTransfer::create([
|
|
$transfer = PaymentTransfer::create([
|
|
|
- 'payment_id' => $payment->id,
|
|
|
|
|
- 'provider_id' => $schedule->provider_id,
|
|
|
|
|
- 'gateway_provider' => 'pagarme',
|
|
|
|
|
- 'gateway_transfer_target_reference' => $schedule->provider->recipient_id,
|
|
|
|
|
- 'gateway_transfer_target_label' => 'recipient',
|
|
|
|
|
- 'status' => 'pending',
|
|
|
|
|
- 'gross_amount' => $serviceAmount,
|
|
|
|
|
- 'gateway_fee_amount' => 0,
|
|
|
|
|
- 'net_amount' => $serviceAmount,
|
|
|
|
|
- 'metadata' => [
|
|
|
|
|
|
|
+ 'payment_id' => $payment->id,
|
|
|
|
|
+ 'provider_id' => $schedule->provider_id,
|
|
|
|
|
+ 'gateway_provider' => 'pagarme',
|
|
|
|
|
+ 'gateway_transfer_target_reference' => $schedule->provider->recipient_id,
|
|
|
|
|
+ 'gateway_transfer_target_label' => 'recipient',
|
|
|
|
|
+ 'status' => 'pending',
|
|
|
|
|
+ 'gross_amount' => $serviceAmount,
|
|
|
|
|
+ 'gateway_fee_amount' => 0,
|
|
|
|
|
+ 'net_amount' => $serviceAmount,
|
|
|
|
|
+
|
|
|
|
|
+ 'metadata' => [
|
|
|
'schedule_id' => (string) $schedule->id,
|
|
'schedule_id' => (string) $schedule->id,
|
|
|
],
|
|
],
|
|
|
]);
|
|
]);
|
|
|
|
|
|
|
|
- $items = $this->buildOrderItems($schedule, $grossAmount);
|
|
|
|
|
- $customer = $this->buildCustomerPayload($schedule);
|
|
|
|
|
- $split = $this->pagarmePaymentService->buildSplitFromTransfers(collect([$transfer]));
|
|
|
|
|
-
|
|
|
|
|
- $orderResponse = $paymentMethod === 'credit_card'
|
|
|
|
|
- ? $this->pagarmePaymentService->createOrderWithCreditCard(
|
|
|
|
|
- payment: $payment,
|
|
|
|
|
- items: $items,
|
|
|
|
|
- customer: $customer,
|
|
|
|
|
- creditCard: [
|
|
|
|
|
- 'installments' => 1,
|
|
|
|
|
- 'statement_descriptor' => Str::limit((string) config('app.name', 'SOFTPAR'), 13, ''),
|
|
|
|
|
- 'operation_type' => 'auth_and_capture',
|
|
|
|
|
- 'card_token' => $clientPaymentMethod->token,
|
|
|
|
|
- ],
|
|
|
|
|
- options: ['split' => $split],
|
|
|
|
|
- )
|
|
|
|
|
- : $this->pagarmePaymentService->createOrderWithPix(
|
|
|
|
|
- payment: $payment,
|
|
|
|
|
- items: $items,
|
|
|
|
|
- customer: $customer,
|
|
|
|
|
- pix: [
|
|
|
|
|
- 'expires_at' => $payment->expires_at?->toISOString(),
|
|
|
|
|
|
|
+ $split = $this->pagarmePaymentService->buildSplitFromTransfers(collect([$transfer]));
|
|
|
|
|
+
|
|
|
|
|
+ if ($platformFee > 0) {
|
|
|
|
|
+ $split[] = [
|
|
|
|
|
+ 'amount' => $this->pagarmePaymentService->toGatewayAmountInCents($platformFee),
|
|
|
|
|
+ 'recipient_id' => $platformRecipientId,
|
|
|
|
|
+ 'type' => 'flat',
|
|
|
|
|
+
|
|
|
|
|
+ 'options' => [
|
|
|
|
|
+ 'charge_processing_fee' => true,
|
|
|
|
|
+ 'charge_remainder_fee' => true,
|
|
|
|
|
+ 'liable' => true,
|
|
|
],
|
|
],
|
|
|
- options: ['split' => $split],
|
|
|
|
|
- );
|
|
|
|
|
|
|
+ ];
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ try {
|
|
|
|
|
+ $creditCardReference = $paymentMethod === 'credit_card'
|
|
|
|
|
+ ? $this->resolveCreditCardReference($clientPaymentMethod, $options)
|
|
|
|
|
+ : [];
|
|
|
|
|
+
|
|
|
|
|
+ if ($paymentMethod === 'credit_card') {
|
|
|
|
|
+ Log::channel('pagarme')->info('Resolved credit card reference for payment', [
|
|
|
|
|
+ 'payment_id' => $payment->id,
|
|
|
|
|
+ 'client_payment_method_id' => $clientPaymentMethod?->id,
|
|
|
|
|
+ 'reference_type' => array_key_first($creditCardReference),
|
|
|
|
|
+ 'gateway_card_id' => $clientPaymentMethod?->gateway_card_id,
|
|
|
|
|
+ ]);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ $orderResponse = $paymentMethod === 'credit_card'
|
|
|
|
|
+ ? $this->pagarmePaymentService->createOrderWithCreditCard(
|
|
|
|
|
+ payment: $payment,
|
|
|
|
|
+ items: $items,
|
|
|
|
|
+ customer: $customer,
|
|
|
|
|
+ creditCard: [
|
|
|
|
|
+ 'installments' => 1,
|
|
|
|
|
+ 'statement_descriptor' => Str::limit((string) config('app.name', 'SOFTPAR'), 13, ''),
|
|
|
|
|
+ 'operation_type' => 'auth_and_capture',
|
|
|
|
|
+ ] + $creditCardReference,
|
|
|
|
|
+ options: [
|
|
|
|
|
+ 'split' => $split,
|
|
|
|
|
+ 'customer_id' => $customerId,
|
|
|
|
|
+ ],
|
|
|
|
|
+ )
|
|
|
|
|
+ : $this->pagarmePaymentService->createOrderWithPix(
|
|
|
|
|
+ payment: $payment,
|
|
|
|
|
+ items: $items,
|
|
|
|
|
+ customer: $customer,
|
|
|
|
|
+ pix: [
|
|
|
|
|
+ 'expires_at' => $payment->expires_at?->toISOString(),
|
|
|
|
|
+ ],
|
|
|
|
|
+ options: [
|
|
|
|
|
+ 'split' => $split,
|
|
|
|
|
+ 'customer_id' => $customerId,
|
|
|
|
|
+ ],
|
|
|
|
|
+ );
|
|
|
|
|
+ } catch (\Throwable $e) {
|
|
|
|
|
+ $payment->forceFill([
|
|
|
|
|
+ 'status' => 'failed',
|
|
|
|
|
+ 'failed_at' => now(),
|
|
|
|
|
+ 'failure_message' => $e->getMessage(),
|
|
|
|
|
+ ])->save();
|
|
|
|
|
+
|
|
|
|
|
+ $transfer->update(['status' => 'failed']);
|
|
|
|
|
+
|
|
|
|
|
+ throw $e;
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
- return $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
|
|
|
|
|
|
|
+ $payment = $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
|
|
|
|
|
+
|
|
|
|
|
+ $this->syncScheduleStatusAfterPayment($schedule, $payment);
|
|
|
|
|
+
|
|
|
|
|
+ return $payment;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- /**
|
|
|
|
|
- * @return array<int, array<string, mixed>>
|
|
|
|
|
- */
|
|
|
|
|
|
|
+ //
|
|
|
|
|
+
|
|
|
private function buildOrderItems(Schedule $schedule, float $grossAmount): array
|
|
private function buildOrderItems(Schedule $schedule, float $grossAmount): array
|
|
|
{
|
|
{
|
|
|
$description = $schedule->customSchedule?->serviceType?->description
|
|
$description = $schedule->customSchedule?->serviceType?->description
|
|
@@ -178,17 +284,20 @@ class PaymentService
|
|
|
]];
|
|
]];
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- /**
|
|
|
|
|
- * @return array<string, mixed>
|
|
|
|
|
- */
|
|
|
|
|
- private function buildCustomerPayload(Schedule $schedule): array
|
|
|
|
|
|
|
+ private function buildCustomerPayload(Schedule $schedule, array $options = []): array
|
|
|
{
|
|
{
|
|
|
$client = $schedule->client;
|
|
$client = $schedule->client;
|
|
|
$user = $client->user()->first(['id', 'name', 'email', 'phone']);
|
|
$user = $client->user()->first(['id', 'name', 'email', 'phone']);
|
|
|
$address = Address::with(['city.state', 'state'])->find($schedule->address_id);
|
|
$address = Address::with(['city.state', 'state'])->find($schedule->address_id);
|
|
|
|
|
|
|
|
- if (! $user?->name || ! $user?->email || ! $client->document) {
|
|
|
|
|
- throw new \InvalidArgumentException('Cliente precisa ter nome, email e documento para criar pedido no Pagar.me.');
|
|
|
|
|
|
|
+ foreach ([
|
|
|
|
|
+ 'nome' => $user?->name,
|
|
|
|
|
+ 'email' => $user?->email,
|
|
|
|
|
+ 'documento' => $client->document,
|
|
|
|
|
+ ] as $field => $value) {
|
|
|
|
|
+ if ($value === null || $value === '') {
|
|
|
|
|
+ throw new \InvalidArgumentException("Cliente precisa ter {$field} para criar pedido no Pagar.me.");
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
if (! $address) {
|
|
if (! $address) {
|
|
@@ -196,11 +305,15 @@ class PaymentService
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
$document = $this->digits($client->document);
|
|
$document = $this->digits($client->document);
|
|
|
- $phone = $this->buildPhonePayload($user->phone);
|
|
|
|
|
- $state = $address->state?->code ?? $address->city?->state?->code;
|
|
|
|
|
- $city = $address->city?->name;
|
|
|
|
|
- $zipCode = $this->digits($address->zip_code);
|
|
|
|
|
- $line1 = implode(', ', array_filter([
|
|
|
|
|
|
|
+
|
|
|
|
|
+ $phone = $this->buildPhonePayload($user->phone)
|
|
|
|
|
+ ?: $this->buildPhonePayload($options['phone'] ?? null);
|
|
|
|
|
+
|
|
|
|
|
+ $state = $address->state?->code ?? $address->city?->state?->code;
|
|
|
|
|
+ $city = $address->city?->name;
|
|
|
|
|
+ $zipCode = $this->digits($address->zip_code);
|
|
|
|
|
+
|
|
|
|
|
+ $line1 = implode(', ', array_filter([
|
|
|
$address->number ?: 'S/N',
|
|
$address->number ?: 'S/N',
|
|
|
$address->address,
|
|
$address->address,
|
|
|
$address->district,
|
|
$address->district,
|
|
@@ -226,7 +339,8 @@ class PaymentService
|
|
|
'document' => $document,
|
|
'document' => $document,
|
|
|
'document_type' => strlen($document) === 14 ? 'CNPJ' : 'CPF',
|
|
'document_type' => strlen($document) === 14 ? 'CNPJ' : 'CPF',
|
|
|
'type' => strlen($document) === 14 ? 'company' : 'individual',
|
|
'type' => strlen($document) === 14 ? 'company' : 'individual',
|
|
|
- 'address' => [
|
|
|
|
|
|
|
+
|
|
|
|
|
+ 'address' => [
|
|
|
'country' => 'BR',
|
|
'country' => 'BR',
|
|
|
'state' => $state,
|
|
'state' => $state,
|
|
|
'city' => $city,
|
|
'city' => $city,
|
|
@@ -234,13 +348,11 @@ class PaymentService
|
|
|
'line_1' => $line1,
|
|
'line_1' => $line1,
|
|
|
'line_2' => $address->complement ?: $address->instructions,
|
|
'line_2' => $address->complement ?: $address->instructions,
|
|
|
],
|
|
],
|
|
|
- 'phones' => ['mobile_phone' => $phone],
|
|
|
|
|
|
|
+
|
|
|
|
|
+ 'phones' => ['mobile_phone' => $phone],
|
|
|
];
|
|
];
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- /**
|
|
|
|
|
- * @return array<string, string>|null
|
|
|
|
|
- */
|
|
|
|
|
private function buildPhonePayload(?string $phone): ?array
|
|
private function buildPhonePayload(?string $phone): ?array
|
|
|
{
|
|
{
|
|
|
$digits = $this->digits($phone);
|
|
$digits = $this->digits($phone);
|
|
@@ -264,4 +376,34 @@ class PaymentService
|
|
|
{
|
|
{
|
|
|
return preg_replace('/\D+/', '', (string) $value) ?? '';
|
|
return preg_replace('/\D+/', '', (string) $value) ?? '';
|
|
|
}
|
|
}
|
|
|
|
|
+
|
|
|
|
|
+ private function isIncompleteGatewayPayment(Payment $payment): bool
|
|
|
|
|
+ {
|
|
|
|
|
+ return $payment->status === 'pending'
|
|
|
|
|
+ && empty($payment->gateway_entity_reference)
|
|
|
|
|
+ && empty($payment->gateway_operation_reference)
|
|
|
|
|
+ && empty($payment->gateway_payload);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private function resolveCreditCardReference(?ClientPaymentMethod $clientPaymentMethod, array $options): array
|
|
|
|
|
+ {
|
|
|
|
|
+ if (! empty($options['card_id'])) {
|
|
|
|
|
+ return ['card_id' => $options['card_id']];
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (! empty($clientPaymentMethod?->gateway_card_id)) {
|
|
|
|
|
+ return ['card_id' => $clientPaymentMethod->gateway_card_id];
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ throw new \InvalidArgumentException('Cartao de pagamento precisa ter gateway_card_id do Pagar.me.');
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ public function syncScheduleStatusAfterPayment(Schedule $schedule, Payment $payment): void
|
|
|
|
|
+ {
|
|
|
|
|
+ if ($payment->status !== 'paid' || $schedule->status === 'paid') {
|
|
|
|
|
+ return;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ $schedule->update(['status' => 'paid']);
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|