Friday 26 February 2016

LARAVEL 5 + GOOGLE APIS CLIENT LIBRARY

Hi Everybody,

Today we will discuss about integration of google api client library with laravel 5.1

Prerequisite

Created a google app project
Enabled Google+ API at your google project
Created new Client ID
Generated API Key
Get service account name

You can find in this google link to do above steps.If you have already done those, you can start the following steps.

Step1


In your composer.json file, add

"require": {
 "google/apiclient": "1.0.*@beta"//This beta version is when I use, get updated version when you use
 }

Step2


(My apiclient version is still beta, so I need to set minimum-stability to dev, but if your version is stable, you don’t need to change and skip to Step3)Find minimum-stability in your laravel project, and change to

"minimum-stability": "dev"

Step3


run >>>>composer update. After that, you will see google folder under yourapp>vendor folder.

Step4


In your composer.json file, add the following;

{ "autoload": 
     { "classmap": [ "vendor/google/apiclient/src/Google" ],
      } 
}

Step5


In your http://console.developers.google.com Create a new Client ID in Credentials, Select Service account and click on Create Client ID

Step6


In config folder, add google.php and add;

return [
    'app_name'          => 'your_app_name', 
    'client_id'         => 'your_client_id',
    'client_secret'     => 'your_client_secret',
    'api_key'           => 'your_api_key',
    'service_account_name' => 'your_service_account_name'
];

Step7


Create app>Services>Google.php file and then add the following code;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;

class Google {

    protected $client;

    protected $service;

    function __construct() {
        /* Get config variables */
        $client_id = Config::get('google.client_id');
        $service_account_name = Config::get('google.service_account_name');
        $key = Config::get('google.api_key');//you can use later

        $this->client = new \Google_Client();
        $this->client->setApplicationName("your_app_name");
        $this->service = new \Google_Service_Books($this->client);//Test with Books Service        
    }

    public function getBooks(){
        $optParams = array('filter' => 'free-ebooks');
        $results = $this->service->volumes->listVolumes('Henry David Thoreau', $optParams);

        dd($results);
    }
}

Step8


In HomeController, modify index function

public function index(Google $google)
{
    $result = $google->getBooks();
    print_r($result);
}


Thanks.

No comments:

Post a Comment