How to properly initialize WebRtcSDK

Hello everyone, I am trying to use the SDK API and WebRtcSDK in a javascript in the test html page we are making for a client of ours. My team and I are on our first experience with GenesysCloud so we are probably doing something wrong. Our test page downloads the following javascript from the network, which is then executed by the browser:
https://sdk-cdn.mypurecloud.com/javascript/latest/purecloud-platform-client-v2.min.js
https://sdk-cdn.mypurecloud.com/webrtc-sdk/v8/genesys-cloud-webrtc-sdk.bundle.min.js

The initialisation and authentication of the "platformClient.ApiClient" works correctly, but we are unable to complete the initialisation of the GenesysCloudWebrtcSdk. Looking through the various examples available, we cannot figure out what we are doing wrong.

  <!-- this code is included in our "index.html" page -->
  <script src="https://sdk-cdn.mypurecloud.com/javascript/latest/purecloud-platform-client-v2.min.js"></script>
  <script src="https://sdk-cdn.mypurecloud.com/webrtc-sdk/v8/genesys-cloud-webrtc-sdk.bundle.min.js"></script>
  <script language="javascript" type="text/javascript">
    // Obtain a reference to the platformClient object
    const platformClient = require('platformClient');
    const client = platformClient.ApiClient.instance;
    client.setEnvironment(platformClient.PureCloudRegionHosts.eu_west_1);
    const clientId = 'xxxxxxxxxxxxxx';
    let currentUser;
    let currentToken;
    let webRtcSDK;
    client.loginImplicitGrant(clientId, "https://our_secure_redirect_uri")
      .then((data) => {
        console.log(data);
        // Do authenticated things: we tried to subscribe notifications and init webRtcSDK
        currentToken = data.accessToken;

        let usersApiInstance = new platformClient.UsersApi();
        usersApiInstance.getUsersMe()
          .then((data) => {
            console.log(`getUsersMe success! data: ${JSON.stringify(data, null, 2)}`);
            currentUser = data;
			// KO
            initWebRtcSDK();
			// successfully completed
            openSubscriptions();
          })
          .catch((err) => {
            console.log("There was a failure calling getUsersMe");
            console.error(err);
            handleCriticalError(err);
          });

      }).catch((err) => {
        // Handle failure response
        console.log('Errore: ' + err);
      });

    function initWebRtcSDK() {
      webRtcSDK = new window.GenesysCloudWebrtcSdk.GenesysCloudWebrtcSdk({
        accessToken: currentToken,
        organizationId: 'yyyyyyyyyyyyyyyyyyyyyyyyyyy',
        environment: 'mypurecloud.ie'
      });
		// NONE of these footprint was available on Chrome console
      webRtcSDK.on('sdkError', (event) => {
        console.log("Event error -> " + event);
      });
      webRtcSDK.on('pendingSession', (event) => {
        console.log("Event pendingSession -> " + event);
      });
      webRtcSDK.on('sessionStarted', (event) => {
        console.log("Event sessionStarted -> " + event);
      });
      // so we tryied to start a new softphone session on current user phone: but we have an error inside Genesys Javascript on sessionManager and/or SessionTypes
     initSoftphoneSessionAsync(webRtcSDK);   

    }

    async function initSoftphoneSessionAsync(webRtcSDK) {
      const x = await webRtcSDK.startSoftphoneSession({ phoneNumber: 4010 });
      console.log('Invoke result '+x); 
    }
	
	// some other js functions not needed for current scenario
	</script>

Hi @filippo.galbusera,

I will take a look at this and some of our own implementations and try to find a discrepancy. Will report back hopefully with a solution.

