Google 课堂:在“createCourse”API 中,出现“Google_Service_Exception - 401”错误

问题描述 投票:0回答:0

谷歌课堂:

我正在尝试使用 google-classroom API 创建课程。

我遵循以下步骤:

  1. 创建新项目(在外部模式下)
  2. 启用“Google Classroom API”
  3. 设置“OAuth 内容屏幕”和“凭据”(使用“OAuth 客户端 ID”创建“credentials.json”)设置。
  4. 在“CodeIgniter”中安装“Google Classroom”相关库: composer 需要 google/apiclient:^2.0

我的代码片段 - PHP CodeIgniter:

defined('BASEPATH') OR exit('No direct script access allowed');
require FCPATH . 'vendor/autoload.php';

use Google\Client;
use Google\Service\Classroom;
use Google\Service\Classroom\Course;
use Google\Service\Exception;

class Googleclassroom extends CI_Controller {
    
    function __construct()
    {       
        parent::__construct();
        $this->load->model('adminusermodel');
        $this->load->library('Aesctr');
        $user_data = $this->session->get_userdata();        
    }
    
    public function createCourse()
    {       
        $client = new Google_Client();
        $client->setApplicationName('Google Classroom API PHP ');
        $client->setScopes(Google_Service_Classroom::CLASSROOM_COURSES_READONLY);
        $client->setAuthConfig('credentials.json');
        $client->setAccessType('offline');
        $client->setPrompt('select_account consent');
        
        $client->addScope("https://www.googleapis.com/auth/classroom.courses");
        $service = new Classroom($client);
        
        $course = new Course([
            'name' => '10th  Biology',
            'section' => 'Period 2',
            'descriptionHeading' => 'Welcome to 10th Grade Biology',
            'description' => 'hi',
            'room' => '301',
            'ownerId' => 'me',
            'courseState' => 'PROVISIONED'
        ]);
        $course = $service->courses->create($course);
        printf("Course created: %s (%s)\n", $course->name, $course->id);
    }
}

当我在浏览器中点击以下网址时,出现如下错误: http://baseUrl/Googleclassroom/createCourse

错误:

遇到未捕获的异常

类型:Google_Service_Exception

Message: { "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google. com/identity/sign-in/web/devconsole-project。 ": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED" } }

请给我建议解决方案。

php google-api google-oauth google-classroom
© www.soinside.com 2019 - 2024. All rights reserved.