PHP Post Request (CURL, JSON) not Working - php

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

Related

Post CURL Request of JSON Data with while loop

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;
}
}

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

Create a image share for linkedin api v2 by php

I write a code which share a post on linkedin account. My code is working fine for text post but facing issue in image post. I tried and search a lot but not find any success for now. Here is my code for image share in linkedin V2 api.
I follow this doc
https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin?context=linkedin/consumer/context
/*1.Register your image to be uploaded.*/
$imageData = array (
'registerUploadRequest' =>
array (
'recipes' =>
array (
0 => 'urn:li:digitalmediaRecipe:feedshare-image',
),
'owner' => 'urn:li:person:'.$data['identifier'],
'serviceRelationships' =>
array (
0 =>
array (
'relationshipType' => 'OWNER',
'identifier' => 'urn:li:userGeneratedContent',
),
),
),
);
$headers = [
'Content-Type' => 'application/json',
'x-li-format' => 'json',
'X-Restli-Protocol-Version' => '2.0.0',
];
$image_request = $adapter->apiRequest('assets?action=registerUpload', 'POST', $imagedata, $headers);
$image_request = json_decode(json_encode($image_request), True);
/*2.Upload your image to LinkedIn.*/
$media = $image_request['value']['asset'];
$image_path = '/var/www/domain.com/img/laptop-green-bg.jpg';
$postfield = array("upload-file" => $image_path );
$headers = array();
$headers[] = 'Authorization: Bearer '.$tokens['access_token'];// token generated above code
$headers[] = 'X-Restli-Protocol-Version: 2.0.0';
$headers[] = 'Content-Type: data/binary';
$headers[] = 'Content-Length: 0';
$ch = curl_init();
$options = array(
CURLOPT_HEADER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $image_request['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'],
CURLOPT_HTTPHEADER => $headers,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_SAFE_UPLOAD => false,
CURLOPT_POSTFIELDS => $postfield
);
curl_setopt_array($ch, $options);
$imgResponse = curl_exec($ch);
if (curl_error($ch)) {
$error_msg = curl_error($ch);
}
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$assets = explode(":", $media);
$assetRequest = $adapter->apiRequest('assets/'.$assets[3], 'GET');
/*3. Create the image share.*/
$status = $this->imagePostArray($data, $media);
function imagePostArray($data, $media) {
$newData = array (
'author' => 'urn:li:person:'.$data['identifier'],
'lifecycleState' => 'PUBLISHED',
'specificContent' =>
array (
'com.linkedin.ugc.ShareContent' =>
array (
'shareCommentary' =>
array (
'text' => $data['introtext'],
),
'shareMediaCategory' => 'IMAGE',
'media' =>
array (
0 =>
array (
'status' => 'READY',
'description' =>
array (
'text' => $data['introtext'],
),
'media' => $media,
'title' =>
array (
'text' => $data['introtext'],
),
),
),
),
),
'visibility' =>
array (
'com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC',
),
);
return $newData;
}
$response = $adapter->apiRequest('ugcPosts', 'POST', $status, $headers);
print_r($response);
/*responsestdClass Object
(
[id] => urn:li:share:XX4665961029465XXXX
)*/
print_r($imgResponse);
/*HTTP/1.1 201 Created
Date: Tue Jun 18 08:15:02 UTC 2019
Server: Play
Set-Cookie: lang=v=2&lang=en-us; Path=/; Domain=api.linkedin.com
x-ambry-creation-time: Tue Jun 18 08:15:02 UTC 2019
access-control-allow-origin: https://www.linkedin.com
Content-Length: 0
X-Li-Fabric: prod-lor1
Connection: keep-alive
X-Li-Pop: prod-esv5
X-LI-Proto: http/1.1
X-LI-UUID: z1rSbeU8qRUA8kkBZSsXXX==
Set-Cookie: lidc="b=OB77:g=1398:u=7:i=1560845701:t=1560926538:s=AQG2sbwmHWudXf8tikgpzQdf4uhbXXX"
X-LI-Route-Key: "b=OB77:g=1398:u=7:i=1560845701:t=1560926538:s=AQG2sbwmHWudXf8tikgpzQdf4uhbXXX"*/
But still cannot see my post in linkedin. Please help to debug or provide some solution.
I've solved posting using Guzzle library of php. It's simple and straight forward.
First we need to upload the image using following code:
$linkedInClient = new GuzzleHttp\Client(['base_uri' => 'https://api.linkedin.com']);
$response = $linkedInClient->post(
'/media/upload', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer {accessToken}',
],
'multipart' => [
[
'name' => 'fileupload',
'contents' => fopen('image-path', 'r'),
],
],
]
);
After that we need to decode the json response the uploaded image to use in the post request as follow:
$contents = json_decode($response->getBody()->getContents());
Now, prepare the data for linkedin post:
$data = array (
'author' => 'author-id',
'lifecycleState' => 'PUBLISHED',
'specificContent' =>
array (
'com.linkedin.ugc.ShareContent' =>
array (
'media' =>
array (
0 =>
array (
'media' => $contents->location,
'status' => 'READY'
),
),
'shareCommentary' =>
array (
'attributes' => [],
'text' => 'Some Comments',
),
'shareMediaCategory' => 'IMAGE',
),
),
'visibility' =>
array (
'com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC',
),
);
Next, we can use this data to post in linkedin as below:
$linkedInClient->post("/ugcPosts", $data);
I hope this helps. We can see the post in the linkedin. However, in my case the post will be visible but the image only gets displayed after some time of upload. But you can see the image on popup after clicking the blank image block.
Thanks.
Work For Me
$curl = curl_init(); //CURL version: 7.29, PHP version: 7.4.26
$imageData = array (
'registerUploadRequest' =>
array (
'recipes' =>
array (
0 => 'urn:li:digitalmediaRecipe:feedshare-image',
),
'owner' => 'urn:li:person:'.$linkedin_id,
'serviceRelationships' =>
array (
0 =>
array (
'relationshipType' => 'OWNER',
'identifier' => 'urn:li:userGeneratedContent',
),
),
),
);
$image_request = json_encode($imageData);
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.linkedin.com/v2/assets?action=registerUpload',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_TIMEOUT => 300,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $image_request,
CURLOPT_HTTPHEADER => array('content-type: application/json', "Accept: application/json",
"Authorization: Bearer ".$access_token)
));
$response = json_decode(curl_exec($curl),true);
echo "<pre>";
print_r($response);

