错误代码401在Laravel上创建Google幻灯片API时发生。

huangapple go评论94阅读模式
英文:

Error code 401 when create a google slide API on Laravel

问题

我现在正在学习在Laravel框架上使用Google Slide API。我想首先创建一个简单的模板,但我遇到了问题。我收到了以下错误信息。

> { "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "CREDENTIALS_MISSING", "domain": "googleapis.com", "metadata": { "service": "slides.googleapis.com", "method": "google.apps.slides.v1.PresentationsService.CreatePresentation" } } ] } }

我一直在按照教程的步骤获取OAuth凭据,使用名为.json的文件,链接在https://console.cloud.google.com,并将其存储在“storage > app”文件夹中。

> {"web":{"client_id":"xxx.apps.googleusercontent.com","project_id":"xxx","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"xxx","redirect_uris":["mydomain"],"javascript_origins":["mydomain"]}}

以下是我的代码

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Google\Client as GoogleClient;
  4. use Google\Service\Slides;
  5. use Google\Service\Slides\BatchUpdatePresentationRequest;
  6. use Google\Service\Slides\Presentation;
  7. use Google\Service\Slides\CreateSlideRequest;
  8. use Google\Service\Slides\LayoutPlaceholderIdMapping;
  9. use Google\Service\Slides\InsertTextRequest;
  10. class SlideController extends Controller
  11. {
  12. public function index()
  13. {
  14. $credentialsPath = storage_path('app/slide-api-credential.json');
  15. $client = new GoogleClient();
  16. $client->setAuthConfig($credentialsPath);
  17. $client->addScope('Slides::PRESENTATIONS');
  18. $slides = new Slides($client);
  19. $presentation = new Presentation([
  20. 'title' => 'My First Slide'
  21. ]);
  22. $slideRequests = [
  23. new CreateSlideRequest([
  24. 'slideLayoutReference' => [
  25. 'predefinedLayout' => 'BLANK'
  26. ],
  27. 'placeholderIdMappings' => [
  28. new LayoutPlaceholderIdMapping([
  29. 'objectId' => 'TITLE',
  30. 'layoutPlaceholder' => [
  31. 'type' => 'TITLE'
  32. ]
  33. ]),
  34. new LayoutPlaceholderIdMapping([
  35. 'objectId' => 'SUBTITLE',
  36. 'layoutPlaceholder' => [
  37. 'type' => 'SUBTITLE'
  38. ]
  39. ])
  40. ]
  41. ]),
  42. new InsertTextRequest([
  43. 'objectId' => 'TITLE',
  44. 'text' => 'Hello,'
  45. ]),
  46. new InsertTextRequest([
  47. 'objectId' => 'SUBTITLE',
  48. 'text' => 'World!'
  49. ])
  50. ];
  51. $batchUpdateRequest = new BatchUpdatePresentationRequest([
  52. 'requests' => $slideRequests
  53. ]);
  54. $createdPresentation = $slides->presentations->create($presentation);
  55. $presentationId = $createdPresentation->presentationId;
  56. $slides->presentations->batchUpdate($presentationId, $batchUpdateRequest);
  57. return "Slide created with ID: $presentationId";
  58. }
  59. }

只是创建一个简单的演示文稿幻灯片。我如何解决这个问题?请帮忙。

英文:

I'm studying google slide API on laravel framework now. i want to create a simple template at first but i stuck. i got this error.

> { "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "CREDENTIALS_MISSING", "domain": "googleapis.com", "metadata": { "service": "slides.googleapis.com", "method": "google.apps.slides.v1.PresentationsService.CreatePresentation" } } ] } }

I've been following the tutorial to obtain the OAuth credential with file .json on https://console.cloud.google.com and store it to folder "storage > app" folder

> {"web":{"client_id":"xxx.apps.googleusercontent.com","project_id":"xxx","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"xxx","redirect_uris":["mydomain"],"javascript_origins":["mydomain"]}}

and here is my code

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Google\Client as GoogleClient;
  4. use Google\Service\Slides;
  5. use Google\Service\Slides\BatchUpdatePresentationRequest;
  6. use Google\Service\Slides\Presentation;
  7. use Google\Service\Slides\CreateSlideRequest;
  8. use Google\Service\Slides\LayoutPlaceholderIdMapping;
  9. use Google\Service\Slides\InsertTextRequest;
  10. class SlideController extends Controller
  11. {
  12. public function index()
  13. {
  14. $credentialsPath = storage_path('app/slide-api-credential.json');
  15. $client = new GoogleClient();
  16. $client->setAuthConfig($credentialsPath);
  17. $client->addScope('Slides::PRESENTATIONS');
  18. $slides = new Slides($client);
  19. $presentation = new Presentation([
  20. 'title' => 'My First Slide'
  21. ]);
  22. $slideRequests = [
  23. new CreateSlideRequest([
  24. 'slideLayoutReference' => [
  25. 'predefinedLayout' => 'BLANK'
  26. ],
  27. 'placeholderIdMappings' => [
  28. new LayoutPlaceholderIdMapping([
  29. 'objectId' => 'TITLE',
  30. 'layoutPlaceholder' => [
  31. 'type' => 'TITLE'
  32. ]
  33. ]),
  34. new LayoutPlaceholderIdMapping([
  35. 'objectId' => 'SUBTITLE',
  36. 'layoutPlaceholder' => [
  37. 'type' => 'SUBTITLE'
  38. ]
  39. ])
  40. ]
  41. ]),
  42. new InsertTextRequest([
  43. 'objectId' => 'TITLE',
  44. 'text' => 'Hello,'
  45. ]),
  46. new InsertTextRequest([
  47. 'objectId' => 'SUBTITLE',
  48. 'text' => 'World!'
  49. ])
  50. ];
  51. $batchUpdateRequest = new BatchUpdatePresentationRequest([
  52. 'requests' => $slideRequests
  53. ]);
  54. $createdPresentation = $slides->presentations->create($presentation);
  55. $presentationId = $createdPresentation->presentationId;
  56. $slides->presentations->batchUpdate($presentationId, $batchUpdateRequest);
  57. return "Slide created with ID: $presentationId";
  58. }
  59. }

just create a simple presentation slide. How do i able to solve this? please help

答案1

得分: 0

要调用Google幻灯片API,您需要提供身份验证方法,通常是访问令牌(Access Token)。slide-api-credential.json文件用于将您的应用与Google Cloud项目关联,以便使用已启用的API。

您的下一步将是查看他们的文档中的第2步:

在应用程序可以使用Google API访问私有数据之前,它必须获取授予对该API的访问权限的访问令牌。

也许这可以帮助您朝正确的方向前进,我使用了他们的GitHub存储库中的这个示例来创建您的代码版本,该版本将用户通过验证,保存令牌并用它调用API:

  1. public function index()
  2. {
  3. /********* 生成客户端和OAuthToken ******************/
  4. $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  5. $client = new GoogleClient();
  6. $client->setScopes('Slides::PRESENTATIONS');
  7. $client->setAuthConfig('app/slide-api-credential.json');
  8. $client->setRedirectUri($redirect_uri);
  9. $client->setAccessType('offline');
  10. $client->setPrompt('select_account consent');
  11. // 从文件中加载以前授权的令牌,如果存在。
  12. // 文件token.json存储用户的访问令牌和刷新令牌,在首次完成授权流程时会自动创建。
  13. $tokenPath = 'token.json';
  14. if (file_exists($tokenPath)) {
  15. $accessToken = json_decode(file_get_contents($tokenPath), true);
  16. $client->setAccessToken($accessToken);
  17. }
  18. // 如果没有以前的令牌或令牌已过期。
  19. if ($client->isAccessTokenExpired()) {
  20. // 如果可能,刷新令牌,否则获取一个新令牌。
  21. if ($client->getRefreshToken()) {
  22. $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
  23. } else {
  24. // 请求用户授权。
  25. $authUrl = $client->createAuthUrl();
  26. header('Location:' . $authUrl);
  27. if (isset($_GET['code'])) {
  28. $accessToken = $client->fetchAccessTokenWithAuthCode($_GET['code'], $_SESSION['code_verifier']);
  29. $client->setAccessToken($accessToken);
  30. // 重定向回示例
  31. header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
  32. $client->setAccessToken($accessToken);
  33. }
  34. }
  35. // 将令牌保存到文件中。
  36. if (!file_exists(dirname($tokenPath))) {
  37. mkdir(dirname($tokenPath), 0700, true);
  38. }
  39. file_put_contents($tokenPath, json_encode($client->getAccessToken()));
  40. }
  41. /******** 授权流程结束 *********/
  42. $slides = new Slides($client);
  43. $presentation = new Presentation([
  44. 'title' => 'My First Slide'
  45. ]);
  46. ...

更多文档:

英文:

To make API calls to the Google Slides API you'll need to provide an authentication method, normally an Access Token, the slide-api-credential.json file is used to link your App to your Google Cloud Project in order to use the enabled APIs.

Your next step would be #2 from their documentation:

>Before your application can access private data using a Google API, it must obtain an access token that grants access to that API.

Maybe this could help you get in the right direction, I used this example from their Github repository in order to create a version of your code that would take the user through verification, save the token and use it to call the API:

  1. public function index()
  2. {
  3. /********* Generating the Client and OAuthToken ******************/
  4. $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  5. $client = new GoogleClient();
  6. $client->setScopes('Slides::PRESENTATIONS');
  7. $client->setAuthConfig('app/slide-api-credential.json');
  8. $client->setRedirectUri($redirect_uri);
  9. $client->setAccessType('offline');
  10. $client->setPrompt('select_account consent');
  11. // Load previously authorized token from a file, if it exists.
  12. // The file token.json stores the user's access and refresh tokens, and is
  13. // created automatically when the authorization flow completes for the first
  14. // time.
  15. $tokenPath = 'token.json';
  16. if (file_exists($tokenPath)) {
  17. $accessToken = json_decode(file_get_contents($tokenPath), true);
  18. $client->setAccessToken($accessToken);
  19. }
  20. // If there is no previous token or it's expired.
  21. if ($client->isAccessTokenExpired()) {
  22. // Refresh the token if possible, else fetch a new one.
  23. if ($client->getRefreshToken()) {
  24. $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
  25. } else {
  26. // Request authorization from the user.
  27. $authUrl = $client->createAuthUrl();
  28. header('Location:' . $authUrl);
  29. if (isset($_GET['code'])) {
  30. $accessToken = $client->fetchAccessTokenWithAuthCode($_GET['code'], $_SESSION['code_verifier']);
  31. $client->setAccessToken($accessToken);
  32. // redirect back to the example
  33. header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
  34. $client->setAccessToken($accessToken);
  35. }
  36. }
  37. // Save the token to a file.
  38. if (!file_exists(dirname($tokenPath))) {
  39. mkdir(dirname($tokenPath), 0700, true);
  40. }
  41. file_put_contents($tokenPath, json_encode($client->getAccessToken()));
  42. }
  43. /******** End of Authorization Flow *********/
  44. $slides = new Slides($client);
  45. $presentation = new Presentation([
  46. 'title' => 'My First Slide'
  47. ]);
  48. ...

More documentation:

huangapple
  • 本文由 发表于 2023年5月29日 07:12:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76353932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定