I am trying to use Google Analytics Measurement protocol (available with Universal Analytics) to track an offline event.
I am using the documentation here : https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#event
Here is the CURL I am calling :
https://www.google-analytics.com/collect?v=1&tid=UA-5520857-25&cid=1260961011.1389432370&t=event&ec=Test-event-cat&ea=Test-event-action&el=&ev=
I get the cid (client ID) via :
ga(function(tracker) {
var clientId = tracker.get('clientId');
});
Here is the full CURL call :
$getString = 'https://www.google-analytics.com/collect?';
$getString .= http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $getString);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
// TEST
echo 'CURL call : '.$getString.'<br />';
echo 'Response : <pre>';
print_r($info);
echo '</pre>';
It returns a 200 HTTP code (but I've read that its always the case, even if something is wrong).
No event is shown in my Google Analytics account, even on the real time section.
Do you have any idea about what I am doing wrong ?
Thank you
The problem was that I wasn't setting the el and ev parameters.
The correct call is :
https://www.google-analytics.com/collect?v=1&tid=UA-5520857-25&cid=1260961011.1389432370&t=event&ec=Test-event-cat&ea=Test-event-action&el=test-label&ev=1
The request in Measurement protocol, does not work, if there is no User-Agent
Related
Wink API is currently on version 2.
My Question: How can you do a simple "Hello World" with the Wink API V2 via PHP?
Notes:
Wink uses PubNub for subscriptions (devices have an event)
Uses OAuth2 standard
Website/Login is often "hokey": (& will error when you login: "Authentication failed!")
Login here: https://developer.wink.com & use Google account (or whatever)
Then change URL to this: https://developer.wink.com/clients
Sometimes you have to do this a couple times!!
You will need to request an Application API key in order to use the API. I followed up with an email to get it approved swiftly.
Once you are approved, you'll get: Client ID, Client Secret, & URLs to assist
API URL: https://api.wink.com/...
Email support: support#wink.zendesk.com (Get Application API key, etc)
OAuth 2:
Wink indicates to use "Authorization Code Grant Type"
Dox & Example: https://developer.byu.edu/docs/consume-api/use-api/choose-grant-type
Related Links:
Wink API: https://winkapiv2.docs.apiary.io/#
Stackoverflow related questions:
How to use Wink API V2 from a non-web app
Issues with Pubnub + Wink Hub and sensors
Wink API Subscriptions Stop Sending Overnight
https://community.home-assistant.io/t/wink-access-token-issue/52197/15
Github Example: https://github.com/cbulock/php-wink (This was last updated 3 years ago; might be on previous API ver)
Information regarding this is extremely limited, so I'll answer my own question hoping to help others. (It took a long time since there wasn't any good info out there.) This example has a user interface (Login required by Wink). I'm hoping someone can post a non-user-interface version (for background scripting, etc).
This will give you raw json output, for you to do with as you wish. This single php page will initially load, take you to Wink's login (you need an account with your devices if this wasn't obvious), after logging it, it will take you back to this same page with a code, call for a token, then use that token to get the device resources.
Create: //[YourServer]/wink_helloworld.php on your http/php server.
wink_helloworld.php:
//Make sure to add this exact URL to your Wink Developer Portal! (https://developer.wink.com/clients)
$redirect_uri = "http://[YourServer]/wink_helloworld.php";
// This is from Wink Developer Portal
$client_id = "abcdefg";
$wink_oauth_url = "https://api.wink.com/oauth2/token";
$client_secret = "hijklmnop";
$devices_url = "https://api.wink.com/users/me/wink_devices";
//need to create a state variable, like a session id. should actually be random tho!!
$randomstring="xyzABC123";
$state = base64_encode($randomstring);
/*_____________________________________________________________________________________________________________________________________ */
echo "<h2>Wink Hello World - Show Devices</h2>";
//If we don't have a code, then send user to login page
if($_GET['code'] == null | $_GET['code'] == ""){
echo "<a href='https://api.wink.com/oauth2/authorize?response_type=code&client_id=".$client_id."&redirect_uri=$redirect_uri&state=".$state."'>Login</a>";
return;
}
$code = $_GET['code'];
//if we dont have a token, lets get one
if($access_token == null | $access_token == ""){
$access_token = getAccessToken();
}
// lets get some data from our devices!
getResource($access_token);
/*_____________________________________________________________________________________________________________________________________ */
// Get token
function getAccessToken() {
global $wink_oauth_url, $code, $client_secret;
echo "<b>getAccessToken()</b> Using Code: $code<br>";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $wink_oauth_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, "{
\"client_secret\": \"$client_secret\",
\"grant_type\": \"authorization_code\",
\"code\": \"$code\"
}");
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response = curl_exec($curl);
//var_dump($response);
formatResults($response); //debug output
curl_close($curl);
return json_decode($response)->access_token;
}
/*_____________________________________________________________________________________________________________________________________ */
// Get Resource(s) with our code & token
function getResource($access_token) {
global $devices_url;
echo "<b>getResource()</b> Using Token: $access_token<p>";
$header = array("Authorization: Bearer {$access_token}");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $devices_url,
CURLOPT_HTTPHEADER => $header,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true
));
$response = curl_exec($curl);
curl_close($curl);
formatResults($response); //debug output
}
/*_____________________________________________________________________________________________________________________________________ */
//debug formatted output functions
function formatResults($json){
echo "<pre>";
echo json_encode(json_decode($json), JSON_PRETTY_PRINT);
echo "</pre>";
}
?>
I am writing a script that does foreign exchange using an API to do it in realtime.
I presume that the problem is in my implementation of curl, as I get no output from this :
$currencyBase = "USD";
$currencyForeign = "EUR";
$url = 'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=' . $currencyBase . '&to_currency=' . $currencyForeign . '&apikey=KCUGBA9AP3Z1E2P8';
echo $currencyBase;
// create curl resource
$c = curl_init($url); //Initialize a cURL session
curl_setopt($c, CURLOPT_HEADER, 0); //Set an option for a cURL transfer
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); //Set an option for a cURL transfer
$this->fxRate = doubleval(curl_exec($c));
curl_close($c); //Close a cURL session
I have hardcoded
$currencyBase = "USD";
$currencyForeign = "EUR";
for debugging and I have also tried print_r($c) to see if I'm passing anything but I still get no output.
I know that my API call works because I have tried the link with entered USD and EUR and I get a response when I enter it in the browser as follows:
https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=USD&to_currency=EUR&apikey=KCUGBA9AP3Z1E2P8
But I always get an empty response when I print the output from the script.
Your problem is this part of the code: $this->fxRate = doubleval(curl_exec($c));
curl_exec returns a string (which happens to be json), which you are casting to doubleval and that results in 0. Try it like this instead:
$this->fxRate = json_decode(curl_exec($c))->{"Realtime Currency Exchange Rate"}->{"5. Exchange Rate"};
I've got the OneNote API PHP Sample (thanks jamescro!) working with all the POST examples, but there's no GET example and I haven't managed to put together code of my own that works. Here's what I've tried without success:
// Use page ID returned by POST
$pageID = '/0-1bf269c43a694dd3aaa7229631469712!93-240BD74C83900C17!600';
$initUrl = URL . $pageID;
$cookieValues = parseQueryString(#$_COOKIE['wl_auth']);
$encodedAccessToken = rawurlencode(#$cookieValues['access_token']);
$ch = curl_init($initUrl);
curl_setopt($ch, CURLOPT_URL, $initUrl); // Set URL to download
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (! $response === false) {
curl_close($ch);
echo '<i>Response</i>: '. htmlspecialchars($response);
}
else {
$info = curl_getinfo($ch);
curl_close($ch);
echo '<i>Error</i>: ';
echo var_export($info);
}
It just returns 'Error' with an info dump. What am I doing wrong?
without information on the specific error I'm not sure what issue you are hitting. Try looking at the PHP Wordpress plugin here: https://github.com/wp-plugins/onenote-publisher/blob/master/api-proxy.php
look at what is sent to wp_remote_get - there are necessary headers that are needed.
Also make sure you have the scope "office.onenote" when you request the access token.
If you need more help, please add information about the specific URL you are attempting to call, as well as the contents of your headers. If you have any errors, please include the output.
Solved:
As Jay Ongg pointed out, "there are necessary headers that are needed".
After adding more detailed error checking and getting a 401 response code, I added:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:text/html\r\n".
"Authorization: Bearer ".$encodedAccessToken));
... and could access the requested page.
I have the following code in order to call a Web Service from php, using curl:
<?php
echo "Init<br />";
$url = 'http://server-ip/applications/time2gate.aspx?x=1182&y=365&map=1002&gate=B3&mode=time2gate&session=5fdf288d-01b0-414a-ba2a-58d3f624e453';
$ch = curl_init($url);
echo "1";
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
$status_code = array();
preg_match('/\d\d\d/', $resp, $status_code);
switch($status_code[0]) {
case 200:
echo "Success<br />";
break;
case 503:
die('Your call to Web Service failed and returned an HTTP 503.');
break;
case 403:
die('Your call to Web Service failed and returned an HTTP status of 403.');
break;
case 400:
die('Your call to Web Services failed and returned an HTTP status of 400.');
break;
default:
die('Your call to Web Services returned an unexpected HTTP status of:' . $status_code[0]);
}
if(curl_errno($ch))
{
echo 'error' . curl_error($ch);
}
curl_close($ch);
?>
The problem is that I receive HTTP response codes like 163, 815, 329... Why is this happening? What do these codes mean? I checked Apache's error log and I have not seen any errors on my code. Also, I tested a call to the url provided and it works with Mozilla's Poster Add-on.
Any ideas? I am working with php 5, on Ubuntu 12.
Thank you,
Nick
When I need to make API calls I use a simple library available on GitHub: https://github.com/rmccue/Requests
I've put an example below which uses this library and it will print out the full response from the API.
<?php
require_once('library/Requests.php');
$url = 'http://server-ip/applications/time2gate.aspx?x=1182&y=365&map=1002&gate=B3&mode=time2gate&session=5fdf288d-01b0-414a-ba2a-58d3f624e453';
// Next, make sure Requests can load internal classes
Requests::register_autoloader();
// Now let's make a request!
$request = Requests::get($url, array('Accept' => 'application/json'));
echo '<pre>';
print_r($request);
echo '</pre>';
API integration description
The API needs a form to be posted to the API URL with some input fields and a customer token. The API processes and then posts response to a callback.php file on my server. I can access the posted vals using $_POST in that file. That's all about the existing method and it works fine.
Requirement
To hide the customer token value from being seen from client side. So I started with sending server side post request.
Problem
I tried with many options but the callback is not happening -
1) CURL method
$ch = curl_init(API_URL);
$encoded = '';
$_postArray['customer_token'] = API_CUSTOMER_TOKEN;
foreach($_postArray as $name => $value)
{
$encoded .= urlencode($name).'='.urlencode($value).'&';
}
// chop off last ampersand
$encoded = substr($encoded, 0, strlen($encoded)-1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
$resp echoes 1 if the line curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); is removed but the callback does not happen. I am setting a session variable in the callback script to verify.Is it needed that the API be synchronous in order to use curl method, so that curl_exec returns the response?
2) without CURL as given in Posting parameters to a url using the POST method without using a form
But the callback is not happening.
I tried with the following code too, but looks like my pecl is not installed properly because the HttpRequest() is not defined.
$req = new HttpRequest($apiUrl, HttpRequest::METH_POST);
$req->addQueryData($params);
try
{
$r->send();
if ($r->getResponseCode() == 200)
{
echo "success";
// success!
}
else
{
echo "failure";
// got to the API, the API returned perhaps a RESTful response code like 404
}
}
catch (HttpException $ex)
{
// couldn't get to the API (probably)
}
Please help me out! I just need to easily send a server side post request and get the response in the callback file.
Try to debug your request using the curl_get_info() function:
$header = curl_getinfo($ch);
print_r($header);
Your request might be OK but it my result in an error 404.
EDIT: If you want to perform a post request, add this to your code:
curl_setopt($ch, CURLOPT_POST, true);
EDIT: Something else I mentioned at your code: You used a '1' at the 'CURLOPT_RETURNTRANSFER' but is should be 'true':
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
At least this is how I usually do it, and you never know if the function will also understand a '1' as 'true';
EDIT: The real problem: I copy-pasted your source and used it on one of my pages getting this error:
Warning: urlencode() expects parameter 1 to be string, array given in C:\xampp\htdocs\phptests\test.php on line 8
The error is in this line:
foreach($_postArray as $name => $value)
$_postArray is an array with one value holding the other values and you need either another foreach or you simple use this:
foreach($_postArray['customer_token'] as $name => $value)
As discussed in the previous question, the callback is an entirely separate thing from your request. The callback also will not have your session variables, because the remote API is acting as the client to the callback script and has its own session.
You should really show some API documentation here. Maybe we're misunderstanding each other but as far as I can see, what you are trying to do (get the callback value in the initial CURL request) is futile, and doesn't become any less futile by asking twice.