PagarmePaymentService.php 13 KB

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