edisonthk/google-oauth-laravel4

优化 artdarek/oauth-4-laravel 以支持 laravel 4 的 Google OAuth 2.0

1.0.5 2014-06-22 20:03 UTC

This package is not auto-updated.

Last update: 2024-09-24 06:49:11 UTC


README

oauth-4-laravel 是一个简单的 laravel 4 Google OAuth 2.0 扩展。它与 Lusitanian/PHPoAuthLibartdarek/oauth-4-laravel 集成,后者为 PHP 5.3+ 提供了 laravel 4 的 OAuth 2.0 支持。

安装

此包可在 packagist.org 上找到。您可以通过在 composer.json 中添加以下内容来安装它

"require": {
    "edisonthk/google-oauth-laravel4": "dev-master"
},

然后,通过以下方式安装

composer update

安装完成后,请在 app/config/app.php 中导入服务提供者和别名

'providers' => array(
	'Edisonthk\GoogleOAuth\GoogleOAuthServiceProvider',
)

 :
 :

'aliases' => array(
	'GoogleOAuth'	=> 'Edisonthk\GoogleOAuth\Facade\GoogleOAuth',
)

配置 & 凭据

从 Google 开发者控制台获取您的 client_secret 和 client_id。然后,使用 laravel 进行配置。您可以配置以下两个选项之一。

选项 1

使用 artisan 命令创建配置文件。

$ php artisan config:publish edisonthk/google-oauth-laravel4

然后,配置文件将在 app/config/packages/edisonthk/google-oauth-laravel4/config.php 中生成。填写您的 client_secret、client_id、redirect_url 和作用域。

选项 2

在 app/config 目录中创建一个名为 google-oauth-laravel4.php 的配置文件。然后添加以下代码,并填写您的 client_secret、client_id 和 redirect_url。

<?php 

return array( 
	
	/*
	|--------------------------------------------------------------------------
	| oAuth Config
	|--------------------------------------------------------------------------
	*/

	/**
	 * Storage
	 */
	'storage' => 'Session', 

	/**
	 * Consumers
	 */
	'consumers' => array(

		/**
		 * Google
		 */
        'Google' => array(
            'client_id'     => '',
            'client_secret' => '',
            'redirect_url'	=> '',
            'scope'         => array(),
        ),		

	)

);

示例代码

在配置中

'Google' => array(
    'client_id'     => 'Your Google client ID',
    'client_secret' => 'Your Google Client Secret',
    'redirect_url' 	=> 'http://www.example.com/success'
    'scope'         => array('userinfo_email', 'userinfo_profile'),
),

在 app/routes.php 中

Route::controller('/', 'HomeController');

在 app/controllers/HomeController.php 中

<?php

class HomeController extends BaseController {

	public function getIndex()
	{
		$authUrl = GoogleOAuth::getAuthorizationUri();
		$message = "<a href='$authUrl'>Login with Google</a>";

		die($message);
	}

	public function getSuccess()
	{
		$googleService = GoogleOAuth::consumer();

		if(Input::has("code")){
			$code = Input::get("code");
			$googleService->requestAccessToken($code);
			return Redirect::to("/success");
		}

		if(!GoogleOAuth::hasAuthorized()){
			die("Not authorized yet");
		}

        
        $result = json_decode( $googleService->request( 'https://www.googleapis.com/oauth2/v1/userinfo' ), true );

        $message = 'Your unique Google user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
        die($message. "<br/>");


	}

	public function getLogout()
	{
		GoogleOAuth::logout();
		return Redirect::to("/");
	}


}