来自WordPress站点的Valence API D2L / Brightspace API调用

时间:2015-06-09 17:03:39

标签: javascript php ajax wordpress desire2learn

我是Valence API和D2L(Brightspace)的新手,我目前在通过WordPress注册表单发送API请求时遇到问题。以下是我想要实现的一些步骤:

  1. 学生通过我的WordPress网站上的注册表格注册/注册课程
  2. 注册将新学生信息传递给sample.js中的Valence API doAPIRequest函数
  3. sample.js中的Ajax调用包含一个名为'example_wordpress_action'的动作,该动作在functions.php中定义。这是API请求的地方。
  4. 主要问题是,当我尝试使用发布请求时,总会返回400 Bad Request。但是,我可以在没有任何问题的情况下应用GET / whoami请求。问题是否与输入用户信息的方式有关?
  5. 下面是用于发送创建的用户信息的格式的副本(RoldId正在D2L站点上使用,我正在使用方法'POST'和'/ d2l / api / lp /的API请求1.4 / users /'):

    {
      "OrgDefinedId": "SBoateng",
      "FirstName": "Samuel",
      "MiddleName": "",
      "LastName": "Boateng",
      "ExternalEmail": "daerdocta@gmail.com",
      "UserName": "SBoateng",
      "RoleId": 103,
      "IsActive": true,
      "SendCreationEmail": false
    }
    

    这是从请求中返回的内容:

    Unexpected non-JSON response from the server: 
    Array
    (
        [headers] => Array
            (
                [cache-control] => private
                [content-length] => 0
                [server] => Microsoft-IIS/7.5
                [x-powered-by] => ASP.NET
                [x-xss-protection] => 0
                [date] => Tue, 23 Jun 2015 18:35:05 GMT
                [connection] => close
            )
    
        [body] => 
        [response] => Array
            (
                [code] => 400
                [message] => Bad request
            )
    
        [cookies] => Array
            (
            )
    
        [filename] => 
    )
    

2 个答案:

答案 0 :(得分:1)

根据documentation for the create-user route400状态代码作为响应表示以下两种情况之一:您以某种方式为新用户记录提供了无效数据,或者后端服务是(由于某种原因)无法创建新的用户记录(非常罕见,但它确实发生)。在第二种情况下,您将在错误描述中获得更详细的消息,指示无法创建。由于你没有得到这个,最可能的原因是其中之一:

  • 你没有发送你认为你发送的内容;它的格式很糟糕。

  • 您提供的无效RoleId - 它在您测试的环境中有效,但在生产环境中,RoleId不存在。有时会发生这种情况,但在这种情况下,我怀疑没有。要进行验证,请先尝试按Id取回RoleId,然后查看这些结果。

  • 您提供的系统中已存在UserName:此属性是您在登录Brightspace系统时用于标识自己的ID,因此它必须是唯一的。有时客户会发现他们正在使用的“临时测试”UserName已经存在于他们的后端服务中,无论出于何种原因,这可能会导致意外失败。您可以先尝试通过UserName取回用户来验证您是否已经拥有该用户的记录。

答案 1 :(得分:1)

