4

我正在为我的书店使用 postmates API。我正在使用他们的测试凭据,但我不知道如何使用它。请指导我如何进行基本的 api 调用。我正在使用 PHP。我想使用 cURL 发送帖子数据 谢谢

<?php
  $url = "https://api.postmates.com/v1/customers/my-customer-key/delivery_quotes";
  $uname = "my-api-key";
  $pwd = null;
  $data = array(
        'dropoff_address' => '20 McAllister St, San Francisco, CA 94102',
        'pickup_address' => '101 Market St, San Francisco, CA 94105',
    );

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, "$uname:$pwd");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($process, CURLOPT_POST, 1);
    curl_setopt($process, CURLOPT_POSTFIELDS, $data);
    
        $output = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'error:' . curl_error($ch);
        }
        curl_close($ch);

        echo $output;
?>

4

2 回答 2

2

文档中

Postmates API 需要通过 HTTP Basic Auth 标头进行身份验证。您的 API 密钥应作为用户名包含在内。密码应留空。

意味着您需要执行以下操作:

$curl = curl_init();
$url = "http://whatever-this-should-be";
curl_setopt($curl, CURLOPT_URL, $url);
$username = "your-api-key-goes-here";
$password = ""; // leave this blank, as per the doc
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
$res = curl_exec($curl);

您需要调整其他 curl 选项来处理输出等,但这是您需要的核心。

如果您想在稍高(即更容易)的级别上完成所有这些操作,您可能还想查看这个库。

更新:请注意,这只是示例代码。我不提倡将您的 API 密钥存储在您的脚本文件中以用于生产代码!

于 2015-09-21T11:27:13.360 回答
2

我已经制作了这段代码,它工作正常。谢谢大家回答我的问题。

    $url = "https://api.postmates.com/v1/customers/my-customer-id/delivery_quotes";

    $uname = "my-api-key";
    $pwd = null;

    $process = curl_init($url);
    curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded','Accept: application/json'));
    curl_setopt($process, CURLOPT_HEADER, 1);
    curl_setopt($process, CURLOPT_USERPWD, $uname . ":" . $pwd);
    curl_setopt($process, CURLOPT_TIMEOUT, 30);
    curl_setopt($process, CURLOPT_POST, 1);
    curl_setopt($process, CURLOPT_POSTFIELDS, "dropoff_address=20 McAllister St, San Francisco, CA 94102&pickup_address=101 Market St, San Francisco, CA 94105");
    curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
    $return = curl_exec($process);

    curl_close($process);

    var_dump($return);
于 2015-09-21T12:19:23.260 回答