Link Adwords Account: AuthenticationError.OAUTH_TOKEN_INVALID

122 views
Skip to first unread message

xuantoi....@gmail.com

unread,
Jul 27, 2018, 5:10:27 AM7/27/18
to AdWords API and Google Ads API Forum
Hello,
I'm got AuthenticationError.OAUTH_TOKEN_INVALID when try to link adwords account to manager adwords account

here my code at server:


private void sendRequest(ManagedCustomerServiceInterface managedCustomerService, Long customerId, Long managerId) throws RemoteException {
//send email request
LinkOperation linkOp = new LinkOperation();
ManagedCustomerLink link = new ManagedCustomerLink();
link.setClientCustomerId(customerId); //customer id
link.setLinkStatus(LinkStatus.PENDING);
link.setManagerCustomerId(managerId);//manager id
linkOp.setOperand(link);
linkOp.setOperator(Operator.ADD);
managedCustomerService.mutateLink(new LinkOperation[]{linkOp});
log.info("request has been sent!");
}

private void acceptRequest(ManagedCustomerServiceInterface managedCustomerService, Long customerId, Long managerId) throws RemoteException {
//accept
LinkOperation linkOps = new LinkOperation();
ManagedCustomerLink links = new ManagedCustomerLink();
links.setClientCustomerId(customerId); //customer id
links.setLinkStatus(LinkStatus.ACTIVE);
links.setManagerCustomerId(managerId);//manager id
linkOps.setOperand(links);
linkOps.setOperator(Operator.SET);
managedCustomerService.mutateLink(new LinkOperation[]{linkOps});
log.info("request has been accepted!");
}
private AdWordsSession getSessionByAccessToken(String accessToken) {
AdWordsSession session = null;
try {
GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
// Construct an AdWordsSession.
session = new AdWordsSession.Builder()
.withDeveloperToken(developerToken)
.withUserAgent("Knorex-adwords")
.withOAuth2Credential(credential)
.build();
} catch (Exception e) {
log.error(e.getMessage());
}
return session;
}

private Long parseLong(String str){
str = str.replaceAll("-","");
return Long.parseLong(str);
}

public String linkAccount(GoogleSignInObject googleSignInObject){
AdWordsSession session = getSession();
AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();
ManagedCustomerServiceInterface managedCustomerService =
adWordsServices.get(session, ManagedCustomerServiceInterface.class);

Long cusId = parseLong(googleSignInObject.getCustomerId());
Long manId = parseLong(clientCustomer);

try {
sendRequest(managedCustomerService, cusId, manId);
} catch (ApiException e){
log.error(e.getMessage());

} catch (RemoteException e) {
log.error(e.getMessage());
return FAIL;
}

//change session
GoogleTokenResponse tokenResponse;
try {
tokenResponse = new GoogleAuthorizationCodeTokenRequest(
new NetHttpTransport(),
JacksonFactory.getDefaultInstance(),
"https://www.googleapis.com/oauth2/v4/token",
googleSignInObject.getClientId(),
googleSignInObject.getClientSecret(),
googleSignInObject.getAuthCode(),
googleSignInObject.getRedirectUri()) // Specify the same redirect URI that you use with your web
// app. If you don't have a web version of your app, you can
// specify an empty string.
.execute();
} catch (IOException e) {
log.error(e.getMessage());
return FAIL;
}
String accessToken = tokenResponse.getAccessToken();

session = getSessionByAccessToken(accessToken);
session.setClientCustomerId(googleSignInObject.getCustomerId());

ManagedCustomerServiceInterface managedCustomerService2 =
adWordsServices.get(session, ManagedCustomerServiceInterface.class);
try {
acceptRequest(managedCustomerService2, cusId, manId); //i get error here
} catch (RemoteException e) {
log.error(e.getMessage());
return FAIL;
}
return SUCCESS;
}

controller:
@PostMapping(value = "/link/account", consumes = "application/json; charset=UTF-8")
public String link(@RequestBody GoogleSignInObject googleSignInObject){
return manageAccount.linkAccount(googleSignInObject);
}

