使用PHP Curl发布数据后检索响应

时间:2014-06-17 14:35:47

标签: php post curl oauth-2.0 response

我正在尝试使用Curl对Localbitcoins API进行API调用,但是我很难获得正确返回的响应。我查看了我的卷曲请求,没有任何看起来不合适。

以下是我想要的API调用:

基本网址: https://localbitcoins.com/oauth2/access_token/

必填参数: client_idclient_secretusernamepasswordgrant_type=password

可选参数:

如果成功,会立即返回JSON:

{
  "access_token": the access token,
  "scope": "read",
  "expires_in": seconds to expiry,
  "refresh_token": a refresh token
}

这是我编写的用于尝试和检索access_token的函数:

function authenticate($parameters) {
    $url   = 'https://localbitcoins.com/oauth2/access_token/';
    $parameters['client_id'] = 'redacted';
    $parameters['client_secret'] = 'redacted';
    $data = http_build_query($parameters);

    // Initialize the PHP curl agent
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, "curl");
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    // curl_setopt($ch, CURLOPT_VERBOSE, true);

    $result = curl_exec($ch);
    if ($result === false)
        throw new Exception ("curl Error: " . curl_error($ch));

    $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_status != 200)
        throw new Exception("Request Failed. http status: " . $http_status);

    curl_close($ch);

    // Trim any whitespace from the front and end of the string and decode it
    $result = json_decode(trim($result));
    if (($error = get_json_error()) !== false) {
        throw new Exception("json_decode failed: " . $error);
    }

    // Verify that we got a valid response
    if (!isset($result->status))
    {
        throw new Exception("API response did not contain 'status'");
        exit;
    }
    if ($result->status == 'error')
    {
        throw new Exception("API call failed: " . $result->message);
        exit;
    }

    // The API call succeeded, return the requested data
    return $result->data;
}

并调用函数:

authenticate(array(
        'grant_type' => 'password',
        'username' => 'redacted',
        'password' => 'redacted'));

所有这些返回的是FATAL ERROR和BAD REQUEST的400 ERROR。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

你可以试试这个......

        $result = curl_exec($ch);
        echo nl2br($result);
        curl_close($ch);

答案 1 :(得分:0)

我认为值得花时间为当前的Localbitcoins API开发。它有很多破损的功能记录很差。如果你看一下开发者论坛,它的维护得不好,并且充满了抱怨:

https://localbitcoins.com/forums/#!/dev/developers-and-affiliates

我个人询问了一位Localbitcoin开发者的API状态,他告诉我他们将在未来两周内推出更新的API。

根据您的具体问题,似乎问题自2013年10月以来就存在:

https://localbitcoins.com/forums/#!/dev/developers-and-affiliates#problems-with-grant-typepa

看起来像Localbitcoins团队中的任何人都没有解决它。我认为你最好不要推迟使用他们的新API。

干杯!