Curl to wp_remote_post convert - php

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

Related

convert curl post to wp_remote_post

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

How to find x-identity & x-signature in Bitpay (docs)

I'm integrating bitpay in my project
but when i hit api "https://test.bitpay.com/invoices" it give response { error : "Invalid-Signature" }
https://bitpay.com/api/#rest-api-resources-invoices-create-an-invoice
$resourceUrl = 'https://test.bitpay.com/invoices';
$postData = json_encode([
'currency' => 'EUR',
'price' => 10,
'orderId' => 'MerchantOrder123',
'fullNotifications' => true,
'extendedNotifications' => true,
'transactionSpeed' => 'medium',
'notificationURL' => 'https://yournotificationurl.com',
'notificationEmail' => 'merchant#email.com',
'redirectURL' => 'https://yourredirecturl.com',
'buyer' => [
'email' => 'fox.mulder#trustno.one',
'name' => 'Fox Mulder',
'phone' => '555-123-456',
'address1' => '2630 Hegal Place',
'address2' => 'Apt 42',
'locality' => 'Alexandria',
'region' => 'VA',
'postalCode' => '23242',
'country' => 'US',
'notify' => true
],
'posData' => 'tx1234',
'itemDesc' => 'Item XYZ',
'token' => '6oE1tYw1xMqUjM97dk57cwbda5sxbXTkUgg7UKpwkzEE'
]);
$curlCli = curl_init($resourceUrl);
curl_setopt($curlCli, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curlCli, CURLOPT_HTTPHEADER, [
'x-accept-version: 2.0.0',
'Content-Type: application/json',
'x-identity: 02e6228330bb3f4887ec4eb650dc52d668172a7de39076281e030c03bba10bd8a6',
'x-signature: 304502207f4ee84d8d2ff46439ed3958c1b2a1c3efefba0455d5d4ce213d855075bd6353022100ccf8df1b6f1934124ddbc034fb0eddab6bba0a538919bb87a6cf5a0a8f030fda'
]);
curl_setopt($curlCli, CURLOPT_POSTFIELDS, stripslashes($postData));
$result = curl_exec($curlCli);
curl_close($curlCli);
echo $result;

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

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

Yammer ID from Email (Wordpress PHP)

I'm trying to get the yammer ID of a user based on an email address, I wrote this
$emailx="email#email.com";
function get_yammer_id($email){
$url = 'https://www.yammer.com/api/v1/users/by_email.json';
$response = wp_remote_get( $url, array(
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Host' => 'www.yammer.com', 'Authorization' => 'Bearer ********-**********************' ),
'body' => array( 'email' => $email),
'cookies' => array()
)
);
$return = $response;
return $return;
}
$result = get_yammer_id($emailx);
echo $result;
The last echo greets me with "Array" though.
If I try to swap it for
echo $result[0];
I'll get nothing. Any ideas?
It may not be the best solution but I found one
$emailx="email#email.com";
function get_yammer_id($email){
$url = 'https://www.yammer.com/api/v1/users/by_email.json';
$response = wp_remote_get( $url, array(
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Host' => 'www.yammer.com', 'Authorization' => 'Bearer *******-*********************' ),
'body' => array( 'email' => $email),
'cookies' => array()
)
);
$return = (explode(",",$response['body']));
return (int)str_replace('"id":', '', $return[1]);
}
$result = get_yammer_id($emailx);
echo $result;
Does anyone have a better one?

Categories