简体   繁体   English

我如何使用此函数之外的金额变量,请任何人帮助我

[英]How can I use the amount variable outside this function please can any one help me

Please can anyone tell me how can I get the amount variable or its data which I am fetching from req.body outside of the this function?请谁能告诉我如何在此函数之外从req.body获取金额变量或其数据?

app.post("/pay", (req, res) => {
  console.log(req.body); 
  const { amount , description , name } = req.body;    //this is that amount variable
  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: name,
              sku: "001",
              price: amount,
              currency: "USD",
              quantity: 1,
            },
          ],
        },
        amount: {
          currency: "USD",
          total: amount,
        },
        description: description,
      },
    ],
  };

  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);
        }
      }
    }
  });
});

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: amount,    // I want it here also
        },
      },
    ],
  };

  paypal.payment.execute(
    paymentId,
    execute_payment_json,
    function (error, payment) {
      if (error) {
        console.log(error.response);
        ;
      } else {
        console.log(JSON.stringify(payment));
        res.send("Success");
      }
    }
  );
});

It's very unclear from your question, but it seems like you just want to have access to amount from outside the response callback.从您的问题中不清楚,但您似乎只想从响应回调外部访问amount If it is as plain as that, you just need to have a place for it in a higher scope.如果它像那样简单,您只需要在更高的范围内为其放置一个位置即可。 For example, I'm going to store all the payments in a payments array.例如,我要将所有付款存储在一个payments数组中。 I'm also renaming "ammount" to "amount" (it's misspelled).我还将“ammount”重命名为“amount”(拼写错误)。

Whenever a POST is made to app.post("/pay") , we push a payment.每当对app.post("/pay")进行POST ,我们都会推送付款。 payments is available to app.get("/success") because it is in a higher scope. payments可用于app.get("/success")因为它在更高的范围内。

If this isn't what you are trying to do, you need to add more details to your question and explain exactly what isn't working.如果这不是你想要做的,你需要在你的问题中添加更多细节,并准确解释什么不起作用。

index.js

import express from "express";

const app = express();

const payments = [];

app.use(express.json());

app.get("/", (req, res) => {
  res.send("Hello world");
});

app.get("/success", (req, res) => {
  console.log(`There have been ${payments.length} payments`);
  if (payments.length) {
    const {person, amount, time} = payments[payments.length - 1];
    console.log(`Last payment was ${amount} by ${person} @ ${time}`);
  }
  res.sendStatus(200);
});

app.post("/pay", (req, res) => {
  const {person, amount} = req.body;
  const time = Date.now();

  payments.push({person, amount, time});
  console.log(`${person} paid ${amount} @ ${time}`);

  res.sendStatus(200);
});

app.listen(3002, () => {
  console.log("Listening");
});

This is the file that I used to test with.这是我用来测试的文件。 It uses node-fetch as a fetch polyfill.它使用node-fetch作为fetch polyfill。

test.js

import fetch from "node-fetch";

const sleep = (t=1000) => new Promise(r => setTimeout(r, t));

const main = async () => {
  const payResponse = await fetch("http://localhost:3002/pay", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      person: "Bob Barker",
      amount: 500
    })
  });

  await sleep();

  const checkResponse = await fetch("http://localhost:3002/success");
};

main()
  .then(() => console.log("Done"))
  .catch(err => console.error(err));

Running it produces this:运行它会产生这个:

Listening
Bob Barker paid 500 @ 1631202912836
There have been 1 payments
Last payment was 500 by Bob Barker @ 1631202912836

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM