PagarmePaymentService.php 13 KB

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