2

我正在尝试根据以下使用 PHP Curl 添加一个带有 todoist API 的项目:

https://developer.todoist.com/?shell#add-an-item

它引用了这段代码:

$ curl https://todoist.com/API/v6/sync -X POST \
    -d token=0123456789abcdef0123456789abcdef01234567 \
    -d commands='[{"type": "item_add", "temp_id": "43f7ed23-a038-46b5-b2c9-4abda9097ffa", "uuid": "997d4b43-55f1-48a9-9e66-de5785dfd69b", "args": {"content": "Task1", "project_id": 128501470}}]'

我在 PHP 中尝试这个:

$args = '{"content": "Task1", "project_id":'.$project_id.'}';
    $url = "https://todoist.com/API/v6/sync";
    $post_data = array (
        "token" => $token,
        "type" => "item_add",
        "args" => $args,
    );

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_POST, 1);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

    $output = curl_exec($ch);

    curl_close($ch);

所以我有令牌、参数和类型,但我似乎无法让它工作。

该调用的 PHP 等效项是什么?

4

2 回答 2

3

比较 CLI 示例和您的 PHP:

命令行界面

curl https://todoist.com/API/v6/sync -X POST \
  -d token=0123456789abcdef0123456789abcdef01234567 \
  -d commands='[{"type": "item_add", "temp_id": "43f7ed23-a038-46b5-b2c9-4abda9097ffa", "uuid": "997d4b43-55f1-48a9-9e66-de5785dfd69b", "args": {"content": "Task1", "project_id": 128501470}}]'

PHP

// ...
$post_data = array (
    "token" => $token,
    "type" => "item_add",   //<-- NOT PRESENT IN CLI EXAMPLE
    "args" => $args,        //<-- NOT PRESENT IN CLI EXAMPLE
);
//...

CLIPOST的 2 条数据:-d token=...-d commands=.... 但是,您的 PHP 帖子token和. 只需像 cli 请求一样发出 PHP 请求:typeargs

// ...
$post_data = array (
    "token" => $token,
    "commands" => '[{"type": "item_add", "temp_id": "43f7ed23-a038-46b5-b2c9-4abda9097ffa", "uuid": "997d4b43-55f1-48a9-9e66-de5785dfd69b", "args": {"content": "Task1", "project_id": '.$project_id.'}}]',
);
//...
于 2015-05-26T12:23:33.820 回答
1

尝试这个:

$url = "https://todoist.com/API/v6/sync";
$post_data = [
    'token' => $token,
    'commands' => 
        '[{"type": "item_add", ' .
        '"temp_id": "43f7ed23-a038-46b5-b2c9-4abda9097ffa", ' .
        '"uuid": "997d4b43-55f1-48a9-9e66-de5785dfd69b", ' . 
        '"args": {"content": "Task1", "project_id":'.$project_id.'}}]'
];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

$output = curl_exec($ch);

curl_close($ch);

我还没有测试过,但我很确定这是在 PHP 中实现的等效 curl 命令。让我知道它是如何工作的。

于 2015-05-26T12:20:43.333 回答