Error creating new user in Moodle via webservice

3

I have tried adding a new user to Moodle using their api webservice

I have already modified the parameters passed through post several times, tried using an array instead of an object, tested some changes in the array structure that is passed, but I always get the same response from moodle:

"Missing required key in single structure: users"

The answer:

{
    "exception":"invalid_parameter_exception",
    "errorcode":"invalidparameter",
    "message":"Valor inv\u00e1lido de par\u00e2metro detectado",
    "debuginfo":"Missing required key in single structure: users"
}

My code:

$functionname = 'core_user_create_users';
$user1 = new stdClass();
$user1->id = 1;  //
$user1->username = 'testusername1';
$user1->password = 'testpassword1';
$user1->firstname = 'testfirstname1';
$user1->lastname = 'testlastname1';
$user1->email = '[email protected]';
$user1->auth = 'manual';
$user1->idnumber = 'testidnumber1';
$user1->description = 'Hello World!';
$user1->city = 'testcity1';
$user1->country = 'BR';

$token = 'mytoken';
$domainname = 'localhost/moodle';
$functionname = 'core_user_create_users';
$restformat = 'json';
$serverurl = $domainname . '/webservice/rest/server.php'. '?wstoken=' . $token . '&wsfunction='.$functionname.'&moodlewsrestformat=' . $restformat;

$users = array($user1);
$params = array('users' => $users); 

$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',                    
        'header' => 'Content-Type: text/plain',
        'content' => $params                             
    )
));

$contents = file_get_contents($serverurl, null, $context);            

//print_r($contents);

$resposta = json_decode($contents);  

As I checked, all required fields are filled out.

I am using a valid token, and the user has the permission required to use the core_user_create_users function.

I used the following code as base

UPDATE

Common errors when attempting to create a user via webservice are

  • Try to enter mandatory field with empty value

  • Try to register a password that does not meet the password policy defined in the moodle configuration

  • Forget to encapsulate the object (s) with user information in an array and switch to 'users'

    $users = array($user1, $user2);
    $params = array('users' => $users);
    
asked by anonymous 18.12.2013 / 15:04

1 answer

5

This error may be related to the Moodle password policy which by default requires the password to contain:

  

Minimum characters: 8
  Minimum Number of Numbers: 1
  Lowercase letters: 1
  Minimum of lowercase letters: 1
  Minimum non-alphanumeric characters: 1

Information can be read here .

Check to see if you really respect these requirements.

Notes:
These settings can be changed in the site policies at:

  

Settings → Site administration → Security → Site policies.

    
18.12.2013 / 17:32