font-end:
<html itemscope itemtype="http://schema.org/Article">
<head>
  </script>
  </script>
  <script>
    function start() {
      gapi.load('auth2', function() {
        auth2 = gapi.auth2.init({
          client_id: 'my clientId',
          // Scopes to request in addition to 'profile' and 'email'
        });
      });
    }
  </script>
</head>
<body>
<button id="signinButton">Sign in with Google</button>
<script>
  $('#signinButton').click(function() {
    auth2.grantOfflineAccess().then(signInCallback);
  });
function signInCallback(authResult) {
  if (authResult['code']) {

    $('#signinButton').attr('style', 'display: none');
    var googleSignInObject = {
        authCode: authResult['code'],
        clientId: 'my client id,
        clientSecret: 'my client secret',
        customerId: 'my customer id',
        redirectUri: 'http://localhost:9000'
      };
    $.ajax({
      type: 'POST',
      dataType: "json",
      headers: {
        'Authorization' : 'Bearer authorized-code'
      },
      contentType: 'application/json',
      success: function(result) {
      },
      processData: false,
      data: JSON.stringify(googleSignInObject)

    });
  } else {
  }
}
</script>
</body>
</html>

i got error when try to accept request

pleas help!

Milind Sankeshware (AdWords API Team)

unread,
Jul 27, 2018, 11:45:03 AM7/27/18
to AdWords API and Google Ads API Forum
Hi Duong,

The error OAUTH_TOKEN_INVALID occurs when your access token passed with the HTTP header was not correct. To verify that your credentials are correct, you could also try the CURL request provided below and see if you are able to generate the access tokens? If the credentials are correct, you should get an access token for the below request.

curl https://www.googleapis.com/oauth2/v4/token \
-d refresh_token=your-refresh_token \
-d client_id=your-client-id \
-d client_secret=your-client-secret \
-d grant_type=refresh_token

If your credentials are incorrect and still facing issues then could you generate a new refresh token with the help of this guide and retry your request? Also, please make sure that you are authenticating as the Manager account while making this call. If you are still facing an issue please share the client customer id of your AdWords account and manager AdWords account.

Thanks,
Milind, AdWords API Team 

xuantoi....@gmail.com

unread,
Jul 30, 2018, 1:00:35 AM7/30/18
to AdWords API and Google Ads API Forum
Hi Milind,

my access token was correct, i can get some information like profile, email ... 
but i can't use this access token to accept invitation from mcc account, i use this code to accept

Milind Sankeshware (AdWords API Team)

unread,
Jul 30, 2018, 4:00:17 PM7/30/18
to AdWords API and Google Ads API Forum
Hi,

The access tokens short lived (about 1 hour). If you tried to use the token after it expired that will result in a failed API request. If this is not the case, could you please share the SOAP logs without redacting any information along with your properties file? If you need instructions to enable logging, please check the README file in the client library that you are using (eg, for Java, please check here). Please share the details using Reply privately to author option while sharing the sensitive information. 

Thanks,
Milind, AdWords API Team.

xuantoi....@gmail.com

unread,
Jul 31, 2018, 11:07:37 PM7/31/18
to AdWords API and Google Ads API Forum
Hi,
I wonder, do I miss any scope when sign-in and send code to server
Because I can read some information of this account however I cant accept mcc request

xuantoi....@gmail.com

unread,
Aug 1, 2018, 2:43:07 AM8/1/18
to AdWords API and Google Ads API Forum
Hi,

I was solved the problem, just put scope:"https://www.googleapis.com/auth/adwords" to gapi.auth2.init 

Sreelakshmi Sasidharan (AdWords API Team)

unread,
Aug 1, 2018, 12:59:27 PM8/1/18
to AdWords API and Google Ads API Forum
Hello, 

Glad to know that you were able to resolve the issue. 

Thanks,
Sreelakshmi, AdWords API Team
Reply all
Reply to author
Forward
0 new messages