从WordPress站点调用Valence API D2L/Brightspace API

Valence API D2L/Brightspace API calls from WordPress Site

本文关键字:API D2L Brightspace Valence WordPress 站点 调用      更新时间:2023-09-26

我是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. 主要问题是,当我尝试使用post请求时,总是有400个错误请求返回。但是,我能够应用GET/whoami请求而没有任何问题。是否有可能是输入用户信息的方式出了问题?

下面是用于发送创建的用户信息的格式的副本(RoldId正在D2L站点上使用,我正在使用方法'POST'和'/D2L/API/lp/1.4/users/'的API请求):

{
  "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] => 
)

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

  • 您发送的不是您认为要发送的内容;

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

  • 你提供了一个已经存在于系统中的UserName:这个属性是你登录到Brightspace系统时用来识别自己的ID,所以它必须是唯一的。偶尔,客户端会发现他们正在使用的"临时测试"UserName已经存在于他们的后端服务中,不管出于什么原因,这可能会导致意外的失败。

  • 您可以尝试通过先通过UserName取回一个用户来验证您是否已经有该用户的记录。

我已经能够在一些帮助下解决这个问题。下面是我使用的代码,以防将来有人遇到这种情况。

  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['student_profile'] = $_POST;

    $ first_name = $ _SESSION [' student_profile '] [' name_first '];

    $ middle_name = $ _SESSION [' student_profile '] [' middle_name '];

    $ last_name = $ _SESSION [' student_profile '] [' last_name '];

    邮件= _SESSION美元[' student_profile ']['邮件'];

    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. functions .php中使用wp_remote_request:

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");