I have been working on adding properties to my Google Analytics account, I have been stuck with this for more than 24 hrs now, and I have no idea on what I am doing wrong... every time I try to create a Web property it returns a 403 (insufficient permission)
error.
Here is my code:
$client = new Google_Client();
$accountName = "xxxxxxxxxxxcl@developer.gserviceaccount.com";// Email Address
$p12 = $applicationPath."/google-api-php-client-master/API-xxxxx-xxxxxxx.p12";
$client->setScopes(array(
'https://www.googleapis.com/auth/analytics',
'https://www.googleapis.com/auth/analytics.manage.users'
));
$client->setApplicationName('My App Sample');
$client->setClientId('xxxxxxxxxxxcl.apps.googleusercontent.com');// Client Id
$client->setAccessType('offline');
$client->setAssertionCredentials(new Google_Auth_AssertionCredentials(
$accountName,
array('https://www.googleapis.com/auth/analytics'),
file_get_contents($p12), 'xxxxxxxx')
);
$analytics = new Google_Service_Analytics($client);
try {
$property = new Google_Service_Analytics_Webproperty();
$property->setName('sample-property');
$analytics->management_webproperties->insert('123456', $property);// 123456 my View Id
} catch (apiServiceException $e) {
print 'There was an Analytics API service error '
. $e->getCode() . ':' . $e->getMessage();
} catch (apiException $e) {
print 'There was a general API error '
. $e->getCode() . ':' . $e->getMessage();
}
I tried everything but I keep getting the (403) Insufficient Permission
error. someone please point me in the right direction, thanks.
You need to send Account id not view id.
$analytics->management_webproperties->insert('123456', $property);// 123456 my View Id
Have you applied for Beta access?
Beta Access: Write operations in the Management API (e.g. create, update, delete, patch) for Web Property, View (Profile), and Goal resources is currently available as a developer preview in limited beta. If you're interested in using these features, request access to the beta.
Request Access form: here
Required field
If you have been grated beta access you might want to try posting on the beta forum I cant remember if there was anyone there with PHP code. But I think setWebsiteUrl might be required as part of the Property body. But it doesn't appear to be documented for PHP that it is I will have to test that.
Service Account
It also appears that you are using a service account, did you give the service account write access at the account level to the Google Analytics Account you are trying to create a new web property for
? I did a test and you can use insert with a service account that has been grated access.