Syed Galib
Syed Galib

Reputation: 13

Sabre Dev Studio API call by Javascript

I am trying to make a web application of Sabre Dev Studio using there Rest API. I am using javascript. I collected the required access tokens and client secret for the app .
I wrote this code to send an api request:

var clientId = "V1:abcD123:OPQRST:UVW";
var clientSecret = "aBcdEfG";

// Using jQuery Plugin for Encoding
var authorizationBasic = $.base64.btoa(clientId + ':' + clientSecret); 
authorizationBasic = $.base64.btoa(authorizationBasic);

var request = new XMLHttpRequest();
request.open('POST', 'https://api.sabre.com/v2/auth/token HTTP/1.1', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.setRequestHeader('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36');
request.setRequestHeader('Origin', 'chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo');
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', '*/*');
request.send("grant_type=client_credentials");

request.onreadystatechange = function () {
    if (this.readyState === 4) {
       alert(this.responseText);
    }
};

If the request is valid, the API will send a response that contains the access token else it shuld give me an error massage object. But in my case I dont receive anything. The alert function shows me a blank alert window. I dont know where is the problem. Can anyone help me to this problem?

Upvotes: 1

Views: 641

Answers (2)

Dave Cole
Dave Cole

Reputation: 2775

FWIW after banging my head against a wall for a while I wrote a general-purpose authentication method using fetch() if anyone needs it. It returns a promise with the JSON object the auth api returns.

static authenticate(clientId, clientSecret, baseURL = 'https://api.test.sabre.com/', apiPath = 'v2/auth/token') {

    let authToken = {};

    return fetch(`${baseURL}${apiPath}?grant_type=client_credentials`, {
        method: 'POST',
        headers: {
            'Accept': '*/*',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic ' + window.btoa(window.btoa(clientId) + ':' + window.btoa(clientSecret))
        }
    }).then((response) => response.json()).then(response => {
        if (response){
            return Promise.resolve(response);

        } else {
            console.error('SabreAPI authenticate Error - no response');
            return Promise.reject(response);
        }


    }).catch(error => {
        console.error('SabreAPI authenticate Error: '+error);
        return Promise.reject(error);
    });
}

Usage:

authenticate('myId', 'mySecret').then(response => {
   let authToken = {};
   authToken.access_token = response.access_token;
   authToken.expires_in = response.expires_in;
   authToken.token_type = response.token_type;
   authToken.expiration_datestamp = new Date(new Date().getTime() + 1000 * (response.expires_in));
}).catch(error => {
   ... do whatever you want to catch the error
});

After that you can do regular fetch GET/PUT/POST/DELETE calls by passing 'Bearer': authToken.access_token in the header; you might need to escape it first, not positive on that one.

Upvotes: 1

Giancarlo
Giancarlo

Reputation: 1429

I'm not a javascript expert, but I see at least 2 errors:

  1. var authorizationBasic = $.base64.btoa(clientId + ':' + clientSecret);
    You need to do base64 to the clientId and clientSecrect separately, and then to both together with a colon in between

  2. request.open('POST', 'https://api.sabre.com/v2/auth/token HTTP/1.1', true);
    I am not sure you can define the HTTP that you'll be using in the URL string, and it does not seem to be required either.

Below is a function that I've tested successfully:

function doFunction() {
    var clientId = "V1:abcD123:OPQRST:UVW";
    var clientSecret = "aBcdEfG";
    var authorizationBasic = window.btoa(window.btoa(clientId) + ':' + window.btoa(clientSecret));
    request = new XMLHttpRequest();
    var url = "https://api-crt.cert.havail.sabre.com/v2/auth/token";
    request.open("POST", url, true);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Authorization", "Basic " + authorizationBasic);
    var payload = "grant_type=client_credentials";

    request.send(payload);

    request.onreadystatechange = function () {
        if (request.readyState == 4 && request.status == 200) {
            alert(request.responseText);
            document.getElementById("txt").value = request.responseText;
        }
    }
}

Upvotes: 2

Related Questions