PagarmePaymentService.php 14 KB

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