PagarmePaymentService.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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, array $items, array $customer, array $paymentMethod, array $options = []
  56. ): array {
  57. if (empty($items)) {
  58. throw new \InvalidArgumentException('items nao pode estar vazio.');
  59. }
  60. if (empty($paymentMethod['payment_method'])) {
  61. throw new \InvalidArgumentException('payment_method e obrigatorio.');
  62. }
  63. $payload = [
  64. 'code' => $options['order_code'] ?? "payment-{$payment->id}",
  65. 'items' => $items,
  66. 'customer' => $customer,
  67. 'payments' => [$paymentMethod],
  68. 'closed' => $options['closed'] ?? true,
  69. 'metadata' => array_merge([
  70. 'payment_id' => (string) $payment->id,
  71. 'schedule_id' => (string) $payment->schedule_id,
  72. 'client_id' => (string) $payment->client_id,
  73. 'provider_id' => (string) $payment->provider_id,
  74. ], $options['metadata'] ?? []),
  75. ];
  76. if (! empty($options['channel'])) {
  77. $payload['channel'] = $options['channel'];
  78. }
  79. $response = $this->pagarmeRequest($this->idempotencyKey($payment))
  80. ->post($this->pagarmeUrl('/orders'), $payload);
  81. if ($response->failed()) {
  82. Log::channel('pagarme')->error('Pagar.me order creation failed', [
  83. 'status' => $response->status(),
  84. 'body' => $response->json() ?? $response->body(),
  85. 'payload' => $payload,
  86. ]);
  87. throw new \RuntimeException('Erro ao criar pedido de pagamento no Pagar.me.');
  88. }
  89. $order = $response->json();
  90. if (empty($order['id'])) {
  91. Log::channel('pagarme')->error('Pagar.me order creation returned empty id', [
  92. 'payment_id' => $payment->id,
  93. 'response' => $order,
  94. ]);
  95. throw new \RuntimeException('Pagar.me order creation returned an empty id.');
  96. }
  97. return $order;
  98. }
  99. public function applyGatewayResponseToPayment(Payment $payment, array $orderResponse): Payment
  100. {
  101. $charge = $orderResponse['charges'][0] ?? [];
  102. $transaction = $charge['last_transaction'] ?? [];
  103. $chargeStatus = $charge['status'] ?? null;
  104. $transactionStatus = $transaction['status'] ?? null;
  105. $payment->forceFill([
  106. 'gateway_provider' => 'pagarme',
  107. 'gateway_entity_reference' => $charge['id'] ?? $orderResponse['id'] ?? null,
  108. 'gateway_entity_label' => isset($charge['id']) ? 'charge' : 'order',
  109. 'gateway_operation_reference' => $transaction['id'] ?? $charge['id'] ?? $orderResponse['id'] ?? null,
  110. 'gateway_operation_label' => isset($transaction['id']) ? 'transaction' : (isset($charge['id']) ? 'charge' : 'order'),
  111. 'status' => $this->mapPaymentStatus($chargeStatus, $transactionStatus),
  112. 'paid_at' => $charge['paid_at'] ?? null,
  113. 'authorized_at' => $this->resolveAuthorizedAt($transactionStatus, $transaction),
  114. 'gateway_payload' => $orderResponse,
  115. 'failure_code' => $this->extractFailureCode($transaction),
  116. 'failure_message' => $this->extractFailureMessage($transaction),
  117. ])->save();
  118. return $payment->fresh();
  119. }
  120. /**
  121. * @param Collection<int, PaymentTransfer> $transfers
  122. * @return array<int, array<string, mixed>>
  123. */
  124. public function buildSplitFromTransfers(Collection $transfers): array
  125. {
  126. return $transfers
  127. ->filter(fn (PaymentTransfer $transfer) => ! empty($transfer->gateway_transfer_target_reference))
  128. ->map(function (PaymentTransfer $transfer) {
  129. return [
  130. 'amount' => $this->toGatewayAmountInCents((float) $transfer->gross_amount),
  131. 'recipient_id' => $transfer->gateway_transfer_target_reference,
  132. 'type' => 'flat',
  133. ];
  134. })
  135. ->values()
  136. ->all();
  137. }
  138. public function toGatewayAmountInCents(float $amount): int
  139. {
  140. return (int) round($amount * 100);
  141. }
  142. //
  143. private function pagarmeUrl(string $path): string
  144. {
  145. return rtrim(config('services.pagarme.base_url'), '/').'/'.ltrim($path, '/');
  146. }
  147. private function idempotencyKey(Payment $payment): string
  148. {
  149. return "payment-{$payment->id}-schedule-{$payment->schedule_id}";
  150. }
  151. //
  152. private function buildCreditCardPayload(array $creditCard): array
  153. {
  154. $payload = [];
  155. foreach ([
  156. 'installments',
  157. 'statement_descriptor',
  158. 'operation_type',
  159. 'recurrence_cycle',
  160. 'metadata',
  161. 'extended_limit_enabled',
  162. 'extended_limit_code',
  163. 'merchant_category_code',
  164. 'authentication',
  165. 'auto_recovery',
  166. 'payload',
  167. 'payment_type',
  168. 'funding_source',
  169. 'initiated_type',
  170. 'recurrence_model',
  171. 'channel',
  172. 'payment_origin',
  173. ] as $field) {
  174. if (array_key_exists($field, $creditCard)) {
  175. $payload[$field] = $creditCard[$field];
  176. }
  177. }
  178. $allowedCardOptions = ['card', 'card_id', 'card_token', 'network_token'];
  179. $provided = array_values(array_filter(
  180. $allowedCardOptions,
  181. static fn (string $field) => ! empty($creditCard[$field])
  182. ));
  183. if (count($provided) !== 1) {
  184. throw new \InvalidArgumentException('Informe exatamente uma opcao entre card, card_id, card_token ou network_token.');
  185. }
  186. $selected = $provided[0];
  187. $payload[$selected] = $creditCard[$selected];
  188. return $payload;
  189. }
  190. private function buildPixPayload(array $pix): array
  191. {
  192. if (empty($pix['expires_in']) && empty($pix['expires_at'])) {
  193. throw new \InvalidArgumentException('pix.expires_in ou pix.expires_at e obrigatorio.');
  194. }
  195. $payload = [];
  196. foreach (['expires_in', 'expires_at', 'additional_information'] as $field) {
  197. if (array_key_exists($field, $pix)) {
  198. $payload[$field] = $pix[$field];
  199. }
  200. }
  201. return $payload;
  202. }
  203. //
  204. private function resolveAuthorizedAt(?string $transactionStatus, array $transaction): ?string
  205. {
  206. if (in_array($transactionStatus, ['authorized_pending_capture', 'captured', 'partial_capture'], true)) {
  207. return $transaction['created_at'] ?? now()->toISOString();
  208. }
  209. return null;
  210. }
  211. //
  212. private function extractFailureCode(array $transaction): ?string
  213. {
  214. return $transaction['gateway_response']['code'] ?? null;
  215. }
  216. private function extractFailureMessage(array $transaction): ?string
  217. {
  218. return $transaction['acquirer_message'] ?? null;
  219. }
  220. //
  221. private function mapPaymentStatus(?string $chargeStatus, ?string $transactionStatus): string
  222. {
  223. $status = strtolower((string) ($transactionStatus ?: $chargeStatus));
  224. return match ($status) {
  225. 'captured', 'paid' => 'paid',
  226. 'authorized_pending_capture', 'waiting_capture', 'pending' => 'authorized',
  227. 'processing' => 'processing',
  228. 'not_authorized', 'with_error', 'failed' => 'failed',
  229. 'voided', 'partial_void' => 'cancelled',
  230. default => 'pending',
  231. };
  232. }
  233. //
  234. private function pagarmeRequest(string $idempotencyKey)
  235. {
  236. $secretKey = config('services.pagarme.secret_key');
  237. if (empty($secretKey)) {
  238. Log::channel('pagarme')->error('PAGARME_SECRET_KEY is not configured.');
  239. throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
  240. }
  241. return Http::withBasicAuth($secretKey, '')
  242. ->withHeaders([
  243. 'Idempotency-Key' => $idempotencyKey,
  244. 'Content-Type' => 'application/json',
  245. 'Accept' => 'application/json',
  246. ]);
  247. }
  248. }