Connect to Google AdSense API via PHP - php

I'm trying to connect to AdSense API using a PHP script.
I started using this tutorial by google: https://developers.google.com/api-client-library/php/start/get_started#build-the-client-object
However, I didn't manage to connect. This is what I've tried:
$client = new Google_Client();
$client->setApplicationName("AppName");
$client->setDeveloperKey(API_Key);
$client->setAuthConfigFile('../AdSense/google-api-php-client/client_secret.json');
$service = new Google_Service_AdSenseTest($client);
$results = $service->testReportsGenerate();
foreach($results as $item)
{
echo $item;
}
And I came across a few problems, the main one is that the code doesn't recognize the "Google_Service_AdSenseTest" class - even though the code suggested it.
So my real question is this: What service should I use if I want to pull data from AdSense? And how do I set the needed parameters (meaning - which dimensions and metrics to get)?
Thank you.

You need to implement OAuth requests as you do for every single google api, (use Phil Sturgeon's OAuth2.0 protocol if you use codeigniter, well implemented.) or any oauth2 client scripts will do.
The google api library is here : https://github.com/googleapis/google-api-php-client-services. Use composer to install these libraries.
The adsense class is here : https://github.com/googleapis/google-api-php-client-services/blob/master/src/Google/Service/AdSense.php
The class/function which makes the request to google must setup an oauth client and specify a redirect url (which in turn must be registered on google api console )
The scopes are
../auth/adsense
../auth/adsense.readonly
Once everything is done, you can make a request.
I implemented it with Codeigniter for searchconsole, adsense and other useful libraries they all works awesome. Besides i connected google sheets as well, so every report is available to me in google sheet as it is needed.
With oAuth Access token, The code :
$client = new Google_Client();
$adsenseService = new Google_Service_AdSense(...);
$client->setApplicationName("Adsense Console");
$client->setDeveloperKey($apiKey);
$client->setAccessToken( $token->access_token );
$params = array('maxResults' => 1000, 'pageToken' => null, 'alt' => 'json', 'fields' => array(), 'prettyPrint' => true, 'quotaUser' => '', 'userIp' => '' );
$accounts = $adsenseService->accounts->listAccounts($params);
//this will print a json array
echo '<pre>' ; print_r($accounts); echo '<pre>'; die();
for adclients,
$adsense->adclients->listAccountsAdclients($params);
The params ref is here,
https://developers.google.com/adsense/management/v1.4/reference/accounts/adclients/list#try-it

you could try the example from https://github.com/googleads/googleads-adsense-examples/tree/master/php-clientlib-1.x/v1.x
More info at https://developers.google.com/adsense/management/getting_started

Related

Google Analytics Data API returns 400 invalid_scope when trying to run a report

I'd like to create a small dashboard containing some analytics data from my mobile application. I found the new Google Analytics Data API which would be perfect for that. I want to run reports in my backend PHP application, so I'm using the PHP client library: https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/analyticsdata
Unfortunately I keep running against a 400 error on oauth2.
These are the steps I've done so far:
I've migrated my Firebase project to use a Google Analytics 4
property
Followed the steps in the guide of the client library for PHP
Registered & enabled the API for my project
Add credentials:
Using Google Analytics Data API
Using web server
Accessing application data
This results in a message saying an active service account already qualifies
For that service account I created a new key and downloaded the .json file
Added the client_email field as a user to my Google Analytics property with read access
In my PHP projects I installed the necessary dependencies and added the credentials .json file and copied the sample code:
$kernel = $this->getConfigurationPool()->getContainer()->get('kernel');
$path = $kernel->locateResource('#ApplicationBundle/Resources/config/credentials.json');
$property_id = '123456789';
$credentials_json_path = $path;
$client = new BetaAnalyticsDataClient(['credentials' =>
$credentials_json_path]);
// Make an API call.
$response = $client->runReport([
'property' => 'properties/' . $property_id,
'dateRanges' => [
new DateRange([
'start_date' => '2020-03-31',
'end_date' => 'today',
]),
],
'metrics' => [new Metric(
[
'name' => 'activeUsers',
])
]
]);
This results in a 400 bad request on https://oauth2.googleapis.com/token with the following response:
{"error":"invalid_scope","error_description":"Invalid OAuth scope or ID token audience provided."}
Which seems weird since it's supposed to use the service account no? I think I followed all the steps from the docs. Did I miss something?
Thanks in advance.

Shopify Webhooks work in testing but not in practice

I'm having some problems with my Shopify 'orders/paid' webhook that I install onto the users store via the Shopify SDK (using a PHP wrapper: https://github.com/phpclassic/php-shopify). Anyways, I create the webhook like so:
$shop = $this->request->getVar('shop'); // Get Shopify store URL
// Get access token for store
$config = array('ShopUrl' => $shop, 'ApiKey' => 'xxx', 'SharedSecret' => 'xxx');
\PHPShopify\ShopifySDK::config($config);
$accessToken = \PHPShopify\AuthHelper::getAccessToken();
// Keep track of access_token for SDK calls and authenticate to store for webhook creation
$addToken = $this->Stores->addAccessToken($shop, $accessToken);
$config = array('AccessToken' => $accessToken, 'ShopUrl' => $shop);
$shopify = new \PHPShopify\ShopifySDK($config);
// Create orders/paid webhook
$orderPaidHook = array('topic' => 'orders/paid', 'address' => 'https://api.autoloapp.com/webhook/create', 'format' => 'json');
try {
$webhooks = $shopify->Webhook->post($orderPaidHook);
}
This code as far as I can tell works, using print_r($webhooks) gives me a valid Webhook that has (in theory) been installed on to the store. However, when an order is actually paid for on the store I DO NOT get a message.
Using the "Test Webhook" settings under "Notification" in the Shopify Admin my webhook works perfectly. Using PostMan to simulate a webhook call works perfectly.
The code to process the webhook looks like this:
$headers = getallheaders();
$topic = $headers['X-Shopify-Topic'];
$storeName = $headers['X-Shopify-Shop-Domain'];
if ($topic == 'orders/paid') {
// Do some stuff, insert row into database
}
Again, when I use PostMan or the built-in "Test Webhook" setting for Shopify the row in my database gets created just fine. When I do it with a real webhook nothing happens. I'm not sure why this is happening, as far as I know all the headers should be the same. Do I need to verify the webhook in some way?
For reference I'm using CodeIgniter 4.0, PHP 7.0, and the newest version of the Shopify SDK.
I found this note on Shopify's Docs: "Note that if you are using a Rack based framework such as Ruby on Rails or Sinatra the header you are looking for is HTTP_X_SHOPIFY_HMAC_SHA256". With my current set-up I should still be using X-Shopify-Shop-Domain instead of HTTP_X_Shopify_Shop_Domain correct? Any help greatly appreciated!
So I finally figured out that for some reason the 'orders/paid' webhook wouldn't work for me in "production environments" despite working fine in my test environments. Simply changing the topic to 'orders/create' resolved my problem.

How to update Google Sheets file with API PHP Client

I've been taking a look at the Google API PHP Client and would like to use it to add rows to a Google Sheet. From the code, it looks like one would use this method:
public function insert($fileId, Google_Service_Drive_Property $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_Drive_Property");
}
but I can't really tell what the parameters would be. Am I heading in the right direction? Also, not quite sure on how to connect to a specific Sheet. Please advise.
Thanks!
Use Google sheets class from zend framework 1.12. They have very nicely coded library for Google Spreadsheets
https://github.com/zendframework/zf1/tree/master/library/Zend/Gdata/Spreadsheets
I figured out how to work this and wanted to share with you guys. As I stated in a comment, I did not think using Zend's GData class was a good way for me since it's very dependent on other classes throughout the framework, thus being too heavy.
So I ended up using this Spreadsheet Client on top of Google's API. Google's API is used to authenticate my service, then I start calling the Spreadsheet Client library afterwards.
After spending over a day of Googling for various problems I had for the authentication process, here's what I did to make things work:
Created a new project for Google API here
Clicked "APIs" menu on the left side under "APIs & Auth"
Searched the Drive API and enabled it (can't remember if it was necessary)
Clicked the "Credentials" menu on the left
Clicked "Create new Client ID" button under OAuth
Selected "Service Account"
After info showed & json downloaded (not needed), I clicked "Generate new P12 Key" button
I saved the p12 file somewhere I could access it through PHP
Then in the code, I added the following lines:
$email = 'somethingsomethingblahblah#developer.gserviceaccount.com';
$CLIENT_ID = $email;
$SERVICE_ACCOUNT_NAME = $email;
$KEY_FILE = 'path/to/p12/file';
$SPREADSHEETS_SCOPE = 'https://spreadsheets.google.com/feeds';
$key = file_get_contents($KEY_FILE);
$auth = new Google_Auth_AssertionCredentials(
$SERVICE_ACCOUNT_NAME,
array($SPREADSHEETS_SCOPE),
$key
);
$client = new Google_Client();
$client->setScopes(array($SPREADSHEETS_SCOPE));
$client->setAssertionCredentials($auth);
$client->getAuth()->refreshTokenWithAssertion();
$client->setClientId($CLIENT_ID);
$accessToken = $client->getAccessToken();
Also, I had to make sure I:
Shared my spreadsheet specifically with the email address on my service account in the code above
Synced my server's time (I'm running Vagrant CentOS so it's slightly different)
I believe you can run this code with other services beyond Spreadsheets, such as Youtube, Analytics, etc., but you will need to get the correct scope link (see $SPREADSHEETS_SCOPE above). Remember, this is only when using the Service Account on the Google Console, which means you are programmatically getting data from your code. If you are looking to have others users sign in using the API, then it's different.

Using Google's API through laravel/hybridauth

I want to create an app that uses Google+ APIs through hybridauth.
I'm using atticmedia/anvard version of hybridauth, that is already configured with Google's clientID and secretKey that have been generated through Google Developer Console (I have inserted these info inside the hybridauth.php file inside the config folder of laravel). I have setted the scope too (as Google suggest).
"scope" => "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email",
I do the following in a laravel route:
if (!$hybridauth->isConnectedWith('Google')) {
$adapter = $hybridauth->authenticate('Google');
}
else {
$adapter = $hybridauth->getAdapter('Google');
}
$profile = $adapter->getUserProfile();
Till now, everything goes well. The profile is correctely printed using the var_dump() function. So I can assume I am logged in. Now I want to make a call to Google APIs (for example this). In the same laravel route, after printing the user's profile, i do the following:
$answer= $adapter->api()->api('/people', 'get', array(
'query' => 'Google'
));
As shown in this page, I can use the api() method to do the call. But the only result I can print is "NULL". I suspect that somehow the request is not correct, but I tryed almost anything, and I have not found yet a "real" example of Google API in conjuction with laravel/hybridauth.
When calling $adapter->api in hybridauth to access Google APIs, you must use the full HTTP URL request.
$answer= $adapter->api()->api('https://www.googleapis.com/plus/v1/people/me');
For other services, such as Facebook, you don't need to
$answer= $adapter->api()->api('/me');
I'm using Laravel 4.2.11 and hybridauth dev-master
Reference: http://hybridauth.sourceforge.net/userguide/tuts/advanced-access-google-api.html

UserVoice's OAuth Implementation in PHP

I am able to get the Records of the UserVoice by calling and Unauthorized Requests but now i want to create and Update things in which i need OAuth but i am unable to find the UserVoice's PHP Implementation of OAuth and Create/Update/Delete with UserVoice API is there anyone can guide me how to Implement such thing??
We have quite recently worked on this and released an OAuth-based library which makes it a bit easier to access UserVoice API from a PHP version 5 application.
An example on how to create a ticket using an access token for user#example.com:
<?php
require_once('vendor/autoload.php'); // Using Composer
$client = new \UserVoice\Client('subdomain-name', 'API KEY', 'API SECRET');
$access_token = $client->login_as('user#example.com');
$result = $access_token->post("/api/v1/tickets", array(
'ticket' => array(
'state' => 'open',
'subject' => 'PHP SDK',
'message' => "Would you have any OAuth example for PHP?"
)
));
?>
Despite the fact that the library is still under development, I believe it's already useful to you. See the blog post and more examples like responding to tickets as an account owner at:
http://developer.uservoice.com/docs/api/php-sdk/

Categories