I have a website where I send events to Google Analytics using javascript function:
ga('send', 'event', 'showphone', 'feedback', 'result');
However I also need to send some similar events from server-side using PHP. I tried this quick start tutorial: Hello Analytics API: PHP quickstart for service accounts and reporting works like a charm, but I have no idea how to send event.
Could you please show me step-by-step what I should code to send exactly same event like mentioned above.
Hello Analytics API: PHP quickstart for service accounts is not going to help you at all. That code uses the core reporting API the core reporting API is for requesting data from Google Analytics not sending data to Google Analytics.
To send data to Google Analytics we use the Measurement Protocol. The measurement protocol is used to send information to Google analytics the JS snippet you posted also uses the measurement protocol.
You can use the measurement protocol from any language that supports HTTP post or Http Get. That being said there is no PHP specific library for sending information to Google analytics you are going to have to format your post yourself. A tip would be to use Validating hits to check it before you send it to Google while you are developing this.
It will probably look something like this
http://www.google-analytics.com/collect?v=1&tid=UA-XXX-Y&cid=35009a79-1a05-49d7-b876-2b884d0f825b&an=My%20Awesom%20APP&aid=com.daimto.awesom.app&av=1.0.0&aiid=come.daimto.awesom.installer &t=event&ec=list&ea=accounts&userclicked&ev=10
There is a PHP library php-ga-measurement-protocol by theiconic on github which can be used to send data using Measurement Protocal.
use TheIconic\Tracking\GoogleAnalytics\Analytics;
// Instantiate the Analytics object
// optionally pass TRUE in the constructor if you want to connect using HTTPS
$analytics = new Analytics(true);
// Build the GA hit using the Analytics class methods
// they should Autocomplete if you use a PHP IDE
$analytics
->setProtocolVersion('1')
->setTrackingId('UA-26293728-11')
->setClientId('12345678')
->setDocumentPath('/mypage')
->setIpOverride("202.126.106.175");
// When you finish bulding the payload send a hit (such as an pageview or event)
$analytics->sendPageview();
Here is an example of how to do it with PHP.
First build your request with Google Analytics Hit Builder, test it with https://google-analytics.com/debug/collect?_query_here, and then send it with file_get_contents (see here).
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => 'v=1&t=transaction&tid=UA-xxxxxxx-x&cid=xxxxxx&ti=abcdef&tr=100&in=productname'
)
);
$context = stream_context_create($options);
$result = file_get_contents('https://www.google-analytics.com/collect', false, $context);
Related
I would like to send email messages with our corporate emails provided by Gmail. In order to do that, I would like to use Gmail API with rest commands (basically launched with a php procedural code, for legacy purpose).
I have that code :
I go to this url :
// https://accounts.google.com/o/oauth2/auth?client_id=my_client_id&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/gmail.send&response_type=code
// and obtain a token like that : 4/1AX4XfWgmW0ZdxXpJn8YzkVeDs3oXZUHyJcR7abE2TuqQrcmo4c1W02ALD4I
/*
echo GoogleAuthCurl("GET", '', array(
'client_id' => $GOOGLE_CLIENT_ID,
'redirect_uri'=>'urn:ietf:wg:oauth:2.0:oob',
'scope' => 'https://www.googleapis.com/auth/gmail.send',
'response_type' => 'code'
), array());
then I can use requests in curl for getting my access token :
curl \
--request POST \
--data "code=[Authentcation code from authorization link]&client_id=[Application Client Id]&client_secret=[Application Client Secret]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code" \
https://accounts.google.com/o/oauth2/token */
$tokenJson = json_decode( GoogleTokenCurl("POST", '', array(), array(
'code' => '4/1AX4XfWiEWngRngF7qryjtkcOG1otVtisYpjHnej1E54Pujcrchef8REvdt0',
'client_id' => $GOOGLE_CLIENT_ID,
'client_secret' => $GOOGLE_CLIENT_SECRET,
'redirect_uri'=>'urn:ietf:wg:oauth:2.0:oob',
'grant_type' => 'authorization_code'
)
));
print_r($tokenJson);
This far, I've got food for my authorization header. My issue is in the first step (with the consent asked to user). I wish i can do this step without putting my url in the browser, validate two screens to grant access before getting the authorization code.
I'm also interested in advices to create gmail messages with rest requests driven by curl. I found postman collection about all actions gmail api can do, but one or two call examples wouldn't do harm ;)
thanks !
In the current state, by the method you are using, &response_type=code, you need two calls to the OAuth client to get the access token. You can find an example of how to handle it just using HTTP/REST requests here.
In any case, you could use Google API Client Library for PHP. Allows you to handle the OAuth authentication flow, only needing one interaction to get the token.
You can find a full example on how this works here, notice that this example uses the Drive API, if you want to use it within the Gmail API, you can check Gmail API PHP library.
Documentation:
PHP Gmail API
OAuth 2.0 to Access Google APIs
I am using a fairly simple piece of code to send events to a Google Analytics account:
$req = curl_init('https://www.google-analytics.com/collect');
curl_setopt_array($req, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS =>
"v=1&t=event&tid=UA-40825301-52&cid=123456&ec=test&ea=test2&el=test3&ev=123&utmcsr=google&utmcmd=organic"
));
$response = curl_exec($req);
What I am trying to achieve is sending offline conversions to our Google Analytics as events. We do know the initial source of these conversions and want this data in Google Analytics too. utmcsr and utmcmd are supposed to be used to send source & medium data but.. all events end up as direct traffic. Any idea what might be the issue?
What you're using is called Measurement protocol. There are multiple comfortable libraries to use it. You still can use it through curl, but then I don't recognize the utmcsr and utmcmd. Where are they from?
Here is the parameter reference for it: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters I don't see there the parameters you're trying to pass in your request.
The utm params are a part of the dl parameter. The document location. You can inspect an existing collect call and see how this info is passed. Here, I used SO's existing tracking, just faked the utm params:
Disregard all cd parameters and the dp. You don't seem to be needing them for now.
Feel free to explore the measurement protocol properly starting from here: https://developers.google.com/analytics/devguides/collection/protocol/v1
It appears that using the cm and cs parameters allow you to post source and medium to Google Analytics with server side analytics tracking.
What helped me tremendously:
https://ga-dev-tools.web.app/hit-builder/
https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
My code:
$req = curl_init('https://www.google-analytics.com/collect');
curl_setopt_array($req, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS =>
"v=1&t=transaction&tid=UA-40825301-52&cid=e87f9f6f-fba1-4922-9319-98e3c1d6f7c6&dp=%2Freceipt&dt=Receipt%20Page&ti=T12345&ta=Direct&tr=37.39&tt=2.85&ts=5.34&tcc=SUMMER2013&pa=purchase&pr1id=P12345&pr1nm=Android%20Warhol%20T-Shirt&pr1ca=Apparel&pr1br=Google&pr1va=Black&pr1ps=1&utm_source=google&utm_medium=ads&ds=web&cs=google&cm=organic"
));
$response = curl_exec($req);
$curl = curl_init();
We got an email regarding updating discovery document.
Starting November 1, 2021, projects which have not updated their discovery document will no longer be supported and will stop working.
We are using external API library: googleapis/google-api-php-client, for Webmasters API.
Currently I'm using the below API call.
$client = new Google_Client();
$client->setApplicationName(xxxxxxxxxxxxxxxx);
$client->setAuthConfig(xxxxxxxxxxxxxxxxxxxxxx);
$scopesArray = array(
'https://www.googleapis.com/auth/webmasters'
);
$client->setScopes($scopesArray);
...................................................
.....................................................
$googlewebmasterssearchsnalyticsobject = new \Google_Service_Webmasters_SearchAnalyticsQueryRequest();
$googlewebmasterssearchsnalyticsobject->setStartDate('1970-01-01');
$endDate = gmdate('Y-m-d');
$googlewebmasterssearchsnalyticsobject->setEndDate($endDate);
$googlewebmasterssearchsnalyticsobject->setDimensions(['page', 'date']);
$googlewebmasterssearchsnalyticsobject->setSearchType('web');
..................................................................
What should I update in the above API call?
You aren't directly using the discovery document the Client library does for you. Any issues should have been addressed in that library already.
If you are worried you should cross post this issue over on their issue forum. if there is an issue its something that should be fixed in the library
I can see this question was cross posed to Update the Google Search Console API discovery document #2149
If you're using Google's client library, you must update the discovery doc
From: https://www.googleapis.com/discovery/v1/apis/webmasters/v3/rest
To: https://searchconsole.googleapis.com/$discovery/rest
In my case, I was using Google's JavaScript client library, and was not providing the discoveryDocs parameter. I needed to replace instances of webmaster / v3 to searchconsole / v1, as shown below.
From:
gapi.client.load('webmasters', 'v3').then(function(){
To:
gapi.client.load('searchconsole', 'v1').then(function(){
I need major help!
I am having troubles getting the Pubnub subscribe function to work with PHP! I can get the publish function to work, but not the subscribe function. I have copied some code straight from the Pubnub site, but I am not getting anything. Any help? Also, my PHP version is 5.2.*.
Code:
<?
include("Pubnub.php");
$pubnub = new Pubnub(
"not showing you", // PUBLISH_KEY
"not showing you", // SUBSCRIBE_KEY
"", // SECRET_KEY
false // SSL_ON?
);
$pubnub->subscribe(array(
'channel' => 'Chat',
'callback' => create_function(
'$message',
'var_dump($message); return true;'
)
));
?>
⚠️ ALERT: SDK has been upgraded ⚠️
New SDK URL: https://github.com/pubnub/php
You are asking about a way to use the Subscribe method within a web server like Apache using PHP as the dynamic processing language. Note that this is not a good practice and generally not necessary to do. You would not use the Subscribe({...}) method in a request/response.
The correct way to utilize the $pubnub->subscribe(...) method is in a long-lived PHP process, not involving a web server request-response model. Here are some examples that are confirmed to work:
https://github.com/pubnub/php
Note that each example is assumed to be in a solitary PHP process outside of a web server like Apache when using the Subscribe API in PHP. However! The Publish() API can be used anywhere, including an Apache web server.
Reading History w/ Apache PHP
As an alternative you will be happy to take advantage of our HISTORY API. You can query messages in the Queue with this and receive messages. Here is an example PHP History API usage:
<?php
## Capture Publish and Subscribe Keys from Command Line
$publish_key = "YOUR_PUBLISH_KEY";
$subscribe_key = "YOUR_SUBSCRIBE_KEY";
## Require Pubnub API
require('../Pubnub.php');
## -----------------------------------------
## Create Pubnub Client API (INITIALIZATION)
## -----------------------------------------
$pubnub = new Pubnub( $publish_key, $subscribe_key );
## Get History
echo("Requesting History...\n");
$messages = $pubnub->history(array(
'channel' => 'hello_world', ## REQUIRED Channel to Send
'limit' => 100 ## OPTIONAL Limit Number of Messages
));
var_dump($messages); ## Prints Published Messages.
?>
The php subscribe function is broken and will be fixed in a new upcoming api, I talked with support recently about this and they gave me the this information.
I'm trying to use the Google API v3 to access one google calendar and according to the documentation here : http://code.google.com/apis/calendar/v3/using.html#intro and here : https://code.google.com/apis/console/, the solution I need is the "Simple API Access" & "Key for server apps (with IP locking)".
Now, when I create a page with this code :
session_start();
require_once 'fnc/google-api-php-client/src/apiClient.php';
require_once 'fnc/google-api-php-client/src/contrib/apiCalendarService.php';
$apiClient = new apiClient();
$apiClient->setUseObjects(true);
$service = new apiCalendarService($apiClient);
if (isset($_SESSION['oauth_access_token'])) {$apiClient->setAccessToken($_SESSION['oauth_access_token']);
} else {
$token = $apiClient->authenticate();
$_SESSION['oauth_access_token'] = $token;
}
and in my "config.php" file I add ONLY my developper key (in place of the "X") :
global $apiConfig;
$apiConfig = array(
// True if objects should be returned by the service classes.
// False if associative arrays should be returned (default behavior).
'use_objects' => false,
// The application_name is included in the User-Agent HTTP header.
'application_name' => '',
// OAuth2 Settings, you can get these keys at https://code.google.com/apis/console
'oauth2_client_id' => '',
'oauth2_client_secret' => '',
'oauth2_redirect_uri' => '',
// The developer key, you get this at https://code.google.com/apis/console
'developer_key' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
// OAuth1 Settings.
// If you're using the apiOAuth auth class, it will use these values for the oauth consumer key and secret.
// See http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html for info on how to obtain those
'oauth_consumer_key' => 'anonymous',
'oauth_consumer_secret' => 'anonymous',
But then I get errors and it tells me it's trying to authenticate using the "OAuth 2.0" system which I don't want to use. I only want to access one calendar with an API key.
And amazingly, when I search in google "Simple API Access key" I find nothing, nothing on their docs, no examples, no tutorials, nothing. Am I the only one using this thing?
So can someone tell me what I'm doing wrong?
(i know this is an old question but i would've been glad if someone
gave a real answer here so i'm doing it now)
I came on the same problem, Simple API access is not well documented (or maybe just not where i searched), but using the Google API Explorer i found a way to get what i need, which is in fact pretty straightforward. You don't need specific lib or anything : it's actually really simple.
In my case i simply needed to search a keyword on G+, so i just had to do a GET request:
https://www.googleapis.com/plus/v1/activities?query={KEYWORD}&key={YOUR_API_KEY}
Now, for a calendar access (see here), let's pretend we want to fetch access control rules list. We need to refer to calendar.acl.list which give us the URI :
https://www.googleapis.com/calendar/v3/calendars/{CALENDAR_ID}/acl?key={YOUR_API_KEY}
Fill in the blanks, and that's pretty much all you need to do. Get a server key (API Access submenu), store it somewhere in your project and call it within URIs you're requesting.
You cannot access your calendar information using API Key. API keys (or simple API acess key) are not authorized tokens and can only be used for some API calls such as a Google search query etc; API keys will not let you access any user specific data, which I am assuming is your objective through this calendar application.
Also, from what I see in your code, you are creating a client object which is going to use OAuth 2.0 authentication and hence you are getting authentication error messages.
There is no such a thing called Simple API Access key.
Normally OAuth 2.0 is used for authorization. But since you have your reason not to use it.
If you want to use OAuth1.0 for authorization. You need an API key in Simple API Access section on the API Access page.
If you want to use username & password login instead of OAuth, you can refer to ClientLogin, but this is not recommanded.
I got to this thread when trying to do the same today. Although this is way late, but the answer is YES, there is actually simple API key for those apis that does not need user authorizations, and the official client library support this.
The api library do this by Options, which is key, value pair.
Take the example of get information of a given youtube video, you would use this api: https://godoc.org/google.golang.org/api/youtube/v3#VideosListCall.Do
To use api key, simply make a type that implements the CallOption interface, and let it return the api key:
type APIKey struct {
}
func (k *APIKey) Get() (string, string) {
return "key", "YOU API KEY HERE"
}
Then when calling the API, supply the APIKey to it:
youtube, err := youtube.New(&http.Client{})
call := youtube.Videos.List("snippet,contentDetails,statistics").Id(id)
rsp, err := call.Do(opt)
This way, you can construct the youtube client with the vallina http client, rather than oauth client, and enjoy the simple api key.
The first answer said you can use http GET directly, but then you will need to handle the errors and parse the result yourself.
See below link which is helpfull to you. The Google API Client Library enables you to work with Google APIs such as Analytics, Adsense, Google+, Calendar, Moderator, Tasks, or Latitude on your server, in the language of your choice.
http://code.google.com/p/google-api-php-client/
Thanks,
Chintu