0
votes

I want to get data(customer ID) from the Stripe webhook then save it to my db, I get the data but the problem is customer_id is still nil on my db. Here's my code

StripeEvent.configure do |events|
 events.all do |event|
if event.type == 'customer.created'
 customer = event.data.object
 user = User.where('customer_id LIKE ?', "%#{customer['id']}%").first
 if user
   customer = Stripe::Customer.retrieve(JSON.parse(user.customer_id)['id'])
   user.customer_id = customer.to_json
   user.save!
  end
 end
 end
end

This code :

user = User.where('customer_id LIKE ?', "%#{customer['id']}%").first

gives this output:

SELECT  "users".* FROM "users" WHERE (customer_id LIKE '%cus_EEIReNX3M4je2U%') ORDER BY "users"."id" ASC LIMIT

And when I get to my db, my customer_id field is still nil, here's the output:

<User id: 3, email: "[email protected]", created_at: "2018-12-27 03:47:41", updated_at: "2018-12-27 03:47:41", first_name: "Achie", last_name: nil, gender: nil, gender_preferences: nil, description: "trial stripe", photo: nil, provider: nil, uid: nil, name: nil, image: nil, customer_id: nil>

Can anyone please see something that I'm missing out on? I will really appreciate the help. Thanks!

1
the user object is nilNithin
I can't understand one thing: if it was an event of creating customer in Stripe why do you try to find user by customer_id - you don't have this data in DB, and how @Nithin noticed user always will be nil.kunashir
Kunashir, I am capturing the customer id from stripe and I want to save it on my db. I don't understand how my user object is nil, please explain more.Linda Kadz
@Nithin I don't understand how my user object is nil, please explain.Linda Kadz

1 Answers

1
votes

My code was all wrong, not all though. The user object was nil because I was trying to get a customer_id that was not yet available, so I got the user using email, then passed the stripe customer id to them then finally saved them. It worked!

StripeEvent.configure do |events|
 events.all do |event|
  if event.type == 'customer.created'
   customer = event.data.object
   user = User.find_by(email: customer.email)
   if user
    user.customer_id = customer.id
    user.save!
 end
end
end