0
votes

I'm implementing Stripe's custom payment form as described in the Stripe documentation (Stripe Documentation, Stripe Git Repository) and I have trouble setting the instance variable @userafter form submission.

Controller

def payment
  @user = User.find(session[:user_id])
  if params[:stripeToken] != nil
    @token = params[:stripeToken]
    if @user.update(:stripe_pmt_token => @token)
      create_stripe_customer
      redirect_to confirm_path
    else
      render 'payment'
    end  
  end  
end

def create_stripe_customer
  Stripe.api_key = "<TOKEN>"   
  #Create a Customer
  @customer = Stripe::Customer.create(
    :source => @user[:stripe_pmt_token],
    :description => "#{@user.first_name}"
  )
  @user.update(:stripe_customer_id => @customer.id)
end 

Routes

 get 'payment' => 'checkout#payment'
 post 'payment' => 'checkout#payment'

Server Logs

Started POST "/payment" for 69.23.75.159 at 2016-03-31 11:49:01 +0000
Processing by CheckoutController#payment as HTML
Parameters: {"stripeToken"=>"tok_17v<TOKEN>"}
Can't verify CSRF token authenticity
User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id"       = ? LIMIT 1  [["id", nil]]
Completed 404 Not Found in 2ms (ActiveRecord: 0.2ms)

ActiveRecord::RecordNotFound (Couldn't find User with 'id'=):
app/controllers/checkout_controller.rb:5:in `payment'

When the payment page loads for the first time the instance variable @user = User.find(session[:user_id])gets set correctly. However, when the payment form is submitted and the code of def paymentexecutes the second time the instance variable is not set correctly.

Error message: ActiveRecord::RecordNotFound and Couldn't find User with 'id'=

Somehow rails cannot retrieve the [:user_id] value from the session, even though it is set and I am able to display it on the payment page with <%= session[:user_id] %>. Please let me know why this is the case and what I need to change. Thanks!

1
Could you post the errors from the development log please. Out of interest are you using the payment method as both a GET and POST? - Robin Fisher
Hi Robin, I updated the original post with the routes and server log data. The data shows that the Stripe token is received successfully, but the @user variable is not set. I need to associate the token to an existing user and the send that token back to Stripe to create a customer in Stripe. - mr. jman

1 Answers

0
votes

This issue seems to be unrelated to Stripe but to User.find(session[:user_id]) where the session[:user_id] is empty.

How do you handle user authentication and session? You can look using the Devise gem for that.

Also, using User.find means that you need to handle the exception ActiveRecord::RecordNotFound somewhere (preferably universal) in your application. Otherwise, using User.find_by and checking if the result returns nil is an alternative.