质谱图 | PHP |获取照片 - Laravel 404 异常
MS Graph | PHP | GET Photo - Laravel 404 exception
我正在使用 MS Graph 使用 Azure 身份验证构建网站。
正如您在下面看到的,我想登录并获取我自己的数据以及我的经理,这些数据工作正常,但是当我想要 select 照片时,问题就开始了。
$graph = new Graph();
$graph->setAccessToken($accessToken->getToken());
$user = $graph->createRequest('GET', '/me?$expand=manager($levels=1;$select=displayName,givenName,surname,mail)&$select=displayName,givenName,surname,mail&$count=true')
->addHeaders(array("Content-Type" => "application/json"))
->setReturnType(Model\User::class)
->execute();
$photo = $graph->createRequest('GET', '/me/photo/$value')
->addHeaders(array("Content-Type" => "image/jpeg"))
->execute();
$photo = $photo->getRawBody();
$avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
当用户没有设置个人资料照片时,它会 return 一个 404 Not Found 没关系,但我不希望我的脚本停止如果没有照片。我想要的是这样的:
if($photo->getStatus(404)){
$avatar = null;
}
else{
$photo = $photo->getRawBody();
$avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
}
如果没有照片我想将 $avatar 设置为 null 而不是出现以下错误:
提前致谢!
全功能
public function callback(Request $request)
{
// Validate state
$expectedState = session('oauthState');
$request->session()->forget('oauthState');
$providedState = $request->query('state');
if (!isset($expectedState)) {
// If there is no expected state in the session,
// do nothing and redirect to the home page.
return redirect('/');
}
if (!isset($providedState) || $expectedState != $providedState) {
return redirect('/')
->with('error', 'Invalid auth state')
->with('errorDetail', 'The provided auth state did not match the expected value');
}
// Authorization code should be in the "code" query param
$authCode = $request->query('code');
if (isset($authCode)) {
// Initialize the OAuth client
$oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => config('azure.appId'),
'clientSecret' => config('azure.appSecret'),
'redirectUri' => config('azure.redirectUri'),
'urlAuthorize' => config('azure.authority').config('azure.authorizeEndpoint'),
'urlAccessToken' => config('azure.authority').config('azure.tokenEndpoint'),
'urlResourceOwnerDetails' => '',
'scopes' => config('azure.scopes')
]);
try {
// Make the token request
$accessToken = $oauthClient->getAccessToken('authorization_code', [
'code' => $authCode
]);
$graph = new Graph();
$graph->setAccessToken($accessToken->getToken());
$user = $graph->createRequest('GET', '/me?$expand=manager($levels=1;$select=displayName,givenName,surname,mail)&$select=displayName,givenName,surname,mail&$count=true')
->addHeaders(array("Content-Type" => "application/json"))
->setReturnType(Model\User::class)
->execute();
$photo = $graph->createRequest('GET', '/me/photo/$value')
->addHeaders(array("Content-Type" => "image/jpeg"))
->execute();
$photo = $photo->getRawBody();
$avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
$manager = $user->getManager();
$tokenCache = new TokenCache();
$tokenCache->storeTokens($accessToken, $user, $manager, $avatar);
// Define user details and manager details
$userFirstName = $user->getGivenName();
$userSurname = $user->getSurname();
$userEmail = $user->getMail();
$managerFirstName = $manager->getGivenName();
$managerSurname = $manager->getSurname();
$managerEmail = $manager->getMail();
return redirect('/');
}
catch (Exception $e) {
$avatar = null;
return redirect('/')
->with('error', 'Error requesting access token')
->with('errorDetail', json_encode($e->getResponseBody()));
}
}
return redirect('/')
->with('error', $request->query('error'))
->with('errorDetail', $request->query('error_description'));
}
我不熟悉 Microsoft 图表 api,但基本的 PHP Try - Catch 块应该可以解决问题。
https://www.php.net/manual/en/language.exceptions.php
尝试获取图像 -> 以防发生异常将 $avatar 设置为 null
请使用try/catch块。这用于在您端处理错误,而不是服务器为您处理错误。
我还注意到 '/me/photo/$value'
这不会正确地使用单引号替换 $value。请在此处使用双引号 "/me/photo/$value"
.
use Exception; //import right after namespace
try {
$photo = $graph->createRequest('GET', '/me/photo/$value')
->addHeaders(array("Content-Type" => "image/jpeg"))
->execute();
$photo = $photo->getRawBody();
$avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
} catch (Exception $e) {
//in-case of error
$avatar = null;
}
尝试捕获确切的异常错误是 404 状态代码的客户端异常尝试直接捕获它并捕获其响应。我也从未听说过函数 $e->getResponseBody()
它应该是 guzzle 文档中给出的 $e->getResponse()
。您可以从this answer
中获取更多参考
public function callback(Request $request)
{
// Validate state
// ...
// Initialize the OAuth client
try {
// Make the token request
// ...
// Define user details and manager details
// ...
}
catch(\GuzzleHttp\Exception\ClientException $e){
if($e->hasResponse()){
if ($e->getResponse()->getStatusCode() == '404'){
$avatar = null;
return redirect('/')
->with('error', 'Error requesting access token')
->with('errorDetail', json_encode($e->getResponse()));
}
}
}
catch (Exception $e) {
$avatar = null;
return redirect('/')
->with('error', 'Error requesting access token')
->with('errorDetail', json_encode($e->getResponseBody()));
}
}
return redirect('/')
->with('error', $request->query('error'))
->with('errorDetail', $request->query('error_description'));
}
我正在使用 MS Graph 使用 Azure 身份验证构建网站。 正如您在下面看到的,我想登录并获取我自己的数据以及我的经理,这些数据工作正常,但是当我想要 select 照片时,问题就开始了。
$graph = new Graph();
$graph->setAccessToken($accessToken->getToken());
$user = $graph->createRequest('GET', '/me?$expand=manager($levels=1;$select=displayName,givenName,surname,mail)&$select=displayName,givenName,surname,mail&$count=true')
->addHeaders(array("Content-Type" => "application/json"))
->setReturnType(Model\User::class)
->execute();
$photo = $graph->createRequest('GET', '/me/photo/$value')
->addHeaders(array("Content-Type" => "image/jpeg"))
->execute();
$photo = $photo->getRawBody();
$avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
当用户没有设置个人资料照片时,它会 return 一个 404 Not Found 没关系,但我不希望我的脚本停止如果没有照片。我想要的是这样的:
if($photo->getStatus(404)){
$avatar = null;
}
else{
$photo = $photo->getRawBody();
$avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
}
如果没有照片我想将 $avatar 设置为 null 而不是出现以下错误:
提前致谢!
全功能
public function callback(Request $request)
{
// Validate state
$expectedState = session('oauthState');
$request->session()->forget('oauthState');
$providedState = $request->query('state');
if (!isset($expectedState)) {
// If there is no expected state in the session,
// do nothing and redirect to the home page.
return redirect('/');
}
if (!isset($providedState) || $expectedState != $providedState) {
return redirect('/')
->with('error', 'Invalid auth state')
->with('errorDetail', 'The provided auth state did not match the expected value');
}
// Authorization code should be in the "code" query param
$authCode = $request->query('code');
if (isset($authCode)) {
// Initialize the OAuth client
$oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => config('azure.appId'),
'clientSecret' => config('azure.appSecret'),
'redirectUri' => config('azure.redirectUri'),
'urlAuthorize' => config('azure.authority').config('azure.authorizeEndpoint'),
'urlAccessToken' => config('azure.authority').config('azure.tokenEndpoint'),
'urlResourceOwnerDetails' => '',
'scopes' => config('azure.scopes')
]);
try {
// Make the token request
$accessToken = $oauthClient->getAccessToken('authorization_code', [
'code' => $authCode
]);
$graph = new Graph();
$graph->setAccessToken($accessToken->getToken());
$user = $graph->createRequest('GET', '/me?$expand=manager($levels=1;$select=displayName,givenName,surname,mail)&$select=displayName,givenName,surname,mail&$count=true')
->addHeaders(array("Content-Type" => "application/json"))
->setReturnType(Model\User::class)
->execute();
$photo = $graph->createRequest('GET', '/me/photo/$value')
->addHeaders(array("Content-Type" => "image/jpeg"))
->execute();
$photo = $photo->getRawBody();
$avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
$manager = $user->getManager();
$tokenCache = new TokenCache();
$tokenCache->storeTokens($accessToken, $user, $manager, $avatar);
// Define user details and manager details
$userFirstName = $user->getGivenName();
$userSurname = $user->getSurname();
$userEmail = $user->getMail();
$managerFirstName = $manager->getGivenName();
$managerSurname = $manager->getSurname();
$managerEmail = $manager->getMail();
return redirect('/');
}
catch (Exception $e) {
$avatar = null;
return redirect('/')
->with('error', 'Error requesting access token')
->with('errorDetail', json_encode($e->getResponseBody()));
}
}
return redirect('/')
->with('error', $request->query('error'))
->with('errorDetail', $request->query('error_description'));
}
我不熟悉 Microsoft 图表 api,但基本的 PHP Try - Catch 块应该可以解决问题。
https://www.php.net/manual/en/language.exceptions.php
尝试获取图像 -> 以防发生异常将 $avatar 设置为 null
请使用try/catch块。这用于在您端处理错误,而不是服务器为您处理错误。
我还注意到 '/me/photo/$value'
这不会正确地使用单引号替换 $value。请在此处使用双引号 "/me/photo/$value"
.
use Exception; //import right after namespace
try {
$photo = $graph->createRequest('GET', '/me/photo/$value')
->addHeaders(array("Content-Type" => "image/jpeg"))
->execute();
$photo = $photo->getRawBody();
$avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
} catch (Exception $e) {
//in-case of error
$avatar = null;
}
尝试捕获确切的异常错误是 404 状态代码的客户端异常尝试直接捕获它并捕获其响应。我也从未听说过函数 $e->getResponseBody()
它应该是 guzzle 文档中给出的 $e->getResponse()
。您可以从this answer
public function callback(Request $request)
{
// Validate state
// ...
// Initialize the OAuth client
try {
// Make the token request
// ...
// Define user details and manager details
// ...
}
catch(\GuzzleHttp\Exception\ClientException $e){
if($e->hasResponse()){
if ($e->getResponse()->getStatusCode() == '404'){
$avatar = null;
return redirect('/')
->with('error', 'Error requesting access token')
->with('errorDetail', json_encode($e->getResponse()));
}
}
}
catch (Exception $e) {
$avatar = null;
return redirect('/')
->with('error', 'Error requesting access token')
->with('errorDetail', json_encode($e->getResponseBody()));
}
}
return redirect('/')
->with('error', $request->query('error'))
->with('errorDetail', $request->query('error_description'));
}