如何使用Node.js支付宝结账集成

452 阅读2分钟

开始使用Node.js支付宝结账集成

PayPal是一个在线支付平台,允许用户在全球范围内转移资金。PayPal使商家更容易通过其网站接受在线支付。PayPal为Visa和Mastercard的付款提供处理。

我们将学习如何将Paypal结账集成到Node.js应用程序中。我们还将渲染一个响应,在用户的交易被取消时通知用户。

项目设置

创建一个名为paywave 的目录。通过执行下面的命令,将工作目录改为上面创建的paywave 目录。

$ mkdir paywave
$ cd paywave

要在我们上面创建的paywave 目录中创建一个Node.js应用程序,执行下面的命令。

$ npm init
  • npm init 命令将 文件添加到我们的 目录,使其成为一个Node.js应用程序。package.json paywave

执行下面的命令,将express ,和paypal-rest-sdk 安装到我们的项目中。

$ npm i express
$ npm i paypal-rest-sdk
  1. paywave 目录中,创建一个名为index.js 的新文件。
  2. 将下面的代码片段添加到上面创建的index.js 文件中。
const express = require('express');
const paypal = require('paypal-rest-sdk');

paypal.configure({
  'mode': 'sandbox', //sandbox or live
  'client_id': '####yourclientid######',
  'client_secret': '####yourclientsecret#####'
});

const app = express();

app.get('/', (req, res) => res.sendFile(__dirname + "/index.html"));


app.listen(PORT, () => console.log(`Server Started on ${PORT}`));

要获得client_idclient_secret ,请登录你的PayPal开发者账户,并创建一个新的应用程序,如下图所示。

Paypal create a new app

创建应用后,点击应用名称,导航到应用的详细信息页面,在那里你将获得client_idclient_secret

在应用程序的详细信息页面,将client_idclient_secret 复制到我们上面创建的index.js 文件中。

Paypal secrete and Id

创建一个沙盒账户

选择侧边栏上的账户菜单项,如下图所示。

Paypal account section

创建一个新的账户,你将在沙盒账户中进行支付时使用。

Paypal creating account

结账视图

  1. paywave 目录中,创建一个名为index.html 的文件。
  2. 将下面的代码片段添加到index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>PayPal Node App</title>
</head>
<body>
  <h1>Nike shoes </h1>
  <h2>Buy For $25</h2>
  <form action="/pay" method="post">
    <input type="submit" value="Buy">
  </form>
</body>
</html>

上面的代码片断向用户展示了项目的名称、购买按钮和它的价格。每当用户点击购买按钮时,将启动Paypal结账。

支付处理程序

index.js 文件中,添加下面的代码片段。

app.post('/pay', (req, res) => {
  const create_payment_json = {
    "intent": "sale",
    "payer": {
        "payment_method": "paypal"
    },
    "redirect_urls": {
        "return_url": "http://localhost:3000/success",
        "cancel_url": "http://localhost:3000/cancel"
    },
    "transactions": [{
        "item_list": {
            "items": [{
                "name": "Redhock Bar Soap",
                "sku": "001",
                "price": "25.00",
                "currency": "USD",
                "quantity": 1
            }]
        },
        "amount": {
            "currency": "USD",
            "total": "25.00"
        },
        "description": "Washing Bar soap"
    }]
};

paypal.payment.create(create_payment_json, function (error, payment) {
  if (error) {
      throw error;
  } else {
      for(let i = 0;i < payment.links.length;i++){
        if(payment.links[i].rel === 'approval_url'){
          res.redirect(payment.links[i].href);
        }
      }
  }
});

});

上面的代码片断包含了Paypal用来启动交易的支付细节。如果付款启动成功,那么用户将看到下图所示的页面,以完成交易。

Complete transaction

成功交易处理程序

每当交易成功时,我们应该从Paypal获得交易细节。从Paypal获得的交易细节可以保存在数据库中,供将来参考。在我们的案例中,我们在终端打印交易日志。

index.js 文件中,添加下面的代码片段,以便在交易成功时从Paypal获得交易细节。

app.get('/success', (req, res) => {
  const payerId = req.query.PayerID;
  const paymentId = req.query.paymentId;

  const execute_payment_json = {
    "payer_id": payerId,
    "transactions": [{
        "amount": {
            "currency": "USD",
            "total": "25.00"
        }
    }]
  };

// Obtains the transaction details from paypal
  paypal.payment.execute(paymentId, execute_payment_json, function (error, payment) {
      //When error occurs when due to non-existent transaction, throw an error else log the transaction details in the console then send a Success string reposponse to the user.
    if (error) {
        console.log(error.response);
        throw error;
    } else {
        console.log(JSON.stringify(payment));
        res.send('Success');
    }
});
});

如果交易成功,那么将向用户显示一个成功页面,如下图所示。

Paypal checkout success

交易取消

当用户取消交易时,我们需要渲染一个响应,告知用户交易已成功取消。为了处理取消交易,请将下面的代码片段添加到index.js 文件中。

app.get('/cancel', (req, res) => res.send('Cancelled'));
  • 只要交易取消成功,上述路由就会向用户返回一个Cancelled 的字符串。

总结

现在你已经学会了如何将Paypal结账集成到Node.js应用程序中,在我们创建的应用程序中添加一个成功和错误页面。