首页 > 解决方案 > 如何使用带有 API Key 和 API Secret 的 PHP 查询 OData API?获取“未设置 URL!” 卷曲错误

问题描述

我是 API 新手,我正在尝试创建一个应用程序,该应用程序将从 Cornerstone OnDemand LMS 提供的 OData API 中获取一些数据。它称为报告 API。Cornerstone OnDemand 文档说,我需要获取 API 密钥和 API 机密,然后获取会话令牌。它解释了生成 API 会话签名之前的过程,并提供了一个示例 PHP 代码。但是,我不确定在生成签名后如何超越这一点。

这是 Cornerstone OnDemand 文档中提供的示例 PHP 代码。

//signature to acquire a session
$apiId = '<insert Api ID>';
$apiSecret = '<Insert API Secret>';

//build the string to sign
//note the order of the entries is important.
//The http headers must be in alphabetical order by key name
$httpMethod = 'POST';
$apiKey = 'x-csod-api-key:'.$apiId;
$httpUrl = '/services/api/sts/session';

date_default_timezone_set('UTC');
$date = 'x-csod-date:'.date('Y-m-d').'T'.date('H:i:s').'.000';
$stringToSign = $httpMethod."\n".$apiKey."\n".$date."\n".$httpUrl;

/* produces the following string:
*  POST\nx-csod-api-key:1lie8ficql9h5\nx-csod-date:2015-09-08T11:27:32.000\n/services/api/sts/session
*/

//Generate the signature
$secretKey = base64_decode($apiSecret);
$signature = base64_encode(hash_hmac('sha512', $stringToSign, $secretKey, true));

我不确定生成签名后该怎么做。在https://github.com/csodedge/csod-rest-api-sample-code-POST的 Cornerstone OnDemand 的 GitHub 存储库中提供了一个 REST API 示例 C# 代码,但是我找不到任何可以用于 PHP 的东西.

我期待着 StackOverflow 社区的帮助。我将非常感谢任何帮助。

编辑 1:经过一番研究,我认为我需要形成标题并使用 Curl 发送请求。我已经添加了 curl 代码,但是我现在收到了一个错误的请求错误。这是更新的代码。任何帮助深表感谢。

//signature to acquire a session
    $apiId = '<removed for safety>';
    $apiSecret = '<removed for safety>';

    //build the string to sign
    //note the order of the entries is important.
    //The http headers must be in alphabetical order by key name
    $httpMethod = 'POST';
    $apiKey = 'x-csod-api-key:'.$apiId;
    $httpUrl = 'https://clientdomain.csod.com/services/api/sts/session?userName=clientuserid&alias=jk01';

    date_default_timezone_set('UTC');
    $date = 'x-csod-date:'.date('Y-m-d').'T'.date('H:i:s').'.000';
    $stringToSign = $httpMethod."\n".$apiKey."\n".$date."\n".$httpUrl;

    //Generate the signature
    $secretKey = base64_decode($apiSecret);
    $signature = base64_encode(hash_hmac('sha512', $stringToSign, $secretKey, true));

    $crl = curl_init();

    curl_setopt($crl, CURLOPT_URL, $httpUrl); 
    curl_setopt($crl, CURLOPT_HTTPHEADER, array (
      'x-csod-api-key: '.$apiId,
      'x-csod-date: '.date('Y-m-d').'T'.date('H:i:s').'.000',
      'x-csod-signature: '.$signature
    ));
    curl_setopt($crl, CURLOPT_POST,true);
    $rest = curl_exec($crl);
    if ($rest === false)
    {
        // throw new Exception('Curl error: ' . curl_error($crl));
        print_r('Curl error: ' . curl_error($crl));
    }

    curl_close($crl);
    print_r($rest);

这段代码现在给了我以下错误:

错误请求 您的浏览器发送了此服务器无法理解的请求。参考#7.9dde387d.1532191458.b66f123 1

请帮忙。

标签: phpapiodata

解决方案


推荐阅读