无法将会话中存储的Access Token用于其他控制器

时间:2018-02-16 18:54:54

标签: php cakephp cakephp-3.0 youtube-data-api

我正在使用Youtube API上传视频,为此,我为 OAUTH2 创建了 YoutubeLoginController 来检索访问令牌和 UploadController 用于上传视频。 我在这里用过,

src / Controller / YoutubeLoginController.php

public function callback()
    {
        $this->autoRender = false;

        $code = $this->request->getQuery('code');

        $client = new \Google_Client();
        $client->setApplicationName('youtube');
        $client->setClientId(OAUTH2_CLIENT_ID);
        $client->setClientSecret(OAUTH2_CLIENT_SECRET);

        $client->setAccessType("offline");        // offline access
        $client->setIncludeGrantedScopes(true);   // incremental auth
        $client->addScope('https://www.googleapis.com/auth/youtube.upload');
        $client->addScope('https://www.googleapis.com/auth/userinfo.email');

        $callback_url = Router::url(['controller' => 'YoutubeLogin', 'action' => 'callback'], true);

        $client->setRedirectUri($callback_url);

        /**
         * retrieve access token
         */
        $accessToken = $client->fetchAccessTokenWithAuthCode($code);



        if (!empty($accessToken['access_token'])) {

            $this->request->getSession->write('access_token',$accessToken['access_token']);
        } else {
            $this->Flash->error('Access token could not be generated');
        }

       debug($this->request->getSession()->read('access_token')); // access token successfully stored  


        return $this->redirect(['controller' => 'Upload', 'action' => 'index']);
    }
  

访问令牌已成功存储,

现在问题是我在 UploadController

中使用它

src / Controller / UploadController.php

public function upload($video, $title, $description)
    {
        $access_token = $this->request->getSession()->read('access_token');
        debug($access_token); // here value is null

        $videoPath = $video;

        if(!file_exists($videoPath)){
            $this->Flash->error('File does not exits');
            return $this->redirect($this->referer());
        }

        $client = new Google_Client();

        $client->setClientID(OAUTH2_CLIENT_ID);
        $client->setClientSecret(OAUTH2_CLIENT_SECRET);
        $client->setAccessToken($access_token);

        $youtube = new Google_Service_YouTube($client);


        try{
            //code
           }
          catch{
                // code
               }

Result for debug($access_token)

  

0 个答案:

没有答案