好的,经过一整天的研究和测试,我已经设法让几乎所有东西都能正常工作。这就是我所做的
第 1 步
rails g scaffold product name:string unit_price:decimal
product控制器:
def index
@products = Product.all
if @products.length != 0
@product = Product.find(1)
end
end
然后创建您的第一个产品
第 2 步
在产品索引中,您可以放置一个类似这样的按钮用于支付宝结帐:
<%= link_to 'checkout', @product.paypal_url(payment_notification_index_url, root_url) %>
第 3 步
在product 模型中
# 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
你可以找到更多关于HTML Variables for PayPal Payments Standard的信息
在这段代码中,对我来说最重要的是:
:return
买家完成付款后,PayPal 将他们的浏览器重定向到的 URL。例如,在您的网站上指定一个显示“感谢您的付款”页面的 URL。
:notify_url
PayPal 以即时付款通知消息的形式发布付款信息的 URL。
:cancel_return
如果买家在完成付款前取消结帐,PayPal 会将他们的浏览器重定向到该 URL。例如,在您的网站上指定一个显示“已取消付款”页面的 URL。
和
:rm
返回方法。用于将数据发送到指定 URL 的 FORM METHOD
通过返回变量。允许的值为:
0 - 所有购物车付款都使用 GET 方法
1 – 买家的浏览器通过使用
GET 方法,但不包含付款变量
2 – 买家的浏览器通过使用
POST方式,包含所有支付变量
第 4 步
rails g controller PaymentNotification create
在这里你需要添加以下内容:
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
第 5 步
rails g model PaymentNotification
在这里添加以下内容
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
在路线中:
resources :payment_notification, only: [:create]
现在您应该可以通过贝宝完成付款了。
不要忘记在每个scaffold 和model 创建之后rake db:migrate。
另外,为了获得自动重定向,您必须在 paypal 的沙箱中指定 url。 Click here to know how
如果我忘记了什么,请告诉我,我已经工作了 10 多个小时才可以正常工作,哈哈