How get CustomerId with OAuth 2.0

1,259 views
Skip to first unread message

Marcin Gdak

unread,
Mar 31, 2015, 11:15:57 AM3/31/15
to adwor...@googlegroups.com

Hi,

How get Customer ID of the user with OAuth 2.0 web flow. 
How I wrote down by hand customer id in webconfig, that's all is acting. But I need to take the id after the Authorization. How I can get Customer Id of the user?

Nadine Sundquist (AdWords API Team)

unread,
Mar 31, 2015, 3:35:51 PM3/31/15
to adwor...@googlegroups.com
Hello Marcin,

Once you've authenticated, you can retrieve the current customer id from the Customer Service. The Customer object contains the customerId as a 10-digit number.

Cheers,
Nadine, AdWords API Team
Message has been deleted

Marcin Gdak

unread,
Apr 1, 2015, 4:39:24 AM4/1/15
to adwor...@googlegroups.com
Hmm I am getting Idas but only then when the same I have written down in webconfig. If it is different I am getting the error AuthorizationError.USER_PERMISSION_DENIED.

My code in C#

CustomerService customerservice = (CustomerService)user.GetService(AdWordsService.v201502.CustomerService);
Customer customerActual = customerservice.get();

Nadine Sundquist (AdWords API Team)

unread,
Apr 1, 2015, 12:32:01 PM4/1/15
to adwor...@googlegroups.com
Hi Marcin,

If you don't put a clientCustomerId in your web.config, then the clientCustomerId passed back from the Customer object is the clientCustomerId related to your OAuth credentials. Based on your explanation and the error that is being returned, it sounds like you may be trying to access a clientCustomerId that your OAuth user does not have permissions to access.

Best,
Nadine, AdWords API Team

Marcin Gdak

unread,
Apr 1, 2015, 2:04:56 PM4/1/15
to adwor...@googlegroups.com
Hi Nadine,
If I don't put a clientCustomerId in my web.config, then OAuth is returning the error "CustomerID is required". 

I am using the help given on the side

In section "Scope" I have link to Adwords. In settings the user account, there is an access of the application to the campaign Adwords.

Please help! :(

Thank you! 

Nadine Sundquist (AdWords API Team)

unread,
Apr 1, 2015, 6:57:56 PM4/1/15
to adwor...@googlegroups.com
Hello,

You can pick from one of the two options depending on what you need.

Option 1
  • Use Case: You want to store your clientCustomerId in your web.config, and you want to retrieve it at runtime.
  • Solution: Check out this wiki post on configuring the ads user instance at runtime.  If you have the clientCustomerId set in web.config, you can create a new AdWordsUser that will contain the clientCustomerId from the web.config. Here's an example:
// Create a default AdWordsUser instance. If any configuration is available in web.config, that configuration will be used.
AdWordsUser user = new AdWordsUser();

// Retrieve the client customer id.
AdWordsAppConfig config = (AdWordsAppConfig) user.Config;
String clientCustomerId = user.Config.clientCustomerId;

Option 2
  • Use Case: You want to dynamically figure out the clientCustomerId without specifying it in web.config.
  • Solution: The Customer Service is the ONLY service that can be called without specifying the clientCustomerId in the web.config file. Once you retrieve the customerId from the service, you will have to set clientCustomerId in your program in order to use any of the other services. Please refer to the  wiki post on configuring the ads user instance at runtime for setting the clientCustomerId after retrieving it from the CustomerService.
Wishing you the best,
Nadine, AdWords API Team

Marcin Gdak

unread,
Apr 2, 2015, 6:13:57 AM4/2/15
to adwor...@googlegroups.com
Thank for your replies :)

I have another problem. I am working with the option 2. 

My code:

AdWordsUser user = new AdWordsUser();
CustomerService customerservice = (CustomerService)user.GetService(AdWordsService.v201502.CustomerService);
long customerId = customerservice.get().customerId;     -> Here I am getting the error, that in webconfig I must have refreshToken.

My Authentication code:

Site from Redirect URIs

