Skip to main content

Google API v3 with PHP using Blogger service

It was really hard for me to understand how the Google APIs are working at the first point and took few days for me to figure out. But after a successful working prototype it seems very easy. And also when I am searching for a simple example I was unable to find a good one that I can understand.

So let me list down step by step what I have done with URLs and as simple as I can.

  1. Create a Google app
    1. location - https://code.google.com/apis/console
  2. Switch on the "Blogger API v3"
  3. Get the latest APIs client library for PHP
    1. location - https://code.google.com/p/google-api-php-client/downloads/list
  4. Upload the files to your host location on on localhost
  5. Extract the files to folder  named "GoogleClientApi"
  6. Create your php file outside of the folder 
  7. Copy paste following code into the file and do the changes as needed 
By changing the scope and the service object you can access all the services that is given by Google APIs through the PHP API library set given.
If there is anything needed to be clarified please leave a comment.

<?php
session_start();
require_once dirname(__FILE__).'/GoogleClientApi/src/Google_Client.php';
require_once dirname(__FILE__).'/GoogleClientApi/src/contrib/Google_BloggerService.php';

$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];

$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('giaws'); //name of the application
$client->setClientId('345345345645.apps.googleusercontent.com'); //insert your client id
$client->setClientSecret('JHJUGHJH6556vhjVHJKds'); //insert your client secret
$client->setRedirectUri($scriptUri); //redirects to same url
$client->setDeveloperKey('jhvjhhj6fvdfvfdv763248732QHGHJBHJ'); // API key (at bottom of page)
$client->setScopes(array('https://www.googleapis.com/auth/blogger')); //since we are going to use blogger services

$blogger = new Google_BloggerService($client);

if (isset($_GET['logout'])) { // logout: destroy token
    unset($_SESSION['token']);
 die('Logged out.');
}

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
}

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];
    $client->setAccessToken($token);
}

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);
    die;
}
//you can get the data about the blog by getByUrl
$data = $blogger->blogs->getByUrl(array('url'=>'http://puwaruwa.blogspot.com/'));

//creates a post object
$mypost = new Google_Post();
$mypost->setTitle('this is a test 1 title');
$mypost->setContent('this is a test 1 content');

$data = $blogger->posts->insert('546547654776577', $mypost); //post id needs here - put your blogger blog id
 var_dump($data);
?>

