无法邀请用户加入Google课堂

时间:2017-09-01 08:33:21

标签: php api curl google-classroom

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

$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是正确的。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

我在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);

答案 1 :(得分:0)

错误400表示您已创建错误请求。

  如果查询参数格式错误,则

INVALID_ARGUMENT

为了便于编码,您可以使用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;
  }
}

希望这有帮助。