Good afternoon! Understanding how to create a user in moodle using api. In particular, through webservice and core_user_create_users.
I found an example on the Internet, slightly modified for myself:
<?php
require_once('../config.php');
require_once($CFG->libdir.'/setup.php');
// Load the MoodleRest class
require_once($CFG->dirroot.'/user/classes/MoodleRest.php');
// Put your webservice url
$webservervice_url = 'https://mysite/webservice/rest/server.php';
// Put a token that have permission to execute core_user_get_users and core_user_create_users
$token = 'mytoken'; //here is my real token in the file
// Instantiate a MoodleRest object
$MoodleRest = new MoodleRest($webservervice_url, $token);
// Query user
$username = 'vvvfilippov';
$query_user['criteria'][0] = array('key' => 'username', 'value' => $username);
$result_query = $MoodleRest->request('core_user_get_users', $query_user);
// Test if an exception was returned when querying the user data
if (!empty($result_query['exception'])) {
print_r(array('Error querying user', $result_query));
die();
}
// Check if the user was returned. If not, create him
if (empty($result_query['users'][0]['id'])) {
$people['users'][0] = array(
'username' => $username,
'password' => '123456',
'firstname' => 'Vladimir',
'lastname' => "Filippovv",
'email' => $username . '@email.fake'
);
$result_insert = $MoodleRest->request('core_user_create_users', $people, MoodleRest::METHOD_POST);
// Test if an exception was returned when creating the user
if (!empty($result_insert['exception'])) {
print_r(array('Error creating user', $result_insert));
die();
}
print_r(array('Created user', $result_insert));
} else {
print_r(array('Returned user', $result_query));
}
The response on the page is: Array ( [0] => Error querying user [1] => Array ( [exception] => webservice_access_exception [errorcode] => accessexception [message] => Access Control Exception ) )
Can you please tell me what I wrote wrong in the code? I created the token on the page /admin/webservice/tokens.php?ftoken&page=1 Is this correct or should I take it somewhere else?