protected void Page_Load(object sender, EventArgs e)
        {
            AdWordsAppConfig config = new AdWordsAppConfig();
            if (config.OAuth2Mode == OAuth2Flow.APPLICATION &&
                 string.IsNullOrEmpty(config.OAuth2RefreshToken))
            {
                DoAuth2Configuration(config);
            }
            if (!string.IsNullOrEmpty(config.OAuth2RefreshToken))
            {
                Response.Redirect("/Pages/Default.aspx");
            }
        }
        private void DoAuth2Configuration(AdWordsAppConfig config)
        {
        config.OAuth2RedirectUri = Request.Url.GetLeftPart(UriPartial.Path);
        OAuth2ProviderForApplications oAuth =
                new OAuth2ProviderForApplications(config);
            if (Request.Params["state"] == null)
            {
            oAuth.State = "callback";
                Response.Redirect(oAuth.GetAuthorizationUrl());
            }
            else if (Request.Params["state"] == "callback")
            {oAuth.FetchAccessAndRefreshTokens(Request.Params["code"]);
               Session["OAuthProvider"] = oAuth;
                // Redirect the user to the main page.
               Response.Redirect("Pages/Default.aspx");
            }

I would like to write in webconfig refreshtoken after the authorization, but oAuth.RefreshToken is null. How can i get RefreshToken from my Authorization code? I don't understand it :(

Nadine Sundquist (AdWords API Team)

unread,
Apr 2, 2015, 3:19:35 PM4/2/15
to adwor...@googlegroups.com
Hello,

Once you issue the line of code, your oAuth (OAuth2ProviderForApplications) instance will be populated with a refresh token. 
oAuth.FetchAccessAndRefreshTokens(Request.Params["code"]);
 You can try accessing the refresh token and setting it in the config (AdWordsAppConfig) before making the call to CustomerService.
String refreshToken = oAuth.RefreshToken;
config
.OAuth2RefreshToken = refreshToken;
Double-check to make sure that you have a refresh token at that point. If not, then there may be an issue with your credentials before you even fetch the refresh token.

Cheers,
Nadine, AdWords API Team

Marcin Gdak

unread,
Apr 3, 2015, 5:01:59 AM4/3/15
to adwor...@googlegroups.com

Hi Nadine,

I try this, but "oAuth.RefreshToken" is empty. I noticed that the same I could not get the user e-mail. If I put a clientCustomerId in my web.config, then I  have a full access to Adwords API. RefreshToken must be good but I can't pick it up :( 

Nadine Sundquist (AdWords API Team)

unread,
Apr 3, 2015, 12:03:00 PM4/3/15
to adwor...@googlegroups.com
Hi Marcin,

Let me recap the process that you're following. It should be this:
  1. Follow the OAuth2 ASP.NET code example on how to do an OAuth2 flow and capture the access and refresh token.
  2. Set the access and refresh token to user.Config dynamically at runtime and call CustomerService.get()
  3.  Set the customerId to user.Config dynamically and make further calls.
Here are some troubleshooting tips on figuring out why your refresh token is not coming back:
  • You may have another login session active somewhere that is interfering with the flow. 
    • Close the browser.
    • Close the Visual Studio debugger web server (if it is accessible from the system tray).
    • Try running through the whole flow again.
  • If that does not work, the refresh token may not be making itself available to the flow.
    • Turn on logging and see if the server is sending the refresh token back. The refresh token may be getting sent back, but the client library may not be picking it up.
    • Here's a guide on capturing messages.
Best,
Nadine, AdWords API Team

Marcin Gdak

unread,
Apr 8, 2015, 10:10:02 AM4/8/15
to adwor...@googlegroups.com
Hi Nadine,

Still my refresh token is empty.
My logs:


AdsClientLibs.RequestInfoLogs Information: 1 : host=accounts.google.com,url=/o/oauth2/token,Content-Type: application/x-www-form-urlencoded, Host: accounts.google.com, TimeStamp: Wed, 08 Apr 2015 15:56:00 GMT, code=4%2feZigbElUJzTfPvRzDcgvxolkIZFJ30jLAGbA3tmn_mY.snhw8qCGuzkbYFZr95uygvUB4KEymQI&client_id=524.....29-lsp7.......6seth.apps.googleusercontent.com&client_secret=******&redirect_uri=http%3a%2f%2flocalhost%3a50246%2fOAuthLogin.aspx&grant_type=authorization_code&refresh_token=******,Result=Success


AdsClientLibs.SoapXmlLogs Information: 1 : 
-----------------BEGIN API CALL---------------------

Request
-------

POST /o/oauth2/token
Content-Type: application/x-www-form-urlencoded
TimeStamp: Wed, 08 Apr 2015 15:56:00 GMT


code=4%2feZ.....QI&client_id=524....029-l......h.apps.googleusercontent.com&client_secret=******&redirect_uri=http%3a%2f%2flocalhost%3a50246%2fOAuthLogin.aspx&grant_type=authorization_code&refresh_token=******

Response
--------

Pragma: no-cache
Content-Disposition: attachment; filename="json.txt"; filename*=UTF-8''json.txt
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Alternate-Protocol: 443:quic,p=0.5
Vary: Accept-Encoding
Transfer-Encoding: chunked
Accept-Ranges: none
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: application/json; charset=utf-8
Date: Wed, 08 Apr 2015 13:56:01 GMT
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Server: GSE
TimeStamp: Wed, 08 Apr 2015 15:56:01 GMT


{"access_token":"******","token_type":"Bearer","expires_in":"3599","id_token":"eyJ...........................................................................................lSHBP3pZMtNCT6oSsOnaKbGUldOA"}
-----------------END API CALL-----------------------

In my opinion, the server is not sending the refresh token back.

I have a few questions.

Parameter "access_type" should not be "offline"?
In request,  Post should not be "/o/oauth2/auth". In my request is "/o/oauth2/token"  

Thank you for help.


Nadine Sundquist (AdWords API Team)

unread,
Apr 9, 2015, 7:00:10 PM4/9/15
to adwor...@googlegroups.com
Hello Marcin,

In response to your questions:
  • Parameter access_type should be offline.
  • The POST address looks correct.
One thing that I noticed that is different about your response from what I would expect is that your are receiving an id_token rather than a refresh_token. This means that you are using an OAuth 2.0 connection mechanism called OpenID Connect. Based on the OpenID documentation related to retrieving tokens, you must make sure that your access_type=offline in order to get back a refresh_token. 

Cheers,
Nadine, AdWords API Team

Marcin Gdak

unread,
Apr 10, 2015, 4:31:53 AM4/10/15
to adwor...@googlegroups.com
Hi Nadine,

I understand my problem, but i don't know how to add access_type in my code. I added in webconfig, but it doesn't work.
I'm using the taken library from nuget packet.

Could you help me?

Anash P. Oommen (AdWords API Team)

unread,
Apr 10, 2015, 11:36:12 AM4/10/15
to adwor...@googlegroups.com
Hi Marcin,

In your Web.config, comment out all the OAuth2 properties other than

    <add key="OAuth2ClientId" value="INSERT_OAUTH2_CLIENT_ID_HERE" />
    <add key="OAuth2ClientSecret" value="INSERT_OAUTH2_CLIENT_SECRET_HERE" />
    <add key="OAuth2Mode" value="APPLICATION" />

When you do this, client library would see that both accessToken and refreshToken are empty, and would then take you through the flow for obtaining an access and refresh token. 

As you mentioned, this call doesn't seem right:

AdsClientLibs.RequestInfoLogs Information: 1 : host=accounts.google.com,url=/o/oauth2/token,Content-Type: application/x-www-form-urlencoded, Host: accounts.google.com, TimeStamp: Wed, 08 Apr 2015 15:56:00 GMT, code=4%2feZigbElUJzTfPvRzDcgvxolkIZFJ30jLAGbA3tmn_mY.snhw8qCGuzkbYFZr95uygvUB4KEymQI&client_id=524.....29-lsp7.......6seth.apps.googleusercontent.com&client_secret=******&redirect_uri=http%3a%2f%2flocalhost%3a50246%2fOAuthLogin.aspx&grant_type=authorization_code&refresh_token=******,Result=Success

A refresh_token=***** shouldn't be there, I'm assuming that's the placeholder value being loaded from the Web.config you downloaded from the nuget package.

Cheers,
Anash P. Oommen,
AdWords API Advisor.

Marcin Gdak

unread,
Apr 13, 2015, 4:33:31 AM4/13/15
to adwor...@googlegroups.com
Hi Anash,

Thank you for help.
In my opinion, that oauth is already acting. I get CustomerId. I would like to get the e-mail address of the user, but my code isn't work.
My code:


 CustomerService customerservice = (CustomerService)user.GetService(AdWordsService.v201502.CustomerService);
                long customerId = customerservice.get().customerId;
                AdWordsAppConfig config = (AdWordsAppConfig)user.Config;
                config.ClientCustomerId = customerId.ToString();
                lit.Text += config.ClientCustomerId.ToString();
                lit.Text += config.Email;

One more time I am thanking you for help.

Marcin Gdak 

Francesco Protano

unread,
Feb 10, 2017, 3:22:53 PM2/10/17
to AdWords API Forum
Hi nadine i guess you are .net expert programmer but i think u are able to explain where i wrong. My goals is to pick all the accounts of a user who have and manage in his an adwords account . I followed all steps suggested from the google guide. After the i taken the access token of the logged user i call a managedaccountservice to fetch all that accounts but with my surprise that are relative of the app owner who have an adword account and not of the logged user. I understood that i some point of the code i have to pass a customer client id of logged user but i m confused about when or where?
Can u help me to get off from the fog?
Thk francesco

Francesco Protano

unread,
Feb 10, 2017, 3:23:12 PM2/10/17
to AdWords API Forum

anash

unread,
Feb 10, 2017, 3:44:00 PM2/10/17
to AdWords API Forum
Hi Francesco,

I wonder if you are mixing up the access token somewhere (between the user's access token and a hardcoded debug access token). Could you turn on logging following the instructions on https://github.com/googleads/googleads-dotnet-lib/wiki/How-to-capture-SOAP-messages (it will also capture OAuth2 exchanges) and see if the access token you send to the server is the same as the one returned when authenticating your user?

Cheers,
Anash P. Oommen,
AdWords API Advisor

Francesco Protano

unread,
Feb 10, 2017, 7:12:14 PM2/10/17
to AdWords API Forum
Hello the u suggested it s for .net my code is for php but it s not important, i think it will an similar solution to capture the soap messages. U seems an expert adwords advice , so, can u send to me an example to archieve my workflow? But first is it possible ? Thk for the reply

Anash P. Oommen (AdWords API Team)

unread,
Feb 15, 2017, 5:47:29 PM2/15/17
to AdWords API Forum
Hi Francesco,

The https://github.com/googleads/googleads-php-lib/blob/master/examples/AdWords/v201609/AccountManagement/GetAccountHierarchy.php code example should help you achieve your workflow, but for that to work, the access token you send as part of the request should belong to the logged-in user. I don't know of an easy way to reverse-lookup a user given the access token though.

Cheers,
Anash P. Oommen,
AdWords API Advisor,
Reply all
Reply to author
Forward
0 new messages