PagarmeCardService.php 2.3 KB

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