2017-01-11 133 views
1

我正在編寫一個應用程序(使用PHP),它將學生添加到Google課堂。我在下面的文檔:使用Google Http批處理和Google課堂API

https://developers.google.com/classroom/guides/batch

我使用批量要求多個學生添加到谷歌的課堂。但批處理請求似乎失敗。我的代碼如下:

$service = new Google_Service_Classroom($client); 

$service->getClient()->setUseBatch(true); 

$batch = $service->createBatch(); 

$courseId = "123456"; 
$studentEmails = ["[email protected]","[email protected]"]; 

foreach($studentEmails as $email) { 
    $student = new Google_Service_Classroom_Student(['userId' => $email]); 
    $request = $service->courses_students->create($courseId, $student); 
    $requestId = $email; 
    $batch->add($request, $requestId); 
} 

$results = $batch->execute(); 


foreach($results as $responseId => $student) { 
    $studentEmail = substr($responseId, strlen('response-')); 
    if ($student instanceof Google_Service_Exception) { 
    $e = $student; 
    printf("Error adding user '%s' to the course: %s\n", $studentEmail, 
     $e->getMessage()); 
    } else { 
    printf("User '%s' was added as a student to the course.\n", 
     $student->profile->name->fullName, $courseId); 
    } 
} 

$service->getClient()->setUseBatch(false); 

此代碼的輸出是:

Error adding user '[email protected]' to the course: Not Found ... 

然而,無論是用戶和過程上的域存在。如果我刪除批次代碼並一次提出一個請求,則學生已成功添加到教室,這導致我相信我錯過了批量請求

回答

0

您可能需要首先檢查PHP Quickstart並確保您將完成給定頁面其餘部分中描述的步驟,以便能夠向批量請求中的using client libraries中提及的Classroom API發出請求。

成功安裝庫並進行設置後,您可以嘗試使用代碼示例演示如何使用Google API客戶端庫進行批量請求。

$courseId = '123456'; 
$studentEmails = array('[email protected]', '[email protected]'); 
$service->getClient()->setUseBatch(true); 
$batch = $service->createBatch(); 
foreach($studentEmails as $studentEmail) { 
    $student = new Google_Service_Classroom_Student(array(
    'userId' => $studentEmail 
)); 
    $request = $service->courses_students->create($courseId, $student); 
    $requestId = $studentEmail; 
    $batch->add($request, $requestId); 
} 
$results = $batch->execute(); 
foreach($results as $responseId => $student) { 
    $studentEmail = substr($responseId, strlen('response-') + 1); 
    if ($student instanceof Google_Service_Exception) { 
    $e = $student; 
    printf("Error adding user '%s' to the course: %s\n", $studentEmail, 
     $e->getMessage()); 
    } else { 
    printf("User '%s' was added as a student to the course.\n", 
     $student->profile->name->fullName, $courseId); 
    } 
} 
$service->getClient()->setUseBatch(false); 
+0

感謝您的回覆,我已經閱讀了快速入門文檔,併成功地在其他Google服務上使用了批量請求。在將學生招收到教室時,似乎並沒有打球 – amburnside