• Austin Villanueva
  • NEWBIE
  • 40 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 20
    Questions
  • 17
    Replies
Hi guys, can you help me figure it out because before it was working and I didn't change any code but now it stops working.
So before when I calling sforce.opencti.setSoftphonePanelVisibility({visible: true}); it works fine. 
but right it throws some error 
User-added image
as you can see there's nothing wrong with the result of the callback. It says success but it still doesn't work.
Does anyone of who come across this problem? Let me know if knows about.

Thank you.

Sincerely,
Austin
 
Hi, 

Right now SF doesn't support a task for a queue or group so what I decided to do is use cases.
so what I'm trying to do is create a public group.
after that, when there is an incoming call I will create a case but I don't want other users to see those cases if they are not a member of the public group that I created. 

How can I achieve it? I tried to use sharing rules for cases. but it doesn't work. The other users can still see the cases. 
What I did is 
case owned by members of Group : {public group name}
share with Group : {public group name}
I also uncheck the Grant Access Using Hierarchies to make sure that only members of this group can see the cases. Also, if I view the members of this rule it only shows the members that is supposed to appear but still the non member can still see it if I go to cases tab and select "All Open Cases"

Can someone help be about this case? or maybe somebody tried something similar to this? 
My target to create a list of call log cases that is private to the group to make an alternative to the task as a call log.

I hope you can help me. Thank you. 

- Austin


 
Hi everyone. In our company we are currently implementing the opencti for our customers.
So one of the feature that we want is to create a call log while or after the call is finish. 
I saw that I can use the 
sforce.opencti.screenPop({
                            type: sforce.opencti.SCREENPOP_TYPE.NEW_RECORD_MODAL, 
                            params: { entityName: 'Task'}
}); 

because I read something that a call log is the same as task but unfortunately this is not shareable. 
Only the one user can see the this call log that is not our customer wants. Is there any other way around that can solve this?
I tried to create a public group and assign the task but it's not working only contacts and lead can be assign or relate to the task.
Is there any open cti function that I can use regarding this issue? because this is a sample scenario we want. 
For example, there are list of phone numbers that the agents need to call, if the other agents already called this number there's no need to call
that number. and so agents need to know about it by having a call log that is visible to all assigned users in a open cti call center.

I hope you can help me about this. Thank you.

Austin
Why my other account can't login to developer forums? 
I'm getting this error. 

We can't authorize you because of an OAuth error. For more information, contact your Salesforce administrator.
You didn't complete the approval process before it expired. Please try again."

but the same account can login to developer account, only in forum I can't login. 
Also my other account which can login in both ways, I don't know why this is happening. Does anybody experience this?
HI guys, we are using the opencti api for our click to dial but we want to add an interface to create a case during calls,
so I found jsforce. but unfortunately, I can't use it it's getting me an error of No Access-Control-Allow-Origin. 
Our webphone is in different domain but opencti works fine because it is in iframe but I don't why jsforce is not working if opencti api works perfectly fine.
Is there anybody that use opencti along with jsforce? If you guys have ideas let me know. Thank you.
Hi everyone, How can I pass string to lightning search?
Is there a way similar to classic where we can pass a string instead of typing the search keyword? 
If there is any solution let me know. Our clients wants to do it in lightning instead of classic. 

Thank you.

Austin
Hi guys, is there a global search in Lightning similar to Classic that use &startURL=/_ui/search/ui/UnifiedSearchResults?str=valueToSearch ?.
If you know something please let me know. Thank you.

-Austin
Hi guys, I've been struggling why the opencti callback doesnt trigger.

Here is the situation that it works: 
If I put the url of our third party webphone in the call center definition as opencti adapter url. It works fine(all callbacks works) this use the absolute path to use the opencti api.