Comments

  1. hello sir

    im using same script as here for post on my blogger, but i get error as

    "error": {
    "errors": [
    {
    "domain": "usageLimits",
    "reason": "accessNotConfigured",
    "message": "Access Not Configured"
    }
    ],
    "code": 403,
    "message": "Access Not Configured"
    }

    pls help me.

    ReplyDelete
  2. Hi Vijay,
    have u done the step
    -- Switch on the "Blogger API v3"
    seems like that is the issue.
    It takes some time and u may have to send a mail to activate blogger API service.

    ReplyDelete
  3. yes i send request but still its off, i hope its reason for error.
    same error occurs while i fetch through url with my API key

    https://www.googleapis.com/blogger/v3/blogs/560242224718758304/posts/333295137170484745?key={API-key}

    thanks a lot,
    God Bless You.

    ReplyDelete
  4. Great job Gayan, you know an equivalent in c#?
    Thanks in advance.

    ReplyDelete
  5. I'm truly enjoying the design and layout of your site. It's a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a designer to create your theme? Great work!
    seo service provider

    ReplyDelete
  6. I am geting this error Fatal error: Call to undefined function setaccesstype()
    how to fix that error

    ReplyDelete
  7. I m getting same error too....Fatal error: Call to undefined function setaccesstype()

    ReplyDelete
  8. it should be actually '$client->setAccessType('online'); // default: offline'

    ReplyDelete
  9. Ohhh thanks Luckyy Cool. I fixed it.

    ReplyDelete
  10. Thats okay Gyan, I have got all the access for the app now and I don't know what is missing. I created a new client id as - 'web application' type, set the redirect URI as 'www.mysite.blogspot.in/oauth2callback' but when i run the script above (after setting credentials) it asks for permission then redirects me to this page but saying page not found. I guess there is someting wrong with redirect uri....do i need to have a folder like oauth2callback on my server ??

    ReplyDelete
  11. I got it working thanks. It should be correct url. how silly haha.

    ReplyDelete
  12. if i want to post blog with different username and passwords ?

    ReplyDelete
    Replies
    1. I do not know how to do this. I do not think this is possible since I have not seen APIs that allows like that.

      Delete
  13. Dear Gayan,

    I have submitted my access request, how long will it take for my form to get approved?


    Thank you.
    Jo

    ReplyDelete
    Replies
    1. i hope within 5 working day its approved.

      Delete
  14. hello, i incorrect :(

    Warning: rawurlencode() expects parameter 1 to be string, array given in D:\xampp\htdocs\GoogleAPI\src\io\Google_REST.php on line 109

    Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET https://www.googleapis.com/blogger/v3/blogs/byurl?url=&key=AIzaSyBIGW9Z__a9CD9WLHQufs78CZoMRAydNhw: (404) Not Found' in D:\xampp\htdocs\GoogleAPI\src\io\Google_REST.php:66 Stack trace: #0 D:\xampp\htdocs\GoogleAPI\src\io\Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1 D:\xampp\htdocs\GoogleAPI\src\service\Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest)) #2 D:\xampp\htdocs\GoogleAPI\src\contrib\Google_BloggerService.php(88): Google_ServiceResource->__call('getByUrl', Array) #3 D:\xampp\htdocs\GoogleAPI\blog.php(41): Google_BlogsServiceResource->getByUrl(Array) #4 {main} thrown in D:\xampp\htdocs\GoogleAPI\src\io\Google_REST.php on line 66

    ReplyDelete
  15. I can't find Client Secret. Can you help me?

    ReplyDelete
  16. Im getting Fatal error: when im trying to call below method while adding blogger post
    $post->setCustomMetaData("");

    ReplyDelete
  17. I got error (403) Access Not Configured. Please use Google Developers Console to activate the API for your project. please help .

    ReplyDelete
  18. Can anyone say me how to get my blog id.

    ReplyDelete
  19. 404 error Error: redirect_uri_mismatch error plz help

    ReplyDelete
  20. Good One :)

    Thanks
    Aman (php-tutorial-php.blogspot.in)

    ReplyDelete
  21. I'm not able to create of Post class getting error Class 'Google_Post' not found. I'm using this class Google_Service_Blogger

    ReplyDelete
    Replies
    1. Google_Post() is no longer valid kindly use
      $mypost = new Google_Service_Blogger_Post();
      $mypost->setTitle('This is a Test Post !');

      Delete
  22. this is not working now days and the latest client lib dose not contains any file like this "/GoogleClientApi/src/Google_Client.php"

    reply please

    ReplyDelete
    Replies
    1. it still works!
      here is what you ought to do:
      require_once dirname(__FILE__) . '/../src/Google/autoload.php';

      kindly include only the autoload.php and every thing would work just fine.

      Thank you!

      Delete
  23. For newest lib:
    require_once( 'GoogleClientApi/src/Google/autoload.php' );

    ReplyDelete
  24. Pimcore is a leading open source .Pimcore is a powerful and robust Zend Framework based PHP content management system (WCMS) for creating and managing digital content and assets.Innverse Technologies Provides best services in PHP Development services. choose our wide range of package and we create a website for you according your requirement.

    ReplyDelete
  25. Given library deprecated, can you share latest one

    ReplyDelete
  26. i have error like this
    Warning: rawurlencode() expects parameter 1 to be string, array given in C:\xampp\htdocs\LiveSoccerUpdate\XmlDUMP\GoogleClientApi\src\io\Google_REST.php on line 109

    please help me. thanks

    ReplyDelete
  27. It's very good, but you may update this post and explain this better, because actually is not working.

    I would apreciate your help, .... thanks

    ReplyDelete
  28. Also if someone can, please explain me how to login and use the blogger api directly, the console api fields and the login fields, thanks

    ReplyDelete
  29. how to set label and post date ?

    ReplyDelete
  30. i set but i receive this error can you guide me whats the problem

    Fatal error: Uncaught exception 'Google_AuthException' with message 'Error fetching OAuth2 access token, message: 'invalid_grant'' in C:\xampp\htdocs\GoogleClientApi\src\auth\Google_OAuth2.php:115 Stack trace: #0 C:\xampp\htdocs\GoogleClientApi\src\Google_Client.php(127): Google_OAuth2->authenticate(Array, NULL) #1 C:\xampp\htdocs\raminautoposttobloggervgoogleapiv3.php(39): Google_Client->authenticate() #2 {main} thrown in C:\xampp\htdocs\GoogleClientApi\src\auth\Google_OAuth2.php on line 115

    ReplyDelete
  31. i do not undertstand how fill in?

    ReplyDelete
  32. hello Gayan what's the problem , could you help me please ?


    Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET https://www.googleapis.com/blogger/v3/blogs/byurl?url=&key=my api key: (403) There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.' in /home/xxxxxx/public_html/GoogleClientApi/src/io/Google_REST.php:66 Stack trace: #0 /home/xxxxxx/public_html/GoogleClientApi/src/io/Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1 /home/u102235337/public_html/GoogleClientApi/src/service/Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest)) #2 /home/xxxxxx/public_html/GoogleClientApi/src/contrib/Google_BloggerService.php(88): Google_ServiceResource->__call('getByUrl', Array) #3 /home/xxxxxx/public_html/blogergonder.php(40): Google_BlogsServiceResour in /home/xxxxxx/public_html/GoogleClientApi/src/io/Google_REST.php on line 66

    ReplyDelete
  33. Warning: rawurlencode() expects parameter 1 to be string, array given in /home/xxxxxx/public_html/GoogleClientApi/src/io/Google_REST.php on line 109

    ReplyDelete
  34. Wenn die Suche nach Dienstleistungen E-Commerce- Website-Entwicklung und Design sind hier beste E-Commerce- Design und Entwicklungsdienstleistungen . Bitte kontaktieren Sie uns unter http://www.accuratesolutionsltd.com/kontaktieren-sie-uns/

    ReplyDelete
  35. i can't use it...could you please help. I can't get the api to work.

    ReplyDelete
  36. The ERROR i am getting is:
    The redirect URI in the request, http://localhost:8080/zer/test2.php, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/apis/credentials/oauthclient/930000822425-0g008l4h84iugas0l73v6b2atfep8ef5.apps.googleusercontent.com?project=930000822425 to update the authorized redirect URIs.

    ReplyDelete
  37. //you can get the data about the blog by getByUrl
    $data = $blogger->blogs->getByUrl(array('url'=>'http://puwaruwa.blogspot.com/'));
    replace with
    $data = $blogger->blogs->getByUrl( 'http://puwaruwa.blogspot.com/' );

    ReplyDelete
  38. This comment has been removed by the author.

    ReplyDelete
  39. This information is really useful. Keep sharing these kind of useful updates.

    PHP Training in Chennai

    ReplyDelete

