PHP Server to Server example

319 views
Skip to first unread message

Eric Haskins

unread,
Mar 21, 2012, 2:41:46 PM3/21/12
to AdSense API Forum
I going over the docs and all the examples are tailored to the Web
Application. I was wondering if anyone has done a Server to Server
OAuth2 for the Management API yet?? But this:

"Libraries should abstract these specifics from your application.
Again, developers are strongly encouraged to attempt to use an
existing library rather than building your own support for server-to-
server interactions"

Does seem to point where in Googles provided library is the code for
Abstracting it. Since a server to server app cant use a redirect url
Im kinda lost in translation I think

Thx
Eric

Silvano Luciani

unread,
Mar 22, 2012, 4:52:06 AM3/22/12
to AdSense API Forum
Hello Eric,

we haven't published any examples of Server to Server flow yet, but
maybe some of our users have done it and can help you.

If that's not the case, you can try to ask for help or examples for
other APIs in one of the following forums:

OAuth 2.0 developer's forum:
https://groups.google.com/forum/#!forum/oauth2-dev

Client library's specific forums:
Java: http://groups.google.com/group/google-api-java-client
Python: https://groups.google.com/group/google-api-python-client
PHP: http://groups.google.com/group/google-api-php-client

Cheers,
Silvano

--
Silvano Luciani | Developer Programs Engineer

Google UK Limited
Registered Office: Belgrave House, 76 Buckingham Palace Road, London
SW1W 9TQ
Registered in England Number: 3977902

Eric Haskins

unread,
Mar 22, 2012, 12:04:32 PM3/22/12
to AdSense API Forum

> we haven't published any examples of Server to Server flow yet, but
> maybe some of our users have done it and can help you.
>
> If that's not the case, you can try to ask for help or examples for
> other APIs in one of the following forums:
>
> OAuth 2.0 developer's forum:https://groups.google.com/forum/#!forum/oauth2-dev
>

Silvano,

Then why even put it in your docs??? Seriously and I mean no
disrespect if you say in the Docs "Here choose from these methods to
link your application" Oh ok ours is a server to server application
so we choose it but we cant find any documentation on how to query or
create the JWT (which I figured out but have no clue how to use now).
If it isnt documented why even show the option I would think Google is
better than that. The OAuth implementation is weird and it doesnt
seem to fit with a stats server coming in and needing to get the daily
stats if you have to have a person go and click an "Authorize"
button. I have tried using the refresh token method and my server
keeps getting a

[error] => invalid_grant

Eric Haskins
Voodoo.Com

Silvano Luciani

unread,
Mar 22, 2012, 12:34:22 PM3/22/12
to AdSense API Forum
Hello Eric,

the refresh token method should work fine, are you using the Google
API PHP Client Library?
If that's the case, are the AdSense examples working for you?
http://code.google.com/p/google-api-php-client/source/browse/#svn%2Ftrunk%2Fexamples%2Fadsense

Cheers,
Silvano

--
Silvano Luciani | Developer Programs Engineer

Google UK Limited
Registered Office: Belgrave House, 76 Buckingham Palace Road, London
SW1W 9TQ
Registered in England Number: 3977902

Nikolai P.

unread,
Mar 25, 2012, 6:15:39 PM3/25/12
to adsen...@googlegroups.com
Oh, but some examples of generating JWT do exist in docs. Here they are:


So here's my PHP working code base on those rules:

<?php
$now = time();
$jwt_header = base64_encode(json_encode(array(
'alg' => 'RS256',
'typ' => 'JWT'
)));
$jwt_claim = base64_encode(json_encode(array(
'iss' => '268481************@developer.gserviceaccount.com',
'exp' => $now+3600,
'iat' => $now
)));

# here i include one class from PHP client library to create JWT signature
require_once 'google-api-php-client/src/auth/apiSigner.php';
$p12 = new apiP12Signer('707ea88c********-privatekey.p12', 'notasecret');
$jwt_signature = base64_encode($p12->sign($jwt_header . '.' . $jwt_claim));

$c = curl_init();
curl_setopt_array($c, array(
CURLOPT_HEADER => false,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => array(
'grant_type' => 'assertion',
'assertion' => implode('.', array($jwt_header,$jwt_claim,$jwt_signature))
),
));
$x = curl_exec($c); $token = json_decode($x, true);

/*
at this point i'm authorized
$x contains something like this:

{
  "access_token" : "1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M",
  "token_type" : "Bearer",
  "expires_in" : 3600
}

so i just json_decode it and continue my requests to Adsense API:
*/

$query = 'access_token=' . $token['access_token'];
$query .= '&accountId=pub-*****';
$query .= '&startDate=2012-03-01';
$query .= '&endDate=' . date('Y-m-d');
$query .= '&metric=PAGE_VIEWS&metric=AD_REQUESTS&metric=MATCHED_AD_REQUESTS&metric=CLICKS&metric=EARNINGS';
$query .= '&dimension=DATE';

curl_setopt_array($c, array(
CURLOPT_HTTPGET => true,
));
$x = curl_exec($c); curl_close($c);
?>

However i have one problem at this final step. Request ALWAYS gives me noAdSenseAccount reply and i have no clue how to fix it..

But authorization works great anyway.

