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?