我已经能够在一些帮助下解决这个问题了。下面是我使用的代码,如果有其他人在将来遇到这个代码。

  1. 摘录保存表单的PHP:

                            <input class="required textInput" id="name_first" name="name_first"  size="35" maxlength="255" placeholder= "First Name"  type="text" value="<?php echo $_SESSION["student_profile"]["name_first"]; ?>" required />
                            <label class="required_lables" for="name_first"><em></em></label>
    
                            <!--  Middle Initial  -->
                            <label for="name_middle"><em></em></label>
                            <input class="textInput optional" id="name_middle" name="name_middle" size="35" maxlength="255" placeholder= "Middle Name (optional)" type="text" value="<?php echo $_SESSION["student_profile"]["name_middle"]; ?>" />
    
                            <!--  Last Name  -->
                            <input class="required textInput" id="name_last" name="name_last"  size="35" maxlength="255" placeholder= "Last Name" type="text" value="<?php echo $_SESSION["student_profile"]["name_last"]; ?>" required/>
                            <label class="required_lables" for="name_last"><em></em></label>
    
  2. 表单提交页面。 Ajax调用在这里进行:

    $ _ SESSION [&#39; student_profile&#39;] = $ _POST;

    $如first_name = $ _ SESSION [&#39; student_profile&#39;] [&#39; name_first&#39;];

    $ middle_name = $ _ SESSION [&#39; student_profile&#39;] [&#39; middle_name&#39;];

    $ last_name = $ _ SESSION [&#39; student_profile&#39;] [&#39; last_name&#39;];

    $ email = $ _ SESSION [&#39; student_profile&#39;] [&#39; email&#39;];

    echo '<script>';
    echo 'var data = {"OrgDefinedId": "'. $orgDefinedId .'",  "FirstName": "'. $first_name .'",  "MiddleName": "'. $middle_name .'",  "LastName": "'. $last_name .'",  "ExternalEmail": "'. $email .'",  "UserName": "'. $uName .'",  "RoleId": 103,  "IsActive": true,  "SendCreationEmail": false};';
    echo 'var type = "CREATE";';
    echo 'window.$vars = {dataField : data};';
    echo 'window.$vartype = {typeField : type};';
    echo 'doAPIRequest();';//direction to js file with the ajax call
    echo '</script>';
    
    ?>
    
  3. wordpress中使用的Ajax:使用的操作称为example_wordpress_action,它在functions.php中定义

    function doAPIRequest() {
     var host = "myHostSite.com";
     var port = "443";
     var scheme = "https";
     var req = "/d2l/api/lp/1.4/users/";
     var method =  "POST";
     var typeAPI = window.$vartype.typeField;
     var ajaxurl = "/wp-admin/admin-ajax.php";  
     var data = window.$vars.dataField;     
     var userName = window.$varsUname.useNameField;
     var anon = "";
     var appId = myAppID;
     var appKey = myAppKey;
            $.ajax({
                url: ajaxurl,
                data: {
                    action : 'example_wordpress_action',
                    host: host,
                    port: port,
                    scheme: scheme,
                    anon: anon,
                    apiRequest: req,
                    typeapp: typeAPI,
                    apiMethod: method,
                    appUser: userName,
                    data: data,
                    appId: appId,
                    appKey: appKey
                },
                success: function(data) {
                    var output;
                    if(data == '') {
                        output = 'Success!';
                        return;
                    } else {
                        try {
                            output = JSON.stringify(JSON.parse(data), null, 4);
                        } catch(e) {
                            output = "Unexpected non-JSON response from the server: " + data;
                        }
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {               
                },
            });
    

    }

  4. 使用wp_remote_request进行请求的Funcions.php:

  5. function example_wordpress_action_function(){

        $host = $_GET['host'];
        $port = $_GET['port'];
        $scheme = $_GET['scheme'];
        $data = $_GET['data'];
        $apiMethod = $_GET['apiMethod'];
        $appId = $_GET['appId'];
        $appKey = $_GET['appKey'];
        $appRequest = $_GET['apiRequest'];
        $appUserName = $_GET['appUser'];
    
        $data_string = json_encode($data);
    
        $userId = $myUserId;
        $userKey = $myUserKey;
    
        $authContextFactory = new D2LAppContextFactory();
        $authContext = $authContextFactory->createSecurityContext($appId, $appKey);
        $hostSpec = new D2LHostSpec($host, $port, $scheme);
        $opContext = $authContext->createUserContextFromHostSpec($hostSpec, $userId, $userKey);
    
        $uri = $opContext->createAuthenticatedUri($appRequest, $apiMethod);
        $headers = array( 'authorization' => 'basic ', 'accept' => 'application/json', 'content-type' => 'application/json', 'content-length' => strlen( $data_string ) ); 
        $post = array( 'method' => $apiMethod, 'headers' => $headers, 'body' => $data_string );
        $createResponses = wp_remote_request($uri, $post);
        die();
    }
    add_action( 'wp_ajax_example_wordpress_action', 'example_wordpress_action_function' );
    add_action("wp_ajax_nopriv_example_wordpress_action", "example_wordpress_action_function");