Post a Comment

Popular posts from this blog

How to get indexed by Google & Yahoo

I have seen a lot of ads and services online that provide the facility to get higher page ranks on search engines. But when I asked about those services on Google their respond was not much positive because they said it can decrease you page rank (because those services cannot be trusted always). It is happening because the page rank is depending on page visitors (as Google say). So the better way is to let the Google to index your site by sending them the address of your website. http://www.google.com/webmasters/ : here you can improve the traffic with the webmaster tools and you can send your website contents also. It is a legal, simple and direct hit.
You can send your web site address (even the blog) to Yahoo: https://siteexplorer.search.yahoo.com also. It helps them to index your pages on their search engines.


It is better to come up with the content and services which are really useful for the visitors and the traffic will be increased regularly. I have gone through a lot of expe…

How to Install ColdFusion 8 on Linux?

It was real pain for me to install ColdFusion on my Linux box with Apache. Anyway we have installed it and I thought to share it because this may help you also to install ColdFusion on a Linux box.
First of all open a shell and then continue on this.

Grant Execute permission to the Coldfusion‐8‐lin.bin binary file
chmod +x Coldfusion‐8‐lin.bin

Execute Coldfusion‐8‐lin.bin
./Coldfusion‐8‐lin.bin

Enter the Locale
1 (English)

Hit Enter 28 times to continue the agreement

Enter "Y" to accept the agreement

Enter the version to install
3 (Developer Edition)

Enter the next task to perform
1 (Server Configuration)

Enter whether you have an existing server configuration
2 (No existing server configuration)

Enter the next task to perform
5 (continue installation)

Enter the installation path
Hit enter to accept the default path

Hit Enter 30 times to continue the agreement

Enter "Y" to accept the agreement

Enter the serial number
Hit Enter for no serial number

Enter whether you h…