PagarmePaymentService.php 13 KB

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