0
votes

I am a salesforce developer, our company are planning to extend the service for global users, so we decided to use google translate to improve our customers' experience.

I have read the google api document, however, we met an issue when requesting GCP access token, the tutorial google provided in document which supports different languages, like java, c#, python etc. Since we are suing apex (a type of salesforce platform script), we weren't able to use your library to get GCP token.

Instead, we also checked "OAuth 2.0 for Server Accounts", unfortunately, neither worked from me.

Is there any suggestions?

1

1 Answers

0
votes

I got token by below code, and the error I met was caused by special characters encode.

public with sharing class SwitchLanguageByGoogleAPIController {
   private static final String ENDPOINT = '**';
   private static final String TOKEN_ENDPOINT = 'https://accounts.google.com/o/oauth2/token';
   private static final String SCOPE = 'https://www.googleapis.com/auth/cloud-platform';
   private static final String PROJECT_ID = '**';
   private static final String GLOSSARY_ID = '88';
   private static final String LOCATION_ID = 'us-central1';
   private static final String CLIENT_SECRET = '**';
   private static final String PRIVATE_KEY = '**';
   private static final String CLIENT_EMAIL = '**';

   public static void translateByGlossary() {
       Token token = getToken();

       HttpRequest request = new HttpRequest();
       request.setHeader('Content-Type', 'text/plain');
       request.setEndpoint(ENDPOINT + PROJECT_ID + '/locations/' + LOCATION_ID + ':translateText?access_token=' + token.access_token);
       request.setMethod('POST');
       String contents = 'Personal Information, Middle Name e, first First Name';
       String sourceLanguageCode = 'en';
       String targetLanguageCode = 'zh';
       request.setBody('{"sourceLanguageCode":"' + sourceLanguageCode + '","targetLanguageCode":"' + targetLanguageCode + '","contents":"'+ contents +'","glossaryConfig":{"glossary":"projects/' + PROJECT_ID +'/locations/' + LOCATION_ID + '/glossaries/' + GLOSSARY_ID + '"}}');

       HTTP http = new HTTP();
       HttpResponse reponse =  http.send(request);
       System.debug(reponse.getBody());
   }

   private static Token getToken() {
       Http http = new Http();
       HttpRequest req = new HttpRequest();
       HttpResponse res = new HttpResponse();
       //Making the call out
       req.setEndpoint(TOKEN_ENDPOINT);
       req.setMethod('POST');
       req.setHeader('Content-Type','application/x-www-form-urlencoded');

       string URLEncodedGrantType = encodingUtil.urlEncode('urn:ietf:params:oauth:grant-type:jwt-bearer','UTF-8');
       string jwtSigned = generateJWT();
       req.setBody('grant_type='+URLEncodedGrantType+'&assertion='+jwtSigned);

       res = http.send(req);
       system.debug('Response : '+res.getBody());

       return (Token)JSON.deserialize(res.getBody(), Token.Class);
   }

   private static String generateJWT() {
       Http http = new Http();
       HttpRequest req = new HttpRequest();
       HttpResponse res = new HttpResponse();

       String JWTHeader =  '{"typ":"JWT","alg":"RS256"}';
       String Base64EncodedJWTHeader = EncodingUtil.base64Encode(Blob.valueOf(JWTHeader));

       long issued_at = datetime.now().getTime()/1000;
       long expires_at = datetime.now().addHours(1).getTime()/1000;

       JWTClaimSet claimSet = new JWTClaimSet();
       claimSet.iss = CLIENT_EMAIL;
       claimSet.scope = SCOPE;
       claimSet.aud = TOKEN_ENDPOINT;
       claimSet.iat = issued_at;
       claimSet.exp = expires_at;

       String strClaimSetJSON = JSON.Serialize(claimSet);
       String Base64EncodedClaimset = EncodingUtil.base64Encode(Blob.valueOf(strClaimSetJSON));
       system.debug('Base64 Encoded Claimset::'+Base64EncodedClaimset);
       Base64EncodedClaimset = PerformPostBase64Encode(Base64EncodedClaimset);
       system.debug('persorm post Claimset::'+Base64EncodedClaimset);

       string Base64EncodedString = Base64EncodedJWTHeader + '.' + Base64EncodedClaimset;

       String algorithmName = 'RSA-SHA256';
       Blob privateKey = EncodingUtil.base64Decode(PRIVATE_KEY);

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

       String base64EncodedSignature = EncodingUtil.base64Encode(Blobsign);
       base64EncodedSignature = PerformPostBase64Encode(base64EncodedSignature);

       system.debug('Base 64 encoded signature ::'+base64EncodedSignature );
       system.debug('Encoded assertion : ' + Base64EncodedString+'.'+base64EncodedSignature);

       string URLEncodedUTF8Assertion = encodingUtil.urlEncode(Base64EncodedString+'.'+base64EncodedSignature,'UTF-8');
       return URLEncodedUTF8Assertion;
   }

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

   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;}
   }

   private class Token{
       private String access_token;
       private String token_type;
       private String expires_in;
 }
}