Now because we needed an email of the user each time the webphone refreshes, what I did is create a simple VisualForce page that gets email address using "{!$User.Email}"(because I can't access it in our site directly) then, inside the visual page I put a javacript code that changes the window location, using window.location="urlPathOfOurWebphone"+emailAddress; then it redirects the current iframe to our page but when I look at the logs in browser. The callbacks are not being called. There is no error but callbacks are not being called. 

Can you guys help me figure it out why? All I did was get the email and pass it to our url and do the redirect page. That's all but why the callbacks stops working. 

I hope you can help me guys. Thank you. 

-Austin

 
Hi guys, right now I'm struggling to get the email of the user from salesforce. 
Basically, my setup is, my current page is inside iframe of softphoneIFrame(this is the iframe use for opencti adapter url) 
if I use visualforce I can get the email by using {!$User.Email} but how can I achieve the same thing without using visualforce or apex,
I tried using the opencti api functions but there is no public function to get the logged in user's email address. I hope you can help me guys.

Thank you. 

Austin
Hi guys, I'm currently working on our integration with opencti, 
The issue is after I redirect the visual force to our (external page webphone) using window.location or window.location.href,
the opencti stops working but it is loaded successfully I think so because I checked it in browser debugger, it just stops running the enable click to dial. but if I put the external page webphone url as the opencti adapter url instead of the visual page(just to do the redirect), it works perfectly fine. 
The reason I want to do the redirect is because the Iframe in opencti always refresh each time the user switch page and we don't want our user to sign in again and again in our system. so my solution is to pass the email address of the user, but I can't access it with our site alone so I used the visualforce page to get the email and pass it as parameter to our site, and our site includes the opencti javascript url, so it should work but It's not working( the opencti js calls)

but as you can see the opencti stops working when I do the redirection but works if I put the direct url of our webphone. 
If you guys face the same issue, please help me guys. Thank you. 
all I need to accomplised is to avoid our user to login to our system each time they switch pages in salesforce.


 
Hi guys, I'm new to Salesforce Open CTI integration, I just wanna ask about the call center definition file,
Is every user can access the call centers or only certain users can access those? 
If so, what access right do they need to access the call centers? 
 
I'm thinking if every user can create or import their own Call Center definition File. 

I hope you can help me about this guys. Thank you.
Hi guys, I'm pretty new to Open CTI and I wanted to do a click to dial but I don't want to create a softphone from scratch with VisualForce and Apex.
Is it possible to use the webphone that is host in different server or page instead of doing the visulaforce and apex? Because I already have the softphone and I just need it to embed in salesforce page. If so, how can I achieve it? 

I hope you can help me guys about this and thoughts and inputs are welcome. 
Thank you
Why I'm not getting the data from the connected app that I'm accessing? I have the right client_id and client secret and I put the "full access to the connected app" and in the users of the auth I can't see why my other account is not listed. Somebody please help me,
Why I got zero result in other account when I'm accessing other's connected app? I'm using SOQL with the host user account and I get the right result but when I use other account I succeeded in authentication with the right clientId and right clientsecret but when I do SOQL I got this 

{
    "done": true,
    "records": [],
    "totalSize": 0
}

When I'm using the HOST account which is the creator of the connected app I get the right result. Also, I put the "FULL ACCESS" when authentication is success and yet no result.

Can somebody help me? I use two developer's edition account.

 
I'm trying to access a connected app through api. I created two accounts as developer account. Now, when I try to use the first account which is the account that has the "connected app" it works fine. it gets the access token and data. 

After that, I try to access the "connected app" with the other account which is developer account also. I use the "CONSUMERKEY" and "CONSUMER_SECRET" of the connected app like the other account to access it and I use the account's OWN"SECURITY_TOKEN' 

I thought at first that security token is universal also like the client_id and client_secret but it's not so I used different "SECURITY_TOKEN" for each account.

when I execute the code with the second account authentication is success but there is no data. no result. 
{
    "done": true,
    "records": [],
    "totalSize": 0
}

but in my first account there is resul. I wanted to get the data of a contact that I made for testing. but why I didn't get any result from other account???? I also put "Selected OAuth Scopes" as Full access(full). 

I also want to understand how other users access the connected app if you guys can explain please let me know. 
I am integrating salesforce to our web app so I need to know how it works. 

Thank you.!         
 
I am having a problem of accessing the code or access_token when the user successfully log in, javascript doesn't allow me to access the
window.location.href property so that I can get the access_token or authorization_code so that I can continue and make a soql query.
I also tried to use the username and password authentication it works but I'm not sure if using this authentication will need the 
account of the person's USERNAME and PASSWORD who create the connected app just to log in? Also, it requires the SECURITY_TOKEN, 
Is this security token universal to the user's who want to log to the connected app? 

I hope you can help me because I'm not sure about how the other users can access the connected app using the username password if this is the only way I could do if I accessing the url of the pop up window is not possible. 
I am trying to get the access token but always get 
{"error":"unknown_error","error_description":"retry your request"} 
in java platform 1.7 

but then I just tried to changed it to java 1.8 and it works fine and I get the right response with the access token.

so my question is why is it like that? do I need to use 1.8 to do the http request? and there is no option if I used java 1..7?
I've been struggling to do authentication and get the accesskey in java.

I did it with different web services and I didn't get any problem. 

but for some reason the http call to salesforce always give me a response of 
{"error":"unknown_error","error_description":"retry your request"}

then, I just tried to changed the platform to java 8 and it works fine. I'm using java 7 in other web services and it works but salesforce need to use java 8? Is that it? 
I'm trying to authenticate and get token access using java. I first use httpayncclient and it works fine in my laptop
I also use curl and it works fine

but I doesn't work in my workplace. I used the curl command in my workstation and it works fine. No problem.

I try to changed the httpclient I use and try okhttpclient

It works fine with my laptop and again it doesn't work in my workstation. 

I already try to call http request with other services using their api and there is no problem. That's what I really don't know why it doesnt work 
and we are not using any proxy. 

I hope someone there can help me about this issue. 

Thank you. 

Sincerely,
Austin
I try it with curl and it works but I don't know why it doesn't work on my workplace
curl -v https://login.salesforce.com/services/oauth2/token -d "grant_type=password&client_id={clientid}&client_secret={clientsecret}&username={emailadd}&password={password+securityToken}" -H "Content-Type:application/x-www-form-urlencoded"

I also try it in my own laptop and it works. That's what I don't understand. I used the same jar file for httpclient for both pc and in my laptop it works but not on my work place. Is there any other reason why it doesn't work this is the sample code


CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();
    
    String authenticationUrl = "https://login.salesforce.com/services/oauth2/token";
    
    // authentication
    HttpPost requestPost = new HttpPost(authenticationUrl);
    requestPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    requestPost.setHeader("Accept", "application/json");
    
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("grant_type", "password"));
    params.add(new BasicNameValuePair("client_id", client_id));
    params.add(new BasicNameValuePair("client_secret", client_secret));
    params.add(new BasicNameValuePair("username", username));
    params.add(new BasicNameValuePair("password", password+securityToken));
    requestPost.setEntity(new UrlEncodedFormEntity(params));
    HttpResponse response = client.execute(requestPost, null).get();
    
    
    System.out.println("Status code:" + response.getStatusLine().getStatusCode());
    System.out.println("Entity: " + response.getEntity().getContent().toString());
    
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    System.out.println(responseString);
 
