• Nicola Spreafico
  • NEWBIE
  • 10 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
How to authenticate google service account for google adword api. By using this document. 
https://developers.google.com/accounts/docs/OAuth2ServiceAccount
My code Is as following :
public class GoogleAdWordApi{
     public Static String getAccessToken(){
        String accesstoken = '';
        
        String headerStr64 = EncodingUtil.base64Encode(Blob.valueOf('{"alg":"RS256","typ":"JWT"}'));
        headerStr64 = headerStr64.split('=')[0];

        String str = '{"iss":"965360208690-a6qbrksf61b5dl7punv126ntb5aspu93@developer.gserviceaccount.com",';
        str += '"scope":"' + 'https://www.googleapis.com/auth/prediction' + '",';
        str += '"aud":"' + 'https://accounts.google.com/o/oauth2/token' + '",';
        str += '"exp":' + system.now().addminutes(30).gettime()/1000 + ',';
        str += '"iat":'+system.now().gettime()/1000;
        str += '}';
        
        System.debug('@@@ str==>'+str);
        
        String claim_set64 = EncodingUtil.base64Encode(Blob.valueOf(str));
        claim_set64 = claim_set64.split('=')[0];
        System.debug('@@ claim_set64==>'+claim_set64);
        
        //make signature
        String sigInputstr =   headerStr64 + '.' + claim_set64 ;
        Blob signInputByteData = Blob.valueOf(sigInputstr);
        Blob signByteData = System.Crypto.signWithCertificate('RSA-SHA256',signInputByteData,'privatekey');
        String sigStr64 = EncodingUtil.base64Encode(signByteData);
        System.debug('@@@ sigStr64==>'+sigStr64);
        sigStr64 = sigStr64.split('=')[0];
        System.debug('@@@ sigStr64==>'+sigStr64);
        
        String jwtStr = headerStr64 + '.' + claim_set64 + '.' + sigStr64;
        
        System.debug('@@@ jwtStr==>'+jwtStr);
        
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://accounts.google.com/o/oauth2/token');
        req.setMethod('POST');
        req.setHeader('Host','accounts.google.com');
        req.setHeader('Content-Type','application/x-www-form-urlencoded');
        String body = 'grant_type='+ EncodingUtil.urlEncode('urn:ietf:params:oauth:grant-type:jwt-bearer','UTF-8');
        body += '&assertion=' + jwtStr;
        req.setBody(body);
        System.debug('@@ body==>'+body);
        Http http = new Http();
        HTTPResponse res = http.send(req);
        System.debug(res.getBody());    
        
        return accesstoken;
    }
}
--------------------------
Please tell me what is going worng with it.