masanchezmemo | 2018-11-09 03:32:41 UTC | #1
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) <!DOCTYPE html> <html> <head> <title></title> <!-- Librerias jquery--> <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script> <!-- SDK pure cloud--> <script type="text/javascript" src="https://sdk-cdn.mypurecloud.com/javascript/39.0.0/purecloud-platform-client-v2.min.js "></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- Instancia archivo a.js donde se realizan todas las funciones javascript--> <script type="text/javascript" src="a.js"></script> </head> <body> <h1>prueba 1</h1> <!-- Button that calls the log function on file a.js-->
<button onclick="log();">auntenticacion</button> <!--<button onclick="iniciar();">oauth</button>--> </body> </html>
(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 = { responsetype : "token", clientid : "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
tim.smith | 2018-11-09 14:46:08 UTC | #2
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.
masanchezmemo | 2018-11-09 17:24:43 UTC | #3
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
tim.smith | 2018-11-09 17:40:16 UTC | #4
masanchezmemo, post:3, topic:3949
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?
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
system | 2018-12-10 17:40:17 UTC | #5
This topic was automatically closed 31 days after the last reply. New replies are no longer allowed.
This post was migrated from the old Developer Forum.
ref: 3949