Special character not allowed error on website while intregating paytm - ruby-on-rails

I want to integrate paytm using ruby on rails for web only, now the problem is that when I fetched the values of attributes form database like MID, CUST_ID, WEBSITE, CALLBACK_URL, INDUSTRY_TYPE_ID and some others attributes, then one problem is occurring which is below.
Attributes:
paramList["WEBSITE"] = "WEBSTAGING"
Error:
invalid: Special character not allowed
def start_payment
unless #paytm_keys.nil?
paramList = Hash.new
paramList["MID"] = ""
paramList["ORDER_ID"] = "#{Time.now.to_i.to_s}"
paramList["CUST_ID"] = "#{Time.now.to_i.to_s}"
paramList["INDUSTRY_TYPE_ID"] = #paytm_keys.industry_type_id
paramList["CHANNEL_ID"] = #paytm_keys.channel_id
paramList["TXN_AMOUNT"] = #payable_amount
paramList["MOBILE_NO"] = #paytm_keys.mobile_number
paramList["EMAIL"] = #paytm_keys.email
paramList["WEBSITE"] = "WEBSTAGING"
paramList["CALLBACK_URL"] = #paytm_keys.paytm_url
#paramList=paramList
puts #paramList
#checksum_hash = generate_checksum()
respond_to do |format|
format.js
format.html
end
else
redirect_to new_checkout_path, alert: "Right now you don't have to pay."
end
end

It seems there are some special characters in one of the params you're passing in your hash. Have a look at the output of
puts #paramList
It might be helpful if you could post this in your question, but you probably want to obfuscate real credentials by perhaps substituting or removing all valid alphanumeric characters from your puts so you can give us the output of:
puts paramList.to_s.gsub(/\w/, '')
# this should only contain non alphanumeric characters which
# would be safe to post in your question.

Related

How to enter a list of codes in the text field, through "," and get the same number of separate objects Rails

I am writing one project Ruby on Rails, and i'm stuck in one place.. I have a class Product, this class has_many: class Codes. Now, i enter the codes one at a time into the text box, and I get one object with one code.
I want to enter a list of codes in the text field, through "," and get the same number of separate objects.
I am getting this error -
TypeError in GiftCodesController#create
no implicit conversion of String into Integer
When I check with a debugger, I don't see any Integer
#code = Code.new(code_params)
if #code.code.include? ","
#array = #code.ode.split(",")
#array.each do |n|
#code.code = #array[n]
#code.save
end
flash[:success] = "CodeĀ“s added!"
redirect_to root_path
else
if #code.save
flash[:success] = "Code added!"
redirect_to root_path
else
flash[:danger] = "Error!"
end
end
The each method returns the VALUE of each array element, not the index.
So this is wrong...
#array.each do |n|
#code.code = #array[n]
#code.save
end
This would be correct...
So this is wrong...
#array.each do |n|
#code.code = n
#code.save
end
But even that would be wrong, as you want to create a new code for each array element, so...
#array.each do |n|
code = #product.codes.build
code.code = n
code.save
end
There are some edge cases you'll also need to address, like how to edit existing codes for a product, but hopefully this will start you off.

How to retrieve sixth record from database in rails using Where query

