Creating a Moodle User via Web Services

We can do lots of stuff in moodle via api but I found the technical doc confusing and lacking…

Here, we’re going to allow external system to talk to moodle via soap, in fact to create a user in moodle. Here are the steps.

1. In moodle, go to site admin -> advance feature -> enable web services.

2. site admin -> web services -> external services -> add (add a new service called from_wordpress and checked “enabled” and “authorised users only”. After clicking on submit, you will be asked to add functions. Lets add “core_user_create_users” function for example.

3. Under site admin -> web services -> external services again, click on “authorized users” and add your admin user.

4. under site admin -> web services -> manage protocol, turn on the soap protocol and turn off the rest of the protocol for the sake of security.

5. under site admin -> web services -> manage token -> add, select the admin user and choose the from_wordpress service. You will now get a token that you can use in other apps.

6. now to connect to moodle via soap, your url should be something like this:

http://your_moodle_install/webserver/soap/server.php?wsdl=1&wstoken=your_token

and using native php soap library, your code could be along the lines of:

// SETUP - NEED TO BE CHANGED
$functionname = 'core_user_create_users';
$user1 = new stdClass();
$user1->username = 'abcd';
$user1->password =  'Password123!';
$user1->firstname = 'ali';
$user1->lastname = 'asdsad';
$user1->email = 'asd@asd.com';
$user1->city = 'apo';
$user1->country = 'addfa';
$user1->auth = 'manual';
$params = array($user1);

// SOAP CALL
$serverurl = 'http://your_moodle_install.com/webservice/soap/server.php?wsdl=1&wstoken=your_token';
///Do the main soap call
$client = new SoapClient($serverurl);
try {
  $resp = $client->__soapCall($functionname, array($params));
}
catch (SoapFault $e) {
  exit($e->faultstring);
}

* the moodle comes with minimal documentation at http://your_moodle_site/admin/webservice/documentation.php

Like it.? Share it:
Tags:

2 Responses to Creating a Moodle User via Web Services

  1. saqib

    For this,
    $client = new SoapClient($serverurl);

    which class is required to include?

    as we are creating an object of SoapClient class. so this class should be included.

  2. Michel Camus

    I’m beginner in Moodle and thanks for this step by step list.