thống nguyễn
thống nguyễn

Reputation: 831

Wordpress post API with the request's body

I'm trying to make a POST request to klaviyo using their API by wp_remote_post(). This is their guide:

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

Example Request:

{
    "api_key": "api_key_comes_here",
    "profiles": [
        {
            "email": "[email protected]",
            "example_property": "valueA"
        },
        {
            "email": "[email protected]",
            "phone_number": "+12223334444",
            "example_property": "valueB"
        }
    ]
}

api_key: stringThe API key for your account.

profiles: list of JSON objectsThe profiles that you would like to add to the list. Each object in the list must have an email, phone_number, or push_token key. You can also provide additional properties as key-value pairs.

This is what i tried:

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

and the response is: "unable to parse profiles"

What am I doing wrong and how can I fix this?

Upvotes: 0

Views: 1369

Answers (2)

thống nguyễn
thống nguyễn

Reputation: 831

Finally, i find the solution for this:

#1: add 'content type' => application/json to headers

#2: force the profile array into object - due to the guild said: profiles parameter is list of JSON objects

Working codes:

$args = ["api_key" => "your_API_key",
         "profiles" => array(
                (object)['email' => '[email protected]']
             )
        ];



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

Thank @j4g0 for all of your help. Have a great weekend!

Upvotes: 0

j4g0
j4g0

Reputation: 198

You are not encoding your complete request body like the example request seems to suggest

$args = [
    "api_key" => 'some_api_key_string',
    "profiles" => [
        [
            "email" => "[email protected]",
            "value" => "some value",
        ],
        [
            "email" => "[email protected]",
            "value" => "some other value",
        ]
    ],
];


$listId = 123;

$url = "https://a.klaviyo.com/api/v2/list/{$listId}/members";

$response = wp_remote_post($url, json_encode($args));

this will give you an output like in the example

Upvotes: 1

Related Questions