有几种语言的官方代码示例,但找不到Rails的。
class PaymentNotificationsController < ApplicationController
protect_from_forgery :except => [:create] #Otherwise the request from PayPal wouldn't make it to the controller
def create
response = validate_IPN_notification(request.raw_post)
case response
when "VERIFIED"
# check that paymentStatus=Completed
# check that txnId has not been previously processed
# check that receiverEmail is your Primary PayPal email
# check that paymentAmount/paymentCurrency are correct
# process payment
when "INVALID"
# log for investigation
else
# error
end
render :nothing => true
end
protected
def validate_IPN_notification(raw)
live = 'https://ipnpb.paypal.com/cgi-bin'
sandbox = 'https://ipnpb.sandbox.paypal.com/cgi-bin'
uri = URI.parse(sandbox + '/webscr?cmd=_notify-validate')
http = Net::HTTP.new(uri.host, uri.port)
http.open_timeout = 60
http.read_timeout = 60
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.use_ssl = true
response = http.post(uri.request_uri, raw,
'Content-Length' => "#{raw.size}",
'User-Agent' => "My custom user agent"
).body
end
end
这段代码受到了Railscast 142和Tanel Suurhans的启发。
ipn_valid?
的布尔方法,使其变得超级简单。def notify
@api = PayPal::SDK::Merchant.new
if @api.ipn_valid?(request.raw_post) # return true or false
# params contains the data
end
end
https://github.com/paypal/merchant-sdk-ruby/blob/master/samples/IPN-README.md
protect_from_forgery except: [:notify]
,以便POST请求不会因为无法验证CSRF令牌的真实性而被拒绝。 - scarver2您可以在此处找到DWilke的Paypal IPN gem:
https://github.com/dwilkie/paypal
请查看IPN模块。这是一段很好的代码:
https://github.com/dwilkie/paypal/blob/master/lib/paypal/ipn/ipn.rb
您可以在此处使用IPN模拟器进行测试:
https://developer.paypal.com/webapps/developer/applications/ipn_simulator
我使用ngrok将本地主机的端口3000暴露在公共URL上,然后将模拟器指向该地址。
我在我的一个项目中实现了IPN,你的代码看起来很好。那么你遇到了什么问题?
看一下ActiveMerchant宝石,其中包括多个网关实现,其中之一是Paypal的IPN。
希望有所帮助
您只需执行此操作即可获取 IPN 详细信息。结果将显示验证状态。您可以从正文中获取所有详细信息。
post '/chinese/ipn' do
url = "https://sandbox.paypal.com/cgi-bin/webscr?cmd=_notify-validate&#{@query}"
body = request.body.string
result = RestClient.post url, body
end
有一些PayPal宝石,至少其中一个(paypal-sdk-rest)包括PayPal::SDK::Core::API::IPN.valid?
方法。
以下是如何使用它:
class YourController < ApplicationController
skip_before_action :verify_authenticity_token, only: :your_action
def your_action
verified = PayPal::SDK::Core::API::IPN.valid?(request.raw_post)
if verified
# Verification passed, do something useful here.
render nothing: true, status: :ok
else
# Verification failed!
render nothing: true, status: :unprocessable_entity
end
end
end
live = 'https://ipnpb.paypal.com/cgi-bin' sandbox = 'https://ipnpb.sandbox.paypal.com/cgi-bin' uri = URI.parse(sandbox + '/webscr?cmd=_notify-validate')
- Maayan Naveh