Hi guys, is there a global search in Lightning similar to Classic that use &startURL=/_ui/search/ui/UnifiedSearchResults?str=valueToSearch ?.
If you know something please let me know. Thank you.

-Austin
I'm trying to authenticate and get token access using java. I first use httpayncclient and it works fine in my laptop
I also use curl and it works fine

but I doesn't work in my workplace. I used the curl command in my workstation and it works fine. No problem.

I try to changed the httpclient I use and try okhttpclient

It works fine with my laptop and again it doesn't work in my workstation. 

I already try to call http request with other services using their api and there is no problem. That's what I really don't know why it doesnt work 
and we are not using any proxy. 

I hope someone there can help me about this issue. 

Thank you. 

Sincerely,
Austin
Hi guys, can you help me figure it out because before it was working and I didn't change any code but now it stops working.
So before when I calling sforce.opencti.setSoftphonePanelVisibility({visible: true}); it works fine. 
but right it throws some error 
User-added image
as you can see there's nothing wrong with the result of the callback. It says success but it still doesn't work.
Does anyone of who come across this problem? Let me know if knows about.

Thank you.

Sincerely,
Austin
 
Hi, 

Right now SF doesn't support a task for a queue or group so what I decided to do is use cases.
so what I'm trying to do is create a public group.
after that, when there is an incoming call I will create a case but I don't want other users to see those cases if they are not a member of the public group that I created. 