Eric Haskins

unread,
Mar 26, 2012, 4:02:18 PM3/26/12
to AdSense API Forum
Nikolai,

You are the man! I realized with your help of course I was putting
in the Client ID instead of the Email Address for the Service Account
in the iss Field which would result in invalid_grant ;-)

Eric

On Mar 25, 6:15 pm, "Nikolai P." <nik.p...@gmail.com> wrote:
> Oh, but some examples of generating JWT do exist in docs. Here they are:
>
> https://developers.google.com/accounts/docs/OAuth2ServiceAccount
>
> So here's my PHP working code base on those rules:
>
> <?php
> $now = time();
> $jwt_header = base64_encode(json_encode(array(
> 'alg' => 'RS256',
> 'typ' => 'JWT'
> )));
> $jwt_claim = base64_encode(json_encode(array(
> 'iss' => '268481*********...@developer.gserviceaccount.com',

Eric Haskins

unread,
Mar 27, 2012, 2:59:11 PM3/27/12
to AdSense API Forum
Nikolai,

It appears the Service Accounts lack the credentials to act on
behalf of a user is what I am guessing and the reason that we get
noAdSenseAccount Error. So we are proceeding with the installed
Application and a refresh token path. I do not like this route because
of all people Google should understand the need for servers to be able
to communicate without the requirement of user clicking a button
especially if there are private and public keys in play. We will just
have to create a function to generate an Auth Url in the case of
accidental or unforseen token revocation.

We are posing these pitfalls and ridiculous hurdles to our Partner
Team in hopes google will make the wheel round again instead of
reinventing it square. Although the next variation will most likely be
an octagon ;-)

Eric Haskins
Voodoo.com

Silvano Luciani

unread,
Mar 28, 2012, 6:38:24 AM3/28/12
to AdSense API Forum
Hello Eric and Nikolai,

Sorry for the late answer but I was away, and thanks Nikolai for
helping out Eric!

On Mar 27, 7:59 pm, Eric Haskins <e...@voodoo.com> wrote:
> Nikolai,
>
>       It appears the Service Accounts lack the credentials to act on
> behalf of a user is what I am guessing and the reason that we get
> noAdSenseAccount Error.

Correct: Service Accounts can be used only when an end-user is not
involved, which is not the case of the AdSense APIs where you access
data on behalf of a user.

> So we are proceeding with the installed
> Application and a refresh token path. I do not like this route because
> of all people Google should understand the need for servers to be able
> to communicate without the requirement of user clicking a button
> especially if there are private and public keys in play. We will just
> have to create a function to generate an Auth Url in the case of
> accidental or unforseen token revocation.

I understand your point about automation, but the problem here is that
to access data on behalf of a user, you need their consent to do so.
Consequently they'll have to log in with their Google account to grant
permissions to your application at least once. If the application
requests offline access, it gets a refresh token that can be used to
renew the access token, so no need for clicks after the first time.
You could also set the option 'approval_prompt' to 'auto' so that a
given user sees the consent page for a given set of scopes only the
first time through the sequence.

>
> We are posing these pitfalls and ridiculous hurdles to our Partner
> Team in hopes google will make the wheel round again instead of
> reinventing it square. Although the next variation will most likely be
> an octagon ;-)

I'm sorry if this is your perception of what we are doing, but I don't
think that we are reinventing the wheel.
We are implementing a specification being developed within the IETF
OAuth WG, you can find the latest draft here:
http://tools.ietf.org/html/draft-ietf-oauth-v2-25

To ease the integration of the OAuth 2.0 flow, we are developing and
open sourcing client libraries for 9 programming languages:
http://code.google.com/apis/discovery/libraries.html

I hope you'll find the above useful, please let me know if there's
anything else we can do to support you.

Cheers,
Silvano

--
Silvano Luciani | Developer Programs Engineer

Google UK Limited
Registered Office: Belgrave House, 76 Buckingham Palace Road, London
SW1W 9TQ
Registered in England Number: 3977902

>

Eric Haskins

unread,
Mar 28, 2012, 12:05:54 PM3/28/12
to AdSense API Forum
Silvano,

I would agree if our app was for more than our publisher account
but it isn't. We are a parking partner so our systems need a way to
access only our earnings. My point is we are the programmers for
Voodoo (voodoo is a company not a person but is treated as a user) and
we are writing the systems to total earnings and reporting, if our
employer gives us access to the account and our partner team links our
Google Accounts to access it we have already been given permission. So
I see your system is great for consumer situations but it really
doesn't support partners like us. If we are pulling public and private
keys and jumping thru hoops ........ It takes less to run credit card
transactions with Authorize.net and we are only talking about
statistics. There should be a way to auth a service account to a user
account plain and simple or by virtue of the private key allow a
service account to act on behalf of the user. The user could revoke
said key at anytime if there was an issue.

We have to generate code to create auth urls on systems that usually
dont get accessed via the web like our stats farm. I know the refresh
token route but we have to plan for inadvertent or unforeseen token
revocation.

There should be a better way and I have expressed this to our Partner
Team

Eric Haskins
Voodoo.com


On Mar 28, 6:38 am, Silvano Luciani <silvano.luci...@google.com>
wrote:
Reply all
Reply to author
Forward
0 new messages