I am developing a Google Adwords app. I tried using the API libraries available in PHP. I found, I need "clientCustomerId" in "adsapi_php.ini". I don't see anyway to get this "clientCustomerId" using API with OAuth. Am I trying something wrong?
This really depends on your application design.
My setup is using a top-level manager account that has access to all the client accounts.
clientCustomerID is set to that manager id.
With that, you can grab a list of your clients using the ManagedCustomerService->get() method provided by the PHP library. You can look at the example code here:
https://github.com/googleads/googleads-php-lib/blob/master/examples/AdWords/v201710/AccountManagement/GetAccountHierarchy.php
That repo is now depreciated. As of Oct 2018 you should use this documentation: https://github.com/googleads/googleads-php-lib/blob/master/examples/AdWords/v201802/AccountManagement/GetAccountHierarchy.php
Try CustomerService
CustomerService provides information about your accounts. It has a
getCustomers() method that takes no arguments and returns a list of
Customer objects containing fields such as customerId, currencyCode,
and dateTimeZone. CustomerService
Reference: Managing Accounts
Google Adwords Authencation code ( Using PHP Client Lib )
You may check code samples from Google Adwords PHP sample
Get Credentials for API use
$oauth2 = new OAuth2([
'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
'redirectUri' => 'http://localhost/adwordsWork/index.php',
'clientId' => '1139632-xxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
'clientSecret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'scope' => 'https://www.googleapis.com/auth/adwords'
]);
if (!isset($_GET['code'])) {
$oauth2->setState(sha1(openssl_random_pseudo_bytes(1024)));
$_SESSION['oauth2state'] = $oauth2->getState();
$config = [
'access_type' => 'offline'
];
header('Location: ' . $oauth2->buildFullAuthorizationUri($config));
exit;
}
elseif (empty($_GET['state'])
|| ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state.');
} else {
$oauth2->setCode($_GET['code']);
$authToken = $oauth2->fetchAuthToken();
$refresh_token = $authToken['refresh_token'];
}
/* --------------------------- Authencation section End --------------------------------*/
// echo "<pre>";
// print_r($authToken);
// die;
/*---------------------------- Session Builder -----------------------------------------*/
$session = (new AdWordsSessionBuilder())
->fromFile('adsapi_php.ini')
->withOAuth2Credential($oauth2)
->build();
/* ------------------------- Session build ---------------------------------------------*/
/* -------------------------------- Adwords Services section ----------------------------*/
/* Creating object of Adwords services */
$adWordsServices = new AdWordsServices();
/* Adwords Customer services */
$customerService = $adWordsServices->get($session, CustomerService::class);
$customers = $customerService->getCustomers();
$customerId = $customers[0]->getCustomerId(); // Getting main customer client id
echo $customerId; // customer id from adwords account
Related
I want to integrate Twilio SMS Api in Phalcon 3 using dependency injection.It would be great if anyone could guide me in this process.
Just like any other PHP library that you want to use, you first need to check what is the installation method.
As noted by Nikolay Mihaylov in the comments, check the documentation for Twillo here:
https://www.twilio.com/docs/libraries/php
As you will see they do offer an installation through composer. All you need to do in your project then is:
composer require twilio/sdk
Registering Twillo in your DI container is the same as any other service:
// Your Account SID and Auth Token from twilio.com/console
$config = [
'sid' => 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'token' => 'your_auth_token',
]
// $di is the DI container
// Using the $config variable in the current scope
$di->set(
'db',
function () use ($config) {
$sid = $config['sid'];
$token = $config['token'];
$client = new \Twilio\Rest\Client($sid, $token);
return $client;
}
);
References:
https://docs.phalconphp.com/en/latest/reference/di.html
https://www.twilio.com/docs/libraries/php
I am attempting to retrieve the data from our content experiments from google analytics...
I am using the following code, my creds are good, and have been censored for this post...
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Hello Analytics API Sample');
// Visit https://cloud.google.com/console to generate your
// client id, client secret, and to register your redirect uri.
$client->setDeveloperKey('xxxxx');
$service = new Google_Service_Analytics($client);
try {
$results = $service->management_experiments->listManagementExperiments('xxxx', 'xxxx', 'xxxx');
} 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();
}
echo '<pre>';
print_r($results);
echo '</pre>';
I am using the following example ....
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#list
Any ideas on why I am getting a 401 unauthorized? That a login is required?
The problem is that you haven't Authorized access to your data yet. Since you say its only your own data you want to access i sugest you look into a service account. By setting up a service account in Google apis console it will allow you to access your own data with out needing to login and autenticate the code all the time.
Check the following link. Read though Before you begin make sure you do all that.
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#service
Register your application in the Google Developers Console
Authorize access to Google Analytics data.
Create an Analytics service object
You have skiped the first two steps and gone directly to step 3 creating the service object. Once you have done step 1 you can use the following code for step 2.
Here is an example of how to use a service account in php ServiceAccount
That sample project is for the PredictionService not the google analytics service. You need to edit it slightly.
require_once '../../src/Google/Client.php';
require_once '../../src/Google/Service/Analytics.php';
// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = 'INSERT_YOUR_CLIENT_ID';
const SERVICE_ACCOUNT_NAME = 'INSERT_YOUR_SERVICE_ACCOUNT_NAME';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = '/super/secret/path/to/key.p12';
$client = new Google_Client();
$client->setApplicationName("Google Analytics Sample");
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME(Email),
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents(KEY_FILE))
);
$client->setClientId(CLIENT_ID);
$service = new Google_Service_Analytics($client);
Now you have $service that you can use with the rest of your calls. Note: I didnt have time to test that code let me know if it doesnt work and i will give you a hand in fixing it.
Version 0.6.3 of the Google API php Client appears to support the importRows command:
public function importRows($tableId, $optParams = array()) {
$params = array('tableId' => $tableId);
$params = array_merge($params, $optParams);
$data = $this->__call('importRows', array($params));
if ($this->useObjects()) {
return new Google_Import($data);
} else {
return $data;
}
}
The importRows documentation doesn't really coincide with the way the function has been implemented in the php Client, as there doesn't appear to be anywhere to pass the CSV information too.
Does anyone have any example code using the Google API php Client 0.6.3 successfully implementing importRows?
I have my implementation working with a service account entering one row at a time. Obviously I'd prefer to do it in bulk rather than loop through an 'insert' or 'sql'.
I know this is a late reply, but for future reference, I will reply it anyway:
You need to use the uploadType, mimeType and data on the optParams array.
Example:
importRows( [tableId], array(
'uploadType' => 'media' ,
'mimeType' => 'application/octet-stream' ,
'data'=>'1,Moth, 30, 2012')
);
I am working on a website that allows the user to search for the top ten twitter trends in a city or country. At first I was only relying on Twitter's Rest API, but I was having a lot of rate limit issues (at school my rate limit disappears faster than I have a chance to use it). I know that authenticating my API calls will help me to better deal with this issue (Authenticated API calls are charged to the authenticating user’s limit while unauthenticated API calls are deducted from the calling IP address’ allotment).
I implemented #abraham's PHP library (https://github.com/abraham/twitteroauth), unfortunately my API calls aren't being authenticated. I know I have implemented #abraham's PHP library, because it prints out my user information at the end like it should. I have my twitter trend search underneath it but the API call isn't being authenticated. I am not sure how to fix this, and any help would really be appreciated!
This is what I use to get the top ten trends by country:
function showContent(){
// we're going to point to Yahoo's APIs
$BASE_URL = "https://query.yahooapis.com/v1/public/yql";
// the following code should only run if we've submitted a form
if(isset($_REQUEST['location']))
{
// set a variable named "location" to whatever we passed from the form
$location = $_REQUEST['location'];
// Form YQL query and build URI to YQL Web service in two steps:
// first, we show the query
$yql_query = "select woeid from geo.places where text='$location'";
// then we combine the $BASE_URL and query (urlencoded) together
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
//var_dump($location);
// show what we're calling
// echo $yql_query_url;
// Make call with cURL (curl pulls webpages - it's very common)
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
// Confirm that results were returned before parsing
if(!is_null($phpObj->query->results)){
// Parse results and extract data to display
foreach($phpObj->query->results as $result){
//var_dump($result);
$woeid = $result[0]->woeid;
if (is_numeric ($location))
{
echo "<span style='color:red; padding-left: 245px;'>Please enter a city or a country</span>";
}
else if(empty($result)){
echo "No results found";
}
else {
/* echo "The woeid of $location is $woeid <br />"; */
}
}
}
$jsontrends=file_get_contents("http://api.twitter.com/1/trends/".$woeid.".json");
$phpObj2 = json_decode($jsontrends, true);
echo "<h3 style='margin-top:20px'>TRENDS: ".$phpObj2[0]['locations'][0]['name']."</h3> \r\n";
$data = $phpObj2[0]['trends'];
foreach ($data as $item) {
echo "<br />".$item['name']."\r\n";
echo "<br /> \r\n";
}
if(empty($item)){
echo "No results found";
}
}
}
I then add it to #abraham's html.inc file (along with some php to see the rate limit status) and html.inc is included in the index.php:
<h1>Top Twitter Trends</h1>
<form name='mainForm' method="get">
<input name='location' id='location' type='text'/><br/>
<button id='lookUpTrends'>Submit</button>
</form>
<?php showContent();
$ratelimit = file_get_contents("http://api.twitter.com/1/account/rate_limit_status.json");
echo $ratelimit;
?>
</div>
#abraham's index.php file has some example calls, and since my call doesn't look like this I think that is probably why it isn't being authenticated.
/* Some example calls */
//$connection->post('statuses/update', array('status' => date(DATE_RFC822)));
//$connection->post('statuses/destroy', array('id' => 5437877770));
//$connection->post('friendships/create', array('id' => 9436992));
//$connection->post('friendships/destroy', array('id' => 9436992));
Please help me find what I need to fix so that my API calls are authenticated.
update 10-21
I think in order to make an authenticated API call I need to include something like this is my code:
$connection->get('trends/place', array('id' => $woeid));
It didn't fix my problem, but maybe it is on the right track?
First off, you'll find that keeping your PHP and HTML separate will really help streamline your code and keep logical concerns separate (aggregating the data and displaying it are two different concerns)(many PHPers like MVC).
The code you have shared appears to be correct. My guess is that the issue lies in the creation of the OAuth connection, which should look something like:
<?php
/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $token,$secret);
Where CONSUMER_KEY and CONSUMER_SECRET are from your Trends Test app and $token and $secret are from the user signing in to twitter and allowing your app permission. Are all these values showing up when you create the TwitterOAuth object?
Also, be sure you update the config items in the twitteroauth.php file (specifically line 21 should be set to use the 1.1 API and line 29 should be set to 'json').
I used to be able to query the Google Analytics API with my account's login & password.
Google is now using OAuth for authentication which is great...
The only issue is that I only need ONE access token.
I don't wanna allow other users to fetch THEIR analytics data.
I just wanna be able to fetch MY data.
Is there a way I can generate an access token only for my app or my analytics account?
I know such solutions exists... For instance, Twitter provides what they call a "single-user oauth" for apps that don't require a specific user to sign in.
One again, all I'm trying to accomplish here is to fetch MY OWN analytics data via the API.
Is there a way to properly do that?
I'm adding a PHP answer - you may be able to adjust or convert it to garb / ruby code.
You should be able to use Analytics with service accounts now. You will indeed have to use a private key instead of an access token.
Create an app in the API Console
Basically, you go to the Google API Console and create an App.
Enable Google Analytics in the services tab.
In the API Access tab, create a new OAuth ID (Create another client ID... button), select service account and download your private key (Generate new key... link). You'll have to upload the key to your web server later.
On the API Access page, in the Service account section, copy the email address (#developer.gserviceaccount.com) and add a new user with this email address to your Google Analytics profile. If you do not do this, you'll get some nice errors
Code
Download the latest Google PHP Client off SVN (from the command line svn checkout http://google-api-php-client.googlecode.com/svn/trunk/ google-api-php-client-read-only).
You can now access the Analytics API in code:
require_once 'Google_Client.php';
require_once 'contrib/Google_AnalyticsService.php';
$keyfile = 'dsdfdss0sdfsdsdfsdf44923dfs9023-privatekey.p12';
// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('Your product name');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'11122233344#developer.gserviceaccount.com',
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($keyfile)
)
);
// Get this from the Google Console, API Access page
$client->setClientId('11122233344.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
// We have finished setting up the connection,
// now get some data and output the number of visits this week.
// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id = 'ga:1234';
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $analytics->data_ga->get($analytics_id,
$lastWeek,
$today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
Terry Seidler answered this nicely for php. I want to add a java code example.
Api console setup
Start by doing the required steps in the google api console as Terry explained:
Basically, you go to the Google API Console and create an App. Enable
Google Analytics in the services tab. In the API Access tab, create a
new OAuth ID (Create another client ID... button), select service
account and download your private key (Generate new key... link).
You'll have to upload the key to your web server later.
On the API Access page, in the Service account section, copy the email
address (#developer.gserviceaccount.com) and add a new user with this
email address to your Google Analytics profile. If you do not do this,
you'll get some nice errors
Get the necessary libraries
Download the google analytics java client from:
https://developers.google.com/api-client-library/java/apis/analytics/v3
Or add the following maven dependencies:
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-analytics</artifactId>
<version>v3-rev94-1.18.0-rc</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson</artifactId>
<version>1.18.0-rc</version>
</dependency>
Now for the code:
public class HellowAnalyticsV3Api {
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
public void analyticsExample() {
// This is the .p12 file you got from the google api console by clicking generate new key
File analyticsKeyFile = new File(<p12FilePath>);
// This is the service account email address that you can find in the api console
String apiEmail = <something#developer.gserviceaccount.com>;
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(apiEmail)
.setServiceAccountScopes(Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY))
.setServiceAccountPrivateKeyFromP12File(analyticsPrivateKeyFile).build();
Analytics analyticsService = new Analytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(<your application name>)
.build();
String startDate = "2014-01-03";
String endDate = "2014-03-03";
String mertrics = "ga:sessions,ga:timeOnPage";
// Use the analytics object build a query
Get get = analyticsService.data().ga().get(tableId, startDate, endDate, mertrics);
get.setDimensions("ga:city");
get.setFilters("ga:country==Canada");
get.setSort("-ga:sessions");
// Run the query
GaData data = get.execute();
// Do something with the data
if (data.getRows() != null) {
for (List<String> row : data.getRows()) {
System.out.println(row);
}
}
}
You can use a refresh token. Store the refresh token in a db or secure config file, then use it to show the stats.
Google API Offline Access Using OAuth 2.0 Refresh Token will give you an idea of how to capture then store your refresh token.
See also Using OAuth 2.0 for Web Server Applications - Offline Access
Hello I found a solution, it works for me
you have to change this one
immediate: true
to
immediate: false
and it looks like
function checkAuth() {
gapi.auth.authorize({
client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
}
Google has the 'Service Account' (Calls Google APIs on behalf of your application instead of an end-user), but the way it works is a bit different as it won't use access tokens but a private key instead.
You can find more details at https://developers.google.com/accounts/docs/OAuth2ServiceAccount