带有请求正文的 WordPress post API

我正在尝试使用他们的 API 向 klaviyo 发出 POST 请求wp_remote_post()。这是他们的指南:

网址:POST https://a.klaviyo.com/api/v2/list/{LIST_ID}/members

请求示例:

{

    "api_key": "api_key_comes_here",

    "profiles": [

        {

            "email": "george.washington@example.com",

            "example_property": "valueA"

        },

        {

            "email": "thomas.jefferson@example.com",

            "phone_number": "+12223334444",

            "example_property": "valueB"

        }

    ]

}

api_key:字符串您帐户的 API 密钥。


配置文件:JSON 对象列表您要添加到列表中的配置文件。列表中的每个对象都必须有一个电子邮件、电话号码或推送令牌键。您还可以以键值对的形式提供其他属性。


这是我尝试过的:


    $profiles = ['email' => $content];

    $args = ["api_key" => {API_key},

             "profiles" => json_encode($profiles)

        ];

    

 $res = wp_remote_retrieve_body( wp_remote_post( 'https://a.klaviyo.com/api/v2/list/{LIST_ID}/members', [

        'body'=> $args

    ] ));

响应是:“无法解析配置文件”


我做错了什么以及如何解决这个问题?


元芳怎么了
浏览 41回答 2
2回答

至尊宝的传说

您没有像示例请求所示那样对完整的请求正文进行编码$args = [    "api_key" => 'some_api_key_string',    "profiles" => [        [            "email" => "john_doe@somewhere.com",            "value" => "some value",        ],        [            "email" => "jane_doe@somewhere.com",            "value" => "some other value",        ]    ],];$listId = 123;$url = "https://a.klaviyo.com/api/v2/list/{$listId}/members";$response = wp_remote_post($url, json_encode($args));这将为您提供如示例中所示的输出

红糖糍粑

最后,我找到了解决方案:#1: 将 'content type' => application/json 添加到标头#2: 强制将配置文件数组转换为对象 - 由于行会表示:配置文件参数是 JSON 对象列表工作代码:$args = ["api_key" => "your_API_key",         "profiles" => array(                (object)['email' => 'email@something.success']             )        ];    $res = wp_remote_retrieve_body( wp_remote_post( 'https://a.klaviyo.com/api/v2/list/you_list_ID/members', [        'headers' => ['Content-Type' => 'application/json'],        'body' => json_encode($args)    ]));
打开App,查看更多内容
随时随地看视频慕课网APP