CreditCard Model
def charge_cents!(cents)
begin
gateway = ActiveMerchant::Billing::AuthorizeNetGateway.new($installation[:authorize])
response = nil
Timeout::timeout(120.seconds) {
response = gateway.purchase(cents, self.to_am_creditcard, {
:order_id => self.customer.contract_number[1..-1],
:cust_id => self.customer.contract_number[1..-1]
}.merge(self.am_billing_address_hash))
}
return response
rescue
return response = nil
end
end
to_am_creditcard
def to_am_creditcard
ActiveMerchant::Billing::CreditCard.new({
:number => self.number,
:month => self.month,
:year => self.year,
:first_name => self.first_name,
:last_name => self.last_name,
})
end
am_billing_address_hash
def am_billing_address_hash
{:billing_address => self.to_hash }
end
Now, Take last credit card
1.9.3p484 :003 > #card = CreditCard.last
=> #<CreditCard id: 17263, crypted_number: "uXHr8wFYPvlaLWkB7hMltzex60ZtINOMH7EDB+/uSZU=\n", last_4: "4242", first_name: "test3", last_name: "test4", phone: "1234567890", customer_id: 66837, month: 7, year: 2017, address_id: 230222, created_at: "2014-07-11 03:36:21", updated_at: "2014-07-11 03:36:21">
and Now, use charge_cents method
1.9.3p484 :006 > response = #card.charge_cents!(amount * 100.0)
=> #<ActiveMerchant::Billing::Response:0xbac6ce0 #params={"response_code"=>2, "response_reason_code"=>"2", "response_reason_text"=>"This transaction has been declined.", "avs_result_code"=>"U", "transaction_id"=>"6328764577", "card_code"=>"", "authorization_code"=>"", "cardholder_authentication_code"=>"", "action"=>"AUTH_CAPTURE"}, #message="This transaction has been declined", #success=false, #test=false, #authorization="6328764577", #fraud_review=false, #avs_result={"code"=>"U", "message"=>"Address information unavailable.", "street_match"=>nil, "postal_match"=>nil}, #cvv_result={"code"=>nil, "message"=>nil}>
See : response_reason_text : Getting This transaction has been declined
I don't know why I am getting this error, It's working on test mode but when I remove a test mode then getting this error.
or, If any other way to integrate auth.net with ruby on rails 3.2 then please help for this with code.
Update
I am passing this data:
CC Number : 4242424242424242
ExpireDate : 11/2015
Please Help Me.
Thanks, In Advance.
First, when you specify Test Mode, the gateway only checks if the API Login and Transaction Key are correct and returns success if valid. This is true for both the sandbox or production. You should never use test mode in the sandbox.
Try using 4111111111111111 in the sandbox with test mode=false to test a transaction.
Related
In rails i'm getting the error uninitialized constant CartController::EXPRESS_CHECKOUT while i'm calling the method express_checkout of the controller CartController, i think that the problem is in config/environments/development.rb file, because i defined
config.after_initialize do
ActiveMerchant::Billing::Base.mode = :test
paypal_options = {
login: "<mail>",
password: "<pass>",
signature: "<sig>"
}
::EXPRESS_GATEWAY =
ActiveMerchant::Billing::PaypalExpressGateway.new(paypal_options)
end
But even if i tried to change something in this file, i can't fix this error.
This is the code of cart_controller.rb
def express_checkout
response = EXPRESS_GATEWAY.setup_purchase(params[:amount], ip: request.remote_ip, return_url: "http://localhost:8080/checkout_details", cancel_return_url: "http://localhost:8080", currency: "EUR", allow_guest_checkout: true, items: [{name: "Order", description: "Order description", quantity: "1", amount: params[:amount]}]
)
redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
end
def checkout_details
#token = params[:token]
#payer_id = params[:PayerID]
#details = EXPRESS_GATEWAY.details_for(#token)
end
def purchase
#t = params[:token]
#p = params[:PayerID]
#result = EXPRESS_GATEWAY.purchase(params[:amount], {:token => #t, :payer_id => #p, :currency => "EUR"})
end
I checked the version of the gem activemerchant and is version 1.66.0, so the version of this gem is not a problem.
Anyone knows something about this?
As Tobias suggested me, i corrected the mistake in CartController.rb, modifying EXPRESS_GATEWAY in ::EXPRESS_GATEWAY. After this change, i restarted the rails server and everything works perfectly!
I am trying to implement paypal payment gateway using activemerchet but getting error-A field was longer or shorter than the server allows
i am using credrntials of pro account. I saw other SO questions but it was not helpful
require 'rubygems'
require 'active_merchant'
ActiveMerchant::Billing::Base.mode = :test
gateway = ActiveMerchant::Billing::TrustCommerceGateway.new(
:login => 'XXX#gmail.com',
:password => 'my_password',
:signature => 'my_signature')
credit_card = ActiveMerchant::Billing::CreditCard.new(
:first_name => 'f_name',
:last_name => 'l_name',
:number => '4032034467080704',
:month => '9',
:year => '2021',
:verification_value => '123',
:brand => 'VISA'
)
AMOUNT = 1000
def purchase_options
{
ip: "127.0.0.1",
billing_address: {
name: "Flaying Cakes",
address1: "123 5th Av.",
city: "New York",
state: "NY",
country: "US",
zip: "10001"
}
}
end
if credit_card.validate.empty?
response = gateway.purchase(AMOUNT, credit_card, purchase_options)
if response.success?
puts "Successfully charged to the credit card #{credit_card.display_number}"
else
raise StandardError, response.message
end
else
puts "credit card is not valid #{credit_card.errors.full_messages.join(". ")}"
end
I changed
gateway = ActiveMerchant::Billing::TrustCommerceGateway.new
to
gateway = ActiveMerchant::Billing::PaypalGateway.new
and it worked fine.
Hi I'm Integrating Paypal express checkout using Activemerchant.
I'm able to make successful transaction but I'm not seeing My Item's description in transaction details page.It display all the other option correctly but the Options column is empty.
However I'm seeing Items details in the checkout page.
Here is my code.I probably doing something wrong.
def express_checkout
listing = Listing.find(session[:listing_id].to_f)
response = EXPRESS_GATEWAY.setup_purchase(session[:amount].to_f,
ip: request.remote_ip,
return_url: "http://esignature.lvh.me:3000/en/transactions/status",
cancel_return_url: "http://esignature.lvh.me:3000/",
currency: "USD",
allow_guest_checkout: true,
items: [{name: listing.title, description: listing.description, quantity: session[:number_of_days], amount: listing.price_cents},
{name: "Service Charge" ,description: "Service Charge", amount: session[:service_charge]}
]
)
redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
end
def status
if (params[:token].present? && params[:PayerID].present?)
token = params[:token]
#response = EXPRESS_GATEWAY.details_for(token).params
listing = Listing.find(session[:listing_id].to_f)
express_purchase_options = {
:ip => request.remote_ip,
:token => params[:token],
:payer_id => params[:PayerID],
items: [{ name: listing.title, description: listing.description, quantity: session[:number_of_days], amount: listing.price_cents},
{ name: "Service Charge", description: "Service Charge", amount: session[:service_charge ]}
]
}
response = EXPRESS_GATEWAY.purchase(session[:amount].to_f, express_purchase_options)
if response.message == "Success"
listing = Listing.find(session[:listing_id].to_f)
BookingInfo.create!(listing_id: listing.id, start_on: session[:start_date].to_date, end_on: session[:end_date].to_date)
render 'status'
else
render 'status_error'
end
reset_session_params
else
reset_session_params
redirect_to homepage_without_locale_path
end
end
here I'm setting Item details in both setup_purchase as well as in purchase.Any suggestion will be appreciated.Thank you
I'm having an issue with my scheduled text messages. I run a rake task that checks to see if a text message should be put into a Sidekiq queue. The record is processed (the text is sent) but a new empty record is generated and the sentstatus is not updated to "true".
send_scheduled_text.rake
require_relative '../../app/workers/send_text_worker'
namespace :send_scheduled_text do
task:texts => :environment do
TextMessage.all.each do |text_message|
if text_message.sentstatus == false
if (Date.today == text_message.scheduled_date) && (Time.now.hour >= text_message.scheduled_time.hour)
# Sidekiq code:
SendTextWorker.perform_async(text_message.id)
end
end
end
end
end
send_text_worker.rb
class SendTextWorker
include Sidekiq::Worker
def perform(text_message_id)
text = TextMessage.find(text_message_id)
text.send_text_message(text.content, text.phone)
end
end
text_message.rb
require 'twilio-ruby'
require 'date'
class TextMessage < ActiveRecord::Base
belongs_to :client, dependent: :destroy
belongs_to :step, dependent: :destroy
has_many :coach_emails
before_save :grab_phone
def grab_phone
self.phone = phone
end
def send_text_message(message, phone)
twilio_sid = ENV["TWILIO_ACCT_SID"]
twilio_token = ENV["TWILIO_AUTH_TOKEN"]
twilio_phone_number = ENV["TWILIO_PHONE_NUMBER"]
begin
#twilio_client = Twilio::REST::Client.new(twilio_sid, twilio_token)
#twilio_client.account.sms.messages.create(
:from => "+1#{twilio_phone_number}",
:to => phone,
:body => message)
rescue Twilio::REST::RequestError => e
puts e.message
end
if e != "400" || e != "500"
self.sentstatus = true
end
self.save!
send
send
Rails console: before rake task is called
(sentstatus is false)
irb(main):001:0> TextMessage.all
TextMessage Load (0.5ms) SELECT "text_messages".* FROM "text_messages"
=> #<ActiveRecord::Relation [#<TextMessage id: 164, client_id: nil, content: "Testing Sidekiq processing", incoming_message: false, created_at: "2015-02-02 04:43:29", updated_at: "2015-02-02 04:43:29", scheduled_date: "2015-02-01", sentstatus: false, step_id: 4, phone: "+14127364161", scheduled_time: "2000-01-01 14:00:00">]>
Rails console: After rake task is called
(sentstatus is false, should be true. I also have this new bizarre empty record)
irb(main):001:0> TextMessage.all
TextMessage Load (0.5ms) SELECT "text_messages".* FROM "text_messages"
=> #<ActiveRecord::Relation [#<TextMessage id: 164, client_id: nil, content: "Testing Sidekiq processing", incoming_message: false, created_at: "2015-02-02 04:43:29", updated_at: "2015-02-02 04:43:29", scheduled_date: "2015-02-01", sentstatus: false, step_id: 4, phone: "+14127364161", scheduled_time: "2000-01-01 14:00:00">,
#<TextMessage id: 165, client_id: nil, content: nil, incoming_message: nil, created_at: "2015-02-02 04:45:24", updated_at: "2015-02-02 04:45:24", scheduled_date: nil, sentstatus: true, step_id: nil, phone: nil, scheduled_time: nil>]>
I have a feeling this is a Sidekiq nuance that I'm missing. Thanks for any thoughts!
I ended up moving my model logic to my worker. Presto -- timing works and I'm not generating any extra nil records.
I use this logic in my app:
controller
#current_user = User.find_or_create_from_oauth(auth_hash)
user.rb
def self.find_or_create_from_oauth(auth_hash)
provider = auth_hash["provider"]
uid = auth_hash["uid"].to_s
case provider
when 'twitter'
if user = self.find_by_twitter_uid(uid)
return user
else
return self.create_user_from_twitter(auth_hash)
end
end
end
def self.create_user_from_twitter(auth_hash)
a = self.create({
:twitter_uid => auth_hash["uid"],
:name => auth_hash["info"]["name"]
})
puts a.inspect
user = User.find_by_twitter_uid(a.twitter_uid)
puts '---'
puts user.inspect
end
Immediately after self.create I would need to run this line:
Assignment.create(:user_id => a.id, :role_id => 2)
The problem is, that the line puts user.inspect return something like this:
#<User id: nil, name: "...name...", twitter_uid: "96580821", provider: "twitter", created_at: nil, updated_at: nil>
Why is in the hash returned id: nil?
Or, is there any other way, how to get the ID of last created record?
If the user has been correctly saved, you can use directly a:
a.assignments.create(:role_id => 2)
Otherwise (check using create! instead of create) there may be a validation error.