Search code examples
javascripttypescriptpaypalxmlhttprequestnativescript

Where to put Grant_Type in XHR


I tried to access my OAuth2 Token via XHR-Request in TypeScript. I keep getting either 400: {"error":"unsupported_grant_type","error_description":"Grant Type is NULL"}

I am making my call via a NativeScript Application (in TypeScript Template) running on an iOS emulator.

My code:

    var oReq = new XMLHttpRequest();     
    oReq.open("POST", "https://api.sandbox.paypal.com/v1/oauth2/token", true);
  //  oReq.withCredentials = true;
  //  oReq.setRequestHeader('grant_type', "client_credentials");
  // where client_credentials = clientID:secret 

    oReq.setRequestHeader('Authorization', "Basic " + this.authorizationBasic); 
//where AutorizationBasic is the base64 String of my credentials
    oReq.setRequestHeader('Accept', "application/json");
    oReq.setRequestHeader('Accept-Language', "en_US");

    oReq.onreadystatechange = function () {
        console.log("state changed - new state: " + oReq.readyState + " and Status: " + oReq.status);
        if (oReq.readyState === 4) {
            if (oReq.status === 200) {
                console.log(oReq.responseText);
            } else { 
                console.log("Error: " + oReq.status + " Message: " + oReq.responseText);
            } 
        }    
    };
    console.log("Status: " + oReq.status);  
    oReq.send();

After doing some research I found out, that some others had the same issue with the PayPal API (e.g. here). Did someone solve that issue? Is it perhaps my code that is just wrong? In the code above I commented some other things that I tried, nothing seems to work.

The API: https://developer.paypal.com/docs/integration/direct/make-your-first-call/

I am trying quite desperately since this is taking far too long to simple call that API. I tried the curl-command with my clientID + secret, which worked for me. Does anyone have an idea what to do? Is there perhaps an easier way than using XHR?


Solution

  • If someone else is searching for this:

    You need to provide the Grant Type as the body in xhr.send()-Method:

    xhr.send('grant_type=client_credentials');