PagarmePaymentService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. <?php
  2. namespace App\Services\Pagarme;
  3. use App\Data\Pagarme\Request\CustomerRequestData\CustomerAddressRequestData;
  4. use App\Data\Pagarme\Request\CustomerRequestData\CustomerPhonesRequestData\CustomerPhoneData;
  5. use App\Data\Pagarme\Request\CustomerRequestData\CustomerPhonesRequestData\CustomerPhonesRequestData;
  6. use App\Data\Pagarme\Request\CustomerRequestData\CustomerRequestData;
  7. use App\Data\Pagarme\Request\OrderRequestData\OrderItemData;
  8. use App\Data\Pagarme\Request\OrderRequestData\OrderPaymentData\OrderCreditCardData;
  9. use App\Data\Pagarme\Request\OrderRequestData\OrderPaymentData\OrderPaymentData;
  10. use App\Data\Pagarme\Request\OrderRequestData\OrderPaymentData\OrderPixAdditionalInformationData;
  11. use App\Data\Pagarme\Request\OrderRequestData\OrderPaymentData\OrderPixData;
  12. use App\Data\Pagarme\Request\OrderRequestData\OrderPaymentData\OrderSplitData;
  13. use App\Data\Pagarme\Request\OrderRequestData\OrderPaymentData\OrderSplitOptionsData;
  14. use App\Data\Pagarme\Request\OrderRequestData\OrderRequestData;
  15. use App\Data\Pagarme\Response\OrderResponseData\OrderResponseData;
  16. use App\Enums\PaymentSplitStatusEnum;
  17. use App\Enums\PaymentStatusEnum;
  18. use App\Models\Address;
  19. use App\Models\Payment;
  20. use App\Models\PaymentSplit;
  21. use App\Models\Schedule;
  22. use App\Services\Pagarme\Concerns\FormatsPagarmeData;
  23. use App\Services\Pagarme\Concerns\SendsPagarmeRequests;
  24. use Illuminate\Support\Str;
  25. class PagarmePaymentService
  26. {
  27. use FormatsPagarmeData;
  28. use SendsPagarmeRequests;
  29. public function processPayment(
  30. Payment $payment,
  31. Schedule $schedule,
  32. string $paymentMethod,
  33. ?string $cardId = null,
  34. array $options = [],
  35. ): array {
  36. $grossAmount = (float) $payment->gross_amount;
  37. $items = $this->buildOrderItems($schedule, $grossAmount);
  38. $customer = $this->buildCustomer($schedule, $options);
  39. $split = $this->buildSplit($payment, $options);
  40. $pixOptions = config('services.pagarme.pix_disable_split')
  41. ? []
  42. : ['split' => $split];
  43. $orderOptions = array_merge(['split' => $split], $pixOptions);
  44. if ($paymentMethod === 'credit_card') {
  45. $creditCard = new OrderCreditCardData(
  46. cardId: $cardId,
  47. installments: 1,
  48. statementDescriptor: Str::limit((string) config('app.name', 'SOFTPAR'), 13, ''),
  49. operationType: 'auth_and_capture',
  50. );
  51. return $this->createOrderWithCreditCard(
  52. payment: $payment,
  53. items: $items,
  54. customer: $customer,
  55. creditCard: $creditCard,
  56. options: $orderOptions,
  57. );
  58. }
  59. $pixData = new OrderPixData(
  60. expiresIn: 1800,
  61. additionalInformation: [
  62. new OrderPixAdditionalInformationData(
  63. name: 'Agendamento',
  64. value: (string) $schedule->id,
  65. ),
  66. ],
  67. );
  68. return $this->createOrderWithPix(
  69. payment: $payment,
  70. items: $items,
  71. customer: $customer,
  72. pix: $pixData,
  73. options: $pixOptions,
  74. );
  75. }
  76. public function createOrderWithCreditCard(
  77. Payment $payment,
  78. array $items,
  79. CustomerRequestData $customer,
  80. OrderCreditCardData $creditCard,
  81. array $options = []
  82. ): array {
  83. return $this->createOrder(
  84. payment: $payment,
  85. items: $items,
  86. customer: $customer,
  87. paymentMethod: OrderRequestData::creditCardPaymentMethod(
  88. creditCard: $creditCard,
  89. split: is_array($options['split'] ?? null) ? $options['split'] : null,
  90. ),
  91. options: $options,
  92. );
  93. }
  94. public function createOrderWithPix(
  95. Payment $payment,
  96. array $items,
  97. CustomerRequestData $customer,
  98. OrderPixData $pix,
  99. array $options = []
  100. ): array {
  101. return $this->createOrder(
  102. payment: $payment,
  103. items: $items,
  104. customer: $customer,
  105. paymentMethod: OrderRequestData::pixPaymentMethod(
  106. pix: $pix,
  107. split: is_array($options['split'] ?? null) ? $options['split'] : null,
  108. ),
  109. options: $options,
  110. );
  111. }
  112. public function createOrder(
  113. Payment $payment,
  114. array $items,
  115. CustomerRequestData $customer,
  116. OrderPaymentData $paymentMethod,
  117. array $options = []
  118. ): array {
  119. $metadata = array_merge([
  120. 'payment_id' => (string) $payment->id,
  121. 'schedule_id' => (string) $payment->schedule_id,
  122. 'client_id' => (string) $payment->client_id,
  123. 'provider_id' => (string) $payment->provider_id,
  124. ], $options['metadata'] ?? []);
  125. $requestData = new OrderRequestData(
  126. code: $payment->ensureGatewayCode(),
  127. items: $items,
  128. payments: [$paymentMethod],
  129. metadata: $metadata,
  130. customer: $customer,
  131. customerId: $options['customer_id'] ?? null,
  132. closed: $options['closed'] ?? true,
  133. channel: $options['channel'] ?? null,
  134. );
  135. $order = OrderResponseData::fromArray($this->pagarmeRequest(
  136. method: 'POST',
  137. path: '/orders',
  138. payload: $requestData,
  139. idempotencyKey: $this->idempotencyKey($payment),
  140. errorMessage: 'Erro ao criar pedido de pagamento no Pagar.me.',
  141. ));
  142. $order->requireId();
  143. return $order->toArray();
  144. }
  145. //
  146. public function applyGatewayResponseToPayment(Payment $payment, array $orderResponse): Payment
  147. {
  148. $order = OrderResponseData::fromArray($orderResponse);
  149. $newStatus = $order->paymentStatus();
  150. $failureCode = null;
  151. $failureMessage = null;
  152. if ($newStatus === PaymentStatusEnum::FAILED) {
  153. $failureCode = $order->failureCode();
  154. $failureMessage = $order->failureMessage();
  155. }
  156. $payment->forceFill([
  157. 'gateway_provider' => 'pagarme',
  158. 'gateway_entity_reference' => $order->gatewayEntityReference(),
  159. 'gateway_entity_label' => $order->gatewayEntityLabel(),
  160. 'gateway_operation_reference' => $order->gatewayOperationReference(),
  161. 'gateway_operation_label' => $order->gatewayOperationLabel(),
  162. 'status' => $newStatus,
  163. 'paid_at' => $order->paidAt(),
  164. 'authorized_at' => $order->authorizedAt(),
  165. 'gateway_payload' => $orderResponse,
  166. 'failure_code' => $failureCode,
  167. 'failure_message' => $failureMessage,
  168. ])->save();
  169. $splitStatus = match ($newStatus) {
  170. PaymentStatusEnum::PAID => PaymentSplitStatusEnum::TRANSFERRED,
  171. PaymentStatusEnum::FAILED => PaymentSplitStatusEnum::FAILED,
  172. PaymentStatusEnum::CANCELLED => PaymentSplitStatusEnum::CANCELLED,
  173. PaymentStatusEnum::AUTHORIZED => PaymentSplitStatusEnum::PROCESSING,
  174. default => PaymentSplitStatusEnum::PENDING,
  175. };
  176. PaymentSplit::query()
  177. ->where('payment_id', $payment->id)
  178. ->update(['status' => $splitStatus]);
  179. return $payment->fresh();
  180. }
  181. //
  182. private function buildCustomer(Schedule $schedule, array $options = []): CustomerRequestData
  183. {
  184. $client = $schedule->client;
  185. $user = $client->user()->first(['id', 'name', 'email', 'phone']);
  186. $address = Address::with(['city.state', 'state'])->find($schedule->address_id);
  187. foreach ([
  188. 'nome' => $user?->name,
  189. 'email' => $user?->email,
  190. 'documento' => $client->document,
  191. ] as $field => $value) {
  192. if ($value === null || $value === '') {
  193. throw new \InvalidArgumentException("Cliente precisa ter {$field} para criar pedido no Pagar.me.");
  194. }
  195. }
  196. if (! $address) {
  197. throw new \InvalidArgumentException('Endereco do agendamento nao encontrado para criar pedido no Pagar.me.');
  198. }
  199. $document = $this->digits($client->document);
  200. $phone = $this->buildPhonePayload($user->phone)
  201. ?: $this->buildPhonePayload($options['phone'] ?? null);
  202. $state = $address->state?->code ?? $address->city?->state?->code;
  203. $city = $address->city?->name;
  204. $zipCode = $this->digits($address->zip_code);
  205. $line1 = implode(', ', array_filter([
  206. $address->number ?: 'S/N',
  207. $address->address,
  208. $address->district,
  209. ]));
  210. foreach ([
  211. 'documento' => $document,
  212. 'estado' => $state,
  213. 'cidade' => $city,
  214. 'cep' => $zipCode,
  215. 'endereco' => $line1,
  216. 'telefone' => $phone,
  217. ] as $field => $value) {
  218. if ($value === null || $value === '' || $value === []) {
  219. throw new \InvalidArgumentException("Cliente precisa ter {$field} valido para criar pedido no Pagar.me.");
  220. }
  221. }
  222. $customerAddress = new CustomerAddressRequestData(
  223. line1: $line1,
  224. line2: $address->complement ?: $address->instructions,
  225. zipCode: $zipCode,
  226. city: $city,
  227. state: $state,
  228. country: 'BR',
  229. );
  230. $customerPhones = null;
  231. if ($phone) {
  232. $customerPhones = new CustomerPhonesRequestData(
  233. mobilePhone: new CustomerPhoneData(
  234. countryCode: $phone['country_code'],
  235. areaCode: $phone['area_code'],
  236. number: $phone['number'],
  237. ),
  238. );
  239. }
  240. return new CustomerRequestData(
  241. name: $user->name,
  242. email: $user->email,
  243. document: $document,
  244. type: strlen($document) === 14 ? 'company' : 'individual',
  245. documentType: strlen($document) === 14 ? 'CNPJ' : 'CPF',
  246. code: "client-{$client->id}",
  247. address: $customerAddress,
  248. phones: $customerPhones,
  249. );
  250. }
  251. private function buildOrderItems(Schedule $schedule, float $grossAmount): array
  252. {
  253. $description = $schedule->customSchedule?->serviceType?->description
  254. ?? "Servico {$schedule->id}";
  255. return [new OrderItemData(
  256. code: "schedule-{$schedule->id}",
  257. amount: OrderRequestData::amountInCents($grossAmount),
  258. quantity: 1,
  259. description: $description,
  260. )];
  261. }
  262. private function buildPhonePayload(?string $phone): ?array
  263. {
  264. $digits = $this->digits($phone);
  265. if (strlen($digits) < 10) {
  266. return null;
  267. }
  268. if (str_starts_with($digits, '55')) {
  269. $digits = substr($digits, 2);
  270. }
  271. return [
  272. 'country_code' => '55',
  273. 'area_code' => substr($digits, 0, 2),
  274. 'number' => substr($digits, 2),
  275. ];
  276. }
  277. private function buildSplit(Payment $payment, array $options): array
  278. {
  279. $transfers = PaymentSplit::query()
  280. ->where('payment_id', $payment->id)
  281. ->get();
  282. $split = OrderRequestData::splitFromTransfers($transfers);
  283. $platformFee = (float) ($payment->platform_fee_amount ?? 0);
  284. if ($platformFee > 0) {
  285. $platformRecipientId = config('services.pagarme.platform_recipient_id');
  286. $split[] = new OrderSplitData(
  287. amount: OrderRequestData::amountInCents($platformFee),
  288. recipientId: $platformRecipientId,
  289. type: 'flat',
  290. options: new OrderSplitOptionsData(
  291. chargeProcessingFee: true,
  292. chargeRemainderFee: true,
  293. liable: true,
  294. ),
  295. );
  296. }
  297. return $split;
  298. }
  299. // evita criacao duplicada de payment
  300. private function idempotencyKey(Payment $payment): string
  301. {
  302. return "payment-{$payment->id}-schedule-{$payment->schedule_id}";
  303. }
  304. }