Google Youtube API Insert Comment always returns error response 403 - “Insufficient Permission” - domain “global”

我的梦境 提交于 2019-12-22 12:39:15

问题


I followed the docs and code samples from documentation guide i.e., here: https://developers.google.com/youtube/v3/docs/commentThreads/insert But when I execute the script it always returns a response with error code: 403 message: "Insufficient Permission"

Here's complete response object:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "insufficientPermissions",
    "message": "Insufficient Permission"
   }
  ],
  "code": 403,
  "message": "Insufficient Permission"
 }
}

I spent alot of time in debugging and surfing on internet to find out how to fix the problem but didn't get any resource where I can find the solution to this problem. I'd be very thankful if anyone can give me some hint or solution to this or tell me if I'm missing something.

P.S. I also have used other API methods in my app like liking a video, subscribing a channel, Login with Google and all these have been worked great. don't why this Inserting a comment thing not working.

Any help will be appreciated. Thanks.

Here's my API script for making the API call.

<?php    
// filename: api.php    
    class GoogleApi {

            private $client_id;
            private $client_secret;
            private $redirect_uri;

            private $client; // stored client instance
            private $yt_service; // youtube service instance for making all api calls

            public function __construct($client_id, $client_secret, $redirect_uri, $token = '') {
                $this->client_id = $client_id;
                $this->client_secret = $client_secret;
                $this->redirect_uri = $redirect_uri;

                // create google client instance
                $this->client = $this->getClient();

                if(!empty($token)) {
                    // set / refresh access token
                    $this->setRefreshAccessToken($token);
                    // Define an object that will be used to make all API requests.
                    $this->yt_service = new Google_Service_YouTube($this->client);
                }
            }

            // Get a google client instance
            // docs: https://developers.google.com/youtube/v3/guides/auth/server-side-web-apps
            private function getClient($redirect_uri = '') {
                if (!empty($redirect_uri)) {
                    $this->redirect_uri = $redirect_uri;
                }

                $client = new Google_Client();
                $client->setAuthConfig('client_secrets.json');
                $client->setScopes([
                    "https://www.googleapis.com/auth/userinfo.email",
                    "https://www.googleapis.com/auth/userinfo.profile",
                    "https://www.googleapis.com/auth/plus.me",
                    "https://www.googleapis.com/auth/plus.profiles.read",
                    "https://www.googleapis.com/auth/youtube"
                ]);
                // available scopes: https://developers.google.com/identity/protocols/googlescopes
                $client->setRedirectUri($this->redirect_uri);
                $client->setState(mt_rand());
                $client->setAccessType('offline');
                $client->setApprovalPrompt('force');
                $client->setIncludeGrantedScopes(true);   // incremental auth

                return $client;
            }

            public function setRefreshAccessToken($accessToken) {
                // Set the access token
                $this->client->setAccessToken($accessToken);
                // Refresh the token if it's expired.
                if ($this->client->isAccessTokenExpired()) {
                    // update access token
                    $this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
                }
            }

            // Insert a comment on video
            // docs: https://developers.google.com/youtube/v3/docs/commentThreads/insert
            public function commentVideo($videoId, $commentText) {
                $this->client->addScope('https://www.googleapis.com/auth/youtube');
                $this->client->addScope('https://www.googleapis.com/auth/youtube.force-ssl');

                # Create a comment snippet with text.
                $commentSnippet = new Google_Service_YouTube_CommentSnippet();
                $commentSnippet->setTextOriginal($commentText);

                # Create a top-level comment with snippet.
                $topLevelComment = new Google_Service_YouTube_Comment();
                $topLevelComment->setSnippet($commentSnippet);

                # Create a comment thread snippet with channelId and top-level comment.
                $commentThreadSnippet = new Google_Service_YouTube_CommentThreadSnippet();
                // $commentThreadSnippet->setChannelId($CHANNEL_ID);
                $commentThreadSnippet->setVideoId($videoId); // Insert video comment
                $commentThreadSnippet->setTopLevelComment($topLevelComment);

                # Create a comment thread with snippet.
                $commentThread = new Google_Service_YouTube_CommentThread();
                $commentThread->setSnippet($commentThreadSnippet);

                # Call the YouTube Data API's commentThreads.insert method to create a comment.
                $response = $this->yt_service->commentThreads->insert('snippet', $commentThread);

                // print_r($response);
                return $response;
            }

        }
?>

And here's the script for my end-point (I perform ajax call on this script).

<php

// filename: comment.php

require_once("api.php");

// Insert a comment on youtube video.

if(empty($_POST['token'])) {
    return die('parameter `token` is required.');
}
if(empty($_POST['videoId'])) {
    return die('parameter `videoId` is required.');
}
if(empty($_POST['commentText'])) {
    return die('parameter `commentText` is required.');
}

try {
    // GoogleApi class instance
    $api = new GoogleApi(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_CALLBACK, $_POST['token']);

    $data = $api->commentVideo($_POST['videoId'], $_POST['commentText']);

    // send response.
    echo json_encode($result);
} catch(Exception $err) {
    return die($err -> getMessage());
}

?>

回答1:


if you consolation the documentation for CommentThreads: insert

Authorization
This request requires authorization with at least one of the following scopes (read more about authentication and authorization).

Scope https://www.googleapis.com/auth/youtube.force-ssl

You will notice that in order to access this method you need to include this scope.

Tip: The documentation for all of the methods includes this authorization section if you are required to be authorized in order to access the method in question. If you always check that then you wont have this problem again.



来源:https://stackoverflow.com/questions/50458183/google-youtube-api-insert-comment-always-returns-error-response-403-insuffici

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!