无法邀请用户加入 Google 课堂

Not able to invite users to Google Classroom

我正在尝试使用以下 PHP 代码邀请用户加入 Google 课堂:

$paramertos = array(
    "role" => "STUDENT", 
    "userId" => $mail, 
    "courseId" => $courseId
);

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => "https://classroom.googleapis.com/v1/invitations",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => $paramertos,
    CURLOPT_HTTPHEADER => array(
        "authorization: Bearer $access_token"
    )
));

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

if ($err) {
    echo "cURL Error:" . $err;
} else {
    $response = json_decode($response, true);
    var_dump($response);
}

结果是:

array(1) { 
    ["error"]=> array(3) {
        ["code"]=> int(400) 
        ["message"]=> string(37) "Request contains an invalid argument."
        ["status"]=> string(16) "INVALID_ARGUMENT" 
    }
 } 

$access_token、$mail 和 $courseId 正确。

如有任何帮助,我们将不胜感激。

错误 400 意味着您创建了一个错误的请求。

INVALID_ARGUMENT if the query argument is malformed.

为了更容易编码,您可以使用 Google API client library。这是一个示例代码,可帮助您更多地了解 Google PHP 客户端库(不幸的是,我没有任何用于创建邀请的代码示例)。

$courseId = '123456';
$teacherEmail = 'alice@example.edu';
$teacher = new Google_Service_Classroom_Teacher(array(
  'userId' => $teacherEmail
));
try {
  $teacher = $service->courses_teachers->create($courseId, $teacher);
  printf("User '%s' was added as a teacher to the course with ID '%s'.\n",
      $teacher->profile->name->fullName, $courseId);
} catch (Google_Service_Exception $e) {
  if ($e->getCode() == 409) {
    printf("User '%s' is already a member of this course.\n", $teacherEmail);
  } else {
    throw $e;
  }
}

希望对您有所帮助。

我在Google API client library代码中找到了解决方案。找不到邀请的文档。

$service = new Google_Service_Classroom($client);

$googleInvitation = new Google_Service_Classroom_Invitation(
    array("role" => "STUDENT",
    "userId" => $mail,
    "courseId" => $courseId)
);
try{
    $invitationRes = $service->invitations->create($googleInvitation);
}catch(Exception $exception){
    echo $exception;
    die();
}
var_dump($invitationRes);