我正在使用 Symfony 连接 Google Plus。这是我在登录后连接谷歌并获取访问令牌的代码:
$app->match('/connect', function (Request $request) use ($app, $client) {
$token = $app['session']->get('token');
if (empty($token)) {
// Ensure that this is no request forgery going on, and that the user
// sending us this connect request is the user that was supposed to.
if ($request->get('state') != ($app['session']->get('state'))) {
return new Response('Invalid state parameter', 401);
}
// Normally the state would be a one-time use token, however in our
// simple case, we want a user to be able to connect and disconnect
// without reloading the page. Thus, for demonstration, we don't
// implement this best practice.
//$app['session']->set('state', '');
$code = $request->getContent();
// Exchange the OAuth 2.0 authorization code for user credentials.
$gPlusId = $request->get['gplus_id'];
$client->authenticate($code);
$token = json_decode($client->getAccessToken());
// Verify the token
$reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' .
$token->access_token;
$req = new Google_HttpRequest($reqUrl);
$tokenInfo = json_decode(
$client::getIo()->authenticatedRequest($req)->getResponseBody());
// If there was an error in the token info, abort.
if ($tokenInfo->error) {
return new Response($tokenInfo->error, 500);
}
// Make sure the token we got is for the intended user.
if ($tokenInfo->userid != $gPlusId) {
return new Response(
"Token's user ID doesn't match given user ID", 401);
}
// Make sure the token we got is for our app.
if ($tokenInfo->audience != CLIENT_ID) {
return new Response(
"Token's client ID does not match app's.", 401);
}
//$_SESSION['token']=$token;
// You can read the Google user ID in the ID token.
// "sub" represents the ID token subscriber which in our case
// is the user ID. This sample does not use the user ID.
$attributes = $client->verifyIdToken($token->id_token, CLIENT_ID)
->getAttributes();
$gplus_id = $attributes["payload"]["sub"];
// Store the token in the session for later use.
$app['session']->set('token', json_encode($token));
$response = 'Successfully connected with token: ' . print_r($token, true);
}
return new Response($response, 200);
})->method('POST');
在html文件中我使用ajax调用之前的PHP代码:
connectServer: function() {
$.ajax({
type: 'POST',
url: window.location.href + '/connect?state={{ STATE }}',
cache:false,
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
console.log(result);
// helper.people();
},
error:function(e){
console.log(e);
},
processData: false,
data: this.authResult.code
});
但我总是收到一个错误:MethodNotAllowedHttpException:找不到“GET /connect”的路由:不允许方法(允许:POST)。我该如何解决这个错误?