am currently working on integrating my sample site with Authorize.NET.
So I created a Sandbox account in Authorize.NET.
Using this test account, I am testing DPM and using Relay Response URL.
I have Public IP
I am setting the x_relay_response="TRUE"; x_relay_url="http://182.180.157.5:3000/payments/relay_response";
Controller
class PaymentsController < ApplicationController
layout 'authorize_net'
helper :authorize_net
protect_from_forgery :except => :relay_response
# GET
# Displays a payment form.
def payment
#amount = 125.00
#sim_transaction = AuthorizeNet::SIM::Transaction.new(AUTHORIZE_NET_CONFIG['api_login_id'], AUTHORIZE_NET_CONFIG['api_transaction_key'], #amount, :relay_response => true, :relay_url => "http://182.180.157.5:3000/payments/relay_response")
end
# POST
# Returns relay response when Authorize.Net POSTs to us.
def relay_response
puts "In Relay Response"
puts "Params: #{params}"
sim_response = AuthorizeNet::SIM::Response.new(params)
if sim_response.success?(AUTHORIZE_NET_CONFIG['api_login_id'], AUTHORIZE_NET_CONFIG['merchant_hash_value'])
render :text => sim_response.direct_post_reply("http://182.180.157.5:3000/payments/receipt", :include => true)
else
render
end
end
# GET
# Displays a receipt.
def receipt
#auth_code = params[:x_auth_code]
end
end
Getting This Error
An error occurred while trying to report this transaction to the merchant. An e-mail has been sent to the merchant informing them of the error. The following is the result of the attempt to charge your credit card.
This transaction has been approved.
It is advisable for you to contact the merchant to verify that you will receive the product or service.
Any Solution For This
Related
Building an application in rails that uses stripe for its payment/checkout system. I have the charges controller, new.html.erb and all the necessary gems in place but for some reason whenever I use my credit card to test stripe with a real payment (the charge is only $2 so it doesn't hurt to test) it appears in my logs as a v1/token rather than a v1/charge and does not appear in the payments section. I have researched extensively the conversion from token to charge and have found multiple answers pointing to the same solution (creating a begin method that turns tokens into charges which I have) but when implementing it doesn't work for me. this is my current charges controller:
require "stripe"
class ChargesController < ApplicationController
def new
# this will remain empty unless you need to set some instance variables to pass on
end
def create
# Amount in cents
#amount = 200
# Set your secret key: remember to change this to your live secret key in production
# See your keys here https://dashboard.stripe.com/account/apikeys
Stripe.api_key = "pk_live_z....." //taken out for security reasons
# Get the credit card details submitted by the form
token = params[:stripeToken]
# Create the charge on Stripe's servers - this will charge the user's card
begin
charge = Stripe::Charge.create(
:amount => #amount, # amount in cents, again
:currency => "usd",
:source => token,
:description => "Example charge"
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
end
end
your create method is not being called which executes the logic of payment.
I'm currently trying to make a 'Buy now' button with a fixed price amount.
After the user pays I want to redirect them to the root url and send them an email with an attached PDF file.
I've been researching how to create a simple checkout using paypal but with no success, I've found tutorials that are years old and some of the code is deprecated.
I've tried using BRAINTREE and it worked perfectly on testing/sandbox but I am unable to create a production account since I currently live in Puerto Rico(this limits my options for payment gateways).
What I've done so far
Following a tutorial
I've created a scaffold for products with name and unit_price
In my product model:
# This defines the paypal url for a given product sale
def paypal_url(return_url)
values = {
:business => YOUR_MERCHANT_EMAIL,
:cmd => '_cart',
:upload => 1,
:return => return_url,
:invoice => UNIQUE_INTEGER
}
values.merge!({
"amount_1" => unit_price,
"item_name_1" => name,
"item_number_1" => id,
"quantity_1" => '1'
})
# This is a paypal sandbox url and should be changed for production.
# Better define this url in the application configuration setting on environment
# basis.
"https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query
end
In the tutorial they said that this should be enough to be able to process the payment but they ask to click the 'Buy now' link which I have no idea where to point it or how to create it.
If it's not much to ask, could someone point me in the right direction here (step by step -> easy single checkout payment with paypal -> documentations).
Thanks a million.
EDIT:
Was able to create the checkout button:
<%= link_to 'checkout', product.paypal_url(products_url) %>
Now it works BUT how do I make it so you get redirected back to my website with a notice?
Thanks!
Ok so after a full day of research and testing, I've manage to get almost everything working. Here's what I've done
Step 1
rails g scaffold product name:string unit_price:decimal
product controller:
def index
#products = Product.all
if #products.length != 0
#product = Product.find(1)
end
end
Then create your first product
Step 2
In the index for products you can put a button like this for a paypal checkout:
<%= link_to 'checkout', #product.paypal_url(payment_notification_index_url, root_url) %>
Step 3
in the product model
# This defines the paypal url for a given product sale
def paypal_url(return_url, cancel_return)
values = {
:business => 'your_sandbox_facilitato_email#example.com',
:cmd => '_xclick',
:upload => 1,
:return => return_url,
:rm => 2,
# :notify_url => notify_url,
:cancel_return => cancel_return
}
values.merge!({
"amount" => unit_price,
"item_name" => name,
"item_number" => id,
"quantity" => '1'
})
# For test transactions use this URL
"https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query
end
has_many :payment_notifications
You can find more info about the HTML Variables for PayPal Payments Standard
In this code the most important ones for me are:
:return
The URL to which PayPal redirects buyers' browser after they complete their payments. For example, specify a URL on your site that displays a "Thank you for your payment" page.
:notify_url
The URL to which PayPal posts information about the payment, in the form of Instant Payment Notification messages.
:cancel_return
A URL to which PayPal redirects the buyers' browsers if they cancel checkout before completing their payments. For example, specify a URL on your website that displays a "Payment Canceled" page.
and
:rm
Return method. The FORM METHOD used to send data to the URL specified
by the return variable. Allowable values are:
0 – all shopping cart payments use the GET method
1 – the buyer's browser is redirected to the return URL by using the
GET method, but no payment variables are included
2 – the buyer's browser is redirected to the return URL by using the
POST method, and all payment variables are included
Step 4
rails g controller PaymentNotification create
In here you need to add the following:
class PaymentNotificationController < ApplicationController
protect_from_forgery except: [:create]
def create
# #payment = PaymentNotification.create!(params: params, product_id: params[:invoice], status: params[:payment_status], transaction_id: params[:txn_id] )
#payment = PaymentNotification.create!(params: params, product_id: 1, status: params[:payment_status], transaction_id: params[:txn_id])
# render nothing: true
if #payment.status == 'Completed'
redirect_to root_url, notice: 'Success!'
else
redirect_to root_url, notice: 'Error'
end
end
end
Step 5
rails g model PaymentNotification
in here add the following
class PaymentNotification < ActiveRecord::Base
belongs_to :product
serialize :params
after_create :success_message
private
def success_message
if status == "Completed"
puts 'Completed'
...
else
puts 'error'
...
end
end
end
in routes:
resources :payment_notification, only: [:create]
And now you should be able to have a complete processing payment via paypal.
Don't forget to rake db:migrate after each scaffold and model creationg.
Another thing, in order to get the automatic redirect, you have to specify the url in the sandbox of paypal. Click here to know how
If I forgot something let me know, been working for more than 10 hours to get this working lol
I am using stripe to setup a payment system. I am having an issue with my credit_card model displaying the stripe errors in my user model, as the first credit card is submitted as a child of the user. Also, I am using Devise for my users auth.
class CreditCard < ActiveRecord::Base
def create_stripe_credit_card
customer = Stripe::Customer.retrieve(self.user.stripe_customer_id)
credit_card = customer.cards.create(:card => self.stripe_token)
rescue Stripe::CardError => e
logger.error "Stripe Error: " + e.message
errors.add(:base, "#{e.message}")
false
end
end
class RegistrationsController < Devise::RegistrationsController
def create
build_resource(sign_up_params)
if resource.save
# User created
else
clean_up_passwords resource
return render :status => 400, :json => resource.errors
end
end
end
After some googling I came upon this SO question
Ruby on Rails: how to get error messages from a child resource displayed?
but it seems that I would have to put a validator in my CreditCard model to trigger the errors in my User model, and since the only way to get this error raised is to try it, not sure how to put it into a validator.
Any help would be greatly appreciated.
I am building a simple web app that sends SMS messages to cell phones using Twilio. I want to ensure that the user has entered a full 10 digit phone number before it will allow a message to attempt to be sent.
When I test it with a less-than or greater-than 10 digit number, in heroku logs, I see Twilio::REST::RequestError (The 'To' number 1234567890 is not a valid phone number.).
I have tried to use a begin/rescue wrapper and am telling it to render text: "Try again with a valid number." and tried a variety of if statements to try to avoid the error.
I am pretty new to Ruby and Rails and Twilio, but I promise i have been through every guide I have found. Any help is greatly appreciated. Full code of my UserController below:
require 'twilio-ruby'
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(params[:user])
account_sid = '...'
auth_token = '...'
if #user.save
render text: "Wasn't that fun? Hit the back button in your browser to give it another go!"
begin
client = Twilio::REST::Client.new account_sid, auth_token
client.account.sms.messages.create(
from: '+16035093259',
to: #user.phone,
body: #user.message
)
rescue Twilio::REST::RequestError
render text: "Try again with a valid number."
end
else
render :new
end
end
end
I'd extract the SMS sending logic into a separate model/controller and use a background job to process the submitting. The UserController should only handle, well, user creation/modification.
Scaffolding:
$ rails g model sms_job user:references message:text phone submitted_at:datetime
$ rake db:migrate
Model:
class SmsJob < AR::Base
attr_accessible :user_id, :message, :phone
belongs_to :user
validates_presence_of :message, :phone, :user_id
validates :phone,
length: { min: 10 },
format: { with: /\+?\d+/ }
scope :unsubmitted, where(submitted_at: nil)
TWILIO = {
from_no: '...',
account_sid: '...',
auth_token: '...'
}
# find a way to call this method separately from user request
def self.process!
unsubmitted.find_each do |job|
begin
client = Twilio::REST::Client.new TWILIO[:account_sid], TWILIO[:auth_token]
client.account.sms.messages.create(
from: TWILIO[:from_no],
to: job.phone,
body: job.message
)
job.submitted_at = Time.zone.now
job.save
rescue Twilio::REST::RequestError
# maybe set update a tries counter
# or delete job record
# or just ignore this error
end
end
end
end
The controller then should just provide the information that the SMS is going to be send:
# don't forget the 'resources :sms_jobs' in your routes.rb
class SmsJobsController < ApplicationController
# index, update, destroy only for only admin?
def new
#sms_job = SmsJobs.new
end
def create
#sms_job = current_user.sms_jobs.build params[:sms_job]
if #sms_job.save
redirect_to root_url, notice: "Your message is being send!"
else
render :new
end
end
end
For the background processing, have a look at these excellent Railscasts :-) You probably need to workaround some concurrency problems if you have to process many messages and/or Twilio has a long response time (didn't use that service yet).
I've been having trouble setting up the IPN Notification on my app to get all the information
send back to my application. My payment is working properly and is functional. I am having trouble with the notify_action. I would like to retrieve the information of the payment and send it back to my app to get all the informations from the payment.
def checkout
....
response = #gateway.setup_purchase(
:return_url => "http://localhost:3000",
:cancel_url => "http://localhost:3000",
:ipn_notification_url => orders_notify_action_url,
:receiver_list => recipients
)
..
redirect_to (#gateway.redirect_url_for(response["payKey"]))
end
def notify_action
notify = ActiveMerchant::Billing::Integrations::PaypalAdaptivePayment::Notification.new(request.raw_post)
p "Notification object is #{notify}"
if notify.acknowledge
p "Transaction ID is #{notify.transaction_id}"
p "Notification object is #{notify}"
p "Notification status is #{notify.status}"
end
render :nothing => true
end
https://gist.github.com/8acceeee72fe12312c09
It would help a lot if you specified what problem you're having. For example, is the problem that notify_action is not being hit by Paypal's IPN? Or is notify.acknowledge returning false?
For strictly IPN this is what my working controller looks like:
class PayController < ApplicationController
include ActiveMerchant::Billing::Integrations
def paypal
notify = Paypal::Notification.new(request.raw_post)
logger.debug "Notification object is #{notify}"
if notify.acknowledge
logger.debug "Transaction ID is #{notify.transaction_id}"
logger.debug "Notification object is #{notify}"
logger.debug "Notification status is #{notify.status}"
end
render :nothing => true
end
end
Then the URL I gave to Paypal is www.yourwebsite.com/pay/paypal
Then simply match the route in route.rb
match 'pay/paypal' => 'pay#paypal'
The notify object should contain all the data for the given purchase.
Important: Watch the log file to see if the function is ever getting called, and if so, what is being printed?