简体   繁体   中英

What am I doing wrong with this curl request in PHP?

I'm trying to write a sample curl request into PHP

POST https://a.klaviyo.com/api/v1/list/{{ LIST_ID }}/members
curl https://a.klaviyo.com/api/v1/list/dqQnNW/members \
  -X POST \
  -d api_key=API_KEY \
  -d email=george.washington@example.com \
  -d properties='{ "$first_name" : "George", "Birthday" : "02/22/1732" }' \
  -d confirm_optin=true

This is my code that I wrote. The part that I'm not getting is how to input the email as data.

$data_string = 
            '{
            "email": "'.$email.'"
            }';



        $ch = curl_init("https://a.klaviyo.com/api/v1/list/$form_id/members?api_key=$mail_api_key");

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
            'Content-Type: application/json'
            )                                                                       
        );            

The error I'm getting is

Array
(
    [status] => 400
    [message] => This request is missing the following required params: "email".
)
<?php
$email='test@gmmail.com';
$data_string =json_encode($email);


$form_id=5;
$mail_api_key=10;

$ch = curl_init("https://a.klaviyo.com/api/v1/list/$form_id/members?api_key=$mail_api_key");

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json'
    )

);

The form_id and api_key i set them hardcoded so i can see the response. This code will work fine for you just remove the $form_id and mail_api_key and set them like you set them first place.

From the php doc: "This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value." So you should change your json string to an array or urlencode your data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM