gpt4 book ai didi

php - Google+ 登录,没有 "Silex/twig"的 PHP 一次性代码/服务器端流程

转载 作者:可可西里 更新时间:2023-11-01 12:36:19 26 4
gpt4 key购买 nike

示例代码来自 Google+ Sign-In for server-side apps

  // Create a state token to prevent request forgery.
// Store it in the session for later validation.
$state = md5(rand());
$app['session']->set('state', $state);
// Set the client ID, token state, and application name in the HTML while
// serving it.
return $app['twig']->render('index.html', array(
'CLIENT_ID' => CLIENT_ID,
'STATE' => $state,
'APPLICATION_NAME' => APPLICATION_NAME
));

enter image description here

问题:如何在没有 silex/twig 的情况下进行服务器端工作?

最佳答案

我用这个Client Library(PHP)
请测试此代码是否正常工作
索引.php

<?php
session_start();
$data['state'] = md5(uniqid(rand(), true));
$_SESSION['state'] = $data['state'];
?>
<html itemscope itemtype="http://schema.org/Article">
<head>
<!-- BEGIN Pre-requisites -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.moments.write https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/plus.profile.agerange.read https://www.googleapis.com/auth/plus.profile.language.read https://www.googleapis.com/auth/plus.circles.members.read https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/userinfo.email" />

<script type="text/javascript">
(function () {
var po = document.createElement('script');
po.type = 'text/javascript';
po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
</script>
<!-- END Pre-requisites -->
</head>
<body>
<!-- Add where you want your sign-in button to render -->
<div id="signinButton">
<span class="g-signin"
data-scope="https://www.googleapis.com/auth/plus.login"
data-clientid="Your clientid"
data-redirecturi="postmessage"
data-accesstype="offline"
data-cookiepolicy="single_host_origin"
data-callback="signInCallback">
</span>
</div>
<button id="signoutButton" style="display:none" onclick="signout()">signout</button>
<div id="result"></div>

<script type="text/javascript">
function signInCallback(authResult) {
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
$('#signoutButton').attr('style', 'display: block');
var state = '<?php echo $_SESSION['state']; ?>';
var param = new Array();
var param = [authResult['code'],state];
// Send the code to the server
$.ajax({
type: 'POST',
url: 'plus.php?storeToken&state',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response if necessary.
console.log(result);
alert('connected');
},
processData: false,
data: param
});
} else if (authResult['error']) {
alert('Could not automatially log in the user');
console.log('There was an error: ' + authResult['error']);
}
}

function signout(){
gapi.auth.signOut();
$('#signoutButton').attr('style', 'display: none');
$('#signinButton').attr('style', 'display: block');
console.log('sign out');
}
</script>
</body>
</html>

加.php

<?php
session_start();
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_PlusService.php';
$client = new Google_Client();
$CLIENT_ID = 'CLIENT ID';
$client->setClientId($CLIENT_ID);
$client->setClientSecret('Client Secret');
$client->setRedirectUri('postmessage');

$code = explode(",",file_get_contents('php://input'));

if (isset($code[1]) && $code[1] === $_SESSION['state'])
{
$plus = new Google_PlusService($client);
$client->authenticate($code[0]);
$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());

$userId = $tokenInfo->user_id;
$userEmail = $tokenInfo->email;

// If there was an error in the token info, abort.
if (isset($tokenInfo->error)) {
print $tokenInfo->error;
}
// Make sure the token we got is for our app.
if ($tokenInfo->audience != $CLIENT_ID) {
print "Token's client ID does not match app's.";
}

print 'Token from result: ' . print_r($token, true);
print '<<<<<<<<<<< tokenInfo >>>>>>> ' . print_r($tokenInfo, true);

}
else
{
echo "Invalid state parameter";
}

不要忘记添加您的CLIENT IDClient Secret
注销不在本地主机上工作。

关于php - Google+ 登录,没有 "Silex/twig"的 PHP 一次性代码/服务器端流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22893643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com