| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386 |
- <?php
- namespace App\Services\Pagarme;
- use App\Data\Pagarme\Request\CustomerRequestData\CustomerAddressRequestData;
- use App\Data\Pagarme\Request\CustomerRequestData\CustomerPhonesRequestData\CustomerPhoneData;
- use App\Data\Pagarme\Request\CustomerRequestData\CustomerPhonesRequestData\CustomerPhonesRequestData;
- use App\Data\Pagarme\Request\CustomerRequestData\CustomerRequestData;
- use App\Data\Pagarme\Request\OrderRequestData\OrderItemData;
- use App\Data\Pagarme\Request\OrderRequestData\OrderPaymentData\OrderCreditCardData;
- use App\Data\Pagarme\Request\OrderRequestData\OrderPaymentData\OrderPaymentData;
- use App\Data\Pagarme\Request\OrderRequestData\OrderPaymentData\OrderPixAdditionalInformationData;
- use App\Data\Pagarme\Request\OrderRequestData\OrderPaymentData\OrderPixData;
- use App\Data\Pagarme\Request\OrderRequestData\OrderPaymentData\OrderSplitData;
- use App\Data\Pagarme\Request\OrderRequestData\OrderPaymentData\OrderSplitOptionsData;
- use App\Data\Pagarme\Request\OrderRequestData\OrderRequestData;
- use App\Data\Pagarme\Response\OrderResponseData\OrderResponseData;
- use App\Enums\PaymentSplitStatusEnum;
- use App\Enums\PaymentStatusEnum;
- use App\Models\Address;
- use App\Models\Payment;
- use App\Models\PaymentSplit;
- use App\Models\Schedule;
- use App\Services\Pagarme\Concerns\SendsPagarmeRequests;
- use Illuminate\Support\Str;
- class PagarmePaymentService
- {
- use SendsPagarmeRequests;
- public function processPayment(
- Payment $payment,
- Schedule $schedule,
- string $paymentMethod,
- ?string $cardId = null,
- array $options = [],
- ): array {
- $grossAmount = (float) $payment->gross_amount;
- $items = $this->buildOrderItems($schedule, $grossAmount);
- $customer = $this->buildCustomer($schedule, $options);
- $split = $this->buildSplit($payment, $options);
- $pixOptions = config('services.pagarme.pix_disable_split')
- ? []
- : ['split' => $split];
- $orderOptions = array_merge(['split' => $split], $pixOptions);
- if ($paymentMethod === 'credit_card') {
- $creditCard = new OrderCreditCardData(
- cardId: $cardId,
- installments: 1,
- statementDescriptor: Str::limit((string) config('app.name', 'SOFTPAR'), 13, ''),
- operationType: 'auth_and_capture',
- );
- return $this->createOrderWithCreditCard(
- payment: $payment,
- items: $items,
- customer: $customer,
- creditCard: $creditCard,
- options: $orderOptions,
- );
- }
- $pixData = new OrderPixData(
- expiresIn: 1800,
- additionalInformation: [
- new OrderPixAdditionalInformationData(
- name: 'Agendamento',
- value: (string) $schedule->id,
- ),
- ],
- );
- return $this->createOrderWithPix(
- payment: $payment,
- items: $items,
- customer: $customer,
- pix: $pixData,
- options: $pixOptions,
- );
- }
- public function createOrderWithCreditCard(
- Payment $payment,
- array $items,
- CustomerRequestData $customer,
- OrderCreditCardData $creditCard,
- array $options = []
- ): array {
- return $this->createOrder(
- payment: $payment,
- items: $items,
- customer: $customer,
- paymentMethod: OrderRequestData::creditCardPaymentMethod(
- creditCard: $creditCard,
- split: is_array($options['split'] ?? null) ? $options['split'] : null,
- ),
- options: $options,
- );
- }
- public function createOrderWithPix(
- Payment $payment,
- array $items,
- CustomerRequestData $customer,
- OrderPixData $pix,
- array $options = []
- ): array {
- return $this->createOrder(
- payment: $payment,
- items: $items,
- customer: $customer,
- paymentMethod: OrderRequestData::pixPaymentMethod(
- pix: $pix,
- split: is_array($options['split'] ?? null) ? $options['split'] : null,
- ),
- options: $options,
- );
- }
- public function createOrder(
- Payment $payment,
- array $items,
- CustomerRequestData $customer,
- OrderPaymentData $paymentMethod,
- array $options = []
- ): array {
- $metadata = array_merge([
- 'payment_id' => (string) $payment->id,
- 'schedule_id' => (string) $payment->schedule_id,
- 'client_id' => (string) $payment->client_id,
- 'provider_id' => (string) $payment->provider_id,
- ], $options['metadata'] ?? []);
- $requestData = new OrderRequestData(
- code: $this->ensurePaymentCode($payment),
- items: $items,
- payments: [$paymentMethod],
- metadata: $metadata,
- customer: $customer,
- customerId: $options['customer_id'] ?? null,
- closed: $options['closed'] ?? true,
- channel: $options['channel'] ?? null,
- );
- $order = OrderResponseData::fromArray($this->pagarmeRequest(
- method: 'POST',
- path: '/orders',
- payload: $requestData,
- idempotencyKey: $this->idempotencyKey($payment),
- errorMessage: 'Erro ao criar pedido de pagamento no Pagar.me.',
- ));
- $order->requireId();
- return $order->toArray();
- }
- //
- public function applyGatewayResponseToPayment(Payment $payment, array $orderResponse): Payment
- {
- $order = OrderResponseData::fromArray($orderResponse);
- $newStatus = $order->paymentStatus();
- $failureCode = null;
- $failureMessage = null;
- if ($newStatus === PaymentStatusEnum::FAILED) {
- $failureCode = $order->failureCode();
- $failureMessage = $order->failureMessage();
- }
- $payment->forceFill([
- 'gateway_provider' => 'pagarme',
- 'gateway_entity_reference' => $order->gatewayEntityReference(),
- 'gateway_entity_label' => $order->gatewayEntityLabel(),
- 'gateway_operation_reference' => $order->gatewayOperationReference(),
- 'gateway_operation_label' => $order->gatewayOperationLabel(),
- 'status' => $newStatus,
- 'paid_at' => $order->paidAt(),
- 'authorized_at' => $order->authorizedAt(),
- 'gateway_payload' => $orderResponse,
- 'failure_code' => $failureCode,
- 'failure_message' => $failureMessage,
- ])->save();
- $splitStatus = match ($newStatus) {
- PaymentStatusEnum::PAID => PaymentSplitStatusEnum::TRANSFERRED,
- PaymentStatusEnum::FAILED => PaymentSplitStatusEnum::FAILED,
- PaymentStatusEnum::CANCELLED => PaymentSplitStatusEnum::CANCELLED,
- PaymentStatusEnum::AUTHORIZED => PaymentSplitStatusEnum::PROCESSING,
- default => PaymentSplitStatusEnum::PENDING,
- };
- PaymentSplit::query()
- ->where('payment_id', $payment->id)
- ->update(['status' => $splitStatus]);
- return $payment->fresh();
- }
- //
- public function ensureCustomerPhone(Schedule $schedule, array $options): void
- {
- $phone = $this->buildPhonePayload($schedule->client?->user?->phone)
- ?: $this->buildPhonePayload($options['phone'] ?? null);
- if (! $phone) {
- throw new \InvalidArgumentException(
- 'Voce precisa cadastrar um numero de celular valido no seu perfil para concluir o pagamento.'
- );
- }
- }
- //
- private function buildOrderItems(Schedule $schedule, float $grossAmount): array
- {
- $description = $schedule->customSchedule?->serviceType?->description
- ?? "Servico {$schedule->id}";
- return [new OrderItemData(
- code: "schedule-{$schedule->id}",
- amount: OrderRequestData::amountInCents($grossAmount),
- quantity: 1,
- description: $description,
- )];
- }
- private function buildCustomer(Schedule $schedule, array $options = []): CustomerRequestData
- {
- $client = $schedule->client;
- $user = $client->user()->first(['id', 'name', 'email', 'phone']);
- $address = Address::with(['city.state', 'state'])->find($schedule->address_id);
- 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) {
- throw new \InvalidArgumentException('Endereco do agendamento nao encontrado para criar pedido no Pagar.me.');
- }
- $document = $this->digits($client->document);
- $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->address,
- $address->district,
- ]));
- foreach ([
- 'documento' => $document,
- 'estado' => $state,
- 'cidade' => $city,
- 'cep' => $zipCode,
- 'endereco' => $line1,
- 'telefone' => $phone,
- ] as $field => $value) {
- if ($value === null || $value === '' || $value === []) {
- throw new \InvalidArgumentException("Cliente precisa ter {$field} valido para criar pedido no Pagar.me.");
- }
- }
- $customerAddress = new CustomerAddressRequestData(
- line1: $line1,
- line2: $address->complement ?: $address->instructions,
- zipCode: $zipCode,
- city: $city,
- state: $state,
- country: 'BR',
- );
- $customerPhones = null;
- if ($phone) {
- $customerPhones = new CustomerPhonesRequestData(
- mobilePhone: new CustomerPhoneData(
- countryCode: $phone['country_code'],
- areaCode: $phone['area_code'],
- number: $phone['number'],
- ),
- );
- }
- return new CustomerRequestData(
- name: $user->name,
- email: $user->email,
- document: $document,
- type: strlen($document) === 14 ? 'company' : 'individual',
- documentType: strlen($document) === 14 ? 'CNPJ' : 'CPF',
- code: "client-{$client->id}",
- address: $customerAddress,
- phones: $customerPhones,
- );
- }
- private function buildPhonePayload(?string $phone): ?array
- {
- $digits = $this->digits($phone);
- if (strlen($digits) < 10) {
- return null;
- }
- if (str_starts_with($digits, '55')) {
- $digits = substr($digits, 2);
- }
- return [
- 'country_code' => '55',
- 'area_code' => substr($digits, 0, 2),
- 'number' => substr($digits, 2),
- ];
- }
- private function buildSplit(Payment $payment, array $options): array
- {
- $transfers = PaymentSplit::query()
- ->where('payment_id', $payment->id)
- ->get();
- $split = OrderRequestData::splitFromTransfers($transfers);
- $platformFee = (float) ($payment->platform_fee_amount ?? 0);
- if ($platformFee > 0) {
- $platformRecipientId = config('services.pagarme.platform_recipient_id');
- $split[] = new OrderSplitData(
- amount: OrderRequestData::amountInCents($platformFee),
- recipientId: $platformRecipientId,
- type: 'flat',
- options: new OrderSplitOptionsData(
- chargeProcessingFee: true,
- chargeRemainderFee: true,
- liable: true,
- ),
- );
- }
- return $split;
- }
- private function digits(?string $value): string
- {
- return preg_replace('/\D+/', '', (string) $value) ?? '';
- }
- //
- private function idempotencyKey(Payment $payment): string
- {
- return "payment-{$payment->id}-schedule-{$payment->schedule_id}";
- }
- private function ensurePaymentCode(Payment $payment): string
- {
- if (! empty($payment->gateway_code)) {
- return $payment->gateway_code;
- }
- $code = 'payment-'.(string) Str::uuid();
- $payment->forceFill(['gateway_code' => $code])->save();
- return $code;
- }
- }
|