GSC_Client and oAuth2 access

I am starting work on a PHP script that will run as a cron job and periodically update product lists through the Google Shopping API.

I downloaded the GSC client library for PHP and am trying to work through the Google Shopping API to access the token. However, it seems that somewhere in the docs some kind of step has gone missing regarding how to actually request a token after creating the URL.

Here is my code:

require ("./lib/shoppingclient/GShoppingContent.php");

const G_MERCHANT_ID     = '**********';
const G_CLIENT_ID       = '**********';
const G_CLIENT_SECRET   = '**********';

$obj_client = new GSC_Client (G_MERCHANT_ID);

// Obtain an OAuth2 token to access the API with
$obj_token  = new GSC_OAuth2Token (G_CLIENT_ID, G_CLIENT_SECRET, USER_AGENT);

$str_url    = $obj_token -> generateAuthorizeUrl ('urn:ietf:wg:oauth:2.0:oob');
echo ($str_url . PHP_EOL);

/* @var $obj_response _GSC_Response */
$obj_response = $obj_token -> makeAuthenticatedRequest (curl_init ($str_url));
echo ($obj_response);

When I run the above from the command line, I get:

https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=blah-blah-blah-etc-etc-etc ...

<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>

Fatal error: Uncaught exception 'GSC_TokenError' with message 'invalid_request' in /var/samba/GoogleShoppingTest/lib/shoppingclient/GShoppingContent.php on line 624

GSC_TokenError: invalid_request in /var/samba/GoogleShoppingTest/lib/shoppingclient/GShoppingContent.php on line 624

Call Stack:
    0.0002     321888   1. {main}() /var/samba/GoogleShoppingTest/logintest.php:0
    0.0065    1446196   2. GSC_OAuth2Token->makeAuthenticatedRequest() /var/samba/GoogleShoppingTest/logintest.php:19
    0.2797    1446684   3. GSC_OAuth2Token->refresh() /var/samba/GoogleShoppingTest/lib/shoppingclient/GShoppingContent.php:722
    0.3992    1448152   4. GSC_OAuth2Token::raiseFromJson() /var/samba/GoogleShoppingTest/lib/shoppingclient/GShoppingContent.php:565

, CURL , , URL- .

URL-, generateAuthorizeUrl(), , . , , , , , .

cron script, , , , , , , - .

- GSC_Client OAuth script? , ?

. API " ", , -, API . , script https://localhost urn:ietf:wg:oauth:2.0:oob URL-.

2. , GSC "-". , API Google, .

, :

require ("./lib/google/oauthclient/Google_Client.php");
require ("./lib/google/shoppingclient/GShoppingContent.php");

const G_MERCHANT_ID     = '********';
const G_CLIENT_ID       = '********';
const G_CLIENT_EMAIL    = '********';
const G_CLIENT_KEY_PATH = '/path/to/the/privatekey.p12';
const G_CLIENT_KEY_PW   = 'notasecret';

$obj_client_auth  = new Google_Client ();
$obj_client_auth -> setApplicationName ('test');
$obj_client_auth -> setClientId (G_CLIENT_ID);
$obj_client_auth -> setAssertionCredentials (new Google_AssertionCredentials (
        G_CLIENT_EMAIL, 
        array (OAUTH_SCOPE), 
        file_get_contents (G_CLIENT_KEY_PATH), 
        G_CLIENT_KEY_PW));

$obj_client_auth -> getAuth () -> refreshTokenWithAssertion ();

// Get a token
$obj_token  = json_decode ($obj_client_auth -> getAccessToken ());
print_r ($obj_token);

, - :

stdClass Object
(
    [access_token] => ya29.AHES6ZRJohl2AfbQCKbFxNlagSqLGcjHwiylqASX1ygmwg
    [expires_in] => 3600
    [created] => 1359123809
)

, .

, GSC_Client. , Google, , , , , -, - , , , .

3

oAuth, Google, API . Content API . , , oAuth, , contrib!