How can I achieve it? I tried to use sharing rules for cases. but it doesn't work. The other users can still see the cases. 
What I did is 
case owned by members of Group : {public group name}
share with Group : {public group name}
I also uncheck the Grant Access Using Hierarchies to make sure that only members of this group can see the cases. Also, if I view the members of this rule it only shows the members that is supposed to appear but still the non member can still see it if I go to cases tab and select "All Open Cases"

Can someone help be about this case? or maybe somebody tried something similar to this? 
My target to create a list of call log cases that is private to the group to make an alternative to the task as a call log.

I hope you can help me. Thank you. 

- Austin


 
Why my other account can't login to developer forums? 
I'm getting this error. 

We can't authorize you because of an OAuth error. For more information, contact your Salesforce administrator.
You didn't complete the approval process before it expired. Please try again."

but the same account can login to developer account, only in forum I can't login. 
Also my other account which can login in both ways, I don't know why this is happening. Does anybody experience this?
Hi everyone, How can I pass string to lightning search?
Is there a way similar to classic where we can pass a string instead of typing the search keyword? 
If there is any solution let me know. Our clients wants to do it in lightning instead of classic. 

Thank you.

Austin
Hi guys, is there a global search in Lightning similar to Classic that use &startURL=/_ui/search/ui/UnifiedSearchResults?str=valueToSearch ?.
If you know something please let me know. Thank you.

-Austin
Hi guys, I'm new to Salesforce Open CTI integration, I just wanna ask about the call center definition file,
Is every user can access the call centers or only certain users can access those? 
If so, what access right do they need to access the call centers? 
 
I'm thinking if every user can create or import their own Call Center definition File. 

I hope you can help me about this guys. Thank you.
Why I'm not getting the data from the connected app that I'm accessing? I have the right client_id and client secret and I put the "full access to the connected app" and in the users of the auth I can't see why my other account is not listed. Somebody please help me,
I am trying to get the access token but always get 
{"error":"unknown_error","error_description":"retry your request"} 
in java platform 1.7 

but then I just tried to changed it to java 1.8 and it works fine and I get the right response with the access token.

so my question is why is it like that? do I need to use 1.8 to do the http request? and there is no option if I used java 1..7?
I'm trying to authenticate and get token access using java. I first use httpayncclient and it works fine in my laptop
I also use curl and it works fine

but I doesn't work in my workplace. I used the curl command in my workstation and it works fine. No problem.

I try to changed the httpclient I use and try okhttpclient

It works fine with my laptop and again it doesn't work in my workstation. 

I already try to call http request with other services using their api and there is no problem. That's what I really don't know why it doesnt work 
and we are not using any proxy. 

I hope someone there can help me about this issue. 

Thank you. 

Sincerely,
Austin
Here is my code:
 
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
public class HttpURLConnectionExample {
    String access="";
    String data = "";
    public static void main(String[] args) throws Exception {
        HttpURLConnectionExample http = new HttpURLConnectionExample();
            
        http.sendPost();
    }
    
    // HTTP POST request
    private void sendPost() throws Exception {
        String url = "https://login.salesforce.com/services/oauth2/token";
        URL obj = new URL(url);
        HttpsURLConnection con1 = (HttpsURLConnection) obj.openConnection();
        //add reuqest header
        con1.setRequestMethod("POST");
         con1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        String urlParameters =    "client_id=" + URLEncoder.encode("****************************************", "UTF-8")+
                "&client_secret=" + URLEncoder.encode("******", "UTF-8")+
                "&grant_type=" + URLEncoder.encode("authorization_code", "UTF-8")+
                "&code=" + URLEncoder.encode("***********", "UTF-8")+
                "&redirect_uri=" + URLEncoder.encode("*******.co.in", "UTF-8");
        // Send post request
        con1.setDoOutput(true);
        try    {
            OutputStream w=con1.getOutputStream();
            DataOutputStream wr = new DataOutputStream(w);
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();
        }
        catch(Exception e){
            System.out.println("Exception test" + e);
        }
        
        int responseCode = con1.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);
        
        BufferedReader in = new BufferedReader(new InputStreamReader(con1.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        access=response.substring(17,129);
        System.out.println(access);
    }
    
}
 
 
//Error Message:
Response Code : 400
 
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://login.salesforce.com/services/oauth2/token
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at org.json.simple.HttpURLConnectionExample.sendPost(HttpURLConnectionExample.java:109)
    at org.json.simple.HttpURLConnectionExample.main(HttpURLConnectionExample.java:26)
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: https://login.salesforce.com/services/oauth2/token
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
    at org.json.simple.HttpURLConnectionExample.sendPost(HttpURLConnectionExample.java:101)
    ... 1 more
 

 
I will really appreciate it if you can help me this out.
 
Thanks
Rhythm Arora
I try it with curl and it works but I don't know why it doesn't work on my workplace
curl -v https://login.salesforce.com/services/oauth2/token -d "grant_type=password&client_id={clientid}&client_secret={clientsecret}&username={emailadd}&password={password+securityToken}" -H "Content-Type:application/x-www-form-urlencoded"

I also try it in my own laptop and it works. That's what I don't understand. I used the same jar file for httpclient for both pc and in my laptop it works but not on my work place. Is there any other reason why it doesn't work this is the sample code


CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();
    
    String authenticationUrl = "https://login.salesforce.com/services/oauth2/token";
    
    // authentication
    HttpPost requestPost = new HttpPost(authenticationUrl);
    requestPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    requestPost.setHeader("Accept", "application/json");
    
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("grant_type", "password"));
    params.add(new BasicNameValuePair("client_id", client_id));
    params.add(new BasicNameValuePair("client_secret", client_secret));
    params.add(new BasicNameValuePair("username", username));
    params.add(new BasicNameValuePair("password", password+securityToken));
    requestPost.setEntity(new UrlEncodedFormEntity(params));
    HttpResponse response = client.execute(requestPost, null).get();
    
    
    System.out.println("Status code:" + response.getStatusLine().getStatusCode());
    System.out.println("Entity: " + response.getEntity().getContent().toString());
    
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    System.out.println(responseString);
 
I want to authenticate using only JavaScript in a HTML page. The objective is to do something similar to web to lead: an html file that could be used to create records in a custom object without using any server application. Off course I know is not totally possible to have a web-to-lead because the authentication is needed to do any transactions in SF and I understand the risk of security hardcoding the credentials access in the page ( that part of security on that HTML is something that it will be managed).
So I've created the next example, using JSFORCE documentation but it is not working. I set some alerts to know which code parts are being executed, but the from alert("step 3" ) nothing happens:
 
<!DOCTYPE html>
<html>
<head>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jsforce/1.6.3/jsforce.min.js"></script>
    <script>    
      alert("step 1" );
      initialize();
      function initialize(){
         alert("step 2" );
         var jsforce = require('jsforce');
         alert("step 3" );
         var conn = new jsforce.Connection({
          oauth2 : {
            // you can change loginUrl to connect to sandbox or prerelease env.
            loginUrl : 'https://login.salesforce.com',
            clientId : '3weweweweweweweweweXX.EIqGx5wXExlptPkkF6alVtMlFmjFeXFpPb76N_p6puepP70VpDfjviFl3bqcIegvj',
            clientSecret : '555555767236744359',
            redirectUri : 'https://www.google.com.co'
           }
         });
        conn.login('user@domain.com', 'pasw1234POpoNARTSERxCY1rtMVf3G0QNq', function(err, userInfo) {
          if (err) { return console.error(err); }
          // Now you can get the access token and instance URL information.
          // Save them to establish connection next time.
          console.log(conn.accessToken);
          console.log(conn.instanceUrl);
          // logged in user property
          console.log("User ID: " + userInfo.id);
          console.log("Org ID: " + userInfo.organizationId);
          // ...
        });
         alert("step 4" );
      }
</script>

</head>

 <body>
    <div>
        Javascript and salesforce  Example
    </div>
 </body>
</html>
I don't need sites, because the client has to adapt to the implementation of the site meanwhile with something like web to lead, the client could integrate easy to their own sites.
Please, anybody could help what I am doing wrong?
 

I have been trying to connect Salesforce and Google API using server to server application.

 

Intent :- To communicate data between Salesforce and Google Spreadsheet which is hosted in Google Sites and using some Google Forms, Google scripts and triggers to update data.

 

So, for doing this I need a server to server application model from Google as it wouldnt require a consent from user while its communicating data. for doing this I need to create a JWT and pass it to Google to get the token and proceed with the next steps.

 

JWT for Google requires a RSA with SHA256 signing of the msg using the private key that google has provided in the certificate when I created the server to server application in Google.

