PHP Curl / Todoist / 添加项目

PHP Curl / Todoist / Adding Item

我正在尝试使用 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 等价物是什么?

试试这个:

$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 命令。让我知道结果如何。

比较 CLI 示例和您的 PHP:

CLI

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
);
//...

CLI POST 有 2 条数据:-d token=...-d commands=...。但是,您的 PHP 帖子 tokentypeargs。只需像 cli 请求一样发出 PHP 请求:

// ...
$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.'}}]',
);
//...