PagarmePaymentService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. $response = $this->pagarmeRequest($this->idempotencyKey($payment))
  99. ->post($this->pagarmeUrl('/orders'), $payload);
  100. if ($response->failed()) {
  101. Log::channel('pagarme')->error('Pagar.me order creation failed', [
  102. 'status' => $response->status(),
  103. 'body' => $response->json() ?? $response->body(),
  104. 'payload' => $payload,
  105. ]);
  106. throw new \RuntimeException('Erro ao criar pedido de pagamento no Pagar.me.');
  107. }
  108. $order = $response->json();
  109. if (empty($order['id'])) {
  110. Log::channel('pagarme')->error('Pagar.me order creation returned empty id', [
  111. 'payment_id' => $payment->id,
  112. 'response' => $order,
  113. ]);
  114. throw new \RuntimeException('Pagar.me order creation returned an empty id.');
  115. }
  116. return $order;
  117. }
  118. //
  119. public function applyGatewayResponseToPayment(Payment $payment, array $orderResponse): Payment
  120. {
  121. $charge = $orderResponse['charges'][0] ?? [];
  122. $transaction = $charge['last_transaction'] ?? [];
  123. $chargeStatus = $charge['status'] ?? null;
  124. $transactionStatus = $transaction['status'] ?? null;
  125. $payment->forceFill([
  126. 'gateway_provider' => 'pagarme',
  127. 'gateway_entity_reference' => $charge['id'] ?? $orderResponse['id'] ?? null,
  128. 'gateway_entity_label' => isset($charge['id']) ? 'charge' : 'order',
  129. 'gateway_operation_reference' => $transaction['id'] ?? $charge['id'] ?? $orderResponse['id'] ?? null,
  130. 'gateway_operation_label' => isset($transaction['id']) ? 'transaction' : (isset($charge['id']) ? 'charge' : 'order'),
  131. 'status' => $this->mapPaymentStatus($chargeStatus, $transactionStatus),
  132. 'paid_at' => $this->filledArrayValue($charge, 'paid_at'),
  133. 'authorized_at' => $this->resolveAuthorizedAt($transactionStatus, $transaction),
  134. 'gateway_payload' => $orderResponse,
  135. 'failure_code' => $this->extractFailureCode($transaction),
  136. 'failure_message' => $this->extractFailureMessage($transaction),
  137. ])->save();
  138. return $payment->fresh();
  139. }
  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 pagarmeUrl(string $path): string
  166. {
  167. return rtrim(config('services.pagarme.base_url'), '/').'/'.ltrim($path, '/');
  168. }
  169. private function idempotencyKey(Payment $payment): string
  170. {
  171. return "payment-{$payment->id}-schedule-{$payment->schedule_id}";
  172. }
  173. //
  174. private function buildCreditCardPayload(array $creditCard): array
  175. {
  176. $payload = [];
  177. foreach ([
  178. 'installments',
  179. 'statement_descriptor',
  180. 'operation_type',
  181. 'recurrence_cycle',
  182. 'metadata',
  183. 'extended_limit_enabled',
  184. 'extended_limit_code',
  185. 'merchant_category_code',
  186. 'authentication',
  187. 'auto_recovery',
  188. 'payload',
  189. 'payment_type',
  190. 'funding_source',
  191. 'initiated_type',
  192. 'recurrence_model',
  193. 'channel',
  194. 'payment_origin',
  195. ] as $field) {
  196. if (array_key_exists($field, $creditCard) && $this->filled($creditCard[$field])) {
  197. $payload[$field] = $creditCard[$field];
  198. }
  199. }
  200. $allowedCardOptions = ['card', 'card_id', 'card_token', 'network_token'];
  201. $provided = array_values(array_filter(
  202. $allowedCardOptions,
  203. static fn (string $field) => ! empty($creditCard[$field])
  204. ));
  205. if (count($provided) !== 1) {
  206. throw new \InvalidArgumentException('Informe exatamente uma opcao entre card, card_id, card_token ou network_token.');
  207. }
  208. $selected = $provided[0];
  209. $payload[$selected] = $creditCard[$selected];
  210. return $payload;
  211. }
  212. private function buildPixPayload(array $pix): array
  213. {
  214. if (! $this->filled($pix['expires_in'] ?? null) && ! $this->filled($pix['expires_at'] ?? null)) {
  215. throw new \InvalidArgumentException('pix.expires_in ou pix.expires_at e obrigatorio.');
  216. }
  217. $payload = [];
  218. foreach (['expires_in', 'expires_at', 'additional_information'] as $field) {
  219. if (array_key_exists($field, $pix) && $this->filled($pix[$field])) {
  220. $payload[$field] = $pix[$field];
  221. }
  222. }
  223. return $payload;
  224. }
  225. //
  226. private function extractFailureCode(array $transaction): ?string
  227. {
  228. return $this->filledArrayValue($transaction['gateway_response'] ?? [], 'code');
  229. }
  230. private function extractFailureMessage(array $transaction): ?string
  231. {
  232. return $this->filledArrayValue($transaction, 'acquirer_message');
  233. }
  234. private function resolveAuthorizedAt(?string $transactionStatus, array $transaction): ?string
  235. {
  236. if (in_array($transactionStatus, ['authorized_pending_capture', 'captured', 'partial_capture'], true)) {
  237. return $this->filledArrayValue($transaction, 'created_at');
  238. }
  239. return null;
  240. }
  241. private function validateItems(array $items): array
  242. {
  243. return collect($items)
  244. ->map(function (array $item, int $index) {
  245. foreach (['code', 'amount', 'quantity'] as $field) {
  246. if (! array_key_exists($field, $item) || ! $this->filled($item[$field])) {
  247. throw new \InvalidArgumentException("items.{$index}.{$field} e obrigatorio.");
  248. }
  249. }
  250. if ((int) $item['amount'] <= 0 || (int) $item['quantity'] <= 0) {
  251. throw new \InvalidArgumentException("items.{$index}.amount e quantity devem ser maiores que zero.");
  252. }
  253. return $this->filterFilledRecursive($item);
  254. })
  255. ->values()
  256. ->all();
  257. }
  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. //
  284. private function mapPaymentStatus(?string $chargeStatus, ?string $transactionStatus): string
  285. {
  286. $status = strtolower((string) ($transactionStatus ?: $chargeStatus));
  287. return match ($status) {
  288. 'captured', 'paid' => 'paid',
  289. 'authorized_pending_capture', 'waiting_capture', 'pending' => 'authorized',
  290. 'processing' => 'processing',
  291. 'not_authorized', 'with_error', 'failed' => 'failed',
  292. 'voided', 'partial_void' => 'cancelled',
  293. default => 'pending',
  294. };
  295. }
  296. //
  297. private function pagarmeRequest(string $idempotencyKey)
  298. {
  299. $secretKey = config('services.pagarme.secret_key');
  300. if (empty($secretKey)) {
  301. Log::channel('pagarme')->error('PAGARME_SECRET_KEY is not configured.');
  302. throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
  303. }
  304. return Http::withBasicAuth($secretKey, '')
  305. ->withHeaders([
  306. 'Idempotency-Key' => $idempotencyKey,
  307. 'Content-Type' => 'application/json',
  308. 'Accept' => 'application/json',
  309. ]);
  310. }
  311. }