【问题标题】:Wordpress post API with the request's body带有请求正文的 Wordpress 发布 API
【发布时间】:2020-09-14 14:21:56
【问题描述】:

我正在尝试使用wp_remote_post() 的 API 向 klaviyo 发出 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 密钥。

profiles: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
    ] ));

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

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

【问题讨论】:

    标签: php wordpress api


    【解决方案1】:

    您没有像示例请求所暗示的那样对完整的请求正文进行编码

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

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

    【讨论】:

    • 感谢您的时间和回答。当我使用:json_encode($args)。这是我得到的响应:“指定的 API 密钥无效”。我认为 - 这意味着第一个解决方案是好的,除了配置文件编码(服务器识别 API_key 和配置文件参数但无法解析)但第二个 - 它们都没有被识别!
    • 您是否将我示例中的 api_key 替换为您的?此外,如果您的原始帖子包含您的实际 api_key,您应该将其删除,因为这是您不想公开的内容
    • 您如何确保在 'a.klaviyo.com/api/v2/list{LIST_ID}/members' 中输入 LIST_ID?我更新了我的答案
    • 感谢您的时间和耐心。是的,API 密钥和 LIS_ID 显示在我的 Klaviyo 帐户设置页面中。我已经使用这两个信息来提出请求并且它的工作!
    • 如果您的问题已得到解答,您是否愿意通过批准我的答案来标记它,或者根据您如何实现它并批准它来创建您自己的答案?
    【解决方案2】:

    最后,我找到了解决方案:

    #1:添加“内容类型”=>应用程序/json到标题

    #2:强制配置文件数组进入对象 - 由于公会说:profiles 参数是 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)
        ]));
    

    感谢 @j4g0 的所有帮助。 周末愉快!

    【讨论】:

      猜你喜欢
      • 2018-12-11
      • 2021-11-17
      • 2018-02-23
      • 2017-08-31
      • 1970-01-01
      • 2021-02-12
      • 2014-07-06
      • 1970-01-01
      • 2019-06-23
      相关资源
      最近更新 更多