0

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?

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");
      }
    }
  );
});
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I don't quite understand. This is a request callback for what looks like an express server. Where else would you expect to use the request data? Show your client-side function that actually calls the `fetch` if that's what you are asking about. – zero298 Sep 09 '21 at 15:12
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – zero298 Sep 09 '21 at 15:12
  • @zero298 i have comment where i want that amount variable data now please if you can help me – AnonymousKing Sep 09 '21 at 15:20
  • Can you also show how you want to use it outside of this function? We don't need a ton of detail, but we do need an [mre]. – zero298 Sep 09 '21 at 15:22
  • i want to use the value in app.get("/success", (req, res)) – AnonymousKing Sep 09 '21 at 15:28

1 Answers1

0

It's very unclear from your question, but it seems like you just want to have access to amount from outside the response callback. 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. I'm also renaming "ammount" to "amount" (it's misspelled).

Whenever a POST is made to app.post("/pay"), we push a payment. payments is available to app.get("/success") because it is in a higher scope.

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.

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
zero298
  • 25,467
  • 10
  • 75
  • 100