Posts tagged with google-authentication

I am writing an Azure Function in C# using .NET core.

I have tried to authenticate as an APPLICATION per this page.

I've tried authenticating with a service account per this page.

In both cases I'm getting an access denied error message.

The root question I have is,

Which authentication method should I use for the Google Ads API from within an Azure Function?

Update:

In my latest attempt to use a service account I have this code

GoogleAdsConfig config = new GoogleAdsConfig()             {            OAuth2Mode = Google.Ads.GoogleAds.Config.OAuth2Flow.SERVICE_ACCOUNT,            OAuth2SecretsJsonPath = pathtojsonfile,            OAuth2PrnEmail = "something@somethingelse.iam.gserviceaccount.com",            OAuth2Scope = "https://www.googleapis.com/auth/adwords",            DeveloperToken = "********"         };                  var responseMessage = "";         var client = new GoogleAdsClient(config);                  // Get the GoogleAdsService.         GoogleAdsServiceClient googleAdsService = client.GetService(Services.V6.GoogleAdsService);         // Create the query.         string query =             @"SELECT              campaign.id,              campaign.name,              ad_group.id,              ad_group.name,              ad_group_criterion.criterion_id,              ad_group_criterion.keyword.text,              ad_group_criterion.keyword.match_type,              metrics.impressions,              metrics.clicks,              metrics.cost_micros          FROM keyword_view          WHERE segments.date DURING LAST_7_DAYS              AND campaign.advertising_channel_type = 'SEARCH'              AND ad_group.status = 'ENABLED'              AND ad_group_criterion.status IN ('ENABLED','PAUSED')          ORDER BY metrics.impressions DESC          LIMIT 50";         try         {             // Issue a search request.             await googleAdsService.SearchStreamAsync(customerId.ToString(), query,                 delegate (SearchGoogleAdsStreamResponse resp)                 {                     // Display the results.                     foreach (GoogleAdsRow criterionRow in resp.Results)                     {                         responseMessage +=                             "Keyword with text " +                             $"'{criterionRow.AdGroupCriterion.Keyword.Text}', match type " +                             $"'{criterionRow.AdGroupCriterion.Keyword.MatchType}' and ID " +                             $"{criterionRow.AdGroupCriterion.CriterionId} in ad group " +                             $"'{criterionRow.AdGroup.Name}' with ID " +                             $"{criterionRow.AdGroup.Id} in campaign " +                             $"'{criterionRow.Campaign.Name}' with ID " +                             $"{criterionRow.Campaign.Id} had " +                             $"{criterionRow.Metrics.Impressions.ToString()} impressions, " +                             $"{criterionRow.Metrics.Clicks} clicks, and " +                             $"{criterionRow.Metrics.CostMicros} cost (in micros) during the " +                             "last 7 days.";                     }                 }             );         }         catch (GoogleAdsException e)         {             responseMessage += "Failure:\n";             responseMessage += $"Message: {e.Message}\n";             responseMessage += $"Failure: {e.Failure}\n";             responseMessage += $"Request ID: {e.RequestId}\n";             throw;         }         return responseMessage; 

When I call this I get the following error:

{     "StatusCode": 16,     "Details": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",     "RequestId": "0Yk2OYrUATjwftZ5I0qi2g",     "Failure": {       "errors": [         {           "errorCode": {             "authenticationError": "NOT_ADS_USER"           },           "message": "User in the cookie is not a valid Ads user."         }       ]     }   }   

I have the service account set up with the Google Ads API Enabled. Why does it think I'm "NOT AN ADS USER" ???

The Company I work with has many clients who uses Google Ads to do marketing for their websites. The company wants to use client's data for Analysis. I am given a project to integrate Google Ads API using C# to get all the data such as Campaigns etc from Google ads and move it to our system for each client. I am only given developer token and customerID for Clients. such as

  1. Customer ID for Client A
  2. Customer ID for Client B

I am bit lost when I went through the google ads API documentation. In the documentation, the OAuth2.0 needs creating in order to use client library which would generate client ID and Client Secret, Refresh token to integrate the API. My question is. Do I need to create OAuth2.0 for each client or do I need to ask my company to generate Client ID and secret in company's Manager Account or Client that uses Google ads would provide me these?

The following Link I found to create OAuth2.

https://developers.google.com/google-ads/api/docs/oauth/cloud-project

This is what I believe would require in C# Content can be found at https://developers.google.com/adwords/api/docs/guides/first-api-call#.net_1

Would highly appreciate if any one can help me what actually I need to configure google ads using C#

I want to link and view the analytics account linked with Google Adwords.

Procedure used:

  1. Authenticating google account with scopes "Ananlytics and Adwords" with following url https://www.googleapis.com/auth/adwords https://www.googleapis.com/auth/analytics
  2. After getting the authentication response creating Google analytics service object.
  3. Google ads link API throwing error "Insufficient Premissions" screenshot attached

Script :

<?php //function to authenticate google account and create analytics service object function googleAuth(){         if (!empty($code)) {                         $postFields = 'client_id=' . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . '&client_secret=' . Configure::read('GOOGLE_OAUTH_CLIENT_SECRET') . '&code=' . $code . '&grant_type=authorization_code&redirect_uri=' . Configure::read('GOOGLE_OAUTH_REDIRECT_URI');                         $ch = curl_init();                         curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');                         curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);                         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);                         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);                         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                         $Rec_Data = curl_exec($ch);                         if (curl_exec($ch) === false) {                                 return $Rec_Data;                         }                         $Rec_Data = json_decode($Rec_Data, true);                         if (isset($Rec_Data['refresh_token'])) {                                                                  try {                                         $credentials = array('client_id' => Configure::read('GOOGLE_OAUTH_CLIENT_ID'), 'client_secret' => Configure::read('GOOGLE_OAUTH_CLIENT_SECRET'), 'redirect_uris' => array(Configure::read('GOOGLE_OAUTH_REDIRECT_URI')));                                         $client = new \Google_Client($credentials);                                                                                                  $client->addScope(\Google_Service_Analytics::ANALYTICS_READONLY);                                                 $client->setAccessToken($Rec_Data['access_token']);                                                 // Create an authorized analytics service object.                                                 $analytics = new \Google_Service_Analytics($client);                                                                          } catch (Exception $e) {                                         echo 'Caught exception: ', $e->getMessage(), "\n";                                         die();                                                                          }                         }                 } else {                         if (!empty($id)) {                                 header("Location:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=" . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . "&redirect_uri=" . Configure::read('GOOGLE_OAUTH_REDIRECT_URI') . "&access_type=offline&approval_prompt=force&state=" . $id . "&scope=https://www.googleapis.com/auth/adwords https://www.googleapis.com/auth/analytics");                                 exit;                         }                 } } //function to fetch linked account list function adwordsLinkAnalytics($analyticsAuth){                 $this->autoRender = false;                          try {                         $adWordsLinks = $analyticsAuth->management_webPropertyAdWordsLinks                                 ->listManagementwebPropertyAdWordsLinks('123456', 'UA-123456-1');                 } catch (apiServiceException $e) {                         print 'There was an Analytics API service error '                         . $e->getCode() . ':+' . $e->getMessage();                         exit;                 } catch (apiException $e) {                         print 'There was a general API error '                         . $e->getCode() . ':-' . $e->getMessage();                         exit;                 }                 pr($adWordsLinks);                 exit;                  } 

Required result: List of the analytics account linked with adwords account.