首页 > 解决方案 > 带有请求正文的 Wordpress 发布 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: string您帐户的API密钥。

配置文件:JSON 对象列表您要添加到列表中的配置文件。列表中的每个对象都必须有一个 email、phone_number 或 push_token 键。您还可以提供其他属性作为键值对。

这是我尝试过的:

    $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
    ] ));

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

我做错了什么,我该如何解决?

标签: phpwordpressapi

解决方案


您没有像示例请求似乎建议的那样对完整的请求正文进行编码

$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));

这将为您提供示例中的输出


推荐阅读