PagarmeCardService.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace App\Services\Pagarme;
  3. use App\Data\Pagarme\Card\CardRequestData;
  4. use App\Data\Pagarme\Card\CardResponseData;
  5. use App\Data\Pagarme\Card\Parts\Request\BillingAddressData;
  6. use App\Models\Address;
  7. use App\Models\ClientPaymentMethod;
  8. use App\Services\Pagarme\Concerns\MocksPagarmeRequests;
  9. use App\Services\Pagarme\Concerns\SendsPagarmeRequests;
  10. class PagarmeCardService
  11. {
  12. use MocksPagarmeRequests;
  13. use SendsPagarmeRequests;
  14. public function __construct(
  15. private readonly PagarmeCustomerService $pagarmeCustomerService,
  16. ) {}
  17. public function createCardForPaymentMethod(ClientPaymentMethod $paymentMethod): ?string
  18. {
  19. if (! empty($paymentMethod->gateway_card_id)) {
  20. return $paymentMethod->gateway_card_id;
  21. }
  22. $paymentMethod->loadMissing('client.user');
  23. $customerId = $this->pagarmeCustomerService->createCustomerForClient(
  24. $paymentMethod->client,
  25. []
  26. );
  27. if ($this->shouldMockPagarmeRequest()) {
  28. $cardId = $this->mockPagarmeId('card', $paymentMethod->id);
  29. $paymentMethod->forceFill([
  30. 'gateway_card_id' => $cardId,
  31. 'brand' => $paymentMethod->brand ?: 'visa',
  32. 'last_four_digits' => $paymentMethod->last_four_digits ?: '1111',
  33. ])->save();
  34. return $cardId;
  35. }
  36. $cardData = CardResponseData::fromArray($this->pagarmeRequest(
  37. method: 'POST',
  38. path: "/customers/{$customerId}/cards",
  39. payload: new CardRequestData(
  40. token: $paymentMethod->token,
  41. label: $paymentMethod->card_name,
  42. billingAddress: BillingAddressData::fromAddress(
  43. Address::query()
  44. ->with(['city.state', 'state'])
  45. ->where('source', 'client')
  46. ->where('source_id', $paymentMethod->client_id)
  47. ->orderByDesc('is_primary')
  48. ->latest('id')
  49. ->first()
  50. ),
  51. ),
  52. idempotencyKey: $this->idempotencyKey($paymentMethod),
  53. errorMessage: 'Erro ao salvar cartao no Pagar.me.',
  54. ));
  55. $cardId = $cardData->requireId();
  56. $paymentMethod->forceFill([
  57. 'gateway_card_id' => $cardId,
  58. 'brand' => $paymentMethod->brand ?: $cardData->brand,
  59. 'last_four_digits' => $paymentMethod->last_four_digits ?: $cardData->lastFourDigits,
  60. ])->save();
  61. return $cardId;
  62. }
  63. // evita criacao duplicada de cartao
  64. private function idempotencyKey(ClientPaymentMethod $paymentMethod): string
  65. {
  66. if (! empty($paymentMethod->idempotency_key)) {
  67. return $paymentMethod->idempotency_key;
  68. }
  69. $key = 'card-'.(string) \Illuminate\Support\Str::uuid();
  70. $paymentMethod->forceFill(['idempotency_key' => $key])->save();
  71. return $key;
  72. }
  73. }