Php 通过谷歌api客户端获取用户信息
我正在从android客户端接收Php 通过谷歌api客户端获取用户信息,php,laravel,google-oauth,google-api-client,laravel-socialite,Php,Laravel,Google Oauth,Google Api Client,Laravel Socialite,我正在从android客户端接收令牌id。 在第一步中,我将通过以下代码验证令牌: $tokenId = $request->get('token-id'); $google_client = new Google_Client(); $google_client->setApplicationName("Ashojash"); $google_client->setClientId
令牌id
。在第一步中,我将通过以下代码验证令牌:
$tokenId = $request->get('token-id');
$google_client = new Google_Client();
$google_client->setApplicationName("Ashojash");
$google_client->setClientId(env("GOOGLE_KEY"));
$google_client->setClientSecret(env("GOOGLE_SECRET"));
$google_client->setIncludeGrantedScopes(true);
$google_client->addScope(['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/plus.login']);
$credentials = $google_client->verifyIdToken($tokenId);
if ($credentials)
{
$data = $credentials->getAttributes();
// validate aud against server client_id
return $data['payload']['sub']; // user ID
}
return false;
从谷歌收到的数据是:
array:2 [
"envelope" => array:2 [
"alg" => "RS256"
"kid" => "23e5872762976b37944c33e4b2602656093ece91"
]
"payload" => array:12 [
"iss" => "https://accounts.google.com"
"aud" => "346904023124-73h70s03c0dipla8ltcbcd2ko076ft43.apps.googleusercontent.com"
"sub" => "111167217866315036918"
"email_verified" => true
"azp" => "346904023124-lehbs8510nibuq5ci125h8mu6u2ir4q1.apps.googleusercontent.com"
"email" => "jhon.f.kenedy777@gmail.com"
"iat" => 1452178925
"exp" => 1452182525
"name" => "john F.kenedy"
"given_name" => "john"
"family_name" => "F.kenedy"
"locale" => "en"]
]
验证令牌id后,如何获取用户信息?我感兴趣的是:
1-电子邮件
2-用户基本信息
3-Google plus信息
我也安装了社交网站,所以如果可能的话,也可以在社交网站中添加你的答案。一旦你从$google\u client->verifyIdToken获得结果,你就可以访问你在问题中已经发布的所有属性 通过以下方式进行测试:
define('ROOT_PATH', $_SERVER['DOCUMENT_ROOT']);
require_once (ROOT_PATH.'/google-api-php-client/src/Google_Client.php');
$ClientID_debug = 'xxxxxxx.apps.googleusercontent.com';
$ClientID_release = 'xxxxxxx.apps.googleusercontent.com';
$mToken = $_POST['mToken'];
$build = $_POST['build'];
$google_client = new Google_Client();
if($build=='DEBUG'){
$google_client->setClientId($ClientID_debug);
}else{
$google_client->setClientId($ClientID_release);
}
$google_result = $google_client->verifyIdToken($mToken);
if ($google_result){
$data = $google_result->getAttributes();
$tokenUserID = $data['payload']['sub'];
$tokenAudience = $data['payload']['aud'];
$tokenEmail = $data['payload']['email'];
//etc..
//send result back to Android client (could also use JSON to send all attributes)
echo($tokenAudience);
}
通过以下方式从Android调用:
受保护的字符串doInBackground(字符串…参数){
试一试{
//始终使用https来防止中间人攻击!
URL=新URL(“https://www.example.com/validateTokenID.php");
Map HTTPpostParams=新LinkedHashMap();
if(BuildConfig.DEBUG){
//调试生成
HTTPpostParams.put(“构建”、“调试”);
}否则{
//发布版本
HTTPpostParams.put(“构建”、“发布”);
}
HTTPpostParams.put(“mToken”,MyGoogleSignedAccount.getIdToken());
StringBuilder postData=新建StringBuilder();
对于(Map.Entry参数:HTTPpostParams.entrySet()){
如果(postData.length()!=0)postData.append('&');
append(URLEncoder.encode(param.getKey(),“UTF-8”);
postData.append('=');
append(URLEncoder.encode(String.valueOf(param.getValue()),“UTF-8”);
}
字节[]postDataBytes=postData.toString().getBytes(“UTF-8”);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“内容类型”、“应用程序/x-www-form-urlencoded”);
conn.setRequestProperty(“内容长度”,String.valueOf(postDataBytes.Length));
连接设置输出(真);
conn.getOutputStream().write(postDataBytes);
Reader in=新的BufferedReader(新的InputStreamReader(conn.getInputStream(),“UTF-8”);
StringBuilder strB=新的StringBuilder();
对于(int c=in.read();c!=-1;c=in.read())strB.append((char)c);
返回strB.toString();
}捕获(例外e){
//这个异常=e;
Log.e(“MyApp”,e.getMessage());
返回e.getMessage();
}
}
您的数据不是来自谷歌吗?是用户信息吗?我看到一个名字、电子邮件等。@sstarlight如果你是指我代码的第二块,它是通过id-token
从谷歌检索到的,我认为$data['payload']['email']包含用户的电子邮件等等。这在v2中发生了变化:$userData=$client->verifyIdToken($idToken)$userId=$userData['sub'];
protected String doInBackground(String... params) {
try {
//Always use https to prevent man-in-the-middle attacks!
URL url = new URL("https://www.example.com/validateTokenID.php");
Map<String, Object> HTTPpostParams = new LinkedHashMap<>();
if (BuildConfig.DEBUG) {
//debug build
HTTPpostParams.put("build", "DEBUG");
}else{
//release build
HTTPpostParams.put("build", "RELEASE");
}
HTTPpostParams.put("mToken", MygoogleSignedInAccount.getIdToken());
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : HTTPpostParams.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder strB = new StringBuilder();
for ( int c = in.read(); c != -1; c = in.read() ) strB.append((char) c);
return strB.toString();
} catch (Exception e) {
//this.exception = e;
Log.e("MyApp", e.getMessage());
return e.getMessage();
}
}