3

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?

ajbraus
  • 2,909
  • 3
  • 31
  • 45
  • Your question is not clear, please try making it more understandable. – Tamer Shlash Nov 23 '13 at 22:31
  • It is like in rails find_or_create - I want to retrieve_or_create card on a customer by passing the customer token and a card token from stripe.js. – ajbraus Nov 26 '13 at 20:56
  • I'm sending in a new or old card token with an old customer id and I want Stripe to create a card on that customer if it is a new card and to charge that card if it is an old card. Instead I get this if the card is new: Stripe::InvalidRequestError: Customer cus_2zosVXrRwbgGXb does not have card with ID tok_31CJdo1nFfTc7T – ajbraus Nov 27 '13 at 15:10
  • @ajbraus did you get a solution to this. I am looking ofr something similar – Sahil Dhankhar Sep 27 '14 at 13:25
  • @ajbraus i was able to achieve that and added that as an answer, lmk if thats helpful – Sahil Dhankhar Sep 27 '14 at 14:22

1 Answers1

4

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?

Community
  • 1
  • 1
Sahil Dhankhar
  • 3,596
  • 2
  • 31
  • 44