使用Unirest调用Moodle Web服务

问题描述 投票:0回答:1

我想与Moodle 2.9的安装进行通信。

以下示例客户端稍作修改:https://github.com/moodlehq/sample-ws-clients/blob/master/PHP-REST/client.php使用Unirest而不是Curl和JSON而不是XML:

        $token = 'd1c74d6466daaaaad59b5d99906bfc84';
        $domainname = 'http://moodle.example.com';
        $functionname = 'core_user_create_users';
        // REST RETURNED VALUES FORMAT
        $restformat = 'json'; 

        $user1 = new \stdClass();
        $user1->username = 'testusername1';
        $user1->password = 'testpassword1';
        $user1->firstname = 'testfirstname1';
        $user1->lastname = 'testlastname1';
        $user1->email = '[email protected]';
        $user1->auth = 'manual';
        $user1->idnumber = 'testidnumber1';
        $user1->lang = 'en';
        $user1->theme = 'standard';
        $user1->timezone = '-12.5';
        $user1->mailformat = 0;
        $user1->description = 'Hello World!';
        $user1->city = 'testcity1';
        $user1->country = 'au';
        $preferencename1 = 'preference1';
        $preferencename2 = 'preference2';
        $user1->preferences = array(
            array('type' => $preferencename1, 'value' => 'preferencevalue1'),
            array('type' => $preferencename2, 'value' => 'preferencevalue2'));

        $user2 = new \stdClass();
        $user2->username = 'testusername2';
        $user2->password = 'testpassword2';
        $user2->firstname = 'testfirstname2';
        $user2->lastname = 'testlastname2';
        $user2->email = '[email protected]';
        $user2->timezone = 'Pacific/Port_Moresby';
        $users = array($user1, $user2);
        $params = array('users' => $users);
        /// REST CALL

        $serverurl = $domainname . '/webservice/rest/server.php' . '?wstoken=' . $token . '&wsfunction=' . $functionname;

        //if rest format == 'xml', then we do not add the param for backward compatibility with Moodle < 2.2
        $restformat = ($restformat == 'json') ? '&moodlewsrestformat=' . $restformat : '';
        $headers = array('Accept' => 'application/json');
        $response = UnirestRequest::post($serverurl . $restformat, $headers, json_encode($params));

执行时我收到一个错误:

“注意:数组转换为字符串”

据称是因为参与体内的参数。所以,我想我必须在发送之前序列化身体,但是当我尝试时:

$response = UnirestRequest::post($serverurl . $restformat, $headers, json_encode($params));

我从Moodle回来了:

{“exception”:“invalid_parameter_exception”,“errorcode”:“invalidparameter”,“message”:“Detectado valor de par \ u00e1metro no v \ u00e1lido”,“debuginfo”:“单个结构中缺少必需的密钥:用户”}◀ “

必须有一些我不了解POST请求必须如何的样子。有什么建议吗?

php moodle unirest moodle-api
1个回答
1
投票

Moodle希望帖子的主体是URL编码的,所以你的身体必须使用http_build_query($params)(或任何其他方法来编码你的数据)来构建,例如:

 $convertedpostdata = implode('&', $params);//where $params is  an array

至于为什么,我真的不记得,我记得前一段时间挣扎着实现,你可以查看[your_moodle_installation.com]/admin/webservice/documentation.php获取更多文档,另外你这里是我所做的一个例子:

https://gist.github.com/Scott972/5d9e9495c1397a2ad728b66288ce1d42

© www.soinside.com 2019 - 2024. All rights reserved.