Connect Salesforce REST API Using JavaScript
const requestData = {
'transId': 'NEFT0123456789',
'transAmount': 20500.50,
'transDate': '25/10/2022',
'transRemark': 'M400 Payment message',
};
const tokenURL = 'https://XXXXXXX.sandbox.my.salesforce.com/services/oauth2/token';
const payloadURL = 'https://XXXXXXX.sandbox.my.salesforce.com/services/apexrest/M400_SFReceiver';
const grant_type = 'password';
const client_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const client_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const username = 'XXXXXXXXXXXXXXXXXXXXXXXXXX';
const password = 'XXXXXXXXXXXXXXXXXXXXX';
fetch(tokenURL + '?grant_type=' + grant_type + '&client_id=' + client_id + '&client_secret=' + client_secret + '&username=' + username + '&password=' + password, {
method: 'POST'
})
.then(resp => resp.json())
.then(json => {
sfdcToken = json.access_token;
this.doM400_APICall(sfdcToken, requestData);
})
.catch(err => {
console.log(err);
const sfdcResponse = document.getElementById('sfdcResponse');
sfdcResponse.innerHTML = err;
});
function doM400_APICall(accessToken, requestBody) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", payloadURL, false);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xmlhttp.send(JSON.stringify(requestBody));
document.getElementById("sfdcStatus").innerHTML = "<font color='green'>Status: " + xmlhttp.status + " " + xmlhttp.statusText + "</font>";
document.getElementById("sfdcResponse").innerText = xmlhttp.responseText;
}
Comments
Post a Comment