Linda Kadz
Linda Kadz

Reputation: 361

Problem saving data coming from Stripe Webhook Rails

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!

Upvotes: 0

Views: 241

Answers (1)

Linda Kadz
Linda Kadz

Reputation: 361

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

Upvotes: 1

Related Questions