Webcallback in JavaScript

Hello there,

We need to activate a button in our webpage to process callbacks. So we first are trying to authenticate to send the callback request but we are having some issues.

My code is the following:

(index.html)

prueba 1

auntenticacion

(a.js)
const platformClient = require('platformClient');
//funcion que realiza la autenticacion
function log(){
//Funcion que separa el token de la url
function getToken(name) {
name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
var regex = new RegExp("[\#&]" + name + "=([^&#])"),
results = regex.exec(location.hash);
return results === null ? "" : decodeURIComponent(results[1].replace(/+/g, " "));
}
//Funcion que verifica si el token existe
function getParameterByName(name) {
name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
var regex = new RegExp("[\#&]" + name + "=([^&#]
)"),
results = regex.exec(location.hash);
//return results === null ? "" : decodeURIComponent(results[1].replace(/+/g, " "));
if(results == ""){
return false;
} else
return true;
}
}
var variable = window.location.hash;
var ifToken =getParameterByName(variable);
console.log(ifToken);
//condicional si el token existe(usuario autenticado)
if(window.location.hash) {
console.log(location.hash);
// var token = getParameterByName('access_token');
var token = getToken(variable);
// siga participante

        //funcion para obtener data del usuario logeado
        //Esta funcion no esta funcionando correctamente, sale que el usuario no esta autenticado
    $.ajax({
        url: "https://api.mypurecloud.com/api/v2/users/me",
        type: "GET",
        beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'bearer ' + token);},
        success: function(data) {
            console.log(data);
            createCallback(token);    
        },
        //verifica los errores existentes
        error: function(error){
            console.log(error);
        }
    });

    location.hash=''
    //condicional si el token no existe(usuario no autenticado)
} else {
    //credenciales
    var queryStringData = {
        response_type : "token",
        client_id : "af1b6a97-a9f7-445a-91a3-16c5afdc1dc0",
        redirect_uri : "http://localhost:8080/index.html"
    }
    //redireccionamiento a pagina de login
   window.location.replace("https://login.mypurecloud.com/oauth/authorize?" + jQuery.param(queryStringData));

}
}
//Funcion para crear callback
function createCallback(token) {

//const purecloud = new platformClient.UsersApi();
console.log(token);
//console.log(platformClient);
platformClient.ApiClient.instance.authentications['PureCloud Auth'].accessToken = token;
var apiInstance = new platformClient.ConversationsApi();
//datos para realizar el callback
var callbackData = {
"routingData": {
"queueId": "cc4b3399-4b27-45b3-9e31-1ff773ce5a1f"
},
"scriptId": "2f0762d0-a4c3-11e6-a1d5-4377309bca4f",
"callbackUserName": "Tutorial Callback",
"callbackNumbers": [
"3172222222"
],
"data":{
"customDataAttribute": "custom value"
}
}
// var conversationApi = new purecloud.platform.ConversationsApi(session);
apiInstance.postConversationsCallbacks(callbackData).then(function(callbackResponseData) {
console.log("Callback Created");
console.log(callbackResponseData);
})
//verifica errores
.catch(function(error) {
console.log(error);
});
}

The error we are having is:

Please your kindly help as usual.

Regards,

Mario

A 401 response means you're not passing the Authorization header with your request. Please refer to the JavaScript SDK Documentation for examples of how to authorize the SDK using the helper functions and how to set the access token manually if you're not using the helper functions for some reason.

1 Like

Hey Time, thank you as usual!!!! You are the one.

Now we solved the issue. One more thing, in order to avoid the web user to enter user and password to authenticate to PureCloud, how can we send the authentication hard coded to do so?

Regards,

Mario

PureCloud users must always authenticate with PureCloud. However, I'm guessing that your situation is that your website visitors aren't PureCloud users. There is no way to create a callback without making an authenticated API request. To allow your website visitors to create callbacks, you will need to have some kind of middleware sitting between your website and PureCloud; that could be the backend of your existing web server.

Your web service will have to handle the request from the website visitor and then make the PureCloud API request from its back-end. Your service can use client credentials to authenticate and make this request as long as that's done server-side. Under no circumstances should you do client credentials authentication in a browser; that exposes your client secret to the world and is literally giving away the credentials to access your org.

There's an example open source project that does this, and includes a chat widget that uses the service as well: https://github.com/MyPureCloud/public-stats-service

This topic was automatically closed 31 days after the last reply. New replies are no longer allowed.