Access Google Blogger API v3 with OAuth 2.0 (PHP)

fmchanprogrammingLeave a Comment

Kick Start with this API instruction

https://developers.google.com/blogger/docs/3.0/using?hl=en_US

Blogger API v3 Doc

https://developers.google.com/blogger/docs/3.0/reference

Set up the credential

https://console.developers.google.com/apis/credentials

You also have to setup OAuth consent screen and enable Blogger V3 in Google Developer Console

Select Resources > Developer Console Project

Oath Playground is a very good test for you to ensure everything is ready and workable

https://developers.google.com/oauthplayground/

select Blogger API V3 on the left sidebar and tick the scope https://www.googleapis.com/auth/blogger

Login Google API Page

<?php
$url = "https://accounts.google.com/o/oauth2/auth";
$params = array(
    "response_type" => "code",
    "client_id" => "check credential page",
    "redirect_uri" => "check credential page",
    "scope" => "https://www.googleapis.com/auth/blogger"
    );
$request_to = $url . '?' . http_build_query($params);
header("Location: " . $request_to);

Callback Page

<?php
if(isset($_GET['code'])) {
    // try to get an access token
    $code = $_GET['code'];
    $url = "https://oauth2.googleapis.com/token";
    $params = array(
        "code" => $code,
        "client_id" => "check credential page",
        "client_secret" => "check credential page",
        "redirect_uri" => "check credential page",
        "grant_type" => "authorization_code"
    );

    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded",
            'method'  => 'POST',
            'content' => http_build_query($params)
        )
    );

    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if ($result === FALSE) { throw new Exception("no result\n"); }
    //var_dump($result);
    $responseObj = json_decode($result);
    echo "Access token: " . $responseObj->access_token;
}

So now you have the access token. The following is what the page returns:

{
  "access_token": "something...",
  "expires_in": 3599,
  "scope": "https://www.googleapis.com/auth/blogger",
  "token_type": "Bearer"
}

This is also a good implementation for accessing google API (PHP) but I do not think it’s necessary.

https://github.com/googleapis/google-api-php-client

Leave a Reply

Your email address will not be published. Required fields are marked *