github AOuth2

_config.php

<?php
require_once './vendor/autoload.php';
session_start();
$github_keys = require('./github-app-keys.php');
$provider = new League\OAuth2\Client\Provider\Github(&#91;
	'clientId' 		=> $github_keys['clientId'],
	'clientSecret'	=> $github_keys['clientSecret'],
]);

$title = "PHP GitHub Login Sample";

github-app-keys.php

<?php
return &#91;
	'clientId' => 'xxxx',
	'clientSecret' => 'xxxxxxxx'
];

login.php

<?php
require_once '_config.php';

$authUrl = $provider->getAuthorizationUrl();

$_SESSION['oauth2state'] = $provider->getState();

header('Location: '.$authUrl);
exit;

callback.php

<?php
require_once '_config.php';

if (empty($_GET&#91;'state'&#93;) || ($_GET&#91;'state'&#93; !== $_SESSION&#91;'oauth2state'&#93;)){
	unset($_SESSION&#91;'oauth2state'&#93;);
	exit('Invalid state');
}

$token = $provider->getAccessToken('authorization_code', [
	'code' => $_GET['code']
]);

echo $token.'\n';
echo 'Successfully callbacked!!'.'\n';

$user = $provider->getResourceOwner($token);

echo '<pre>';
var_dump($user);
echo '</pre>';
[vagrant@localhost api]$ php -S 192.168.33.10:8000

github AOuth

まずComposerを入れます。

$ curl -sS https://getcomposer.org/installer | php

composer.jsonの作成

$ php composer.phar init
[vagrant@localhost api]$ ls
composer.json  composer.phar  google-api-php-client
[vagrant@localhost api]$ sudo mv composer.phar /usr/local/bin/composer

GitHubでApplicationをregisterして、Client IDとClient Secretを取得します。
https://github.com/settings/developers

composerで入れます。

[vagrant@localhost api]$ composer require league/oauth2-client league/oauth2-github
Using version ^2.3 for league/oauth2-client
Using version ^2.0 for league/oauth2-github
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 7 installs, 0 updates, 0 removals
  - Installing paragonie/random_compat (v2.0.11): Downloading (100%)
  - Installing guzzlehttp/promises (v1.3.1): Downloading (100%)
  - Installing psr/http-message (1.0.1): Downloading (100%)
  - Installing guzzlehttp/psr7 (1.4.2): Downloading (100%)
  - Installing guzzlehttp/guzzle (6.3.0): Downloading (100%)
  - Installing league/oauth2-client (2.3.0): Downloading (100%)
  - Installing league/oauth2-github (2.0.0): Downloading (100%)
paragonie/random_compat suggests installing ext-libsodium (Provides a modern crypto API that can be used to generate random bytes.)
guzzlehttp/guzzle suggests installing psr/log (Required for using the Log middleware)
Writing lock file
Generating autoload files
[vagrant@localhost api]$ ls
composer.json  composer.lock  google-api-php-client  vendor

OAuthとは

OAuthは認可情報の委譲のための仕様
-あらかじめ信頼関係を構築したサービス間で、ユーザの同意のもとに、セキュアにユーザの権限を受け渡しする
※自分が利用したいサービスに最低限必要な権限のみを委譲することができる。そのため、basic認証と比べて柔軟かつセキュアな運用が可能

認可情報の委譲を行う仕様には、Google、Yahoo!、Flickr、Facebookなどが独自に提供しているものが

OAuth Service Provider(Google, Yahoo, Twitter)
OAuth Consumer
Users

[vagrant@localhost api]$ php composer.phar
   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 1.6.2 2018-01-05 15:28:41

Usage:
  command [options] [arguments]

Options:
  -h, --help                     Display this help message
  -q, --quiet                    Do not output any message
  -V, --version                  Display this application version
      --ansi                     Force ANSI output
      --no-ansi                  Disable ANSI output
  -n, --no-interaction           Do not ask any interactive question
      --profile                  Display timing and memory usage information
      --no-plugins               Whether to disable plugins.
  -d, --working-dir=WORKING-DIR  If specified, use the given directory as working directory.
  -v|vv|vvv, --verbose           Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  about                Shows the short information about Composer.
  archive              Creates an archive of this composer package.
  browse               Opens the package's repository URL or homepage in your browser.
  check-platform-reqs  Check that platform requirements are satisfied.
  clear-cache          Clears composer's internal package cache.
  clearcache           Clears composer's internal package cache.
  config               Sets config options.
  create-project       Creates new project from a package into given directory.
  depends              Shows which packages cause the given package to be installed.
  diagnose             Diagnoses the system to identify common errors.
  dump-autoload        Dumps the autoloader.
  dumpautoload         Dumps the autoloader.
  exec                 Executes a vendored binary/script.
  global               Allows running commands in the global composer dir ($COMPOSER_HOME).
  help                 Displays help for a command
  home                 Opens the package's repository URL or homepage in your browser.
  info                 Shows information about packages.
  init                 Creates a basic composer.json file in current directory.
  install              Installs the project dependencies from the composer.lock file if present, or falls back on the composer.json.
  licenses             Shows information about licenses of dependencies.
  list                 Lists commands
  outdated             Shows a list of installed packages that have updates available, including their latest version.
  prohibits            Shows which packages prevent the given package from being installed.
  remove               Removes a package from the require or require-dev.
  require              Adds required packages to your composer.json and installs them.
  run-script           Runs the scripts defined in composer.json.
  search               Searches for packages.
  self-update          Updates composer.phar to the latest version.
  selfupdate           Updates composer.phar to the latest version.
  show                 Shows information about packages.
  status               Shows a list of locally modified packages.
  suggests             Shows package suggestions.
  update               Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file.
  upgrade              Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file.
  validate             Validates a composer.json and composer.lock.
  why                  Shows which packages cause the given package to be installed.
  why-not              Shows which packages prevent the given package from being installed.

最新のgoogle-api-php-client

まず、コマンドラインでphpのバージョンを確認します。

[vagrant@localhost api]$ php -v
PHP 5.6.27 (cli) (built: Oct 14 2016 14:06:54)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies

gitも確認。

[vagrant@localhost api]$ git version
git version 2.2.1

githubにあるリポジトリをローカルにcloneします。

[vagrant@localhost api]$ git clone https://github.com/google/google-api-php-client.git
Cloning into 'google-api-php-client'...
remote: Counting objects: 10177, done.
remote: Compressing objects: 100% (16/16), done.
remote: Total 10177 (delta 3), reused 8 (delta 2), pack-reused 10158
Receiving objects: 100% (10177/10177), 6.98 MiB | 1.51 MiB/s, done.
Resolving deltas: 100% (6953/6953), done.
Checking connectivity... done.

入りました。

では、試しに、examplesをサーバーで見てみましょう。

[vagrant@localhost google-api-php-client]$ php -S 192.168.33.10:8000
PHP 5.6.27 Development Server started at Mon Jan 29 16:12:27 2018
Listening on http://192.168.33.10:8000
Document root is /home/vagrant/api/google-api-php-client
Press Ctrl-C to quit.
[Mon Jan 29 16:12:44 2018] 192.168.33.1:59098 [200]: /examples/
[Mon Jan 29 16:12:44 2018] 192.168.33.1:59099 [200]: /examples/styles/style.css
[Mon Jan 29 16:12:44 2018] 192.168.33.1:59101 [404]: /favicon.ico - No such file   or directory
[Mon Jan 29 16:12:47 2018] 192.168.33.1:59100 Invalid request (Unexpected EOF)

foreach loop sample2

We have an associative array that stores name and yield.

<?php
$yield = array(
	"レカム"=> "16,776,900",
	"JALCOホールディングス"=>"15,380,900",
	"明豊エンタープライズ"=>"12,639,200",
	"石垣食品"=>"5,372,100",
	"ネクストウェア"=>"5,073,400"
);

foreach( $yield as $key => $value){
	echo "銘柄: $key, 出来高: $value<br>";
}
?>

foreach文

指定した配列に関してループ処理を実行。各ループ時には、現在の要素の値が変数$valueに代入され、配列ポインタが1つ進められる。

foreach文の使用例

foreach (配列 as value)
 ループ処理

サンプル

<?php
$a = array(
	1 => 1,
	2 => 4,
	3 => 9,
	4 => 16
);

foreach( $a as $value){
	echo $value."<br>\n";
}
?>

拡張構文
各ループで、要素の値が$valに、要素のキーが変数$valに代入される。

foreach(配列 as $key => $val)
 ループ処理;

サンプル

<?php
$body = array(
	"head" => "頭",
	"nose" => "鼻",
	"face" => "顔",
	"hand" => "手"
	);

foreach( $body as $key => $value){
	echo $key. ":" .$value."<br>\n";
}
?>

多次元配列の出力

<?php
$code = array(
	"Mothers"=> array(
		"ブライトパス・バイオ"=> "4594",
		"ジーエヌアイグループ"=> "2160",
		"アンジェス"=> "4563",
		"ナノキャリア"=> "4571"
		),
	"JASDAQ"=> array(
		"レカム"=> "3323",
		"JALCOホールディングス"=> "6625",
		"明豊エンタープライズ"=> "8917",
		"石垣食品"=> "2901"
		)
);

foreach( $code as $key1 => $val1){
	echo "--".$key1. "--<br>\n";

	foreach( $val1 as $key2 => $val2){
		echo $key2. ":" .$val2."<br>\n";
	}
}
?>

Google API Client Librariesとは?

API Client Libraries offers simple, flexible, powerful access to many Google APIs.

Setup
1. sign up Google account
2. create a project in the Google API Console
3. Install the library

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

Authentication and authorization
All API calls must use either simple or authorized access.
API Key: to authenticate your application, use API Key for your Google API Console.

Authorized API access(OAuth 2.0)
your application must be authenticated, the user must grant access for your application, and the user must be authenticated in order to grant that access.
scope: each api defines one or more scopes that declare a set of operations permitted.
Refresh and access tokens: when a user grants your application access, the OAuth 2.0 authorization server provides your application with refresh and access tokens.
Client ID and client secret: these strings uniquely identify your application and are used to acquire tokens.

Build the client object

$client = new Google_Client();
$client->setApplicationName("My Application")
$client->setDeveloperKey("My_SIMPLE_API_KEY")

Build the service object
services are called through queries to service specific objects. These are created by constructing the service object, and passing an instance of Google_Client to it.

$service = new Google_Service_Books($client);

Calling an API
each API provides resources and methods, usually in chain. These can be accessed from the service object in the form $service->resource->method(args). Most method require some arguments, then accept a final parameter of an array containing optional parameters.

$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoeau', $optParams);

Handling the result
There are two main types of response – items and collections of items. Each can be accessed either as an object or as an array.

foreach($results as $item){
	echo $item['volumeInfo']['title'], "<br />\n";
}

Google APIs Client Library for PHP

Google APIs Client Library for PHP
https://code.google.com/archive/p/google-api-php-client/downloads

最新版をダウンロードして、展開します。

[vagrant@localhost youtube]$ tar zxvf google-api-php-client-0.6.7.tar.gz
google-api-php-client/
google-api-php-client/NOTICE
google-api-php-client/README
google-api-php-client/test/
google-api-php-client/test/phpunit.xml
google-api-php-client/test/general/
google-api-php-client/test/general/OAuthHelper.php
google-api-php-client/test/general/CacheTest.php
google-api-php-client/test/general/GeneralTests.php
google-api-php-client/test/general/AuthTest.php
google-api-php-client/test/general/ServiceTest.php
google-api-php-client/test/general/ApiModelTest.php
google-api-php-client/test/general/IoTest.php
google-api-php-client/test/general/testdata/
google-api-php-client/test/general/testdata/test_public_key.pem
google-api-php-client/test/general/ApiClientTest.php
google-api-php-client/test/general/ApiOAuth2Test.php
google-api-php-client/test/general/ApiMediaFileUploadTest.php
google-api-php-client/test/general/ApiBatchRequestTest.php
google-api-php-client/test/general/RestTest.php
google-api-php-client/test/general/ApiCacheParserTest.php
google-api-php-client/test/tasks/
google-api-php-client/test/tasks/TasksTest.php
google-api-php-client/test/tasks/AllTasksTests.php
google-api-php-client/test/adsense/
google-api-php-client/test/adsense/AdSenseTest.php
google-api-php-client/test/AllTests.php
google-api-php-client/test/README
google-api-php-client/test/plus/
google-api-php-client/test/plus/PlusTest.php
google-api-php-client/test/BaseTest.php
google-api-php-client/test/pagespeed/
google-api-php-client/test/pagespeed/PageSpeedTest.php
google-api-php-client/test/pagespeed/AllPageSpeedTests.php
google-api-php-client/test/urlshortener/
google-api-php-client/test/urlshortener/AllUrlShortenerTests.php
google-api-php-client/test/urlshortener/UrlShortenerTests.php
google-api-php-client/src/
google-api-php-client/src/cache/
google-api-php-client/src/cache/Google_MemcacheCache.php
google-api-php-client/src/cache/Google_Cache.php
google-api-php-client/src/cache/Google_FileCache.php
google-api-php-client/src/cache/Google_ApcCache.php
google-api-php-client/src/Google_Client.php
google-api-php-client/src/config.php
google-api-php-client/src/auth/
google-api-php-client/src/auth/Google_LoginTicket.php
google-api-php-client/src/auth/Google_Auth.php
google-api-php-client/src/auth/Google_Verifier.php
google-api-php-client/src/auth/Google_PemVerifier.php
google-api-php-client/src/auth/Google_AssertionCredentials.php
google-api-php-client/src/auth/Google_OAuth2.php
google-api-php-client/src/auth/Google_AuthNone.php
google-api-php-client/src/auth/Google_Signer.php
google-api-php-client/src/auth/Google_P12Signer.php
google-api-php-client/src/io/
google-api-php-client/src/io/Google_HttpStreamIO.php
google-api-php-client/src/io/Google_CacheParser.php
google-api-php-client/src/io/Google_HttpRequest.php
google-api-php-client/src/io/cacerts.pem
google-api-php-client/src/io/Google_CurlIO.php
google-api-php-client/src/io/Google_REST.php
google-api-php-client/src/io/Google_IO.php
google-api-php-client/src/service/
google-api-php-client/src/service/Google_ServiceResource.php
google-api-php-client/src/service/Google_Service.php
google-api-php-client/src/service/Google_MediaFileUpload.php
google-api-php-client/src/service/Google_Utils.php
google-api-php-client/src/service/Google_BatchRequest.php
google-api-php-client/src/service/Google_Model.php
google-api-php-client/src/contrib/
google-api-php-client/src/contrib/Google_SQLAdminService.php
google-api-php-client/src/contrib/Google_PlusService.php
google-api-php-client/src/contrib/Google_UrlshortenerService.php
google-api-php-client/src/contrib/Google_FreebaseService.php
google-api-php-client/src/contrib/Google_DatastoreService.php
google-api-php-client/src/contrib/Google_AdExchangeSellerService.php
google-api-php-client/src/contrib/Google_ReportsService.php
google-api-php-client/src/contrib/Google_StorageService.php
google-api-php-client/src/contrib/Google_SiteVerificationService.php
google-api-php-client/src/contrib/Google_TasksService.php
google-api-php-client/src/contrib/Google_CustomsearchService.php
google-api-php-client/src/contrib/Google_TranslateService.php
google-api-php-client/src/contrib/Google_CalendarService.php
google-api-php-client/src/contrib/Google_ShoppingService.php
google-api-php-client/src/contrib/Google_AndroidpublisherService.php
google-api-php-client/src/contrib/Google_GroupssettingsService.php
google-api-php-client/src/contrib/Google_PredictionService.php
google-api-php-client/src/contrib/Google_FusiontablesService.php
google-api-php-client/src/contrib/Google_MirrorService.php
google-api-php-client/src/contrib/Google_AdSenseService.php
google-api-php-client/src/contrib/Google_AppstateService.php
google-api-php-client/src/contrib/Google_CoordinateService.php
google-api-php-client/src/contrib/Google_DriveService.php
google-api-php-client/src/contrib/Google_AnalyticsService.php
google-api-php-client/src/contrib/Google_DfareportingService.php
google-api-php-client/src/contrib/Google_GamesService.php
google-api-php-client/src/contrib/Google_BooksService.php
google-api-php-client/src/contrib/Google_PagespeedonlineService.php
google-api-php-client/src/contrib/Google_AdsensehostService.php
google-api-php-client/src/contrib/Google_OrkutService.php
google-api-php-client/src/contrib/Google_AdexchangebuyerService.php
google-api-php-client/src/contrib/Google_DirectoryService.php
google-api-php-client/src/contrib/Google_YouTubeService.php
google-api-php-client/src/contrib/Google_LicensingService.php
google-api-php-client/src/contrib/Google_CivicInfoService.php
google-api-php-client/src/contrib/Google_BigqueryService.php
google-api-php-client/src/contrib/Google_ResellerService.php
google-api-php-client/src/contrib/Google_Oauth2Service.php
google-api-php-client/src/contrib/Google_ModeratorService.php
google-api-php-client/src/contrib/Google_ComputeService.php
google-api-php-client/src/contrib/Google_TaskqueueService.php
google-api-php-client/src/contrib/Google_GamesManagementService.php
google-api-php-client/src/contrib/Google_GanService.php
google-api-php-client/src/contrib/Google_BloggerService.php
google-api-php-client/src/contrib/Google_PlusDomainsService.php
google-api-php-client/src/contrib/Google_YouTubeAnalyticsService.php
google-api-php-client/src/contrib/Google_WebfontsService.php
google-api-php-client/src/contrib/Google_AuditService.php
google-api-php-client/src/external/
google-api-php-client/src/external/URITemplateParser.php
google-api-php-client/LICENSE
google-api-php-client/examples/
google-api-php-client/examples/analytics/
google-api-php-client/examples/analytics/simple.php
google-api-php-client/examples/analytics/demo/
google-api-php-client/examples/analytics/demo/managementApiReference.php
google-api-php-client/examples/analytics/demo/index.php
google-api-php-client/examples/analytics/demo/helloAnalyticsApi.php
google-api-php-client/examples/analytics/demo/storage.php
google-api-php-client/examples/analytics/demo/authHelper.php
google-api-php-client/examples/analytics/demo/coreReportingApiReference.php
google-api-php-client/examples/tasks/
google-api-php-client/examples/tasks/index.php
google-api-php-client/examples/tasks/css/
google-api-php-client/examples/tasks/css/style.css
google-api-php-client/examples/customSearch/
google-api-php-client/examples/customSearch/index.php
google-api-php-client/examples/userinfo/
google-api-php-client/examples/userinfo/index.php
google-api-php-client/examples/calendar/
google-api-php-client/examples/calendar/simple.php
google-api-php-client/examples/webfonts/
google-api-php-client/examples/webfonts/simple.php
google-api-php-client/examples/batch.php
google-api-php-client/examples/translate/
google-api-php-client/examples/translate/simple.php
google-api-php-client/examples/adsense/
google-api-php-client/examples/adsense/index.php
google-api-php-client/examples/adsense/style.css
google-api-php-client/examples/adsense/htmlHelper.php
google-api-php-client/examples/adsense/examples/
google-api-php-client/examples/adsense/examples/GetAllAdUnitsForCustomChannel.php
google-api-php-client/examples/adsense/examples/GetAllMetrics.php
google-api-php-client/examples/adsense/examples/GetAllCustomChannels.php
google-api-php-client/examples/adsense/examples/GetAllSavedAdStyles.php
google-api-php-client/examples/adsense/examples/GenerateGeoChart.php
google-api-php-client/examples/adsense/examples/GenerateLineChart.php
google-api-php-client/examples/adsense/examples/GetAllAccounts.php
google-api-php-client/examples/adsense/examples/GetAllSavedReports.php
google-api-php-client/examples/adsense/examples/GetAllAdUnits.php
google-api-php-client/examples/adsense/examples/GetAllUrlChannels.php
google-api-php-client/examples/adsense/examples/GetAllAlerts.php
google-api-php-client/examples/adsense/examples/GenerateTableChart.php
google-api-php-client/examples/adsense/examples/GenerateReportWithPaging.php
google-api-php-client/examples/adsense/examples/GenerateSavedReport.php
google-api-php-client/examples/adsense/examples/GeneratePieChart.php
google-api-php-client/examples/adsense/examples/GetAllDimensions.php
google-api-php-client/examples/adsense/examples/GenerateColumnChart.php
google-api-php-client/examples/adsense/examples/HandleAccountErrors.php
google-api-php-client/examples/adsense/examples/GenerateReport.php
google-api-php-client/examples/adsense/examples/GetAllAdClients.php
google-api-php-client/examples/adsense/examples/GetAccountTree.php
google-api-php-client/examples/adsense/examples/GetAllAdClientsForAccount.php
google-api-php-client/examples/adsense/examples/GetAllCustomChannelsForAdUnit.php
google-api-php-client/examples/adsense/BaseExample.php
google-api-php-client/examples/adsense/AdSenseAuth.php
google-api-php-client/examples/affiliateNetwork/
google-api-php-client/examples/affiliateNetwork/index.php
google-api-php-client/examples/books/
google-api-php-client/examples/books/index.php
google-api-php-client/examples/books/simple.php
google-api-php-client/examples/books/interface.html
google-api-php-client/examples/books/books_browser.css
google-api-php-client/examples/moments/
google-api-php-client/examples/moments/simple.php
google-api-php-client/examples/adexchangebuyer/
google-api-php-client/examples/adexchangebuyer/index.php
google-api-php-client/examples/adexchangebuyer/style.css
google-api-php-client/examples/adexchangebuyer/htmlHelper.php
google-api-php-client/examples/adexchangebuyer/examples/
google-api-php-client/examples/adexchangebuyer/examples/UpdateAccount.php
google-api-php-client/examples/adexchangebuyer/examples/GetAllAccounts.php
google-api-php-client/examples/adexchangebuyer/examples/GetDirectDeals.php
google-api-php-client/examples/adexchangebuyer/examples/SubmitCreative.php
google-api-php-client/examples/adexchangebuyer/examples/GetCreative.php
google-api-php-client/examples/adexchangebuyer/BaseExample.php
google-api-php-client/examples/plus/
google-api-php-client/examples/plus/index.php
google-api-php-client/examples/plus/simple.php
google-api-php-client/examples/plus/style.css
google-api-php-client/examples/plus/README
google-api-php-client/examples/siteVerification/
google-api-php-client/examples/siteVerification/simple.php
google-api-php-client/examples/adsensehost/
google-api-php-client/examples/adsensehost/index.php
google-api-php-client/examples/adsensehost/style.css
google-api-php-client/examples/adsensehost/htmlHelper.php
google-api-php-client/examples/adsensehost/examples/
google-api-php-client/examples/adsensehost/examples/GenerateReportForHost.php
google-api-php-client/examples/adsensehost/examples/AddUrlChannelToHost.php
google-api-php-client/examples/adsensehost/examples/AddCustomChannelToHost.php
google-api-php-client/examples/adsensehost/examples/GenerateReportForPublisher.php
google-api-php-client/examples/adsensehost/examples/UpdateCustomChannelOnHost.php
google-api-php-client/examples/adsensehost/examples/DeleteCustomChannelOnHost.php
google-api-php-client/examples/adsensehost/examples/DeleteAdUnitOnPublisher.php
google-api-php-client/examples/adsensehost/examples/UpdateAdUnitOnPublisher.php
google-api-php-client/examples/adsensehost/examples/VerifyAssociationSession.php
google-api-php-client/examples/adsensehost/examples/GetAllAdUnitsForPublisher.php
google-api-php-client/examples/adsensehost/examples/StartAssociationSession.php
google-api-php-client/examples/adsensehost/examples/GetAccountDataForExistingPublisher.php
google-api-php-client/examples/adsensehost/examples/GetAllUrlChannelsForHost.php
google-api-php-client/examples/adsensehost/examples/GetAllCustomChannelsForHost.php
google-api-php-client/examples/adsensehost/examples/GetAllAdClientsForHost.php
google-api-php-client/examples/adsensehost/examples/GetAllAdClientsForPublisher.php
google-api-php-client/examples/adsensehost/examples/DeleteUrlChannelOnHost.php
google-api-php-client/examples/adsensehost/examples/AddAdUnitToPublisher.php
google-api-php-client/examples/adsensehost/BaseExample.php
google-api-php-client/examples/adsensehost/AdSenseHostAuth.php
google-api-php-client/examples/shopping/
google-api-php-client/examples/shopping/simple.php
google-api-php-client/examples/adexchangeseller/
google-api-php-client/examples/adexchangeseller/AdExchangeSellerAuth.php
google-api-php-client/examples/adexchangeseller/index.php
google-api-php-client/examples/adexchangeseller/style.css
google-api-php-client/examples/adexchangeseller/htmlHelper.php
google-api-php-client/examples/adexchangeseller/examples/
google-api-php-client/examples/adexchangeseller/examples/GetAllAdUnitsForCustomChannel.php
google-api-php-client/examples/adexchangeseller/examples/GetAllMetrics.php
google-api-php-client/examples/adexchangeseller/examples/GetAllCustomChannels.php
google-api-php-client/examples/adexchangeseller/examples/GetAllPreferredDeals.php
google-api-php-client/examples/adexchangeseller/examples/GetAllSavedReports.php
google-api-php-client/examples/adexchangeseller/examples/GetAllAdUnits.php
google-api-php-client/examples/adexchangeseller/examples/GetAllUrlChannels.php
google-api-php-client/examples/adexchangeseller/examples/GetAllAlerts.php
google-api-php-client/examples/adexchangeseller/examples/GenerateReportWithPaging.php
google-api-php-client/examples/adexchangeseller/examples/GenerateSavedReport.php
google-api-php-client/examples/adexchangeseller/examples/GetAllDimensions.php
google-api-php-client/examples/adexchangeseller/examples/GenerateReport.php
google-api-php-client/examples/adexchangeseller/examples/GetAllAdClients.php
google-api-php-client/examples/adexchangeseller/examples/GetAllCustomChannelsForAdUnit.php
google-api-php-client/examples/adexchangeseller/BaseExample.php
google-api-php-client/examples/prediction/
google-api-php-client/examples/prediction/serviceAccount.php
google-api-php-client/examples/prediction/index.php
google-api-php-client/examples/prediction/style.css
google-api-php-client/examples/prediction/README
google-api-php-client/examples/youtube/
google-api-php-client/examples/youtube/my_uploads.php
google-api-php-client/examples/youtube/search.php
google-api-php-client/examples/pagespeed/
google-api-php-client/examples/pagespeed/index.php
google-api-php-client/examples/pagespeed/style.css
google-api-php-client/examples/urlshortener/
google-api-php-client/examples/urlshortener/index.php
google-api-php-client/examples/urlshortener/style.css
google-api-php-client/examples/contacts/
google-api-php-client/examples/contacts/simple.php
google-api-php-client/examples/apps/
google-api-php-client/examples/apps/index.php
[vagrant@localhost youtube]$ ls
google-api-php-client  google-api-php-client-0.6.7.tar.gz  index.php

ruby api sample

require 'google/api_client'
require 'google/api_client/client_secrets'
require 'json'
require 'launchy'
require 'thin'

RESPONSE_HTML = <<stop
<html>
	<head>
		<title>OAuth 2 Flow Complete</title>
	</head>
	<body>
			You have successfully completed the OAuth 2 flow. Please close this browser window and return to your program.
	</body>
</html>
stop

FILE_POSTFIX = '-oauth2.json'

class CommandLineOAuthHelper

	def initialize(scope)
		credentials = Google::APIClient::ClientSecrets.load
		@authorization = Signet::OAuth2::Client.new(
				:authorization_uri => credentials.authorization_uri,
				:token_credential_uri => credentials.token_credential_uri,
				:client_id => credentials.cliend_id,
				:client_secret => credentials.client_secret,
				:redirect_uri => credentials.redirect_uris.first,
				:scope => scope
		)
	end

	def authorize
		credentialsFile = $0 + FILE_POSTFIX

		if File.exist? candentialsFile
			File.open(credentialsFile, 'r') do |file|
				credentials = JSON.load(file)
				@authorization.access_token = credentials['access_token']
				@authorization.client_id = credentials['client_id']
				@authorization.client_secret = credentials['client_secret']
				@authorization.refresh_token = credentials['refresh_token']
				@authorization.expires_in = (Time.parse(credentials['token_expiry']) - Time.now).credentialsFile
				if @authorization.expired?
					@authorization.fetch_access_token!
					save(credentialsFile)
				end
			end
		else
			auth = @authorization
			url = @authorization.authorization_uri().to_s
			server = Thin::Server.new('0.0.0.0', 8080) do
				run lambda { |env|
					req = Rack::Request.new(env)
					auth.code = req['code']
					auth.fetch_access_token!
					server.stop()
					[200, {'Content-Type' => 'text/html'}, RESPONSE_HTML]
				}
		end

		Launchy.open(url)
		server.start()

		save(credentialsFile)
	end

	return @authorization
	end

	def save(credentialsFile)
		File.open(credentialsFile, 'w', 0600) do |file|
			json = JSON.dump({
				:access_token => @authorization.access_token,
				:client_id => @authorization.client_id,
				:client_secret => @authorization.client_secret,
				:refresh_token => @authorization.refresh_token,
				:token_expiry => @authorization.expires_at
				})
				file.write(json)
		end
	end
end