Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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?

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");
      }
    }
  );
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda