• rvg
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 1
    Replies

Hi,

 

I am trying to call REST API from Salesforce Developer Org A ( Source ) to Salesforce Developer Org B ( Target ) but I am running into issue. I went through multiple sites but am getting the same error message. I do get the access_token and have also registered my company domain through My Domain and published it. I still am not able to figure out why I am not able to call the REST API.  Its not able to get to /services/apexrest/getservice1.

 

In Source

<Page>

<apex:page controller="OAuthRestController" action="{!login}">

<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputLabel for="name">Name</apex:outputLabel>
<apex:inputText id="name" value="{!name}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>

<apex:commandButton action="{!submit}" value="Submit"> </apex:commandButton>
<br/><br/> {!getname}
</apex:form>

Get name says "{!getname}"
</apex:page>

 

 

<Created an OAuthRestController>

 

public abstract class OAuthRestController 
{
    static String clientId = '3MVG9A2kN3Bn17huzc3k8LPsmtAMW1btHIyy8rp1RICmQMJB2dr9MnGgeWpKF_66yh2Azg9vDzwRFUVMfcjmp'; // Set this in step 3
    static String clientSecret = '9138556916389229822'; // Set this in step 3
    //static String redirectUri = 'https://mytestdevorg1-dev-ed.my.salesforce.com/apex/RestCall'; 
    static String redirectUri='https://mytestdevorg1-developer-edition.na15.force.com/apex/RestCall';// YOUR PAGE URL IN THE SOURCE ORG
    //static String loginUrl = 'https://mytestdomainorg2-dev-ed.my.salesforce.com'; // YOUR MY DOMAIN URL IN THE TARGET ORG
static String loginUrl = 'https://mytestdevorg2-developer-edition.na15.force.com'; // YOUR MY DOMAIN URL IN THE TARGET ORG    
    static String cookieName = 'oauth';

     
     public PageReference login() {
        // Get a URL for the page without any query params
        String url = ApexPages.currentPage().getUrl().split('\\?')[0];
       
        System.debug('url is '+url);

        String oauth = (ApexPages.currentPage().getCookies().get(cookieName) != null ) ?
            ApexPages.currentPage().getCookies().get(cookieName).getValue() : null;
        if (oauth != null) {
            // TODO - Check for expired token
        }
       
        System.debug('oauth='+oauth);
        if (oauth != null) {
            // All done
            return null;
        }
       
        // If we get here we have no token
        PageReference pageRef;
       
        if (! ApexPages.currentPage().getParameters().containsKey('code')) {
            // Initial step of OAuth - redirect to OAuth service
            System.debug('OAuth Step 1');
       
            String authuri = loginUrl+'/services/oauth2/authorize?'+
                'response_type=code&client_id='+clientId+'&redirect_uri='+redirectUri;
                           
            pageRef = new PageReference(authuri);
        } else {
            // Second step of OAuth - get token from OAuth service
            String code = ApexPages.currentPage().getParameters().get('code');

            System.debug('OAuth Step 2 - code:'+code);
               
            String body = 'grant_type=authorization_code&client_id='+clientId+
                '&redirect_uri='+redirectUri+'&client_secret='+clientSecret+
                '&code='+code;
            System.debug('body is:'+body);
               
            HttpRequest req = new HttpRequest();
            req.setEndpoint(loginUrl+'/services/oauth2/token');
            req.setMethod('POST');
            req.setBody(body);
       
            Http h = new Http();
            HttpResponse res = h.send(req);
   
            String resp = res.getBody();
            System.debug('FINAL RESP IS:'+EncodingUtil.urlDecode(resp, 'UTF-8'));
           
            ApexPages.currentPage().setCookies(new Cookie[]{new Cookie(cookieName,
                res.getBody(), null,-1,false)});
                
              

                getNameMethod(name);
       

            // Come back to this page without the code param
            // This makes things simpler later if you end up doing DML here to            // save the token somewhere           
             pageRef = new PageReference(url);
          pageRef.setRedirect(true);
        }
    return pageRef;   }
   

     public String getname {get;set;}
    public String name{get;set;}
    public PageReference submit() 
    {
        getname=getNameMethod(name);
        return null;
    }
    public static String getNameMethod(String name)
    {
        String oauth = (ApexPages.currentPage().getCookies().get(cookieName) != null ) ?
            ApexPages.currentPage().getCookies().get(cookieName).getValue() : null;
       
        JSONObject oauthObj = new JSONObject( new JSONObject.JSONTokener(oauth));
           
        String accessToken = oauthObj.getValue('access_token').str,
               instanceUrl = oauthObj.getValue('instance_url').str;
        System.debug('Accesstoken'+accessToken);
        System.debug('instance URL'+instanceUrl);
        HttpRequest req = new HttpRequest();
 
        req.setMethod('GET');
        String url = 'https://mytestdevorg2-developer-edition.na15.force.com/services/apexrest/getservice1?name='+name;        
        req.setEndpoint(url);
        //req.setHeader('Authorization', 'Bearer '+'00Di0000000YOBY!ARgAQFCfBkwslWt071wORmSsZT9zcQkgwlxfuzXhqwgXNdgAhYiqcLf8r2oSOTsPVwDqeAGbY1YgwXeh2a2IfCCmzxdBoE_4');
        req.setHeader('Authorization', 'OAuth '+accessToken);
        system.debug(req);
        
        Http http = new Http();
 
        HTTPResponse res = http.send(req);

        System.debug('BODY: '+res.getBody());
        System.debug('STATUS:'+res.getStatus());
        System.debug('STATUS_CODE:'+res.getStatusCode());
       
        return res.getBody();
    }
}

 

In Target:

 

@RestResource(urlMapping='/getservice1/')
global class with sharing getservice1
{
    @HttpGet
    global static String getservice1()
    {
        String name = RestContext.request.params.get('name');
        return 'Hello '+name+',you have invoked your Rest Call';
    }
}

 

I also tried using curl but somehow its not getting to the path /services/apexrest/getservice1. I have also added the target in the Remote Site Settings but still its failing. 

  • May 18, 2013
  • Like
  • 0

I'm trying to use REST APEX API that I created in a dev.Org(A). And I want to use this APEX REST Service in an another Dev Org(B) using REST call to "A" from "B". I cretaed a simple VF page with controller class and some logic inside it to call this serivce.

 

Everything works well till the point i get the "code" value after successful authorization of from "A". But when I try to create a request to get the token/refesh_token part i get a strange error:-  error=unsupported_grant_type&error_description=grant%20type%20not%20supported.

 

following is the piece of code 

 

Http h = new Http();         

HttpRequest req = new HttpRequest();   

req.setMethod('POST');   

req.setHeader('grant_type','authorization_code');       

req.setHeader('code',code);

req.setHeader('client_id',clientId );   

req.setHeader('client_secret',client_secret); 

req.setHeader('redirect_uri',callbackUrl ); 

req.setHeader('Content-Type','application/x-www-form-urlencoded');         

req.setEndpoint('https://login.salesforce.com/services/oauth2/token');            

   

HttpResponse res = null;

res = h.send(req);     

system.debug('###'+res.getBody()+'#####');