1

I would like to make a Basic HTTP authentication call request via javascript but I do not know how to do it.. I have a javascript code and inside of it there is a session parameter. Thus, I need to make first this call, get the session_id from this call as a response and continue my javascript code. This is the doc of this basic http auth: https://ibanke-commerce.nbg.gr/api/documentation/apiDocumentation/rest-json/version/latest/operation/Session%3a%20Create%20Checkout%20Session.html?locale=en_US

It is about payment option between bank and ecommerce.

How will this be written in javascript? My code structure is like this for now:

<script
//need call auth somewhere here I guess

Payment.Config({
... ... ..
Url: "...",
Name: "...",
session: "here I need the response of the call"
...
...
});
</script>

Any help/guidelines would be appreciated

Mario Shtika
  • 1,436
  • 19
  • 31

1 Answers1

1

You need three things:

1. Create you Basic Header for your authentication

The Basic Header is an Base64 encoded string of your user and password. To get that you should encode your credentials as shown below.

user_id:password

In you case user_id is the merchantId

You can use online services like this to encode your credentials strings

Or

You can encode it in your javascript code like this

var clientId = "user_id";
var clientSecret = "password";

// var authorizationBasic = $.base64.btoa(clientId + ':' + clientSecret); // jQuery
var authorizationBasic = window.btoa(clientId + ':' + clientSecret); // Javascript

I would recommend the first option.

2. Make your post request with the Basic Header

You can follow this answer on how to make an HTTP POST authentication basic request using Javascript

3. Use the response from the authentication request in your code

So your final code would be something like this

var url = 'your_url_server';
var authorizationBasic = 'the_created_basic_header';

var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'application/json'); // Modify according to the response format
request.send("parameter1=parameter1_value&parameter2=parameter2_value"); // Any parameter you might need

request.onreadystatechange = function () {
    if (request.readyState === 4) {
       alert(request.responseText);
       Payment.Config({
          ... ... ..
          Url: "...",
          Name: "...",
          session: request.responseText // Here is the response of the call
          ...
          ...
       });
    }
};
Mario Shtika
  • 1,436
  • 19
  • 31