Post CURL Request of JSON Data with while loop - php

I'm sending a post request to an end point using while loop to send several values to the "questions" sub-array as seen below but it says "bad request". The body of the data has a sub-array into which I need to send multiple entries fetching from the database. Do I need a foreach loop instead?
$sql= "SELECT * FROM table WHERE quiz_id = $quiz_id";
while ($row_que =mysqli_fetch_array($sql)) {
$question = $row_que['question'];
$marks = $row_que['marks'];
$optionA = $row_que['optionA'];
$optionB = $row_que['optionB'];
$optionC = $row_que['optionC'];
$optionD = $row_que['optionD'];
$optionE = $row_que['optionE'];
$correct_option = $row_que['correct_option'];
$data =
array(
'id' => '2',
'quizName' => 'Third Semester',
'numberOfQuestions' => '10',
'isTimed' => true,
'numberOfMinutesToComplete' => '10',
'targetedClass' => '10',
'subject' => 'English',
'schoolLevel' => 'Grade 1',
'questions' => array(['question' => $question, 'questionMark' => $marks,
'options' => array(['option' => 'A', 'answer'=> $optionA ], ['option' => 'B', 'answer' => $optionB] , ['option' => 'C', 'answer' => $optionC ], ['option' => 'D',
'answer' => $optionD ], ['option' => 'E', 'answer' => $optionE]),
'hasImage' => true,
'images' => array(['images-1' => 'image-1'], ['images-2' => 'image-2']),
'correctionOption' => $correct_option
]),
'totalValidMarks' => '10',
'validUntil' => '20-08-2020'
);
}
// API URL
$url = 'https://my-end-point';
// Create a new cURL resource
$params = $data;
$data_string = json_encode($data);
$curl = curl_init();
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data_string,
CURLOPT_HTTPHEADER => array(
"x-access-token: $token",
"cache-control: no-cache",
"content-type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
// echo $payload;
}
}

Related

PHP Post Request (CURL, JSON) not Working