I havent found this info anywhere till now :(

In salesforce, we have a crypto class in which can sign with RSA SHA1 (or) generate digest with SHA256, I tried generating a digest using SHA256 and signing that digest usng RSA and the private key given by google. Even thats not working.

 

Google isnt accepting my assertion values (JWT) and its returning an invalid Grant message.

 

I have seen that Jeff douglas has posted some information about this here :-http://blog.jeffdouglas.com/2010/07/06/using-rsa-sha1-with-salesforce-crypto-class/

But unfortunately he has mentioned about domain model and asking us to upload a certificate to google, which i dont want to do or which is not my scenario.

 

Also Google requires a UT8 base64 URL encoded value at all places as mentioned in this link :-https://developers.google.com/accounts/docs/OAuth2ServiceAccount#libraries But salesforce has a separate URL encoding and a separate base64encoding method available in the EncodingUtil class.

 

I have a C# dotnet application which is generating the same value and its able to hit Google and get the value properly. But uses the certificate file and gets the privatekey directly. I used openssl to retrieve the privatekey from the .p12 certificate file provided by Google and have pasted it in my code. I am sure there is some problem in the signing part, because when I compare the values generated by my .NET application and Salesforce Apex code, its returning correct values, but when it comes to the signature part, the length is also same for the returned data (signature) from both .NET and SF but Google returns an invalid grant while calling from SF but returns a bearer token when I call it from my .NET application.

 

public class TestRestAPICall
{
    public class JWTClaimSet
    {
       public string iss {get;set;}
       public string scope {get;set;}
       public string aud {get;set;}
       public Long exp {get;set;}
       public Long iat {get;set;}
       //public string prn {get;set;}
    }

//@future (callout=true)
public static void LoginToGoogle()
{
    //Set your username and password here        
    String clientId = '851234545868.apps.googleusercontent.com';

    //Construct HTTP request and response
    Http http = new Http();
    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();


    String JWTHeader =  '{"typ":"JWT","alg":"RS256"}';
    //String Base64EncodedJWTHeader = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9'; //To encode later using code

    //Taken from .net application
// Since the information is going to be same, I have encoded it already in .NET and using it here
    String Base64EncodedJWTHeader = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9';
// Salesforce returns time in milliseconds, so we are dividing it by 1000 to set the seconds value instead of milliseconds value
    Long expires_at = math.roundToLong(DateTime.now().addMinutes(40).getTime() / 1000);
    Long issued_at = math.roundToLong(DateTime.now().addSeconds(-2).getTime() / 1000);
    //Long issued_at = 1372276504;
    //Long Expires_at = 1372279804;

    JWTClaimSet JWT = new JWTClaimSet();
    //JWT.prn = username;
    JWT.iss = '851234545868@developer.gserviceaccount.com';
    JWT.scope = 'https://www.googleapis.com/auth/drive.file';
    JWT.aud = 'https://accounts.google.com/o/oauth2/token';
    JWT.iat = issued_at;
    JWT.exp = expires_at;

    String strJWTJSON = JSON.Serialize(JWT);
    system.debug('Unencoded claimset::'+strJWTJSON);


    Blob ClaimsetBlob = Blob.valueOf(strJWTJSON);
    String Base64EncodedClaimset = EncodingUtil.base64Encode(ClaimsetBlob);
    //Base64EncodedClaimset = PerformPostBase64Encode(Base64EncodedClaimset);
    system.debug('Base64 Encoded Claimset::'+Base64EncodedClaimset);

    // constructing the base64 encoded string to sign it
    string Base64EncodedString = Base64EncodedJWTHeader + '.' + Base64EncodedClaimset;


    // Steps to sign the base64Encoded string
    String algorithmName = 'RSA';
    String key = 'MIICXAIBAAKBgQCi16h+5TeQU5Fo0DlR6+YmrzYXZ7DLxz+dBEnB8Hj0gznqlz8p7nQ7I4AV/SfiJQ6JbU16sKS5IW7Hob5ieW1DfwxYZeCSBPbEkt7eASrI8xqGU5RVewaQivY3vO+avgSSUT+ZU243XsDvZJQlkE3e46FhBvFedDQvuk2iEfgdxQIDAQABAoGAFaO882f4c0h3qUsKYvWLNxbPhFq2Js5KiM4aEximqi+KEb+ZmDPk5Dr6eXGTzDyKav7IbgZtTWDA/OxkhWeHelsMB9LqBq50L6hLHTK4hHecPrT3oN4GviUXh5y5Vt479A1TopjLKdt7V4AnAs0HEWJzar/euUa+T9eODPWPFP0CQQDWQeK2cqzWSVHUpkufp7a0Sc2RvfcIpOf8kRFBLnKiFGr7BscLz6qsaG1M8TyUNMrCquwLSNSDMvPjl6sCjgRPAkEAwpFx8+lspjN0yV5M5XHPmnoddTHwV/8QHoccMBBq0ZMFs2m1E/rFhwMHRBiFN6flbze8src7YnOmmtYqsGizqwJAfqoEtYel1ikST3zgSEqGIJ9hAEAlwt56pz27zaT/8AHSHQUstzbV14cE1u/muFddZyhU03cC62078djAKIp80QJAKMMT3ofOrVsmYnGRJpibZ7+hoEXgFm9nTx37N86YsmNc1GOW/iKRc2GdChUhA7H3DT/eForwtAWKp/Gqa97jlQJBAKjKOIKvdYS9fTpCzs1nUHg9rvVartRR5xxwLH57bBincuSJSBGjwd1FInAh2tgiUGPWGPsplShP87wao9+n9VQ=';
    Blob privateKey = EncodingUtil.base64Decode(key);

    Blob input = Blob.valueOf(Base64EncodedString);
    //Blob SHA256InputBlob = Crypto.generateDigest('SHA-256',input);

    Blob Blobsign = Crypto.sign(algorithmName, input , privateKey);


    // The following line is just for debugging and viewing the blob data in signature as string and its not used anywhere
    String signature = EncodingUtil.urlEncode(EncodingUtil.convertToHex(Blobsign),'UTF-8');

    system.debug('Unencoded signature ::'+signature);
    String base64EncodedSignature = EncodingUtil.base64Encode(Blobsign); 
    //base64EncodedSignature = PerformPostBase64Encode(base64EncodedSignature);
    system.debug('Base 64 encoded signature ::'+base64EncodedSignature );

    system.debug('Encoded assertion : ' + Base64EncodedString+'.'+base64EncodedSignature);

    string URLEncodedUTF8GrantType = encodingUtil.urlEncode('urn:ietf:params:oauth:grant-type:jwt-bearer','UTF-8');
    string URLEncodedUTF8Assertion = encodingUtil.urlEncode(Base64EncodedString+'.'+base64EncodedSignature,'UTF-8');        

    system.debug('URLEncodedUTF8GrantType : ' + URLEncodedUTF8GrantType);
    system.debug('URLEncodedUTF8Assertion : ' + URLEncodedUTF8Assertion);

    //Making the call out
    req.setEndpoint('https://accounts.google.com/o/oauth2/token');
    req.setMethod('POST');
    //req.setHeader('Content-Length', '-1');
    req.setHeader('Content-Type','application/x-www-form-urlencoded');
    //req.setHeader('grant_type',URLEncodedUTF8GrantType);
    //req.setHeader('assertion',URLEncodedUTF8Assertion);
    req.setBody('grant_type='+URLEncodedUTF8GrantType+'&assertion='+URLEncodedUTF8Assertion);
    res = http.send(req);
    system.debug('Response : '+res.getBody());
}

 public static String PerformPostBase64Encode(String s)
 {
    s = s.Replace('+', '-');
    s = s.Replace('/', '_');
    s = s.Split('=')[0]; // Remove any trailing '='s
    return s;
 }
}

 

 

I have also posted my problem at stackexchange, it would be great if anyone could help me out :-

 

http://salesforce.stackexchange.com/questions/13301/connect-apex-and-google-api-using-jwt-to-retrieve-oauth-2-0-token

I am implementing a SoftPhone using OpenCTI.

In OpenCTI the SoftPhone is displayed in the SalesForce sidebar using an iFrame.

However, when I change focus in SalseForce for instance I am on the Contacts page and I click on the Accounts page the iFrame including the SoftPhone gets reloaded and I lose the state of my softphone.

 

Is there a way using OpenCTI API or another way to not lose the state of my SoftPhone on a SalesForce page reload?