问题描述:

I want to send a customer and card token to stripe and retrieve the card or create a new card on the customer if it doesn't already exist.

Now instead I have to retrieve all cards, check if the card token I have matches any and then send a charge with that card.

Is there a "customer.retrieve_or_create(card_token)"? Or some better solution?

网友答案:

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.

more details about this on: Can I check whether stripe a card is already existed before going to create new one?

相关阅读:
Top