Submit PayPal data encrypted from the code - ruby-on-rails-3

I'm working with Ruby On Rails 3, and I would like to do the following, but from the code behind:
<% form_tag "https://www.sandbox.paypal.com/cgi-bin/webscr" do %>
<%= hidden_field_tag :cmd, "_s-xclick" %>
<%= hidden_field_tag :encrypted, #cart.paypal_encrypted(products_url, payment_notifications_url) %>
<p><%= submit_tag "Checkout" %></p>
<% end %>
I've tried this in my Cart model, but it's not redirecting anywhere, and I don't know what to do:
PAYPAL_CERT_PEM = File.read("#{Rails.root}/certs/paypal_cert.pem")
APP_CERT_PEM = File.read("#{Rails.root}/certs/app_cert.pem")
APP_KEY_PEM = File.read("#{Rails.root}/certs/app_key.pem")
PANEL = 'sandbox.paypal.com'
PATH = '/cgi-bin/webscr'
USERAGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.1) Gecko/20060111 Firefox/1.5.0.1'
def paypal_url(order_id, return_url, notify_url)
http = Net::HTTP.new(PANEL, 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
# GET request -> so the host can set cookies
resp, data = http.get2(PATH, {'User-Agent' => USERAGENT})
cookie = resp.response['set-cookie'].split('; ')[0]
values = {
:cmd => '_s-xclick',
:encrypted => paypal_encrypted(order_id, return_url, notify_url)
}
#headers = {
'Cookie' => cookie,
'Referer' => 'https://'+PANEL+PATH,
'Content-Type' => 'application/x-www-form-urlencoded',
'User-Agent' => USERAGENT
}
resp, data = http.post2(PATH, values.to_query, #headers)
end
def paypal_encrypted(order_id, return_url, notify_url)
values = {
:business => 'seller_1234111143_biz#asciicasts.com',
:cmd => '_cart',
:upload => 1,
:return => return_url,
:invoice => order_id.to_s,
:notify_url => notify_url,
:currency_code => "USD"
}
items.each_with_index do |item, index|
values.merge!({
"amount_#{index + 1}" => item.unit_price,
"item_name_#{index + 1}" => item.product.title,
"item_number_#{index + 1}" => item.product.id + Time.now.to_i,
"quantity_#{index + 1}" => item.quantity.to_i
})
end
encrypt_for_paypal(values)
end
def encrypt_for_paypal(values)
signed = OpenSSL::PKCS7::sign(OpenSSL::X509::Certificate.new(APP_CERT_PEM), OpenSSL::PKey::RSA.new(APP_KEY_PEM, ''), values.map { |k, v| "#{k}=#{v}" }.join("\n"), [], OpenSSL::PKCS7::BINARY)
OpenSSL::PKCS7::encrypt([OpenSSL::X509::Certificate.new(PAYPAL_CERT_PEM)], signed.to_der, OpenSSL::Cipher::Cipher::new("DES3"), OpenSSL::PKCS7::BINARY).to_s.gsub("\n", "")
end
If you're wondering why I can't just use the html form, that's because I let users choose between more than one payment option, using radio fields, and once they have selected one, they will click on the "Submit Order" button, generating the respective movements in my database, before redirecting to the payment method.

Related

Sign up page/form in Rails 3 not considering all fields required/mandatory

My sign up page has login. email, password, password_confirm and company fields . All of them are supposed to be mandatory but when i click on sign up it is not checking if any fields except password and password_confirm are blank!! I dont understand what is the difference as in my app/models/user.rb file i have validates presence for all fields. Please help me
Here's code(required lines)
user.rb
class User < ActiveRecord::Base
has_many :excel_files # One user may have many excel files
has_one :user_access_validity# One user may have one license period
# Virtual attribute for the unencrypted password
attr_accessor :password
attr_accessible :login
attr_accessible :email
attr_accessible :password
attr_accessible :password_confirmation
attr_accessible :company
#changes of 'validates' in accordance with rails 3:
validates :login, :presence => true,
:length => { :within => 3..40},
:uniqueness => { :case_sensitive => false },
:format => { :with => /^([a-z_0-9\.]+)$/i },
:on => :create,
:if => :is_login_entered?
validates :email, :presence => true,
:length => { :within => 7..100},
:uniqueness => { :case_sensitive => false },
:format => {:with => /^([a-z]+((\.?)|(_?))[a-z0-9]+#(mindtree.com|rvce.edu.in))$/i},
:on => :create,
:if => :is_email_entered?
validates :company, :presence => true,
:format => { :with =>/(mindtree|RVCE)/i},
:format => { :with => /^([a-z]+)$/i },
:on => :create,
:if => :is_company_entered?
validates :password, :presence => true,
:length => { :within => 4..40 },
:confirmation => true,
:format => { :with => /^([a-z0-9#!#\$]+)$/i },
:on => :create,
:if => :password_required?
validates :password_confirmation, :presence => { :if => :password_required? }
before_save :encrypt_password
#
# is_email_entered? : checks whether the email field is entered or not
# #params : none
# #return : true - if the email is entered
# false - if the email is not entered
#
def is_email_entered?
!self.email.blank?
end
#
# is_company_entered? : checks whether the company field is entered or not
# #params : none
# #return : true - if the company is entered
# false - if the company is not entered
#
def is_company_entered?
!self.company.blank?
end
#
# is_login_entered? : checks whether the login field is entered or not
# #params : none
# #return : true - if the login is entered
# false - if the login is not entered
#
def is_login_entered?
!self.login.blank?
puts "login"
end
protected
#
# password_required? : Checks whether either of the crypted_password and password field is blank
# #params : none
# #return : true - if either of the crypted_password and password field is blank
# false - if either of the crypted_password and password field is not blank
#
def password_required?
crypted_password.blank? || !password.blank?
puts "in pr?"
end
end
controller.rb
def signup
if logged_in?
flash[:notice] = "<span class='error'>You have already registered with us!</span>".html_safe
redirect_to :action => 'upload_file'
else
#user = User.new(params[:user])
return unless request.post?
#user.save!
self.current_user = #user
random_number = #user.generate_random_number
puts random_number
new_random_number = "c" + #user.id.to_s + random_number
#user.customerid = new_random_number
#user.created_at = get_current_datetime
# #user.updated_time = ''
#user.save
# save user's maximum access days
user_validity = UserAccessValidity.new
user_validity.user_id = self.current_user.id
user_validity.maximum_access_in_days = 90
user_validity.save
# redirect_back_or_default(:controller => '/account', :action => 'welcome')
redirect_to :controller => '/account', :action => 'welcome'
flash[:notice] = "<span class='success'>Thanks for registering!</span>".html_safe
end
end
signup.html.erb
<font color=red>(Fields marked * are mandatory)</font><h3>Sign me up!</h3>
<br>
<span class='error'><%= error_messages_for (#user) %></span>
<%= form_for :user do |f| -%>
<span class='error'><%= flash[:msg] %></span>
<p><label for="login"><span class='redcolor'>*</span>Login</label><br/>
<%= f.text_field :login %></p>
<p><label for="email"><span class='redcolor'>*</span>Email</label><br/>
<%= f.text_field :email %></p>
<p><label for="password"><span class='redcolor'>*</span>Password</label><br/>
<%= f.password_field :password %></p>
<p><label for="password_confirmation"><span class='redcolor'>*</span>Confirm Password</label><br/>
<%= f.password_field :password_confirmation %></p>
<p><label for="company"><span class='redcolor'>*</span>Company</label><br/>
<%= f.text_field :company %></p>
<p><%= f.submit 'Sign up', :name=> 'sign_up' %></p>
<% end -%>
The problem is that you pass an if option to your validation which also applies to the presence validation. Take for example the following
validates :login,
:presence => true,
:length => { :within => 3..40},
:uniqueness => { :case_sensitive => false },
:format => { :with => /^([a-z_0-9\.]+)$/i },
:on => :create,
:if => :is_login_entered?
is_login_entered? is called when validating the presence of login which conflicts with the validation which is why the validation is skipped. Change your validation to
validates :login, :presence => true, :on => :create
validates :login,
:length => { :within => 3..40},
:uniqueness => { :case_sensitive => false },
:format => { :with => /^([a-z_0-9\.]+)$/i },
:on => :create,
:if => :is_login_entered?
This way, the other validations will only run if a login is present.

Rails 3 : In submit button :disable_with is not working

In this following code :disable_with is not working in rails 3. But it is perfectly working in rails 2.2
What is wrong in this code?
<%= submit_tag "Save", :class => "buttons",
:disable_with => "Processing",
:id => 'save_btn' %>
Since version 3.2.5 you should not use :disable_with.
<%= submit_tag "Save", 'data-disable-with' => "Processing", :class => "buttons", :id => 'save_btn' %>
or
<%= submit_tag "Save", data: { disable_with: "Processing" }, :class => "buttons", :id => 'save_btn' %>
Check the following in your raw html:
the submit button has data-disable-with attribute
your page includes jQuery js. For me I have:
https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
you page includes jquery_ujs js. For me I have:
/javascripts/jquery_ujs.js
You can read more on https://github.com/rails/jquery-ujs. Different installations for different rails versions.
I had a similar issue on Safari 8.0.6 and latest rails-ujs. Here's my approach of solving this issue:
%button{ class: 'btn btn-action js-submit', data: { method: :put, 'href' => '...', disable_with: "<i class='icon icon-spinner icon-spin'></i>".html_safe }} Submit
$('.js-select-plan').click(function(event) {
event.preventDefault();
var $target = $(this),
href = $target.data('href'),
method = $target.data('method'),
formTarget = $target.attr('target'),
csrfToken = $('meta[name=csrf-token]').attr('content'),
csrfParam = $('meta[name=csrf-param]').attr('content'),
form = $('<form method="post" action="' + href + '"></form>'),
metaData = '<input name="_method" value="' + method + '" type="hidden" />';
if (csrfParam !== undefined && csrfToken !== undefined) {
metaData += '<input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" />';
}
if (formTarget) {
form.attr('target', formTarget);
}
// disable button/link element
var contentMethod = $target.is('button') ? 'html' : 'val';
var replacement = $target.data('disable-with');
$target.data('ujs:enable-with', $target[contentMethod]());
if (replacement !== undefined) {
$target[contentMethod](replacement);
}
$target.prop('disabled', true);
form.hide().append(metaData).appendTo('body');
setTimeout(function(){
form.submit();
}, 50);
});
This works like a charm in all browsers. For better flexibility you might want to wrap this in a helper.

gmaps4rails having trouble rendering custom marker images

I have 4 types of markers on my map and I am loading an image for each point depending on it's "school type". This is working fine but I'm getting a weird artifact on the map that I don't get when using the standard marker image.
def map
#json = School.where(:disabled => [false, nil]).to_gmaps4rails do |school, marker|
marker.infowindow render_to_string(:partial => "schools/marker", :locals => { :object => school })
if school.school_type_id == 1
marker.picture({ "picture" => view_context.image_path('map_icons/blue_P.png'),"width" => '20',"height" => '34'})
elsif school.school_type_id == 2
marker.picture({ "picture" => view_context.image_path('map_icons/red_C.png'),"width" => '20',"height" => '34'})
elsif school.school_type_id == 3
marker.picture({ "picture" => view_context.image_path('map_icons/yellow_J.png'),"width" => '20',"height" => '34'})
elsif school.school_type_id == 4
marker.picture({ "picture" => view_context.image_path('map_icons/green_I.png'),"width" => '20',"height" => '34'})
end
marker.json({ :id => school.id })
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: #schools }
end
end
Images of the artifact:
http://foa-approved.org/map_artifact1.png
http://foa-approved.org/map_artifact2.png
I am using the css fix for the map controls:
.map_container img {
max-width: none;
}
Can this fix work on the marker image or it is something else entirely?

BancBox REST API POST createClient

I've spent the last day trying to get this to work in my Rails app, but continually get the response:
{"code"=>"E-C-343", "message"=>"Unrecognized JSON Request."}
BancBox's Documentation is pretty light, so I'm at a bit of an impasse on how to solve this.
Does anyone have an example of a successful API call to createClient at BancBox utilizing REST?
My Post API call utilizing HTTParty:
include HTTParty
format :json
def save_with_bancbox(params = {})
post_params = { :authentication => { :apiKey => BANCBOX_KEY,
:secret => BANCBOX_SECRET
},
:subscriberId => BANCBOX_ID,
:firstName => params[:first_name],
:lastName => params[:last_name],
:ssn => params[:ssn],
:dob => params[:dob],
:address => { :line1 => params[:address_line_1],
:line2 => params[:address_line_2],
:city => params[:city],
:state => params[:state],
:zipcode => params[:zipcode]
},
:homePhone => params[:dob],
:email => params[:email]
}
response = HTTParty.post( BANCBOX_REST_URL,
:body => post_params)
logger.debug "Response -- #{response}"
save!
end
Please try the below code after changing apikey, secret and subscriberid
require "net/https"
require 'rubygems'
require 'json'
require 'httparty'
###########################bancbox.rb in config/initializers#################
BANCBOX_API_KEY = "__KEY__"
BANCBOX_API_SECRET = "__SECRET__"
BANCBOX_SUBSCRIBER_ID = "__SUB_ID__"
BANCBOX_API_URL = "https://sandbox-api.bancbox.com/BBXPortRest"
module Bancbox
class API
include HTTParty
debug_output $stdout
base_uri "#{BANCBOX_API_URL}"
def initialize(u=BANCBOX_API_KEY,p=BANCBOX_API_SECRET)
auth = {:apiKey => u, :secret => p}
#options = {:body => {:authentication =>auth,:subscriberId=>BANCBOX_SUBSCRIBER_ID}, :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }}
end
#USERS
def create_client(options={})
options = options.merge(#options[:body])
#options.merge!({:body => options.to_json})
response = self.class.post("/createClient",#options)
#required_fields- subscriberId,firstName,lastName,ssn,dob,address,homePhone,email
end
def get_schedules(options={})
#options.merge!({:query => {:subscriberId => BANCBOX_SUBSCRIBER_ID}})
#options.merge!({:query => options})
self.class.post("/getSchedules",#options)
end
end
end
b = Bancbox::API .new
b.create_client({:firstName=> "Bipen",:lastName=> "Sasi",:ssn=>"334-444-4444",:dob=> Date.parse("January 1st 1988"), :address=>{:line1=> "4408 walnut st", :line2=>"apt 3r",:city=> "philly",:state=>"pa",:zipcode=>"19110"}, :homePhone=> "2672551161",:email=>"bipen#lokalty.com"})
I think you should POST the request to
https://sandbox-api.bancbox.com/BBXPortRest/createClient
instead of
https://sandbox-api.bancbox.com/BBXPortRest/
Also make sure to set the content type as application/json
In general, you post your request to https://sandbox-api.bancbox.com/BBXPortRest/<method>

Actionmailer Rails 3

I have added a contact form to my site and am having a problem, when the message is sent I get my flash message, "successfully sent", however the email never arrives in my inbox. I am in development mode at the moment and my app/config file looks like this
class Application < Rails::Application
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.raise_delivery_errors = true
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:user_name => "myemail#gmail.com",
:password => "example",
:authentication => :plain,
:enable_starttls_auto => true
}
config.action_mailer.default_url_options = {
:host => "gmail.com"
}
My contact Controller is like this
def new
#message = Message.new
end
def create
#message = Message.new(params[:message])
if #message.valid?
NotificationsMailer.new_message(#message).deliver
redirect_to(root_path, :notice => "Message was successfully sent.")
else
flash.now.alert = "Please fill all fields."
render :new
end
end
end
and finally my Notification Mailer
class NotificationsMailer < ActionMailer::Base
default :from => "myemail#gmail.com"
default :to => "myemail#gmail.com"
def new_message(message)
#message = message
if message.file
attachment_name = message.file.original_filename
attachments[attachment_name] = message.file.read
end
mail(:subject => "[myemail#gmail.com] #{message.subject}")
end
end
Am I missing anything obvious here as I have implemented this in another site which worked fine, just cant figure out what is going on
Any help appreciated
I know you set it in your app/config.rb, but I would ensure config.action_mailer.perform_deliveries isn't being overridden in your config/environments/development.rb