FYI, , API ( ):

$obj_client_auth  = new Google_Client ();
$obj_client_auth -> setApplicationName ('test');
$obj_client_auth -> setClientId (G_CLIENT_ID);
$obj_client_auth -> setAssertionCredentials (new Google_AssertionCredentials (
        G_CLIENT_EMAIL, 
        array (
            //'https://www.googleapis.com/auth/structuredcontent',
            'https://www.googleapis.com/auth/shoppingapi'
            ), 
        file_get_contents (G_CLIENT_KEY_PATH), 
        G_CLIENT_KEY_PW));

$obj_client_api   = new Google_ShoppingService ($obj_client_auth);

$arr_results = $obj_client_api -> products -> listProducts ('public', array (
   'country'   => 'GB',
   'q'         => '"mp3 player" | ipod', 
   'rankBy'    => 'relevancy'
));

print_r ($arr_results);
+5
2

, GSC_client OAuth2 Google_Client, . GSC_Client OAuth2 , , Google_Client .

, API Google, . , Google_Client.

, , , Google GSC_Client Google_Client, .

+1

, , , Google API, , .

, . -, . google api ( , p12), Merchant Center Google - , , , , : -)

- API, MPN, AP

require_once realpath(dirname(__FILE__) . '/src/Google/autoload.php');
require_once realpath(dirname(__FILE__) . '/src/Google/Service/ShoppingContent.php');


$merchantId = '<<MY_MERCHANT_ID>>';
$client_id = '<<MY_GOOGLE_API_SERVICE_ACCOUNT_ID>>';
$client_email = <<MY_GOOGLE_API_SERVICE_ACCOUNT_EMAIL>>';
$scopes = array('https://www.googleapis.com/auth/content');
$private_key = file_get_contents('<<MY_GOOGLE_API_SERVICE_ACCOUNT_P12_FILE>>');
$credentials = new Google_Auth_AssertionCredentials(
    $client_email,
    $scopes,
    $private_key
);

$client = new Google_Client();
$client->setAssertionCredentials($credentials);
$client->setScopes($scopes);
$client->setAccessType("offline");

if ($client->getAuth()->isAccessTokenExpired()) $client->getAuth()->refreshTokenWithAssertion();
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $authUrl = $client->createAuthUrl();
}

$service = new Google_Service_ShoppingContent($client);

//Example to get sku information
$ret = getsku($client, $service, $merchantId, 'DC35DS');
echo "<pre>"; print_r($ret); echo "</pre>";

//Example to set price and availability
$ret = update_Price_Availability($client, $service, $merchantId, $itemid, $price, $availability);
echo "<pre>"; print_r($ret); echo "</pre>";


function update_Price_Availability($client, $service, $merchantId, $itemid, $newprice = null, $availability = null) {
    $inventory = new Google_Service_ShoppingContent_InventorySetRequest();
    $price = new Google_Service_ShoppingContent_Price();
    $ctrl = 0;
    if ($newprice !== null) {
        $price->setValue($newprice);
        $price->setCurrency('GBP');
        $inventory->setPrice($price);
        $ctrl = 1;
    }
    if ($availability !== null) {
        $inventory->setAvailability($availability);
        $ctrl = 1;
    } 
    if ($ctrl == 0) {
        return array('Errors'=>array('Nothing to do')); 
    }
    try {
        $return = $service->inventory->set($merchantId, 'online', 'online:en:GB:'.$itemid, $inventory);
    } catch (Google_Service_Exception  $e) {
        return array('Errors'=>$e->geterrors(),'Message'=>$e->getmessage());
    }
    return getsku($client, $service, $merchantId, $itemid);
 }

function getsku($client, $service, $merchantId, $itemid) {
    try {
        $product = $service->products->get($merchantId, 'online:en:GB:'.$itemid);
    } catch (Google_Service_Exception  $e) {
        $product = array('Errors'=>$e->geterrors(),'Message'=>$e->getmessage());
    }
    return $product;
}
0

All Articles