
Create Top WordPress Plugin – Microsoft Graph Education API 101
- May 29, 2020
- Leave a comment
Are you looking for methods to create a WordPress Plugin or Theme for the Microsoft Graph Education API? Then you have landed at the right place! Read ahead and know the most detailed process for the right management system for your educational purposes. Microsoft Graph Education API upgrades Office 365 resources with Azure AD for School Data Sync (SDS) management that is important for educational institutions data about classes, Students, Teachers, assignments, and submissions.
WordPress Plugin Features for Microsoft Graph Education API
WordPress plugin can be easily developed for Microsoft Graph Education API that will not only be customizable but also easy to understand. It will give a platform for professional institutions to develop websites more easily with the following features:
- Azure Active Directory Application
- Install Microsoft Graph SDK for PHP
- Authorization
- Schools
- Classes
- Assignments
- Users
Azure Active Directory Application
You will be required to register an application at the Azure portal by Microsoft Graph Education API. The application would also require permission for Microsoft Graph Education API calls. To create an Application, you will have to log in to the Azure portal. After the login, you will see Azure Active Directory Section—once you click on it there will be App registrations at the left menu. By clicking on the App registrations menu link, it will give the option to manage and create new applications. By clicking on the new registration link you will get a registration form. By adding application name, supported account types, and application Redirect URI, click on register.
Once you create the application, you need to copy Application (client) ID, Directory (tenant) ID, Object ID that will be used for authorization.
Now click on API permissions from the left menu. You need to add application permissions for Microsoft Graph Education API as you can see in the reference.
By clicking on the Certificates & secrets tab from the left menu, you will create a new client secret.
Once you create the client secret, make sure you copy that client’s secret value as it will appear again due to security reasons.
Install Microsoft Graph SDK for PHP
Microsoft Graph Education API SDK will be installed in the plugin directory by using the composer or using composer.json.
composer require microsoft/microsoft-graph.
1 2 3 4 5 |
{ "require": { "microsoft/microsoft-graph": "^1.8" } } |
Authorization
OAuth 2.0 Client library will be used to get authorization. You can install via composer with following command:
1 |
composer require league/oauth2-client |
Or you can add the following in you composer.json file:
1 2 3 4 5 6 |
{ "require": { "microsoft/microsoft-graph": "^1.13", "league/oauth2-client": "^2.4" } } |
We have installed the Microsoft Graph and Oauth2 Client and now it needs to include our plugin.
1 |
require_once __DIR__ . '/vendor/autoload.php'; |
To get an access token for Microsoft Graph Education API you can use this URL for authorization.
First, define your application credentials via constants in your WordPress plugin.
1 2 3 4 5 6 7 8 |
define('OAUTH_APP_ID', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); define('OAUTH_APP_SECRET', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); define('OAUTH_REDIRECT_URI', 'http://localhost/msgrapheducation'); define('OAUTH_AUTHORITY', 'https://login.microsoftonline.com/common'); define('OAUTH_AUTHORIZE_ENDPOINT', '/oauth2/v2.0/authorize'); define('OAUTH_TOKEN_ENDPOINT', '/oauth2/v2.0/token'); define('OAUTH_SCOPES', 'openid profile offline_access user.read Calendars.ReadWrite EduAdministration.ReadWrite EduRoster.ReadWrite '); |
By using PHP oauth2 client auth URL, create as following:
1 2 3 4 5 6 7 8 9 10 11 12 |
$oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([ 'clientId' => OAUTH_APP_ID, // The client ID 'clientSecret' => 'OAUTH_APP_SECRET', // The client secret assigned 'redirectUri' => OAUTH_REDIRECT_URI, 'urlAuthorize' => OAUTH_AUTHORITY.OAUTH_AUTHORIZE_ENDPOINT, 'urlAccessToken' => OAUTH_AUTHORITY.OAUTH_TOKEN_ENDPOINT, 'urlResourceOwnerDetails' => '', 'scopes' => OAUTH_SCOPES ]); // Save client state so we can validate in callback $_SESSION['oauth2state'] = $oauthClient->getState(); $authUrl = $oauthClient->getAuthorizationUrl(); |
You need to set the Application (client) ID with the scope that will define which type of permissions are required.
You will get a response with a code that will be used to get the access token.
Token Request
By using authorization code you will send a request for Access Token that will be used for Microsoft Graph Education API calls with the following parameters:
1 2 |
client_id='OAUTH_APP_SECRET'&scope=EduAdministration.ReadWrite%20EduAdministration.ReadWrite.All&code=OAAABAAAAiL9Kn2ZXr ...&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F&grant_type=authorization_code&client_secret='OAUTH_APP_SECRET' |
Here is a PHP oauth2 client script that will be used to get access token. After sending a token request you will get a successful token response like mentioned below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
$provider = new \League\OAuth2\Client\Provider\GenericProvider([ 'clientId' => OAUTH_APP_ID, 'clientSecret' => 'OAUTH_APP_SECRET', 'redirectUri' => OAUTH_REDIRECT_URI, 'urlAuthorize' => OAUTH_AUTHORITY.OAUTH_AUTHORIZE_ENDPOINT, 'urlAccessToken' => OAUTH_AUTHORITY.OAUTH_TOKEN_ENDPOINT, 'urlResourceOwnerDetails' => '', 'scopes' => OAUTH_SCOPES ]); if (!isset($_GET['code'])) { // Fetch the authorization URL from the provider; this returns the // urlAuthorize option and generates and applies any necessary parameters // (e.g. state). $authorizationUrl = $provider->getAuthorizationUrl(); // Get the state generated for you and store it in the session. $_SESSION['oauth2state'] = $provider->getState(); // Redirect the user to the authorization URL. header('Location: ' . $authorizationUrl); exit; // Check given state against previously stored one to mitigate CSRF attack } elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) { if (isset($_SESSION['oauth2state'])) { unset($_SESSION['oauth2state']); } exit('Invalid state'); } else { try { // Try to get an access token using the authorization code grant. $accessToken = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); // We have an access token, which we may use in authenticated $_SESSION[accessToken] = $accessToken->getToken(); $_SESSION[RefreshToken] = $accessToken->getRefreshToken(); $_SESSION[tokenExpires] = $accessToken->getExpires(); } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) { // Failed to get the access token or user details. exit($e->getMessage()); } } |
Refresh Token Request
- If the token is generated with expired time
When the token expires, it doesn’t require to send a request again but a request will be sent for a ‘refresh token’. Token Expired time will be stored in the session that will be used to check if it’s expired. in such case, a request for refresh token with the following script will be sent:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// Check if token is expired //Get current time + 5 minutes (to allow for time differences) $now = time() + 300; if ($_SESSION[tokenExpires]<= $now) { // Token is expired (or very close to it) // so let's refresh // Initialize the OAuth client $provider = new \League\OAuth2\Client\Provider\GenericProvider([ 'clientId' => OAUTH_APP_ID, 'clientSecret' => 'OAUTH_APP_SECRET', 'redirectUri' => OAUTH_REDIRECT_URI, 'urlAuthorize' => OAUTH_AUTHORITY.OAUTH_AUTHORIZE_ENDPOINT, 'urlAccessToken' => OAUTH_AUTHORITY.OAUTH_TOKEN_ENDPOINT, 'urlResourceOwnerDetails' => '', 'scopes' => OAUTH_SCOPES ]); try { $newToken = $provider>getAccessToken('refresh_token', [ 'refresh_token' => $_SESSION[RefreshToken] ]); $_SESSION[accessToken] = $newToken>getToken(); $_SESSION[RefreshToken] = $newToken>getRefreshToken(); $_SESSION[tokenExpires] = $newToken>getExpires(); } catch (League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) { return ''; } } |
Microsoft Graph Education API-User Data AP
We have done application authentication with an access token, now it’s time to call Microsoft Graph Education API to get user data by using the access token.
1 2 3 4 5 6 7 8 9 10 11 |
$graph = new Graph(); $graph->setAccessToken($_SESSION['ms_graph_token']); $user = $graph->createRequest('GET', '/me') ->setReturnType(Model\User::class) ->execute(); $_SESSION['userName'] = $userName = $user->getDisplayName(); if($user->getMail()){ $_SESSION['userEmail'] = $user->getMail(); } else { $_SESSION['userEmail'] = $user->getUserPrincipalName(); } |
Microsoft Graph Calendar API
Microsoft Graph Education API provides options to create/list calendars, get the calendar, create/ list events. For calendar API permissions, “Calendars.ReadWrite” must be added in the application authentication scope.
Create Calendar
By using Microsoft Graph API, Calendars can be created.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$graph = new Graph(); $graph->setBaseUrl("https://graph.microsoft.com/") ->setApiVersion("beta") ->setAccessToken($_SESSION[accessToken]); $data = [ 'name' => 'School calendar', ]; $jsonStr = json_encode($data); $url = "/me/calendars"; $response = $graph->createRequest("POST", $url) ->attachBody($jsonStr) ->setReturnType(Model\Calendar::class) ->execute(); |
Calendar Listing
Calendars will be listed with the following script:
1 2 3 4 5 6 7 8 9 10 |
$graph = new Graph(); $graph->setBaseUrl("https://graph.microsoft.com/") ->setApiVersion("beta") ->setAccessToken($_SESSION[accessToken]); $url = "/me/calendar"; $calendar = $graph->createRequest("GET", $url) ->addHeaders(array("Content-Type" => "application/json")) ->setReturnType(Model\Calendar::class) ->execute(); $calendar_id = $calendar->getId(); |
Create Event
Calendar Event will be created as follow:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$data = [ 'Subject' => 'Discuss the Calendar Event REST API', 'Body' => [ 'ContentType' => 'HTML', 'Content' => 'I think it will meet our requirements!', ], 'Start' => [ 'DateTime' => '2017-04-03T10:00:00', 'TimeZone' => 'Pacific Standard Time', ], 'End' => [ 'DateTime' => '2017-04-03T11:00:00', 'TimeZone' => 'Pacific Standard Time', ], ]; //add $calendar_id which will be used to create an event $url = "/me/calendars/$calendar_id/events"; $response = $graph->createRequest("POST", $url) ->attachBody($data) ->setReturnType(Model\Event::class) ->execute(); |
Events Listing
Calendar events will be listed by using a calendar ID with the GET method, with the following code.
1 2 3 4 5 |
$url = "/me/calendars/$calendar_id/events"; $calendar_event = $graph->createRequest("GET", $url) ->addHeaders(array("Content-Type" => "application/json")) ->setReturnType(Model\Calendar::class) ->execute(); |
Microsoft Graph Education API
Microsoft Graph provides an education API with following features:
- Schools
- Classes
- User(Students/Teachers)
- Assignment
- Category
- Assignment Submission
Schools
Microsoft Graph Education API uses the EducationSchool class to create, update, and list schools.
Create Schools
To Create School requests, sent in json format with POST method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
$data = [ 'displayName' => 'Fabrikam High School', 'description' => 'Magnet school for the arts. Los Angeles School District', 'status' => 'String', 'externalSource' => 'String', 'principalEmail' => 'AmyR@fabrikam.com', 'principalName' => Amy Roebuck, 'externalPrincipalId' => '14007', 'highestGrade' => '12', 'lowestGrade' => '9', 'schoolNumber' => '10002', 'address' => [ 'city' => 'Los Angeles', 'countryOrRegion' => 'United States', 'postalCode' => '98055', 'state' => 'CA', 'street' => '12345 Main St.', ], 'externalId' => '10002', 'phone' => '+1 (253) 555-0102', ]; $jsonStr = json_encode($data); $url = "/education/schools"; $response = $graph->createRequest("POST", $url) ->attachBody($data) ->setReturnType(Model\EducationSchool::class) ->execute(); |
Classes
Microsoft Graph Education API uses an EducationClass object that will be used to create and list classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$data = [ 'description' => 'Class 9th Frist batch', 'classCode' => '9th-A', 'displayName' => '9th Class', 'externalId' => '11019', 'externalName' => '9th Class', 'externalSource' => 'sis', 'mailNickname' => 'fineartschool.net', ]; $jsonStr = json_encode($data); $url = "/education/classes"; $response = $graph->createRequest("POST", $url) ->attachBody($jsonStr) ->setReturnType(Model\EducationClass::class) ->execute(); |
Classes Listing
EducationClass objects will be used to list classes with the the GET method.
1 2 3 4 |
$url = "/education/classes"; $response = $graph->createRequest("GET", $url) ->setReturnType(Model\EducationClass::class) ->execute(); |
Assignments
There will be assignments for each class which will be created by the teacher or the team owner. Assignments will be assigned to the user. It will be in the draft state once created which needs to publish action to change its status. This functionality will be available in the beta version of Microsoft Graph Education API.
Classes Assignment
EducationAssignment object will be used to create assignments with json data in the request body with the POST method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$data = [ 'dueDateTime' => '2014-02-01T00:00:00Z', 'displayName' => 'Midterm 1', 'instructions' => [ 'contentType' => 'text', 'content' => 'Read chapters 1 through 3', ], 'grading' => [ '@odata.type' => '#microsoft.education.assignments.api.educationAssignmentPointsGradeType', 'maxPoints' => 100, ], 'assignTo' => [ '@odata.type' => '#microsoft.education.assignments.api.educationAssignmentClassRecipient' ], 'status' => 'draft', 'allowStudentsToAddResourcesToSubmission' => true, ]; $jsonStr = json_encode($data); $class_id = ‘xxxxxxx’; $url = "education/classes/$class_id/assignments"; $response = $graph->createRequest("POST", $url) ->attachBody($jsonStr) ->setReturnType(Model\EducationAssignment::class) ->execute(); |
Publish Assignment
By default, the Assignments will be in draft state. Teachers need to publish assignments to make them available to students. It doesn’t require any request body and it returns with a “204 No Content” response.
1 2 3 4 5 6 |
$class_id = ‘xxxxxxx’; $assignment_id = ‘xxxxxxx’; $url = "education/classes/$class_id/assignments/$assignment_id/publish"; $response = $graph->createRequest("POST", $url) ->setReturnType(Model\EducationAssignment::class) ->execute(); |
Assignment Listing
EducationAssignment object will be used for assignment listing with the GET method.
1 2 3 4 5 |
$class_id = ‘xxxxxxx’; $url = "education/classes/$class_id/assignments"; $response = $graph->createRequest("GET", $url) ->setReturnType(Model\EducationAssignment::class) ->execute(); |
Assignment Categories Listing
EducationCategory object will be used for assignment categories listing with the GET method.
1 2 3 4 5 6 7 |
$class_id = ‘xxxxxxx’; $assignment_id = ‘xxxxxxx’; $url = "education/classes/$class_id/assignments/$assignment_id/categories"; $response = $graph->createRequest("GET", $url) ->attachBody($jsonStr) ->setReturnType(Model\EducationCategory::class) ->execute(); |
Assignment Submission Listing
EducationSubmission object will be used for the user assignment submissions listing with the GET method.
1 2 3 4 5 6 |
$class_id = ‘xxxxxxx’; $assignment_id = ‘xxxxxxx’; $url = "education/classes/$class_id/assignments/$assignment_id/submissions"; $response = $graph->createRequest("GET", $url) ->setReturnType(Model\EducationSubmission::class) ->execute(); |
Create Assignment Submission Resource
Students will submit an assignment field to which it is assigned. assignmentEducationSubmissionResource object will be used for user assignment submissions listing with the GET method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
$class_id = ‘xxxxxxx’; $assignment_id = ‘xxxxxxx’; $data = [ "assignmentResourceUrl" => "https://graph.microsoft.com/v1.0/drives/b!8-QjN2tsv0WyGnTv7vOvnQkmGHbbeMNLqYKONmHLVnvCVmBYIGpeT456457AdW9f/items/017NJZI25NOB5XZNLABF7646XAMDZTQQ6T", "resource" => [ "@odata.type" => "#microsoft.graph.educationWordResource", "displayName" => "Report.docx", "createdDateTime" => "2017-10-21T07:52:53.9863696Z", "createdBy" => [ "application" => null, "device" => null, "user" => [ "id" => "63cc91d2-59c7-4732-9594-35b91a26b340", "displayName" => null ] ], "lastModifiedDateTime" => "2017-10-21T07:52:53.9863696Z", "lastModifiedBy" => [ "application" => null, "device" => null, "user" => [ "id" => "63cc91d2-59c7-4732-9594-35b91a26b340", "displayName" => null ] ], "fileUrl" => "https://graph.microsoft.com/v1.0/drives/b!8-QjN2tsv0WyGnTv7vOvnQkmGHbbeMNLqYKONmHLVnvCVmBYIGpeTZ_iul5AdW9f/items/017NJZI27BCN2QI2H7HJGLIVPXR6SD2DH6" ], "@odata.type" => "microsoft.graph.educationResource" ]; $jsonStr = json_encode($data); $url = "education/classes/$class_id/assignments/$assignment_id/submissions"; $response = $graph->createRequest("POST", $url) ->attachBody($jsonStr) ->setReturnType(Model\EducationSubmission::class) ->execute(); |
Users
Teachers or Students can list their schools, classes, and rubrics by using Microsoft Graph Education API.
School Listing
EducationSchool objects will be used for the user’s schools listing with the GET method.
1 2 3 4 5 6 7 8 |
$class_id = ‘xxxxxxx’; $assignment_id = ‘xxxxxxx’; $url = "/education/me/schools"; Or $url = "/education/users/{user_id}/schools"; $response = $graph->createRequest("GET", $url) ->setReturnType(Model\EducationSchool::class) ->execute(); |
Classes Listing
EducationClass object will be used for the user’s classes listed with the GET method.
1 |
$url = "/education/me/classes"; |
or
1 2 3 4 |
$url = "/education/users/{user_id}/classes"; $response = $graph->createRequest("GET", $url) ->setReturnType(Model\EducationClass::class) ->execute(); |
Rubrics Listing
EducationRubric objects will be used for user classes listing with the GET method.
1 2 3 4 5 |
$user_id = ‘xxxxxxx’; $url = "/education/me/rubrics"; $response = $graph->createRequest("GET", $url) ->setReturnType(Model\EducationRubric ::class) ->execute(); |
With this detailed explanation of Microsoft Graph Education API, you can build LMS according to your requirements by using the code snippet mentioned in the detail above.
If you need any help or assistance in creating the WordPress Plugin for Microsoft Graph Education API or if you require a tailored solution, please feel free to get connected to our team at vteams and leave the rest to us.
User Comments