I come humbly before great developers with this issue of mine. Sending a post request in JSON format to Firebase. Here's my code
$token = $_SESSION['token'];
$data = array(
'id' => 156,
'quizName' => $quizName,
'numberOfQuestions' => $numberOfQuestions,
'isTimed' => true,
'numberOfMinutesToComplete' => $numberOfMinutesToComplete,
'targetedClass' => 'Js One',
'subject' => $subject_name,
'schoolLevel' => $schoolLevel,
'questions' => array('question' => $question, 'questionMark' => $marks,
'options' => array('option' => 'A', 'answer'=> $optionA, 'option' => 'B', 'answer'=> $optionB, 'option' => 'C', 'answer' => $optionC, 'option' => 'D', 'answer' => $optionD, 'option' => 'E', 'answer' => $optionE),
'hasImage' => true,
'images' => array('images-1' => 'image-1', 'images-2' => 'image-2'),
'correctionOption' => $correct_option
),
'totalValidMarks' => $totalValidMarks,
'validUntil' => $validUntil
);
// API URL
$url = ' ';
// Create a new cURL resource
$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode( array( "customer"=> $data ) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('x-access-token:'.$token, 'Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.
echo "<pre>$result.</pre>";
But I'm receiving an error:
"details":[{"message":"\"id\" is required","path":["id"],"type":"any.required","context":{"label":"id","key":"id"}}]}
Please try sending like this:
$params = $myDataArray;
$data_string = json_encode($params);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $toEndPoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data_string,
CURLOPT_HTTPHEADER => array(
"x-access-token: $token",
"cache-control: no-cache",
"content-type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
exit;
#godlovesme, to answer for your latest comment:
I don't really like using While loops as they can easily let you fall in an endless loop, but you get what you ask for:
$i = 0;
$questionsArrFormatted = [];
while ($i < count($questionsArr)) {
$hasImage = count($questionsArr[$i]['question']) ? true : false;
$questionsArrFormatted[$i] = [
'question' => $questionsArr[$i]['question'],
'questionMark' => $questionsArr[$i]['marks'],
'options' => $questionsArr[$i]['options'], // options should be an array formatted like in your question
'hasImage' => $hasImage,
'images' => $questionsArr[$i]['images'],
'correctionOption' => $questionsArr[$i]['correct_answer']
];
$i++;
}
$data = array(
'id' => 156,
'quizName' => $quizName,
'numberOfQuestions' => $numberOfQuestions,
'isTimed' => true,
'numberOfMinutesToComplete' => $numberOfMinutesToComplete,
'targetedClass' => 'Js One',
'subject' => $subject_name,
'schoolLevel' => $schoolLevel,
'questions' => $questionsArrFormatted,
'totalValidMarks' => $totalValidMarks,
'validUntil' => $validUntil
);

How to fix 400 bad request using curl and discord api (php)

Whenever I try this it replies with "400 bad request"
I've tried adding a client id but I'm not exactly sure how to get that
$url = 'https://discordapp.com/api/v6/science';
$data = json_decode($response);
$ch = curl_init();
$json = array( "channel_id" => $data->channel->id,
"channel_type" => $data->channel->type,
"client_performance_cpu" => 48,
"client_performance_memory" => 833620,
"client_send_timestamp" => time(),
"client_track_timestamp" => time(),
"client_uuid" => $data->channel->id,
"code" => $_GET["invite"],
"destination_user_id" => null,
"guild_id" => $data->channel->id,
"invite_type" => "Server Invite",
"inviter_id" => $data->inviter->id,
"location" => "Join Guild Modal",
"resolved" => "true",
"size_online" => $data->approximate_presence_count,
"size_total" => $data->approximate_member_count,
"type" => "resolve_invite",
"token" => $_GET["token"]
);
$payload = json_encode($json);
echo $payload;
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array('Authorization: ' . $_GET["token"]),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_POSTFIELDS => $json
));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($payload)
));
$response = curl_exec($ch);
fclose($f);
curl_close($ch);
echo "<br/><br/>" . $response;
(data is defined it's just on another part of my code)
I want it to accept the invite

Rates not returning while creating a shipment using shippo

I am integrating shippo API so far it is working great but there is this problem that when I send the request to create shipment shipment is creating but there is nothing in the rate array but when I send the same request through postman I am getting those rates here is the request that I am sending.
// Receiver Information for making shipment.
$r_name = $result[0]->r_name;
$r_email = $result[0]->r_email;
$r_street = $result[0]->r_street;
$r_city = $result[0]->r_city;
$r_country = $result[0]->r_country;
$r_zip = $result[0]->r_zip;
$r_state = $result[0]->r_state;
// Sender Information for making Shipment.
$s_name = $result[0]->s_name;
$s_email = $result[0]->s_email;
$s_street = $result[0]->s_street;
$s_city = $result[0]->s_city;
$s_country = $result[0]->s_country;
$s_zip = $result[0]->s_zip;
$s_state = $result[0]->s_state;
// Parcel Information for making Shipment.
$p_qty = $result[0]->p_qty;
$p_name = $result[0]->p_name;
$p_price = $result[0]->p_price;
$p_weight = $result[0]->p_weight;
$p_unit = $result[0]->p_unit;
$shipment_array = array(
'address_to' => array(
'name' => $r_name,
'street1' => $r_street,
'city' => $r_city,
'state' => $r_state,
'zip' => $r_zip,
'country' => $r_country,
'phone' => '03212669686',
'email' => $r_email
),
'address_from' => array(
'name' => $s_name,
'street1' => $s_street,
'city' => $s_city,
'state' => $s_state,
'zip' => $s_zip,
'country' => $s_country,
'phone' => '03227577798',
'email' => $s_email
),
'parcels' => array(
array(
"length" => "10",
"width" => "15",
"height" => "10",
"distance_unit" => "in",
"weight" => $p_weight,
"mass_unit" => $p_unit
)
),
'async' => false
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.goshippo.com/shipments/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($shipment_array),
CURLOPT_HTTPHEADER => array(
"Authorization: ShippoToken shippo_test_742eabd1c83ece80052fbce9ee71163181eaee72",
"Cache-Control: no-cache",
"Content-Type: application/json",
"Postman-Token: 906233f7-ac66-3951-f96a-4f0f88c8d419"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Can anyone help me finding out what am I doing wrong here.

Curl to wp_remote_post convert

I would like to convert these into wp_remote_post()
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"'.rawurldecode($this->url).'","source":"widget","userId":"#viewer","groupId":"#self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
$curl_results = curl_exec ($curl);
curl_close ($curl);
$json = json_decode($curl_results, true);
I almost tried with this
$params = array(
'method' => 'POST',
'timeout' => 45,
'blocking' => true,
'headers' => array(
'Content-Type' => 'application/json'
),
'body' => array(
'method' => 'pos.plusones.get',
'id' => 'p',
'params'=> array (
'nolog' => true,
'id' => rawurldecode($url),
'source' => 'widget',
'userId' => '#viewer',
'groupId' => '#self',
),
'jsonrpc' => '2.0',
'key' => 'p',
'apiVersion' => 'v1',
),
);
$connection = wp_remote_post('https://clients6.google.com/rpc', $params);
But there is a error message like this - "Unable to parse json"
Please help
Thank You
This works
$params = array(
'method' => 'POST',
'timeout' => 45,
'blocking' => true,
'headers' => array(
'Content-Type' => 'application/json'
),
'body' => '['.json_encode( array(
'method' => 'pos.plusones.get',
'id' => 'p',
'params' => array(
'nolog' => true,
'id' => rawurldecode( $url ),
'source' => 'widget',
'userId' => '#viewer',
'groupId' => '#self',
),
'jsonrpc' => '2.0',
'key' => 'p',
'apiVersion' => 'v1',
) ).']'
);
$connection = wp_remote_post( 'https://clients6.google.com/rpc', $params );
Noticed a few inconsistencies. not sure if the syntax is throwing the errors but might fix the parsing....
$params = array(
'method' => 'POST',
'timeout' => 45,
'blocking' => true,
'headers' => array(
'Content-Type' => 'application/json'
),
'body' => array(
'method' => 'pos.plusones.get',
'id' => 'p',
'params'=> array(
'nolog' => true,
'id' => rawurldecode($url),
'source' => 'widget',
'userId' => '#viewer',
'groupId' => '#self'
),
'jsonrpc' => '2.0',
'key' => 'p',
'apiVersion' => 'v1'
)
);

Cannot post data correctly to Chargify via PHP cURL

I guess I'm not sending the data required by the API correctly. Any ideas what I am doing wrong?
$ch = curl_init("https://test.chargify.com/customers.json");
$data = array(
'first_name' => 'Test',
'last_name' => 'User',
'email' => 'user#test.com'
);
$data = json_encode($data);
curl_setopt_array($ch, array(
CURLOPT_USERPWD => "yyyyyyyyyyyyyyy:x", // assume this is correct
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data)
)
));
$output = curl_exec($ch);
curl_close($ch);
It returns
{
errors: [
"First name: cannot be blank.",
"Last name: cannot be blank.",
"Email address: cannot be blank."
]
}
Here's the documentation for the API:
http://docs.chargify.com/api-customers
Try this:
$data = array( 'customer' => array(
'first_name' => 'Test',
'last_name' => 'User',
'email' => 'user#test.com'
));

Categories