Using Rails 7, mail_form gem for Contact Us form and SendGrid. Mail sent successfully yet not receiving mail. in inbox - sendgrid

Using rails 7, mail_form gem for 'contact us' page and sendGrid.
When I using Gmail settings for sending mail, it works and I get the 'contact us' form in my inbox but when I use sendGrid settings, it says the emails get sent but I don't see them in my inbox/junk/spam etc... folders.
I am currently using Devise for Users and either gmail settings or sendGrid settings work to send devise emails. I set my email address as 'primary sender' through sendGrid settings which is why I am successfully receiving Devise emails. I can't figure out 'contact us' form is being successfully sent via both gmail and sendGrid yet not receiving them in my inbox. I receive Devise emails fine.
Any ideas?
development.rb
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
# config.action_mailer.smtp_settings = {
# :address => 'smtp.gmail.com',
# :port => 587,
# :user_name => 'ramona.kim#gmail.com',
# :password => Rails.application.credentials.gmail_password,
# :authentication => 'plain',
# :enable_starttls_auto => true
# }
ActionMailer::Base.smtp_settings = {
:user_name => 'apikey', # This is the string literal 'apikey', NOT the ID of your API key
:password => Rails.application.credentials.sendgrid_secret_api, # This is the secret sendgrid API key which was issued during API key creation
:domain => Rails.application.credentials.domain,
:address => 'smtp.sendgrid.net',
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true
}
home_controller.rb
class HomeController < ApplicationController
# Landing page
def contact
#contact = Contact.new
end
def create_contact_message
#contact = Contact.new(params[:contact])
#contact.request = request
if #contact.deliver
flash[:success] = 'Message sent!'
redirect_to action: :contact
else
flash[:error] = 'Could not send message'
render :contact
end
end
end
models/contact.rb
class Contact < MailForm::Base
attribute :name, validate: true
attribute :email, validate: /\A([\w\.%\+\-]+)#([\w\-]+\.)+([\w]{2,})\z/i
attribute :subject, validate: true
attribute :message, validate: true
attribute :nickname, captcha: true
# Declare the e-mail headers. It accepts anything the mail method
# in ActionMailer accepts.
def headers
{
:subject => "Contact Form Inquiry",
:to => "ramonakim#hotmail.com",
:from => "ramonakim#hotmail.com" # <~ Primary send on sendGrid
}
end
end
contact.html.erb
<!-- Start Contact Form -->
<div class="col-lg-8 ">
<h3 class="text-center">Send a message</h3>
<%= simple_form_for(#contact, method: :post, url: create_contact_message_path, defaults: { input_html: { class: 'contact-form row' } }) do |f| %>
<div class="col-lg-12 mb-4">
<div class="form-floating">
<%= f.input_field :name, class: 'form-control form-control-lg light-300', placeholder: 'Name' %>
<label for="floatingname light-300">Name</label>
</div>
</div><!-- End Input Name -->
<div class="col-lg-12 mb-4">
<div class="form-floating">
<%= f.input_field :email, class: 'form-control form-control-log light-300', placeholder: 'Email' %>
<label for="floatingemail light-300">Email</label>
</div>
</div><!-- End Input Email -->
<div class="col-12">
<div class="form-floating mb-4">
<%= f.input_field :subject, class: 'form-control form-control-lg light-300', placeholder: 'Subject' %>
<label for="floatingsubject light-300">Subject</label>
</div>
</div><!-- End Input Subject -->
<div class="col-12">
<div class="form-floating mb-3">
<%= f.input_field :message, as: :text, class: 'form-control light-300', rows: '8', placeholder: 'Message', style: 'height: 200px' %>
<label for="floatingtextarea light-300">Message</label>
</div>
</div><!-- End Textarea Message -->
<div class="d-none">
<%= f.input :nickname %>
</div>
<div class="col-md-12 col-12 m-auto text-end">
<button type="submit" class="btn btn-secondary rounded-pill px-md-5 px-4 py-2 radius-0 text-light light-300">Send Message</button>
</div>
<% end %>
</div>
<!-- End Contact Form -->
console output after filling out contact form and submitting
14:59:10 web.1 | Started POST "/create_contact_message" for ::1 at 2022-06-09 14:59:10 -0700
14:59:10 web.1 | ActiveRecord::SchemaMigration Pluck (0.9ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
14:59:10 web.1 | Processing by HomeController#create_contact_message as HTML
14:59:10 web.1 | Parameters: {"authenticity_token"=>"[FILTERED]", "contact"=>{"name"=>"Some dude", "email"=>"somedude#example.com", "subject"=>"Hello", "message"=>"message here. blah.", "nickname"=>""}}
14:59:10 web.1 | Rendering /home/ramona/.rbenv/versions/3.0.0/lib/ruby/gems/3.0.0/gems/mail_form-1.9.0/lib/mail_form/views/mail_form/contact.erb
14:59:10 web.1 | Rendered /home/ramona/.rbenv/versions/3.0.0/lib/ruby/gems/3.0.0/gems/mail_form-1.9.0/lib/mail_form/views/mail_form/contact.erb (Duration: 2.7ms | Allocations: 1181)
14:59:10 web.1 | MailForm::Notifier#contact: processed outbound mail in 8.8ms
14:59:11 web.1 | Delivered mail 62a26d2e8148c_59d4378b4677d2#rk-7480.mail (1300.2ms)
14:59:11 web.1 | Date: Thu, 09 Jun 2022 14:59:10 -0700
14:59:11 web.1 | From: ramonakim#hotmail.com
14:59:11 web.1 | To: ramonakim#hotmail.com
14:59:11 web.1 | Message-ID: <62a26d2e8148c_59d4378b4677d2#rk-7480.mail>
14:59:11 web.1 | Subject: Contact Form Inquiry
14:59:11 web.1 | Mime-Version: 1.0
14:59:11 web.1 | Content-Type: text/html;
14:59:11 web.1 | charset=UTF-8
14:59:11 web.1 | Content-Transfer-Encoding: 7bit
14:59:11 web.1 |
14:59:11 web.1 | <h4 style="text-decoration:underline">Contact Form Inquiry</h4>
14:59:11 web.1 |
14:59:11 web.1 |
14:59:11 web.1 | <p><b>Name:</b>
14:59:11 web.1 | Some dude</p>
14:59:11 web.1 |
14:59:11 web.1 | <p><b>Email:</b>
14:59:11 web.1 | somedude#example.com</p>
14:59:11 web.1 |
14:59:11 web.1 | <p><b>Subject:</b>
14:59:11 web.1 | Hello</p>
14:59:11 web.1 |
14:59:11 web.1 | <p><b>Message:</b>
14:59:11 web.1 | message here. blah.</p>
14:59:11 web.1 |
14:59:11 web.1 |
14:59:11 web.1 | Redirected to http://localhost:3000/contact
14:59:11 web.1 | Completed 302 Found in 1339ms (ActiveRecord: 0.0ms | Allocations: 10384)
14:59:11 web.1 |
14:59:11 web.1 |
14:59:11 web.1 | Started GET "/contact" for ::1 at 2022-06-09 14:59:11 -0700
14:59:11 web.1 | Processing by HomeController#contact as HTML
14:59:11 web.1 | Rendering layout layouts/application.html.erb
14:59:11 web.1 | Rendering home/contact.html.erb within layouts/application
14:59:11 web.1 | Rendered home/contact.html.erb within layouts/application (Duration: 28.0ms | Allocations: 10826)
14:59:12 web.1 | Rendered layouts/_navbar.html.erb (Duration: 1.2ms | Allocations: 370)
14:59:12 web.1 | Rendered layouts/_flash.html.erb (Duration: 0.9ms | Allocations: 201)
14:59:12 web.1 | Rendered layouts/_footer.html.erb (Duration: 5.7ms | Allocations: 2302)
14:59:12 web.1 | Rendered layout layouts/application.html.erb (Duration: 125.8ms | Allocations: 39002)
14:59:12 web.1 | Completed 200 OK in 132ms (Views: 129.7ms | ActiveRecord: 0.0ms | Allocations: 40513)
14:59:12 web.1 |
14:59:12 web.1 |

Related

Rails 4 ActionMailer Create and send email from form

I am new to actionmailer and can't seem to get ActionMailer to work and route properly, not sure if I'm doing it properly and most tutorials only show how to generate a generic email after a user has first created an account.
What I am trying to do is allow a user to generate an email through a form to send an email message with a link to a view to their clients to view an invoice.
My current error is due to some routing issues but the strange thing was that it's looking for an email template in my controller instead of the mailer controller is my assumption... Missing template invoices/send_invoice_email, application/send_invoice_email
Here is my form which the user would use to build the email.
<%= bootstrap_form_tag url: '/send_invoice' do |l| %>
<%= l.hidden_field :invoice, value: #quote.id %>
<div class="input-group margin-bottom-20">
<span class="input-group-addon" id="from"><i class="fa fa-envelope"> </i></span>
<%= l.text_field :from, hide_label: true, value: current_user.email %>
</div>
<div class="input-group margin-bottom-20">
<span class="input-group-addon" id="to"><i class="fa fa-user"> </i></span>
<%= l.text_field :to, hide_label: true, value: #quote.client.contacts.first.email %>
</div>
<div class="input-group margin-bottom-20">
<span class="input-group-addon" id="cc"><i class="fa fa-users"> </i></span>
<%= l.text_field :cc, hide_label: true, placeholder: "cc:" %>
</div>
<div class="input-group margin-bottom-20">
<span class="input-group-addon" id="bcc"><i class="fa fa-users"> </i></span>
<%= l.text_field :bcc, hide_label: true, placeholder: "bcc:" %>
</div>
<div class="input-group margin-bottom-20">
<span class="input-group-addon" id="subject"> <i class="fa fa-bullhorn"></i></span>
<%= l.text_field :subject, hide_label: true, placeholder: "Subject" %>
</div>
<div class="input-group margin-bottom-20">
<span class="input-group-addon" id="message"> <i class="fa fa-comment"></i></span>
<%= l.text_area :message, hide_label: true, placeholder: "Message", rows:"5" %>
</div>
<%= l.submit "Send", class:'btn-u btn-u-blue btn-block' %>
<% end %>
My controller method in my invoice controller (this is only a show controller, Quote is created in quote model)
def send_invoice_email
quote = Quote.find(params[:invoice])
InvoiceMailer.send_invoice_email(quote, params)
end
And here is the method in my invoice mailer
def send_invoice_email(quote, params)
#quote = quote
mail(
to: current_user.email,
from: params[:from],
content_type: "text/html",
body: params[:body],
content_type: "text/html",
subject: params[:subject],
content_type: "text/html"
)
end
I changed a few things and now it seems to be working... Not sure why but I'll take it. Here are my current configurations..
Form is the same.
In my invoice controller I now have
def send_invoice_email
quote = Quote.find(params[:invoice])
InvoiceMailer.invoice_email(quote, params).deliver_now
end
In my invoice mailer I now have
def invoice_email(quote, params)
#user = quote.user
#quote = quote
#message = params[:body]
mail to: params[:to],
from: #user.email,
body: #message,
subject: params[:subject],
content_type: "text/html"
end

Updating User password & email in separate forms but in same view

My goal is to create a profile page where the (logged in) user can choose to either update their email or their password (in separate forms so not both at the same time) without navigating away from the page.
Updating one's email is as simple as entering their new email and hitting the "Save Changes" submit button.
Updating one's password requires the user to enter their old password, their new password, and a confirmation of their new password then hitting the "Update Password" button. The problem must be in the update_pwd method.
users_controller.rb
# ...
def edit # template: edit.html.erb
#user = User.find(current_user)
end
def update_email
#user = User.find(current_user)
if params[:commit] == 'Save Changes'
if #user.update_attributes(user_params_email)
redirect_to me_url
flash[:notice] = "Your changes have been saved"
else # either invalid or taken
render :edit
end
else
render :edit
end
end
def update_pwd
#user = User.find(current_user)
if params[:commit] == 'Update Password'
if #user.update_attributes(user_params_pwd) && User.find_by(username: current_user.username).try(:authenticate, params[:current_password])
redirect_to me_url
flash[:notice] = "Password updated!"
else
flash.now[:alert] = #user.errors.full_messages[0]
render :edit
end
else
render :edit
end
end
private
#def user_params
#params.require(:user).permit(:id, :username, :email, :password, :password_confirmation)
#end
def user_params_email
params.require(:user).permit(:email)
end
def user_params_pwd
params.require(:user).permit(:password, :password_confirmation, :current_password)
end
edit.html.erb
<%= form_for(current_user, :url => {:controller => 'users', :action => 'update_email'}) do |f| %>
<% if #user.errors.any? %>
<% for message in #user.errors.full_messages %>
<li><%= message %></li>
<% end %>
<% end %>
<p> Current Email: <%= current_user.email %> </p>
<p> New Email: <%= f.text_field :email %> </p>
<%= f.submit "Save Changes" %>
<% end %>
<%= form_for(current_user, :url => {:controller => 'users', :action => 'update_pwd'}) do |g| %>
<p>Old Password<br>
<%= password_field_tag :current_password, params[:password] %></p>
<p>New Password<br>
<%= g.password_field :password %></p>
<p>Confirm New Password<br>
<%= g.password_field :password_confirmation %></p>
<%= g.submit "Update Password" %>
<% end %>
routes.rb
# ...
get '/me' => 'users#edit'
patch '/me' => 'users#update_email'
patch '/me' => 'users#update_pwd'
# ...
Now, I've been able to get the email updating to work as desired (with the necessary error messages/validations and so forth) but whenever the update password button is clicked, the view is rendered but nothing happens. Instead, it seems as if the update_email function is being called:
Started PATCH "/me" for ::1 at 2015-05-20 10:34:31 -0500
Processing by UsersController#update_email as HTML
Parameters: {"utf8"=>"V", "authenticity_token"=>"msEsj6yxfdrbXjjdm6cH3JamrFU8R1EoZ5asmE831GSxLwpiiIW/wmGrr9HiQxFDySJtW5MKK6Ezq9hZaMNFtA==", "current_password"=>"[FILTERED]", "user"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Update Password"}
←[1m←[36mUser Load (0.0ms)←[0m ←[1mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1←[0m [["id", 2]]
DEPRECATION WARNING: You are passing an instance of ActiveRecord::Base to `find`. Please pass the id of the object by calling `.id`. (called from update_email ...)
user.rb
# ...
has_secure_password
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }
validates_uniqueness_of :email
validates :password, length:{ minimum: 8 }, on: :create
validates :password_confirmation, presence: true, on: :create
# ...
application_controller.rb
# ...
helper_method :current_user
private
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
rescue ActiveRecord::RecordNotFound
end
Error log (as seen above)
Started PATCH "/me" for ::1 at 2015-05-20 10:34:31 -0500
Processing by UsersController#update_email as HTML
Parameters: {"utf8"=>"V", "authenticity_token"=>"msEsj6yxfdrbXjjdm6cH3JamrFU8R1EoZ5asmE831GSxLwpiiIW/wmGrr9HiQxFDySJtW5MKK6Ezq9hZaMNFtA==", "current_password"=>"[FILTERED]", "user"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Update Password"}
←[1m←[36mUser Load (0.0ms)←[0m ←[1mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1←[0m [["id", 2]]
DEPRECATION WARNING: You are passing an instance of ActiveRecord::Base to `find`. Please pass the id of the object by calling `.id`. (called from update_email ...)
You can try the following, I think this will help.
Please revert back if you face any issue.
routes.rb
get '/me' => 'users#edit'
patch '/me' => 'users#update_data'
edit.html.erb
<%= form_for(current_user, :url => {:controller => 'users', :action => 'update_data'}) do |f| %>
<% if #user.errors.any? %>
<% for message in #user.errors.full_messages %>
<li><%= message %></li>
<% end %>
<% end %>
<p> Current Email: <%= current_user.email %> </p>
<p> New Email: <%= f.text_field :email %> </p>
<%= f.submit 'Save Changes', name: 'update_email' %>
<% end %>
<%= form_for(current_user, :url => {:controller => 'users', :action => 'update_data'}) do |g| %>
<p>Old Password<br>
<%= password_field_tag :current_password, params[:password] %></p>
<p>New Password<br>
<%= g.password_field :password %></p>
<p>Confirm New Password<br>
<%= g.password_field :password_confirmation %></p>
<%= g.submit 'Update Password', name: 'update_password' %>
<% end %>
users_controller.rb
def edit
#user = User.find(current_user)
end
def update_data
#user = User.find(current_user)
if params[:commit] == "update_email"
if #user.update_attributes(user_params_email)
flash[:notice] = "Your changes have been saved"
redirect_to me_url
else
render :edit
end
elsif params[:commit] == "update_password"
if #user.update_attributes(user_params_pwd) && User.find_by(username: current_user.username).try(:authenticate, params[:current_password])
flash[:notice] = "Password updated!"
redirect_to me_url
else
flash.now[:alert] = #user.errors.full_messages[0]
render :edit
end
else
render :edit
end
end
private
def user_params_email
params.require(:user).permit(:email)
end
def user_params_pwd
params.require(:user).permit(:password, :password_confirmation, :current_password)
end

Hartl Rails Tutorial: Flash rendering message and hash

This is from Railstutorial.org, starting in chapter 7.
I've been banging my head on this one, so if its a simple typo I apologize.
I'm trying to get just the flash message to render, but for some reason I'm seeing the flash and also the hash that produces it showing up on my page. Here's my code (relevant code is lines 12-15).
1 <!DOCTYPE html>$
2 <html>$
3 <head>$
4 <title><%= full_title(yield(:title)) %></title>$
5 <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>$
6 <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>$
7 <%= csrf_meta_tags %>$
8 <%= render 'layouts/shim' %>$
9 </head>$
10 <body>$
11 <%= render 'layouts/header' %>$
12 <div class="container">$
13 <%= flash.each do |message_type, message| %>$
14 <%= content_tag(:div, message, class: "alert alert-#{message_type}") %> $
15 <% end %>$
16 <%= yield %>$
17 <%= render 'layouts/footer' %>$
18 <%= debug(params) if Rails.env.development? %>$
19 </div>$
20 </body>$
21 </html>$
Figured this out... <%= flash.each do |message_type, message| %> is rendering visibly. Took out the '=' above and it fixed things.

Ruby on Rails Tutorial (Book) Chapter 7 (3rd Edition) - No route matches [POST] "/signup"

I'm getting an 'No route matches [POST] "/signup"' error when in Chapter 7, I try to submit the signup form.
These are my routes:
root_path GET / static_pages#home
help_path GET /help(.:format) static_pages#help
about_path GET /about(.:format) static_pages#about
contact_path GET /contact(.:format) static_pages#contact
signup_path GET /signup(.:format) users#new
login_path GET /login(.:format) sessions#new
logout_path GET /logout(.:format) sessions#destroy
users_path GET /users(.:format) users#index
POST /users(.:format) users#create
new_user_path GET /users/new(.:format) users#new
edit_user_path GET /users/:id/edit(.:format) users#edit
user_path GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
sessions_path POST /sessions(.:format) sessions#create
new_session_path GET /sessions/new(.:format) sessions#new
session_path DELETE /sessions/:id(.:format) sessions#destroy
This is my Users controller:
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
flash[:success] = "Welcome to the Sample App!"
redirect_to users_path(#user)
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end
And this is the view where the signup gets posted from:
<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for #user do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :email %>
<%= f.text_field :email, class: 'form-control' %>
<%= f.label :password %>
<%= f.password_field :password, class: 'form-control' %>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation, class: 'form-control' %>
<%= f.submit "Create my account", class: "btn btn-primary" %>
<% end %>
</div>
</div>
Here is my routes file:
Rails.application.routes.draw do
root 'static_pages#home'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
get 'logout' => 'sessions#destroy'
resources :users
resources :sessions, only: [:new, :create, :destroy]
end
Place your resources at the top of the routes.rb file, here is my routes.rb:
Rails.application.routes.draw do
resources :users
resources :sessions, only: [:new, :create, :destroy]
root 'static_pages#home'
match '/signup' , to: 'users#new' , via: 'get'
match '/login' , to: 'sessions#new' , via: 'get'
match '/logout' , to: 'sessions#destroy' , via: 'delete'
match '/help' , to: 'static_pages#help' , via: 'get'
match '/about' , to: 'static_pages#about' , via: 'get'
match '/contact' , to: 'static_pages#contact', via: 'get'
end
Instead of:
Rails.application.routes.draw do
root 'static_pages#home'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
get 'logout' => 'sessions#destroy'
resources :users
resources :sessions, only: [:new, :create, :destroy]
end
Chapter 7 doesn't have any references to sessions.
That happens in Chapter 8.
This is how the routes look like at the end of Chapter 7.
Rails.application.routes.draw do
root 'static_pages#home'
get 'about' => 'static_pages#about'
get 'help' => 'static_pages#help'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
resources :users
end

What is wrong with my coffeescript in Stripe?

I've been working on integrating Stripe into my web application, and it doesn't seem to be working. To help me along, I've been using Ryan Bates's Rails Cast on integrating Stripe. Whenever I try to run the payment form, I get an error saying that "There was a problem with my credit card". I think the problem lies in my coffeescript file, but perhaps I'm wrong. I've included the stripe user token as a part of my user model instead of placing it into its own subscription model. Here is the coffeescript code I have:
jQuery ->
Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))
subscription.setupForm()
user =
setupForm: ->
$('#new_user').submit ->
$('input[type=submit]').attr('disabled', true)
if $('#card_number').length
user.processCard()
false
else
true
processCard: ->
card =
number: $('#card_number').val()
cvc: $('#card_code').val()
expMonth: $('#card_month').val()
expYear: $('#card_year').val()
Stripe.createToken(card, user.handleStripeResponse)
handleStripeResponse: (status, response) ->
if status == 500
$('#user_stripe_card_token').val(response.id)
$('#new_user')[0].submit()
else
$('#stripe_error').text(response.error.message)
$('input[type=submit]').attr('disabled', false)
I'm a beginner when it comes to programming, so any help you can give me would be great.
Here's the error I get in my terminal when I try to sign up:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Xas+iA+a3op7jUi57qTr7XWQSClPscA7fR19rkclkEE=", "user"=>{"stripe_card_token"=>"", "name"=>"Jack", "email"=>"email#example.com", "phone_number"=>"203-xxx-xxxx", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create my account"}
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('jjets718#yahoo.com') LIMIT 1
Stripe error while creating customer: Invalid token id:
My view for the signup is this:
<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(#user) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.hidden_field :stripe_card_token %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :phone_number, "Your cell phone number" %>
<%= f.text_field :phone_number %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation, "Password confirmation" %>
<%= f.password_field :password_confirmation %>
<%= label_tag :card_number, "Credit Card Number" %>
<%= text_field_tag :card_number, nil, name: nil %>
<%= label_tag :card_code, "Security Code on Card (CVV)" %>
<%= text_field_tag :card_code, nil, name: nil %>
<%= label_tag :card_month, "Card Expiration" %>
<%= select_month nil, {add_month_numbers: true}, {name: nil, id: "card_month"}%>
<%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"} %>
<%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
<div id="stripe_error">
<noscript>JavaScript is not enabled and is required for this form. First enable it in your web browser settings.</noscript>
</div>
My code for my controller is this for the create method:
def create
#user = User.new(params[:user])
if #user.save_with_payment
sign_in #user
flash[:success] = "Welcome to the Sample App!"
redirect_to edit_user_path(current_user)
UserMailer.welcome_email(#user).deliver
else
render 'new'
end
end
My code for the database migration for the user token is this:
class AddStripeToUsers < ActiveRecord::Migration
def change
add_column :users, :stripe_customer_token, :string
end
end
And the code for the save_with_payment method in my model is this:
def save_with_payment
if valid?
customer = Stripe::Customer.create(description: email, plan: 1, card: stripe_card_token)
self.stripe_customer_token = customer.id
save!
end
rescue Stripe::InvalidRequestError => e
logger.error "Stripe error while creating customer: #{e.message}"
errors.add :base, "There was a problem with your credit card."
false
end
2 things that come to mind:
You should be doing a status check for 200, not 500
You may need to require the coffeescript file in your application.js
e.g. //= require users
I could be wrong, but at this point:
handleStripeResponse: (status, response) ->
if status == 500
$('#user_stripe_card_token').val(response.id)
In addition to changing if status == 500 to if status == 200, this line $('#user_stripe_card_token').val(response.id) may need to be $('#new_user_stripe_card_token').val(response.id). Make sure to check the input ID.