问题
I'm experiencing an issue with getting the Google Analytics Managment API to work with Data Import.
When I send the data to the API via Google's PHP library, the uploaded file is visible in the "Manage Uploads" section, and appears to be correctly formatted CSV data, although the name of the file is just a random string without ".csv" at the end. See code same of this method below:
$client = new \Google_Client();
$client->setAuthConfig($config);
$client->setScopes(['https://www.googleapis.com/auth/analytics', 'https://www.googleapis.com/auth/analytics.edit']);
$analytics = new Google_Service_Analytics($client);
try {
$analytics->management_uploads->uploadData(
*****, // Account ID
*****, // Property ID
*****, // Data Set ID
[
'data' => $csvData, // contents of tmpfile, created with fputcsv, gathered with fread
'mimeType' => 'application/octet-stream',
'uploadType' => 'media',
]
);
} catch (\Exception $e) {
$response['error'] = 'Analytics Upload Error';
}
Though the data set appeared to be uploaded correctly, there was no corresponding data to be found in any reports. After downloading the file and changing the name to something ending in ".csv" and manually uploading via the web interface, the data became available. I assumed, then, that it meant that despite having the correct contents, Google wasn't handling the file correctly without the ".csv" extension.
So for my second attempt, I found references to using curl instead of their own library; doing so allowed me to pass an actual csv file, instead of just the contents of one. Example below:
$url = 'https://www.googleapis.com/upload/analytics/v3/management/accounts/' . ** Account ID ** . '/webproperties/' . ** Property ID ** . '/customDataSources/' . ** Data Set ID ** . '/uploads?access_token=' . ** Access Token **;
$file = function_exists('curl_file_create') ? curl_file_create($filename, 'application/octet-stream', 'csvData.csv') : '@' . realpath($filename);
$curl = curl_init();
$postFields = ['file_contents' => $file];
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
Again, the resulting (named) file shows up in the upload management view with a ".csv" extension and accurate data, yet it's still not visible to reporting tools. And same as the first time: downloading, renaming, and uploading via web interface works as intended, with the data being accessible in reporting.
The documentation doesn't mention any additional steps that should be taken regarding formatting, headers, etc. I'm not sure what further steps to try, since there appears to be no useful information as to what's going wrong - in fact everything looks to be working properly, yet the data is unavailable to reports when not manually uploaded.
来源:https://stackoverflow.com/questions/43644944/data-import-via-management-api