How to return body from NPM request?

#npm #request #returnBody

Hey there wixers, I’ve been working around with the npm modules but I’m somehow stuck with the request module.

I managed to create a backend function that makes a request to a 3rd party APi and gets a response (as indicated here ) BUT I cannot get the body variable to travel back to the front end. I tried using a callback but it only appears to work within the backend code and not on the page code.

Can you please give it a look?

PAGE CODE

import { charge } from 'backend/authorizeNET';

export async function buttonPay_click(event) {
 let customerID, amount, cardNumber, cardName, cardCVC, cardMonth, cardYear, newData, bodyOut;

    customerID = $w("#customerID");
    amount = $w("#amount");
    cardNumber = $w("#cardNumber");
    cardName = $w("#cardName");
    cardCVC = $w("#cardCVC");
    cardMonth = $w("#cardMonth");
    cardYear = $w("#cardYear");

 if (customerID.valid && cardNumber.valid && cardMonth.valid && cardYear.valid && cardCVC.valid && cardName.valid && amount.value > 0) {
 bodyOut = charge(customerID.value, amount.value, cardNumber.value, cardMonth.value, cardYear.value, cardCVC.value);
 //I want to use the body
    } else {
        console.log("oops!");
    }
}

BACKEND

var request = require("request");

export function charge(policyNumber, amount, cardNumber, cardMonth, cardYear, cardCVC) {

 const apiLogin = "xxxx"; //Sandbox
 const transactionKey = "yyyy"; //Sandbox
 const url = "https://apitest.authorize.net/xml/v1/request.api/createTransactionRequest"; //Sandbox
 //const url = "https://api.authorize.net/xml/v1/request.api/createTransactionRequest"; //Live

 var options = {
        method: 'POST',
        url: url,
        headers: {
 'cache-control': 'no-cache',
 'Content-Type': 'application/json'
        },
        body: {
            createTransactionRequest: {
                merchantAuthentication: { name: apiLogin, transactionKey: transactionKey },
                transactionRequest: {
                    transactionType: 'authCaptureTransaction',
                    amount: amount,
                    payment: {
                        creditCard: {
                            cardNumber: cardNumber,
                            expirationDate: cardYear + '-' + cardMonth,
                            cardCode: cardCVC
                        }
                    },
                    customer: { id: policyNumber }
                }
            }
        },
        json: true
    };

    doRequest(options, function (val) {
        console.log("Body : ", val);
        //Val is the variable I want to use in the page code. 
        return val;
    });

}

function doRequest(options, callback) {
    request(options, function (error, response, body) {
        console.log('error:', error); // Print the error if one occurred
        console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
        console.log(body); 
        callback(body);
    })
}

Thanks!

Hey

Frontend:
Don’t you need to await the charge call?

bodyOut = await charge(customerID.value, amount.value, cardNumber.value, cardMonth.value, cardYear.value, cardCVC.value);

Backend:
Sometimes even the function calling something that will be returned needs to have return in front.

return doRequest(options, function (val) {         
    console.log("Body : ", val); //Val is the variable I want to use in the page code.  
    return val; 
});

Are you sure you get the values you expect in the val variable?

Thanks @andreas-kviby I’ve tried the async / await but it doesn’t work. Also returning the function on the backend doesn’t work either… Any other thoughts?

@felipe-bustos
Are you sure that you placed the async/await syntax correctly?
I’m pretty sure it should work.
Roi.

@roi-bendet @andreas-kviby thanks guys. The issue was that the request module does not support async await. I had requested the addition of request-promise and it is now available. Upon changing it it works like a charm.

Cheers!

Hi Felipe,

I am having exactly the same issue, and so I guess I also need to move from the npm request module to request-promise npm module. I see that it is available for loading in Wix.

btw, do you also have to install the bluebird module, as request-promise depends on it?

I would very much appreciate if you could share the code as to how you modified the above to use the request-promise package - would save me lots of research time!

Kind Regards!

@curator here you go :slight_smile: sorry the format but I’m on the phone.

//var request = require(“request”); //doesn’t work with async await
var request = require (“request-promise”);
let bodyOut;
export async function charge(policyNumber, amount, cardNumber, cardMonth, cardYear, cardCVC, billToData) {
//const apiLogin = “XXXXXX”; //Sandbox
const apiLogin = “XXXXXXX”; //Live
//const transactionKey = “XXXXXX”; //Sandbox
const transactionKey = “XXXXX”; //Live
//const url = " https://apitest.authorize.net/xml/v1/request.api/createTransactionRequest"; //Sandbox
const url = " https://api.authorize.net/xml/v1/request.api/createTransactionRequest "; //Live
let out = “nothing”;
var options = {
method: ‘POST’,
url: url,
headers: {
‘cache-control’: ‘no-cache’,
‘Content-Type’: ‘application/json’
},
body: {
createTransactionRequest: {
merchantAuthentication: { name: apiLogin, transactionKey: transactionKey },
transactionRequest: {
transactionType: ‘authCaptureTransaction’,
amount: amount,
payment: {
creditCard: {
cardNumber: cardNumber,
expirationDate: cardYear + ‘-’ + cardMonth,
cardCode: cardCVC
}
},
customer: { id: policyNumber },
billTo: {
firstName: billToData.firstName,
lastName: billToData.lastName,
address: billToData.address,
city: billToData.city,
state: billToData.state,
zip: billToData.zip
}
}
}
},
json: true
};
out = await request(options, function (error, response, body) {
/console.log(‘error:’, error);
console.log(‘statusCode:’, response && response.statusCode);
console.log(“Body:”, body);
/
})
//console.log(“out”,out);
return out
}

@felipe-bustos , wow, thanks so much for sending this over. /this is a real help.

Kind regards, Tom