takaya030の備忘録

PHP、Laravel、Docker などの話がメインです

Lumen でお手軽に Google API を使う

以前、Laravel から Google API を使う記事を書きましたが、今回は Lumen からより簡単に使ってみます

検証環境

$ php --version
PHP 5.5.34 (cli) (built: Jun 24 2017 00:40:52)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2015 Zend Technologies

$ php artisan --version
Laravel Framework version Lumen (5.1.7) (Laravel Components 5.1.*)

OAuth クライアント ID、Refresh Token の取得

以下の記事を参考に Google API で使用する Client ID、Access Token を取得する
takaya030.hatenablog.com

Google APIs Client Library for PHP のインストー

前回 oauth2 ライブラリは oriceon/oauth-5-laravel を使用しましたが、今回は google/apiclient を使います

$ composer require google/apiclient:v2.1.3

サンプルコード

.env

.env に以下の内容を追加

# oauth
GOOGLE_CLIENT_ID=Your-Clinet-Id
GOOGLE_CLIENT_SECRET=Your-Clinet-Secret
GOOGLE_REFRESH_TOKEN=Your-Refresh-Token

app/Http/Controllers/GmailController.php

<?php

namespace App\Http\Controllers;

class GmailController extends Controller
{
    // show labels
    public function showLabels()
    {
        $client = new \Google_Client();
        $client->setClientId( env('GOOGLE_CLIENT_ID') );
        $client->setClientSecret( env('GOOGLE_CLIENT_SECRET') );
        $client->setScopes([ "https://mail.google.com/" ]);
        $client->refreshToken( env('GOOGLE_REFRESH_TOKEN') );

        $service = new \Google_Service_Gmail($client);

        // Print the labels in the user's account.
        $user = 'me';
        $results = $service->users_labels->listUsersLabels($user);

        $labels = [];
        if (count($results->getLabels()) == 0) {
            $labels[] = "No labels found.";
        } else {
            $labels[] = "Labels:";
            foreach ($results->getLabels() as $label) {
                $labels[] = sprintf("- %s", $label->getName());
            }
        }

        return view( 'gmail.labels', ['labels' => $labels] );
    }
}

app/Http/routes.php

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/

$app->get('/gmail/labels', 'GmailController@showLabels');

resources/views/gmail/labels.blade.php

<!doctype html>
<html>
    <head>
        <title>gmail labels</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
    @foreach($labels as $label)
        {{ $label }}<br />
    @endforeach
    </body>
</html>

動作確認

テストサーバー起動

$ php artisan serve

WEBブラウザで http://localhost:8000/gmail/labels を開いて下の画像のように表示されれば成功です
f:id:takaya030:20170715001557p:plain

まとめ

oriceon/oauth-5-laravel のときはエンドポイントの url を文字列で直接指定したり、レスポンスの json を自分でパースしなければならなかったりといろいろ手間がかかりましたが、google/apiclient ではそれらをライブラリ側で吸収してくれているので以前より簡潔なコードになっています