0

I am using the following code to get acces token from Google Adwords but it is showing error 400 with

grant_type:invalid code:invalid

Though my auth code should be correct. Can anybody tell me what am I missing here?

public void AccessToken()  
{  
    //Getting access token from google 
    redirect_uri = encodingutil.urlEncode(redirect_uri, 'UTF-8'); 
    code = encodingutil.urlEncode(code , 'UTF-8'); 
    secret  = encodingutil.urlEncode(secret , 'UTF-8'); 
    key = encodingutil.urlEncode(key, 'UTF-8'); 

    HttpRequest req = new HttpRequest();  
    req.setMethod('POST');  
    req.setEndpoint('https://accounts.google.com/o/oauth2/token');  
    req.setHeader('content-type', 'application/x-www-form-urlencoded');  
    String messageBody = 'code='+code+'&client_id='+key+'&client_secret='+secret+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code';  
    req.setHeader('Content-length', String.valueOf(messageBody.length()));  
    req.setBody(messageBody);  
    req.setTimeout(60*1000);  

    Http h = new Http();  
    String resp;  
    HttpResponse res = h.send(req);  
    resp = res.getBody();  

    System.debug(' jsonresponse ' + resp);  
   }
}

Is this rest service is applicable for Google adwords?

0

1 Answer 1

1

Try with this:

    HttpRequest req = new HttpRequest();  
    req.setMethod('POST');  
    req.setEndpoint('https://accounts.google.com/o/oauth2/token?code='+code+'&client_id='+key+'&client_secret='+secret+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code'');  
    req.setHeader('content-type', 'application/x-www-form-urlencoded');   
    req.setHeader('Content-length', String.valueOf(messageBody.length()));    
    req.setTimeout(60*1000);  

You need to set parameter in endpoint not in request body.

3
  • what should i give in content-length? Jul 31, 2014 at 6:58
  • I see. If you are using code and other things in body then you don't need to use EncodingUtil.uelEncode. Remove content-type header. @ShaileshGusain
    – Ashwani
    Jul 31, 2014 at 7:15
  • Now only grant_type:invalid is there. Jul 31, 2014 at 8:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .