Posts tagged with google-analytics-api

How to properly report conversions back to google ads when they happen on server side?

I guess my usecase is pretty common but I can't seem to find any relevant information:

  • user clicks an ad on google
  • they are redirected to my website
  • they signup for a free trial
  • I report the "sign up" event back to google analytics (GA4) using gtag
  • the sign up event is linked to google ads as an "offline" event

This works good so far.

Now when trial ends and the user is charged for the first time, I want to further report a "renewal" event with the "value" charged so google ads could further optimise. But how do I do this?

Renewal happens on the server, while I also track the renewal using GA4 api, I'm not sure how to link it to the original user so it can be attributed correctly in GA4 and then in google ads.

Seems like I need to get cookies that google ads create in browser to identify a user when the user first signs up, and then send the cookies to the server and to further pass them to GA4 every time the renewal happens. But I can't see any documentation on that neither.

So how do I report server side events back to GA4/google ads ensuring the even is attributed to the correct user?

As a note, I'm not looking to use Google Tag Manager.

I am working with Google Ads Scripts. Based on my use case, I need to get the impressions, clicks, and other statistics about the products I have in my Google Ads account.

These product statistics will be analyzed in the script and based on certain criteria a Google Sheet document will be updated. The script goes like, retrieving all products (along with their statistics) from Google Ads account, see if the products impression and clicks meet a category (30 Impression, 1 click = Category "A", 20 Impressions, 0 Clicks = "Category B"), determines the product category, open Google Sheet hosted on Google Drive and updates the Category column in the Sheet based on product name or id.

Currently, I am facing an issue with retrieving Products and their statistics from Google Ads Account using Ads Script. I used the following code snippets to look for products but found no method or class that would help me achieve my desired results. I can only retrieve the productGroups, AdGroups, and Campaigns but none of them allow me to extract individual products.

function productGroup(){   var prodGroupIter = AdsApp.productGroups().get();   while (prodGroupIter.hasNext()){     Logger.log("prodGroup: ")     var prodGroup = prodGroupIter.next();     Logger.log(prodGroup.getValue());   } } function adGroup() {   var adGroupIterator = AdsApp.adGroups().get();   while (adGroupIterator.hasNext()) {     var adGroup = adGroupIterator.next();     Logger.log("adGroup: ")     Logger.log(adGroup.getName());   } } function campaign(){   var campIter = AdsApp.campaigns().get();   while (campIter.hasNext()){     var ads = campIter.next().ads().get();     while(ads.hasNext()){       Logger.log(ads.next().getStatsFor("LAST_30_DAYS"));     }   } } function sheet() {   var sheetURL = "https://docs.google.com/spreadsheets/d/1W0zhRrQa1P7qjQf0eXXw-QzdcPKAlDPiVBOcIVEfDgw/edit#gid=1428103052";   var sheet = SpreadsheetApp.openByUrl(sheetURL); } function main(){   campaign();   adGroup();   productGroup(); } 

I then reached out to the Ads Script support team and found out that it is not possible. But they suggested that I can use Shopping Performance Report, Product Partition Report, shopping_performance_view or product_group_view. They are part of AdWord API, and I do not know how to work with them.

So, I am looking for a Google Ads Script that would help me get a list of products (with detailed statistics) from Googe Ads and I am stuck with how to use the above-mentioned AdWord reporting endpoints to do it.

Here is the list of products in my Google Ads Account. They are 107 products along with their statistics.

Please, help with at least comments, ideas, and suggestions, I can write code but I am not sure what I am missing on

usually we add a script to our website to track conversion for google analytics. Is there any way send the data from plain javascript code such as in the case of Facebook. for example:

'use strict'; const bizSdk = require('facebook-nodejs-business-sdk'); const Content = bizSdk.Content; const CustomData = bizSdk.CustomData; const DeliveryCategory = bizSdk.DeliveryCategory; const EventRequest = bizSdk.EventRequest; const UserData = bizSdk.UserData; const ServerEvent = bizSdk.ServerEvent; const access_token = '<ACCESS_TOKEN>'; const pixel_id = '<ADS_PIXEL_ID>'; const api = bizSdk.FacebookAdsApi.init(access_token); let current_timestamp = Math.floor(new Date() / 1000); const userData = (new UserData())                 .setEmails(['joe@eg.com'])                 .setPhones(['12345678901', '14251234567'])                 // It is recommended to send Client IP and User Agent for Conversions API Events.                 .setClientIpAddress(request.connection.remoteAddress)                 .setClientUserAgent(request.headers['user-agent'])                 .setFbp('fb.1.1558571054389.1098115397')                 .setFbc('fb.1.1554763741205.AbCdEfGhIjKlMnOpQrStUvWxYz1234567890'); const content = (new Content())                 .setId('product123')                 .setQuantity(1)                 .setDeliveryCategory(DeliveryCategory.HOME_DELIVERY); const customData = (new CustomData())                 .setContents([content])                 .setCurrency('usd')                 .setValue(123.45); const serverEvent = (new ServerEvent())                 .setEventName('Purchase')                 .setEventTime(current_timestamp)                 .setUserData(userData)                 .setCustomData(customData)                 .setEventSourceUrl('http://jaspers-market.com/product/123')                 .setActionSource('website'); const eventsData = [serverEvent]; const eventRequest = (new EventRequest(access_token, pixel_id))                 .setEvents(eventsData); eventRequest.execute().then(   response => {     console.log('Response: ', response);   },   err => {     console.error('Error: ', err);   } );

or we can do something like: To send new events, make a POST request to this API's /events edge from this path: https://graph.facebook.com/{API_VERSION}/{PIXEL_ID}/events?access_token={TOKEN}. When you post to this edge, Facebook creates new server events.

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.

I am using:

https://developers.google.com/analytics/devguides/collection/protocol/v1/

for server side tracking.

This is the set-up:

  • Google analytics account.
  • Google adwords account.
  • Adwords account is linked to the analytics account.

I create an ad in adwords, the user clicks the ads, the user visits the third party website, the third party website make a https POST request with the visitor gclid from adwords. This is stored in a mysql database.

In the google adwords account I have an event for conversion created. (Using the offline tracking conversion works, but the only reason why I would prefer to use measurement protocol is because the offline tracking only accepts the conversions after 90 minutes. )

And I send the page views and conversion in this way:

/**  * @param $gclid  * @param $clientId  * @return \TheIconic\Tracking\GoogleAnalytics\AnalyticsResponse  */ private function sendPageView($gclid, $clientId){     $this->analytics         ->setProtocolVersion(1)         ->setTrackingId(self::GLOBAL_TRACKING_ID)         ->setGoogleAdwordsId($gclid)         ->setAnonymizeIp(true)         ->setClientId($clientId);     return $this->analytics->sendPageview(); } /**  * @param $gclid  * @param $clientId  * @return \TheIconic\Tracking\GoogleAnalytics\AnalyticsResponse  */ private function sendConversion($gclid, $clientId, $url){     $this->analytics         ->setProtocolVersion(1)         ->setTrackingId(self::GLOBAL_TRACKING_ID)         ->setGoogleAdwordsId($gclid)         ->setAnonymizeIp(true)         ->setClientId($clientId)         ->setEventAction('s2s')         ->setEventCategory('Lead')         ;     return $this->analytics->sendEvent(); } 

Response:

object(TheIconic\Tracking\GoogleAnalytics\AnalyticsResponse)#1008 (3) {   ["httpStatusCode":protected]=>   int(200)   ["requestUrl":protected]=>   string(164) "https://ssl.google-analytics.com/collect?v=1&tid=UA-1XXXXX-1&gclid=EAIaIQobChMInvrxopLZ5gIVXXXXXXXXXXXXXXXXXXXX_BwE&aip=1&cid=1&ea=s2s&ec=Lead&t=event"   ["responseBody":protected]=>   string(35) "GIF89a�����,D;" } 

So the response is 200, however the conversion is not recorded anywhere, and I am not sure if I should be sending any other parameter, or how to debug the issue.