I am trying to get this request working, it is my first time working with Guzzle and i dont know what i'm doing wrong here. The request works with cURL but it does not work with Guzzle:
Guzzle:
$res = $client->request('POST', 'https://api.bol.com/retailer/offers', [
'headers' => [
'Authorization' => 'Bearer ' . $jwt,
'Accept' => 'application/vnd.retailer.v5+json',
'content-type' => 'application/vnd.retailer.v5+json'
],
'body' => json_encode(array(
'ean' => (string)$item->ean_number,
'condition' => [
'name' => 'NEW',
],
'reference' => 'NS-'.(string)$item->ean_number,
'unknownProductTitle' => (string)$item->name,
'pricing' => [
'bundlePrices' =>[
'quantity' => 1,
'unitprice' => round($item->default_price->price * 1.21, 2)
],
],
'stock' => [
'amount' => (int)$item->stock,
'managedByRetailer' => false,
],
'fulfilment' => [
'method' => 'FBR',
'deliveryCode' => '2-3d',
]
))
]);
cURL:
$productjson[] = array(
'ean' => $data[4],
'condition' => array('name' => 'NEW', 'category' => 'NEW'),
'onHoldByRetailer' => 'false',
'reference' => "dy".$data[4],
'unknownProductTitle' => $data[1],
'pricing' => array('bundlePrices' => array('quantity' => 1, 'unitPrice' => $data[12])),
'stock'=> array('amount' => $data[13], 'managedByRetailer' => false),
'fulfilment' => array('method' => 'FBR', 'deliveryCode' => '2-3d')
);
$productjson = json_encode($productjson[0], JSON_FORCE_OBJECT);
$response = callAPI('POST', $bearer, 'https://api.bol.com/retailer/offers', $productjson);
function callAPI($method, $bearer, $url, $data, $accept = 'application/vnd.retailer.v4+json', $ignoreheaders = false){
$curl = curl_init();
if(!$ignoreheaders){
curl_setopt($curl, CURLOPT_HEADER, true);
}
switch ($method){
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: '.$accept, 'Content-Type: '.$accept,
'Authorization: Bearer '.$bearer));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// EXECUTE:
$result = curl_exec($curl);
if(!$ignoreheaders){
if (strpos($result, 'JWT') !== false) {
$responses[] = 'Epired JWT:'.$result;
$bearer = callBearer('POST', 'https://login.bol.com/token?grant_type=client_credentials', NULL);
$result = curl_exec($curl);
}
if(strpos($result, '504') !== false){
$responses[] = '504 error:'.$result;
sleep(1.1);
$bearer = callBearer('POST', 'https://login.bol.com/token?grant_type=client_credentials', NULL);
$result = curl_exec($curl);
}
if(strpos($result, 'FAILURE') !== false){
$responses[] = 'FAILURE:'.$result;
sleep(1.1);
$bearer = callBearer('POST', 'https://login.bol.com/token?grant_type=client_credentials', NULL);
$result = curl_exec($curl);
}
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$header = substr($result, 0, $header_size);
$body = substr($result, $header_size);
$result = json_decode($body);
return $result;
}
It's probably something really stupid, but im basically just asking: how do i execute the working cURL request with guzzle? Because my guzzle request returns a 400 bad request error.
Trying changing body to json and pass array instead of json encoded string, Guzzle will take care of converting this array to json internally
$res = $client->request('POST', 'https://api.bol.com/retailer/offers', [
'headers' => [
'Authorization' => 'Bearer ' . $jwt,
'Accept' => 'application/vnd.retailer.v5+json',
'content-type' => 'application/vnd.retailer.v5+json'
],
'json' => array(
'ean' => (string)$item->ean_number,
'condition' => [
'name' => 'NEW',
],
'reference' => 'NS-'.(string)$item->ean_number,
'unknownProductTitle' => (string)$item->name,
'pricing' => [
'bundlePrices' =>[
'quantity' => 1,
'unitprice' => round($item->default_price->price * 1.21, 2)
],
],
'stock' => [
'amount' => (int)$item->stock,
'managedByRetailer' => false,
],
'fulfilment' => [
'method' => 'FBR',
'deliveryCode' => '2-3d',
]
)
]);
Related
Here is curl code which is working very good
$data = array(
"to" => $to ,
"from" => $options['from_email'] ,
"subject" => $subject,
"body" => $message,
);
$url = 'https://example.com';
$api_key = 'apikeyhere'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Type: application/json',
'X-API-KEY:'.$api_key
));
$response = curl_exec($ch);
But if i try to convert this above code to worpress wp_remote_post i am getting error.
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'blocking' => true,
'sslverify' => false,
'httpversion' => '1.0',
'redirection' => 5,
'headers' => array(
'Accept: application/json',
'Content-Type: application/json',
'X-API-KEY:'.$api_key
),
'body' => json_encode($data),
) );
here is response i am getting
https://pastebin.com/Ap5LpfZb
Please let me know where i am doing wrong ?
I got it there was problem with the header array i was passing that array wrongly
Wrong code was
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'blocking' => true,
'sslverify' => false,
'httpversion' => '1.0',
'redirection' => 5,
'headers' => array(
'Accept: application/json',
'Content-Type: application/json',
'X-API-KEY:'.$api_key
),
'body' => json_encode($data),
) );
Here is correct version of code
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'blocking' => true,
'sslverify' => false,
'httpversion' => '1.0',
'redirection' => 5,
'headers' => array(
'Accept'=> 'application/json',
'Content-Type' =>'application/json',
'X-API-KEY' => $api_key,
),
'body' => json_encode($data),
) );
I am using this script in PHP to capture google products through ZenSerp. I can get an output with all the terms.
Example;
Title
Description
Price
Image
URL Link
Is there a way to print
1.price
2.title
3.description
on another page?
thanks.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$data = [
"q" => "Tools",
"tbm" => "shop",
"device" => "desktop",
"location" => "Manhattan,New York,United States",
];
curl_setopt($ch, CURLOPT_URL, "https://app.zenserp.com/api/v2/search?" . http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"apikey: XXXX",
));
$response = curl_exec($ch);
curl_close($ch);
$json = json_decode($response);
echo '<pre>' . var_export($json, true) . '</pre>';
?>
Output:
(object) array(
'title' => 'Craftsman 320-Piece Mechanic S Tool Set',
'link' => '/aclk?sa=L&ai=DChcSEwjn5sb54NDtAhXHfysKHWT9BIIYABBXGgJzZg&sig=AOD64_1kzP9frQqO7uULjK4LGcDJkpuuGA&ctype=46&q=&ved=0ahUKEwjP9cL54NDtAhUBjeYKHaqqBzgQ_-QECL8H&adurl=',
'description' => 'Mechanic ยท CRAFTSMAN',
'price' => '$149.99',
'source' => 'Sears',
'stars' => 4.5999999999999996447286321199499070644378662109375,
'reviews' => 1084,
'thumbnail' => 'data:image/jpeg;base64,/',
'extensions' =>
array (
),
'product_id' => '13276029442981215243',
'price_parsed' =>
(object) array(
'currency' => 'USD',
'value' => 149.990000000000009094947017729282379150390625,
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
);
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
I am trying to proceed single payout with Paypal Sandbox. The error I am getting is:
'MALFORMED_REQUEST_ERROR' - 'Json request malformed.'
After receiving the token successfully, I setup the single payment details array and encode json, and then use curl to post it, but no luck. The code goes like:
if ($token) {
$ch = curl_init();
$data = [
'sender_batch_header' => [
'email_subject' => "You have a payment",
'sender_batch_id' => '184328423'
],
'items' => [
'recipient_type' => "EMAIL",
'amount' => [
'value' => 12.00,
'currency' => "USD"
],
'receiver' => 'test123test#hotmail.com',
'note' => 'Hello World',
'sender_item_id' => "123"
],
];
$headers = [
'Content-Type:application/json',
'Authorization:Bearer ' . $token,
];
curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/payments/payouts?sync_mode=true");
// curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
if(empty($result))die("Error: No response.");
else
{
$json = json_decode($result);
print_r($json);
}
curl_close($ch);
}
It took some time for me to notice it. The answer:
$data = [
'sender_batch_header' => [
'email_subject' => "You have a payment",
'sender_batch_id' => $randId
],
'items' => [
[
'recipient_type' => "EMAIL",
'amount' => [
'value' => "12.00",
'currency' => "USD"
],
'receiver' => 'test123test#hotmail.com',
'note' => 'Hello World',
'sender_item_id' => "A123"
],
],
];