我正在尝试使用 Laravel 4(MVC 框架)让 Google Plus 登录正常工作。
我目前有两种方法home
和connect
:
public function home()
{
$state = md5(rand());
Session::put('state', $state);
$data = array (
'CLIENT_ID' => 'my client id',
'STATE' => $state,
'APPLICATION_NAME' => 'API Test'
);
return View::make('home')
->with($data);
}
这将创建带有变量的主“主页”视图。
在这里,我有所需的脚本,我的按钮:
<div id="test"></div>
<div id="signinButton">
<span class="g-signin"
data-scope="https://www.googleapis.com/auth/plus.login"
data-clientid="{{ $CLIENT_ID }}"
data-redirecturi="postmessage"
data-accesstype="offline"
data-cookiepolicy="single_host_origin"
data-callback="signInCallback">
</span>
</div>
然后加载我的 signInCallback 函数:
function signInCallback(authResult) {
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
var dataString = 'auth= ' +authResult['code'];
// Send the code to the server
$.ajax({
type: 'POST',
url: 'connect',
dataType: 'html',
data: dataString,
processData: false,
statusCode: {
200: function(result){
$('#test').html(result);
}
},
});
} else if (authResult['error']) {
console.log('There was an error: ' + authResult['error']);
}
}
所有这些都在起作用。
我的连接方法如何接收身份验证码,我想将其交换为所需的令牌:
public function connect()
{
$client = new Google_Client();
$client->setApplicationName('API Test');
$client->setClientId('my client id');
$client->setClientSecret('my client secret');
$client->setRedirectUri('postmessage');
// Get auth code - this works
$code = Input::get('auth');
$client->authenticate($code);
$token = json_decode($client->getAccessToken());
return "Token: $token";
}
但是,这会返回 500 内部服务器错误 - 当我添加$client->authenticate($code);
. 有人可以帮忙吗?我发现文档非常混乱。