I have saved stripe customer id's in my db for later payments. A customer will have multiple cards and I would like to check/validate new customer cards with their existing cards.
Suppose the same card details can be stored multiple times as multiple cards.
I want to check using the Stripe token whether a newly entered card already exists or not. It will use it if it's already there, if not it will create a new card.
Unfortunately while working on Stripe today i noticed that it do allows storing of duplicate cards. To avoid this, i did following steps:
#fetch the customer
customer = Stripe::Customer.retrieve(stripe_customer_token)
#Retrieve the card fingerprint using the stripe_card_token
card_fingerprint = Stripe::Token.retrieve(stripe_card_token).try(:card).try(:fingerprint)
# check whether a card with that fingerprint already exists
default_card = customer.cards.all.data.select{|card| card.fingerprint == card_fingerprint}.last if card_fingerprint
#create new card if do not already exists
default_card = customer.cards.create({:card => stripe_card_token}) unless default_card
#set the default card of the customer to be this card, as this is the last card provided by User and probably he want this card to be used for further transactions
customer.default_card = default_card.id
# save the customer
customer.save
fingerprint of a card stored with stripe is always unique
If you want to make less calls to stripe, it is recommended that you store the fingerprints of all the cards locally and use them for checking uniqueness. Storing fingerprints of cards locally is secure and it uniquely identifies a card.