I'm trying to have my app record successful charges from Stripe via Webhook. This is based on Chris Oliver's GoRails discussion on Stripe Webhooks. I'm using the Koudoku gem to establish the Stripe functionality. I'm running into an error when I try to load the JSON object into the Charges tables.
Here's the error that occurs when I try to record an event:
RecordCharges.new.call(event)
Subscription Load (0.3ms) SELECT "subscriptions".* FROM "subscriptions" WHERE "subscriptions"."stripe_id" = ? LIMIT 1 [["stripe_id", "cus_withheldforexample"]]
NoMethodError: undefined method `charges' for nil:NilClass
In my app, Users have one Subscriptions. Subscriptions have many Charges. Charges belong to Subscriptions.
Here's the schema:
create_table "charges", force: :cascade do |t|
t.string "stripe_id"
t.string "amount"
t.string "card_last4"
t.string "card_type"
t.string "card_exp_month"
t.string "card_exp_year"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "subscription_id"
end
create_table "subscriptions", force: :cascade do |t|
t.string "stripe_id"
t.integer "plan_id"
t.string "last_four"
t.integer "coupon_id"
t.string "card_type"
t.float "current_price"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
My Stripe.rb file
class RecordCharges
def call(event)
charge = event.data.object
subscription = Subscription.find_by(stripe_id: charge.customer)
subscription.charges.create(
stripe_id: charge.id,
amount: charge.amount,
card_last4: charge.source.last4,
card_type: charge.source.brand,
card_exp_month: charge.source.exp_month,
card_exp_year: charge.source.exp_year
)
end
end
StripeEvent.configure do |events|
events.subscribe 'charge.succeeded', RecordCharges.new
end
Any suggestions? Thanks!
Subscription.find_by(stripe_id: charge.customer)
is coming back nil. Either your charge
doesn't have a customer
and/or you don't have a Subscription
by that stripe_id
.
If you do a find_by!
your app will raise an appropriate error and if your app is set up correctly it will 404 in production.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.