Failed to connect to rslr.connectbind.com port 8080: Connection refused

PHP CURL is refusing to open connection
When I call this url on a browser its opens and send an sms
http://rslr.connectbind.com:8080/bulksms/bulksms?username=josy-mbongocash&password=kipese73&type=0&dlr=1&destination=254719401837&source=MbongoCash&message=METHODE-PATRICK
Response OK : 1701|254719401837|e8fbf5af-d7c2-4f34-a80f-94803ffee9d5
when I try calling it with curl
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_PORT => "8080",
CURLOPT_URL => "http://rslr.connectbind.com:8080/bulksms/bulksms?
username=josy-
mbongocash&password=kipese73&type=0&dlr=1&destination=254719401837&
source=MbongoCash&message=METHODE-PATRICK",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Postman-Token: 09ba239d-fcb7-4755-8032-7ff4f768147f",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
RESPONSE :Failed to connect to rslr.connectbind.com port 8080: Connection refused
With CURL
$url="http://rslr.connectbind.com/bulksms/bulksms";
$ch = curl_init();
$variables = array(
'username' => 'Your user name',
'password' => 'Your password',
'type' => '0',
'dlr' => '1',
'destination' => "Mobile number with country code",
'source' => 'Brand Name',
'message' => "sms",
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $variables);
echo $result = curl_exec($ch);
Without CURL
$url="http://rslr.connectbind.com/bulksms/bulksms";
$variables = array(
'username' => 'Your user name',
'password' => 'Your password',
'type' => '0',
'dlr' => '1',
'destination' => "Mobile number with country code",
'source' => 'Brand Name',
'message' => "sms",
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($variables),
),
);
$context = stream_context_create($options);
echo $result = file_get_contents($url, false, $context);
The issue was the port I changed and it worked

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.

Categories