PagarmePaymentService.php 14 KB

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