Meteor应用程序中PayPal的IPN侦听器

IPN listener for PayPal in Meteor app

本文关键字:IPN 侦听器 PayPal 应用程序 Meteor      更新时间:2023-09-26

我遇到了一个问题。我正在尝试将PayPal按钮与流星应用程序集成。但为了获得完整的功能,我需要处理IPN。因为我至少要知道交易状态。我已经有了商业账户,我打开了路径上的IPN:

    http://domein.com/ipn

我试着使用PayPal文档,但也无济于事。我花了两天时间,仍然找不到任何有用的东西。也许有人知道如何在流星应用程序中实现IPN监听器?


编辑:Meteor 1.3+的更新

我发布了一个大大简化了流程的软件包。该包是planefi:paypal ipn监听器。

先安装后打包:

$ meteor add planefy:paypal-ipn-listener

然后,在服务器代码中:

import { IpnListener } from 'meteor/planefy:paypal-ipn-listener';
const listener = new IpnListener({ 
   path: '/mypath', 
   allow_sandbox: true // in development
});
listener.onVerified((err, ipn) => console.log(ipn));
listener.onError((err) => console.log(err));

有关更多选项,请参阅自述文件。

原始答案

为了弄清楚这一点,我也做了很多令人挠头的事。

首先,如果您还没有以下软件包,请添加它们。

meteor add meteorhacks:npm
meteor add meteorhacks:picker

如果你使用的是iron:router,那么你实际上不需要metrohacks:picker(见底部的更新)

在应用程序根目录中创建一个package.json(如果它还不存在),并添加以下内容来告诉metrohacks:npm需要安装哪些npm包:

{
  "paypal-ipn" : "3.0.0",
  "body-parser": "1.14.1",
}

在服务器代码中,配置Picker以正确解析JSON请求/响应:

const bodyParser = Meteor.npmRequire('body-parser');
Picker.middleware(bodyParser.urlencoded({ extended: false }));
Picker.middleware(bodyParser.json());

同样在服务器代码中,定义一个Picker路由来处理传入的IPN消息

Picker.route('/ipn', function(params, req, res, next) {
  res.writeHead(200);
  const ipn = Meteor.npmRequire("paypal-ipn");
  // create a wrapped version of the verify function so that 
  // we can verify synchronously
  const wrappedVerify = Async.wrap(ipn,"verify");
  let verified = false;
  // only handle POSTs
    if (req.method === "POST") {
    // PayPal expects you to immeditately verify the IPN 
    // so do that first before further processing:
        try {
            //second argument is optional, and you'll want to remove for production environments
            verified = wrappedVerify(req.body, {"allow_sandbox" : true});
        } catch (err) {
            // do something with error
        }
        if (verified === 'VERIFIED') {
            let payment = req.body;
            // do stuff with payment 
        }
    }
  res.end();
});

更新:如果你使用iron:router,你不需要使用Picker。你可以直接用iron:router定义一个仅限服务器的路由器,就像这样:

Router.map(function () {
    this.route('ipn', {
        path: '/ipn',
        where: 'server',
        action: function() {
            var ipn = Meteor.npmRequire("paypal-ipn");
            var wrappedVerify = Async.wrap(ipn, "verify");
            var request = this.request;
            var verified;
            if (request.method !== 'POST') {
              this.next();
            } else {
              try {
                verified = wrappedVerify(request.body, {"allow_sandbox" : true});
              } catch (error) {
                //do something with error
              }
              if (verified === "VERIFIED") {
                var payment = request.body;
                //do something with payment
              }
              this.next();
            }
        }
    });
  });