I want to retrieve sixth, seventh and eighth record from database using ruby on rails, but it's possible only till fifth, after that undefined method sixth is coming. Please suggest me if there is any possible way.
Following is my code which I tried:
#reporting_masters_travel_requests4 = ReportingMastersTravelRequest.where(travel_request_id: #travel_request.id,status: nil).fifth
if #reporting_masters_travel_requests2 = ReportingMastersTravelRequest.where(travel_request_id: #travel_request.id,status: nil)[1]
ReportingMastersTravelRequest.where(reporting_master_id: #reporting_masters_travel_requests2.reporting_master_id).update_all(status: "true",daily_bill_comment: #comment)
TravelRequest.where(id: #travel_request.id).update_all(reporting_master_id: #reporting_masters_travel_requests3.reporting_master_id)
flash[:notice] = 'Daily Bill Request Send To Higher Authority For Approval'
elsif #reporting_masters_travel_requests3 = ReportingMastersTravelRequest.where(travel_request_id: #travel_request.id,status: nil)[2]
ReportingMastersTravelRequest.where(reporting_master_id: #reporting_masters_travel_requests3.reporting_master_id).update_all(status: "true",daily_bill_comment: #comment)
TravelRequest.where(id: #travel_request.id).update_all(reporting_master_id: #reporting_masters_travel_requests4.reporting_master_id)
flash[:notice] = 'Daily Bill Request Send To Higher Authority For Approval'
elsif #reporting_masters_travel_requests4 = ReportingMastersTravelRequest.where(travel_request_id: #travel_request.id,status: nil)[3]
ReportingMastersTravelRequest.where(reporting_master_id: #reporting_masters_travel_requests4.reporting_master_id).update_all(status: "true",daily_bill_comment: #comment)
TravelRequest.where(id: #travel_request.id).update_all(reporting_master_id: #reporting_masters_travel_requests5.reporting_master_id)
flash[:notice] = 'Daily Bill Request Send To Higher Authority For Approval'
else
flash[:alert] = 'No Reporting Manager is present'
end
I have used the above code and it works perfectly,but its not so dynamic as i manually need to specify for how many time if want to check in table via array [4].But problem is what if 10 records are present in database then for this the above logic will fail.
You are using where to get records from database and it returns array of objects so you can use something like this:
#reporting_masters_travel_requests4 = ReportingMastersTravelRequest.where(travel_request_id: #travel_request.id,status: nil)[5]
You can do as follows:
#reporting_masters_travel_requests = ReportingMastersTravelRequest.where(travel_request_id: #travel_request.id,status: nil)
#reporting_masters_travel_requests.each do |record|
#Something like record.update record.save
end
#set a msg like no more records after loop
msg="No more records"

How can I convert this hash into workable JSON?

IE10 is returning parameters in what looks like a double conversion to JSON :
=> {"{\"statementId\":"=>
{"\"b3dsecret9-bsecret741-23secreta806c\""=>
{",\"Content-Type\":"=>
{"\"application/json\""=>
{",\"content\":"=>
{"\"{\\\"context\\\":{\\\"registration\\\":\\\"27\\\",\\\"contextActivities\\\":{\\\"parent\\\":{\\\"id\\\":\\\"6LHIJumrnmV_course_id\\\"},\\\"grouping\\\":{\\\"id\\\":\\\"6LHIJumrnmV_course_id\\\"}}},\\\"actor\\\":213,\\\"verb\\\":\\\"attempted\\\",\\\"object\\\":{\\\"id\\\":\\\"6LHIJumrnmV_course_id\\\",\\\"definition\\\":{\\\"name\\\":{\\\"und\\\":\\\"\\\"},\\\"type\\\":\\\"Course\\\",\\\"description\\\":{\\\"und\\\":\\\"\\\"}}}}\""=>
{",\"registration\":"=>
{"\"27\""=>
{",\"AWSAccessKeyId\":"=>
{"\"secretIAIVsecretPHsecretQ\""=>
{",\"Signature\":"=>
{"\"PJ /OW K5secretasyXsecret5A"=>
"\"],\"Expires\":[\"1396873090\"],\"Authorization\":[\"\"]}"}}}}}}}}}}},
"method"=>"PUT",
"controller"=>"quizzes",
"action"=>"statements"}
IE Edge, Safari, Chrome, and Firefox return my params like this :
=> {"registration"=>["27"],
"Content-Type"=>["application/json"],
"Signature"=>["secretkqPJGPEsecret01ksecret"],
"AWSAccessKeyId"=>["Asecret6secretPHsecretQ"],
"statementId"=>["5919c4f4-b71c-40dd-81dc-ab63cfc824bd"],
"Expires"=>["1396873699"],
"Authorization"=>[""],
"content"=>
["{\"object\":{\"definition\":{\"type\":\"Course\",\"name\":{\"und\":\"\"},\"description\":{\"und\":\"\"}},\"id\":\"6LHIJumrnmV_course_id\"},\"verb\":\"attempted\",\"context\":{\"registration\":\"27\",\"contextActivities\":{\"parent\":{\"id\":\"6LHIJumrnmV_course_id\"},\"grouping\":{\"id\":\"6LHIJumrnmV_course_id\"}}},\"actor\":213}"],
"method"=>"PUT",
"controller"=>"quizzes",
"action"=>"statements",
"quiz"=>{}
So my code parses this conveniently doing this :
content = params[:content] || params['content']
response = JSON.parse(content.first)
And presto! I have a workable piece of content. But with that first aforementioned Hash, I'm not sure how to convert that. Should I just be thinking of using a match/gsub technique to remove all those evil forward slashes? Is there a way to decipher that into something that looks like my latter hash?
Starting from your answer, I would parse key using the escape_utils gem:
require 'escape_utils'
def nested_hash_value(obj,key)
# nested_hash_value(params, ",\"content\":")
if obj.respond_to?(:key?) && obj.key?(key)
obj[key]
elsif obj.respond_to?(:each)
r = nil
obj.find{ |*a| r=nested_hash_value(a.last,key) }
r
end
end
extract = nested_hash_value(params, ",\"content\":")
key = extract.keys.first
response = JSON.parse EscapeUtils.unescape_javascript(key).gsub(/^"|"$/,'')
This avoids using the evil eval thing.
More generally, I think you should build your processing in this way:
def smell_of_ie_weirdness?
# Detects whether the request seems like the one sent by IE 10,
# something like params keys formatting checking etc.
end
def extracted_response
if smell_of_ie_weirdness?
# Do weird stuff
extract_response_for_weird_ie
else
# Be clean and polite
extract_response
end
end
Well this gives me an answer.. it's not the best. It's definitely a hack. But I feel like it's the only thing I got.
def nested_hash_value(obj,key)
# nested_hash_value(params, ",\"content\":")
if obj.respond_to?(:key?) && obj.key?(key)
obj[key]
elsif obj.respond_to?(:each)
r = nil
obj.find{ |*a| r=nested_hash_value(a.last,key) }
r
end
end
extract = nested_hash_value(params, ",\"content\":")
key = extract.keys.first
decoded_hash = key.to_s.gsub(/\\/,'').gsub(/\"/,"'").gsub(/'$|^'/,'').gsub(':','=>')
response = eval decoded_hash
If I do a comparison == between the two outputs they return true .
Then I just throw it all in a rescue block..
begin
content = params[:content] || params['content']
response = JSON.parse(content.first)
rescue
perform_fd_up_IE_fixer # :)
end

How to remove special characters from params hash?

I have one application with the following code:
quantity = 3
unit_types = ['MarineTrac','MotoTrac','MarineTrac']
airtime_plan = 'Monthly Airtime Plan'
url = "http://localhost:3000/home/create_units_from_paypal?quantity=#{quantity}&unit_types=#{unit_types}&airtime_plan=#{airtime_plan}"
begin
resp = Net::HTTP.get(URI.parse(URI.encode(url.strip)))
resp = JSON.parse(resp)
puts "resp is: #{resp}"
true
rescue => error
puts "Error: #{error}"
return nil
end
It sends data to my other application via the URL params query string. This is what the controller method of that other application looks like:
def create_units_from_paypal
quantity = params[:quantity]
unit_types = params[:unit_types]
airtime_plan = params[:airtime_plan]
quantity.times do |index|
Unit.create! unit_type_id: UnitType.find_by_name(unit_types[index]),
airtime_plan_id: AirtimePlan.find_by_name(airtime_plan),
activation_state: ACTIVATION_STATES[:activated]
end
respond_to do |format|
format.json { render :json => {:status => "success"}}
end
end
I get this error:
<h1>
NoMethodError
in HomeController#create_units_from_paypal
</h1>
<pre>undefined method `times' for "3":String</pre>
<p><code>Rails.root: /Users/johnmerlino/Documents/github/my_app</code></p>
I tried using both raw and html_safe on the params[:quantity] and other params, but still I get the error. Note I had to use URI.encode(url) because URI.parse(url) returned bad uri probably because of the array of unit_types.
Change:
quantity.times do |index|
To:
quantity.to_i.times do |index|
The reason you are having this problem is because you are treating the params values as the types that you originally tried to send, but they are actually always going to be strings. Converting back to the expected 'type' solves your problem.
However, you have some more fundamental problems. Firstly, you are trying to send an array by simply formatting it to a string. However, this is not the format that the receiving application expects to translate back to an array. Secondly, there is duplication in your request - you don't need to specify a quantity. The length of the array itself is the quantity. A better method would be to build your url like this:
url = 'http://localhost:3000/home/create_units_from_paypal?'
url << URI.escape("airtime_plan=#{airtime_plan}") << "&"
url << unit_types.map{|ut| URI.escape "unit_types[]=#{ut}" }.join('&')
On the receiving side, you can do this:
def create_units_from_paypal
unit_types = params[:unit_types]
airtime_plan = params[:airtime_plan]
quantity = unit_types.try(:length) || 0
#...

Generate a new user programmatically (Auth Logic)

I'm quite new to Ruby on Rails so please bear with me :)
I'm processing an imported .csv file in Rails and I want to programmatically create new users (I'm using the AuthLogic Gem along with Role Requirement), So Far I'm using:
Example Line:
Steve.Jobs#apple.com, Steve, Jobs, 555-APPLE
Code:
def new_user(line)
params = Hash.new
params[:user] = Hash.new
params[:user]["email"] = line[0]
params[:user]["first_name"] = line[1]
params[:user]["last_name"] = line[3]
params[:user]["phone"] = line[4]
user = User.new(params[:user])
user.save
end
The problem being that this doesn't add a new user, it tries to but fails (DB Begin followed by Rollback), I assume because I'm not filling in all the fields, such as login, password etc.
Do I have to explicitly generate values for these fields?
I came across this same problem yesterday. I'm using the oauth addon though so the login/email are not required fields for me, it was failing on the persistence token not being present which I got around by adding
user.reset_persistence_token
just before calling user.save
Hope that helps a bit. Would be nice to find a cleaner way of doing it.
Ok So I've managed to answer my own question, although not in the most ideal of ways:
def new_user(line)
params = Hash.new
params[:user] = Hash.new
params[:user]["email"] = line[0]
params[:user]["first_name"] = line[1]
params[:user]["last_name"] = line[2]
params[:user]["phone"] = line[3]
#generate random password of length 6
password = ActiveSupport::SecureRandom.base64(6)
#generate username by adding first and last name + 3 random characters
username = (line[1] + line[2])
username = username + ActiveSupport::SecureRandom.base64(3)
params[:user]["login"] = username
params[:user]["password"] = password
params[:user]["password_confirmation"] = password
#check to see if user already exists
#existing_user = User.find_by_email(line[0])
if(#existing_user)
#user exists
#do nothing
else
#user is brand new
#new_user = User.new(params[:user])
#new_user.reset_persistence_token
if(#new_user.save)
#new_user = User.find_by_email(line[0])
#user saved successfully
else
#a problem occurred
flash[:errors] = #new_user.errors
end
end
end

Resources