Search code examples
phpapicurlgoogle-classroom

Not able to invite users to Google Classroom


I am trying to invite a user to Google Classroom with the following PHP code:

$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);
}

The result is:

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

The $access_token, $mail, and $courseId are correct.

Any help would be appreciated.


Solution

  • I found a solution serching in the Google API client library code. Not documentation found for invitations.

    $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);