如何将用户关联到 IPN

How to associate user to IPN

我正在使用 rails 创建一个应用程序,用户可以使用 paypal 通过投币。我正在使用在 Paypal 网站上创建的通用立即购买按钮。我将按钮设置为向我网站上的 URL 提供 IPN。 以前我遇到过身份验证问题,但使用下面的代码我已经解决了。现在的问题是,当 IPN 通知控制器但会话被破坏时,我无法使用硬币。所以我的问题是如何 retrieve/keep 会话或用户,以便我可以将硬币添加到正确的帐户?

用户模型(相关部分):

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable, :omniauthable

# Gets the amount of coins the user currently has.
# @return The amount of coins the user has.
def get_coins
self.coins
end

# Adds an amount of coins to the user and saves to the database.
# @param amount The amount of coins to add to the user.
def add_coins(amount)
full_amount = amount + self.coins
self.coins = full_amount
self.save
end

IPN指向的控制器:

class PaymentNotificationsController < ApplicationController
before_action :authenticate_user!, :except => [:create]
# POST /payment_notifications
# POST /payment_notifications.json

def create
puts "made it here"
#PaymentNotification.create!(:params => params)
user =User.find(session[:user_id])
user.coins += 100
user.save!
render :nothing => true
end
end

目前上面的代码有一个错误说 "cant find user with id="

应用程序控制器:

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!
skip_before_filter :verify_authenticity_token
end

IPN 从 PayPal 服务器发送到您的服务器,与用户会话分开。这将是它自己的会话,所以这就是为什么您没有获得任何会话数据的原因。它没有被摧毁。这只是一个完全不同的会话。

如果您想传递用户 ID 以便它在 IPN 中返回,您可以在按钮代码中使用 "custom" 参数。它实际上称为 "custom",您可以在其中发送最多 256 个字符的任何内容。

所以将以下内容添加到您的按钮代码中...

<input type="hidden" name="custom" value="{user_id_value}" />

然后它将作为 $_POST['custom'].

在 IPN 中返回

另一种处理方法(这是我推荐的方法)是您可以在系统中创建发票记录,然后在将用户发送到 PayPal 之前,该记录会有相关的客户记录。然后您可以使用 "invoice" 参数将您的发票 ID 传递给 PayPal。这样它将包含在 PayPal 交易详细信息中,并在 PayPal 详细信息中提供一个很好的参考。

再一次,它会在 IPN 中作为 $_POST['invoice'] 返回,这样您就可以访问您的数据库以提取您需要的任何发票或相关客户详细信息,以便您可以在您的 IPN 脚本中使用它。