PagarmePaymentService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. <?php
  2. namespace App\Services\Pagarme;
  3. use App\Data\Pagarme\Request\PagarmeOrderRequestData\PagarmeOrderRequestData;
  4. use App\Data\Pagarme\Response\PagarmeOrderResponseData\PagarmeOrderResponseData;
  5. use App\Enums\PaymentStatusEnum;
  6. use App\Models\Payment;
  7. use App\Models\PaymentSplit;
  8. use App\Services\Pagarme\Concerns\SendsPagarmeRequests;
  9. use Illuminate\Support\Collection;
  10. use Illuminate\Support\Str;
  11. class PagarmePaymentService
  12. {
  13. use SendsPagarmeRequests;
  14. public function createOrderWithCreditCard(
  15. Payment $payment,
  16. array $items,
  17. array $customer,
  18. array $creditCard,
  19. array $options = []
  20. ): array {
  21. $paymentMethod = [
  22. 'payment_method' => 'credit_card',
  23. 'credit_card' => $this->buildCreditCardPayload($creditCard),
  24. ];
  25. if (! empty($options['split']) && is_array($options['split'])) {
  26. $paymentMethod['split'] = $options['split'];
  27. }
  28. return $this->createOrder(
  29. payment: $payment,
  30. items: $items,
  31. customer: $customer,
  32. paymentMethod: $paymentMethod,
  33. options: $options,
  34. );
  35. }
  36. public function createOrderWithPix(
  37. Payment $payment,
  38. array $items,
  39. array $customer,
  40. array $pix,
  41. array $options = []
  42. ): array {
  43. $paymentMethod = [
  44. 'payment_method' => 'pix',
  45. 'pix' => $this->buildPixPayload($pix),
  46. ];
  47. if (! empty($options['split']) && is_array($options['split'])) {
  48. $paymentMethod['split'] = $options['split'];
  49. }
  50. return $this->createOrder(
  51. payment: $payment,
  52. items: $items,
  53. customer: $customer,
  54. paymentMethod: $paymentMethod,
  55. options: $options,
  56. );
  57. }
  58. //
  59. public function createOrder(
  60. Payment $payment,
  61. array $items,
  62. array $customer,
  63. array $paymentMethod,
  64. array $options = []
  65. ): array {
  66. if (empty($items)) {
  67. throw new \InvalidArgumentException('items nao pode estar vazio.');
  68. }
  69. if (empty($paymentMethod['payment_method'])) {
  70. throw new \InvalidArgumentException('payment_method e obrigatorio.');
  71. }
  72. if (! in_array($paymentMethod['payment_method'], ['credit_card', 'pix'], true)) {
  73. throw new \InvalidArgumentException('payment_method deve ser credit_card ou pix.');
  74. }
  75. $customerIdPayload = $options['customer_id'] ?? null;
  76. $customerObjectPayload = $this->filterFilledRecursive($customer);
  77. if (! $this->filled($customerIdPayload) && empty($customerObjectPayload)) {
  78. throw new \InvalidArgumentException('customer ou customer_id e obrigatorio.');
  79. }
  80. $requestData = new PagarmeOrderRequestData(
  81. code: $this->ensurePaymentCode($payment),
  82. items: $this->validateItems($items),
  83. payments: [$this->filterFilledRecursive($paymentMethod)],
  84. metadata: array_merge([
  85. 'payment_id' => (string) $payment->id,
  86. 'schedule_id' => (string) $payment->schedule_id,
  87. 'client_id' => (string) $payment->client_id,
  88. 'provider_id' => (string) $payment->provider_id,
  89. ], $options['metadata'] ?? []),
  90. customer: ! empty($customerObjectPayload) ? $customerObjectPayload : null,
  91. customerId: $this->filled($customerIdPayload) ? (string) $customerIdPayload : null,
  92. closed: $options['closed'] ?? true,
  93. channel: $options['channel'] ?? null,
  94. );
  95. $order = PagarmeOrderResponseData::fromArray($this->pagarmeRequest(
  96. method: 'POST',
  97. path: '/orders',
  98. payload: $requestData,
  99. idempotencyKey: $this->idempotencyKey($payment),
  100. errorMessage: 'Erro ao criar pedido de pagamento no Pagar.me.',
  101. ));
  102. if (empty($order->id())) {
  103. throw new \RuntimeException('Pagar.me order creation returned an empty id.');
  104. }
  105. return $order->toArray();
  106. }
  107. private function ensurePaymentCode(Payment $payment): string
  108. {
  109. if ($this->hasUuidCode($payment->gateway_code, 'payment')) {
  110. return $payment->gateway_code;
  111. }
  112. $code = 'payment-'.(string) Str::uuid();
  113. $payment->forceFill(['gateway_code' => $code])->save();
  114. return $code;
  115. }
  116. private function hasUuidCode(?string $code, string $prefix): bool
  117. {
  118. return is_string($code)
  119. && preg_match("/^{$prefix}-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i", $code) === 1;
  120. }
  121. //
  122. public function applyGatewayResponseToPayment(Payment $payment, array $orderResponse): Payment
  123. {
  124. $charge = $orderResponse['charges'][0] ?? [];
  125. $transaction = $charge['last_transaction'] ?? [];
  126. $chargeStatus = $charge['status'] ?? null;
  127. $transactionStatus = $transaction['status'] ?? null;
  128. $payment->forceFill([
  129. 'gateway_provider' => 'pagarme',
  130. 'gateway_entity_reference' => $charge['id'] ?? $orderResponse['id'] ?? null,
  131. 'gateway_entity_label' => isset($charge['id']) ? 'charge' : 'order',
  132. 'gateway_operation_reference' => $transaction['id'] ?? $charge['id'] ?? $orderResponse['id'] ?? null,
  133. 'gateway_operation_label' => isset($transaction['id']) ? 'transaction' : (isset($charge['id']) ? 'charge' : 'order'),
  134. 'status' => $this->mapPaymentStatus($chargeStatus, $transactionStatus),
  135. 'paid_at' => $this->filledArrayValue($charge, 'paid_at'),
  136. 'authorized_at' => $this->resolveAuthorizedAt($transactionStatus, $transaction),
  137. 'gateway_payload' => $orderResponse,
  138. 'failure_code' => $this->extractFailureCode($transaction),
  139. 'failure_message' => $this->extractFailureMessage($transaction),
  140. ])->save();
  141. return $payment->fresh();
  142. }
  143. public function buildSplitFromTransfers(Collection $transfers): array
  144. {
  145. return $transfers
  146. ->filter(fn (PaymentSplit $split) => ! empty($split->gateway_transfer_target_reference))
  147. ->map(function (PaymentSplit $split) {
  148. return [
  149. 'amount' => $this->toGatewayAmountInCents((float) $split->gross_amount),
  150. 'recipient_id' => $split->gateway_transfer_target_reference,
  151. 'type' => 'flat',
  152. 'options' => [
  153. 'charge_processing_fee' => false,
  154. 'charge_remainder_fee' => false,
  155. 'liable' => false,
  156. ],
  157. ];
  158. })
  159. ->values()
  160. ->all();
  161. }
  162. public function toGatewayAmountInCents(float $amount): int
  163. {
  164. return (int) round($amount * 100);
  165. }
  166. //
  167. private function idempotencyKey(Payment $payment): string
  168. {
  169. return "payment-{$payment->id}-schedule-{$payment->schedule_id}";
  170. }
  171. private function buildCreditCardPayload(array $creditCard): array
  172. {
  173. $payload = [];
  174. foreach ([
  175. 'installments',
  176. 'statement_descriptor',
  177. 'operation_type',
  178. 'recurrence_cycle',
  179. 'metadata',
  180. 'extended_limit_enabled',
  181. 'extended_limit_code',
  182. 'merchant_category_code',
  183. 'authentication',
  184. 'auto_recovery',
  185. 'payload',
  186. 'payment_type',
  187. 'funding_source',
  188. 'initiated_type',
  189. 'recurrence_model',
  190. 'channel',
  191. 'payment_origin',
  192. ] as $field) {
  193. if (array_key_exists($field, $creditCard) && $this->filled($creditCard[$field])) {
  194. $payload[$field] = $creditCard[$field];
  195. }
  196. }
  197. $allowedCardOptions = ['card', 'card_id', 'card_token', 'network_token'];
  198. $provided = array_values(array_filter(
  199. $allowedCardOptions,
  200. static fn (string $field) => ! empty($creditCard[$field])
  201. ));
  202. if (count($provided) !== 1) {
  203. throw new \InvalidArgumentException('Informe exatamente uma opcao entre card, card_id, card_token ou network_token.');
  204. }
  205. $selected = $provided[0];
  206. $payload[$selected] = $creditCard[$selected];
  207. return $payload;
  208. }
  209. private function buildPixPayload(array $pix): array
  210. {
  211. if (! $this->filled($pix['expires_in'] ?? null) && ! $this->filled($pix['expires_at'] ?? null)) {
  212. throw new \InvalidArgumentException('pix.expires_in ou pix.expires_at e obrigatorio.');
  213. }
  214. $payload = [];
  215. foreach (['expires_in', 'expires_at', 'additional_information'] as $field) {
  216. if (array_key_exists($field, $pix) && $this->filled($pix[$field])) {
  217. $payload[$field] = $pix[$field];
  218. }
  219. }
  220. return $payload;
  221. }
  222. private function extractFailureCode(array $transaction): ?string
  223. {
  224. return $this->filledArrayValue($transaction['gateway_response'] ?? [], 'code');
  225. }
  226. private function extractFailureMessage(array $transaction): ?string
  227. {
  228. $acquirerMessage = $this->filledArrayValue($transaction, 'acquirer_message');
  229. if ($acquirerMessage) {
  230. return $acquirerMessage;
  231. }
  232. $gatewayErrors = $transaction['gateway_response']['errors'] ?? [];
  233. if (! is_array($gatewayErrors) || empty($gatewayErrors)) {
  234. return null;
  235. }
  236. $message = collect($gatewayErrors)
  237. ->pluck('message')
  238. ->filter()
  239. ->implode('; ') ?: null;
  240. return $this->translateGatewayMessage($message);
  241. }
  242. private function filled(mixed $value): bool
  243. {
  244. return $value !== null && $value !== '' && $value !== [];
  245. }
  246. private function filledArrayValue(array $data, string $field): ?string
  247. {
  248. if (! array_key_exists($field, $data) || ! $this->filled($data[$field])) {
  249. return null;
  250. }
  251. return (string) $data[$field];
  252. }
  253. private function filterFilledRecursive(array $data): array
  254. {
  255. $filtered = [];
  256. foreach ($data as $key => $value) {
  257. if (is_array($value)) {
  258. $value = $this->filterFilledRecursive($value);
  259. }
  260. if ($this->filled($value)) {
  261. $filtered[$key] = $value;
  262. }
  263. }
  264. return $filtered;
  265. }
  266. private function translateGatewayMessage(?string $message): ?string
  267. {
  268. if (! $message) {
  269. return null;
  270. }
  271. if (str_contains($message, 'Sem ambiente configurado')) {
  272. return 'Pix não esta habilitado ou configurado neste ambiente do Pagar.me.';
  273. }
  274. return $message;
  275. }
  276. private function mapPaymentStatus(?string $chargeStatus, ?string $transactionStatus): PaymentStatusEnum
  277. {
  278. $status = strtolower((string) ($transactionStatus ?: $chargeStatus));
  279. return match ($status) {
  280. 'captured', 'paid', 'overpaid' => PaymentStatusEnum::PAID,
  281. 'authorized_pending_capture', 'waiting_capture' => PaymentStatusEnum::AUTHORIZED,
  282. 'pending', 'waiting_payment' => PaymentStatusEnum::PENDING,
  283. 'processing' => PaymentStatusEnum::PROCESSING,
  284. 'not_authorized', 'with_error', 'failed',
  285. 'underpaid', 'chargedback' => PaymentStatusEnum::FAILED,
  286. 'voided', 'partial_void', 'canceled',
  287. 'cancelled', 'refunded', 'partial_refunded',
  288. 'partial_canceled' => PaymentStatusEnum::CANCELLED,
  289. default => PaymentStatusEnum::PENDING,
  290. };
  291. }
  292. private function resolveAuthorizedAt(?string $transactionStatus, array $transaction): ?string
  293. {
  294. if (in_array($transactionStatus, ['authorized_pending_capture', 'captured', 'partial_capture'], true)) {
  295. return $this->filledArrayValue($transaction, 'created_at');
  296. }
  297. return null;
  298. }
  299. private function validateItems(array $items): array
  300. {
  301. return collect($items)
  302. ->map(function (array $item, int $index) {
  303. foreach (['code', 'amount', 'quantity'] as $field) {
  304. if (! array_key_exists($field, $item) || ! $this->filled($item[$field])) {
  305. throw new \InvalidArgumentException("items.{$index}.{$field} e obrigatorio.");
  306. }
  307. }
  308. if ((int) $item['amount'] <= 0 || (int) $item['quantity'] <= 0) {
  309. throw new \InvalidArgumentException("items.{$index}.amount e quantity devem ser maiores que zero.");
  310. }
  311. return $this->filterFilledRecursive($item);
  312. })
  313. ->values()
  314. ->all();
  315. }
  316. }