Hi @filippo.galbusera
Just wanted to make sure I understand. You mentioned above that the initialization and authentication of the "platformClient.ApiClient" works correctly. You ended up getting the `getUsersMe success!..." message?

Correct! Platform API init step is successfully completed, I can retrieve my connected user (stored into "currentUser" variable), but then function "initWebRtcSDK" fails.
In the first release of our code we didn't call the method "startSoftphoneSession", but we didn't found any log generated by "webRtcSDK". After adding webRtcSDK.startSoftphoneSession(....) invocation we received the following error:

client.ts:343 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'startSession')
at k. (client.ts:343:48)
at b (runtime.js:63:40)
at Generator._invoke (runtime.js:294:22)
at Generator.next (runtime.js:119:21)
at i (asyncToGenerator.js:5:20)
at s (asyncToGenerator.js:27:9)
at asyncToGenerator.js:34:7
at new Promise ()
at new t (export.js:16:24)
at k. (asyncToGenerator.js:23:12)

Instead our function "openSubscriptions" worked properly (we opened a wss connection and subscribed a set of items for notification).
As you can see the error we get seems to be in "client.ts" file retrieved from the net...but we cannot understand of to fix it.
Thanks a lot for your time

Hi @filippo.galbusera

I believe I found out what was going on with the initialization of the SDK.

You and your team did things correctly regarding the setup with new window.GenesysCloudWebrtcSdk.GenesysCloudWebrtcSdk({...}) and the setting up of event listeners. However, there was one line missing from this and that is webRtcSDK.initialize({...}). This function will help set up the session manager which will actually handle the emission of some of the events you were listening for and expecting such as pendingSession and sdkError. I was testing things locally in a StackBlitz and after adding the initialize line, I was now receiving the events (albeit only the sdkError event but I was seeing it reacted to for the first time). You can see in the console of the StackBlitz that I kept getting a 401 error probably due to the fact that when I called initialize, I passed in an empty object because I wanted to see if that would work at all. I will continue digging to hopefully be able to make a suggestion on the 401s but this should at least get the SDK fully initialized.

(NOTE: A lot of things were removed in the StackBlitz, that was just for testing purposes

Edit 2: There is a chance if you supply a proper token (that gets fetched from platformClient in your current code), then you may not need to supply any params when calling the initialize function.

HI @maxwellmooney13
Adding the "initialize" function invocation we can proceed with our page initialization.
However, now we still received the previos error with startSession on sessionManager, but we have some new 403 responses: maybe some permissions on our application is missing...
The "startSoftphoneSession" method invocation still fails:

Our application scope config is:
application_scopes

Current revised init function:

function initWebRtcSDK() {      
      webRtcSDK = new window.GenesysCloudWebrtcSdk.GenesysCloudWebrtcSdk({
        accessToken: currentToken,
        organizationId: 'xxxxxxxxxxxxxxxxxxxx',
        environment: 'mypurecloud.ie'  
      });
      console.log('WebRTC SDK inited.');
      webRtcSDK.on('sdkError', (event) => {
        console.log("Event error -> " + event);
      });
      webRtcSDK.on('pendingSession', (event) => {
        console.log("Event pendingSession -> " + event);
      });
      webRtcSDK.on('sessionStarted', (event) => {
        console.log("Event sessionStarted -> " + event);
      });
      webRtcSDK.initialize();
      initSoftphoneSessionAsync(webRtcSDK);
    }

    async function initSoftphoneSessionAsync(webRtcSDK) {
      console.log('Call startSoftphoneSession method...');      
      const x = await webRtcSDK.startSoftphoneSession({ phoneNumber: 4010 });
      console.log('startSoftphoneSession invocation returned: '+x); // 10
    }

Maybe we're missing something else ?

Thanks a lot for your time

Hi @maxwellmooney13
we have resolved the issue with the first error.

We have changed our "initialize" function invocation to:

webRtcSDK.initialize().then(() => {
        // the web socket has connected and the SDK is ready to use
        console.log('WebRTC SDK inited.');

        // now this call successfully open a phone session with the configuered number
initSoftphoneSessionAsync(webRtcSDK);
        //TODO: some GUI actions, now WebRTCSDK is properly started
});

We need to wait for "initialize" function complection before ask to start a new phone session...

Also all 403 responses have been removed changing our "OAuth" scopes as follows:

application_scopes_changed

This scope config raises some questions about the behavior of the "diagnostic scope".
The admin GUI in fact does not provide a "diagnostic" scope, but we found a suggest to change authorization to authorization:readonly and our 403 issue magically solved...
However I suppose it is a better idea, to seek/start another discussion to investigate this argument.

Thanks a lot for your support

Hi @filippo.galbusera

I was actually going to suggest awaiting the initialize function whether with async/await or with the .then(...) as you above. Unfortunately I was having some difficulty getting things set up my end so I wasn't able to confirm. But it sounds like things for the most part are good? Glad to hear! Since there may be a new issue/discussion raised, would you consider this one good and handled?

Thank you for your time and patience in the matter!

Hi @maxwellmooney13
we can consider this topic closed!
We'll search/start another discussion about diagnostic scope/tracing javascript function; we need to understand how they can be used for trouble shooting in a production environment.

Thanks

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