How to add php variable in json? - php

I want to send email using Sendinblue API in php.
I added some php variable in the email code, but the script is not working!
<?php
$email = "12345#gmail.com";
$username = "12345";
$html = "<h1>Hi!</h1>";
$subject = "Hello";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sendinblue.com/v3/smtp/email",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\"sender\":{\"name\":\"ABC\",\"email\":\"abc#abc.com\"},\"to\":[{\"email\":\".$email.\",\"name\":\".$username.\"}],\"bcc\":[{\"email\":\"admin#abc.com\",\"name\":\"Admin\"}],\"htmlContent\":\".$html.\",\"subject\":\".$subject.\"\"replyTo\":{\"email\":\"support#abc.com\",\"name\":\"Support\"}}",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"api-key: API-KEY", //hidden because of privacy reason
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
However, I receive this error message:
{"error":{"status":400,"message":"Input must be a valid JSON object","code":"bad_request"}}

Update
$email = "12345#gmail.com";
$username = "12345";
$html = "<h1>Hi!</h1>";
$subject = "Hello";
with
$arr = [
'email'=>"12345#gmail.com",
'username'=>"12345",
'html'=>"<h1>Hi!</h1>",
'subject'=>"Hello",
];
$postData = json_encode( $arr );
Put encode string in curl
CURLOPT_POSTFIELDS => $postData

Related

How to access the CURL to get the json data from php

How to access the CURL to get the json data from php.
By the way, I am using codeigniter framework.
This is curl data:
curl -u <YOUR_KEY_ID>:<YOUR_SECRET> \
-X POST https://api.razorpay.com/v1/orders \
-H "content-type: application/json" \
-d '{
"amount": 50000,
"currency": "INR",
"receipt": "receipt#1"
}'
and this my possible work to cosume it:
$url = 'https://api.razorpay.com/v1/orders';
$curl = curl_init($url);
$data = json_encode(array(
'receipt'=> $orderId,
'amount'=>$amount,
'currency'=> 'INR'
), JSON_FORCE_OBJECT);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json'
//$keyId.':'.$secretKey
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
Please help me to consume it!!
I am in trouble and also in hurry!!
If the response like :
[{"data1":"value1","data1.1":"value1.1"},{"data2":"value2","data2.1":"value2.1"}...]
Use :
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$json = file_get_contents('thelink', false, stream_context_create($arrContextOptions));
$result = json_decode($json, true);
and call it like :
echo $result[0]["data1"];
echo $result[0]["data1.1"];
echo $result[0]["data2"];
echo $result[0]["data2.1"];
If you still want to use curl (example on weatherAPI) :
<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://weatherapi-com.p.rapidapi.com/forecast.json?q=London&days=1",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"x-rapidapi-host: weatherapi-com.p.rapidapi.com",
"x-rapidapi-key: aaaaxxxxbbbb"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$weather = json_decode($response);;
}
?>
Try this, I keep this for whenever I need to consume and API,
$url = 'https://api.razorpay.com/v1/orders';
$curl = curl_init();
$obj = new StdClass();
$obj->receipt = $orderId;
$obj->amount = $amount;
$obj->currency = 'INR';
$payload = json_encode($obj);
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 => $payload,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
//$keyId.':'.$secretKey
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
Get your response and handle any errors, maybe you are just missing a comma in your headers array

Using PHP CURL to Post Data from While Loop in JSON API

The data I want to post into the json api body below is from a while loop. So I want to Select from the database and send multiple students data from the database. I can post individually but I'm unable to do it from a loop. How please? Thanks.
{
"students":[
{
"admissionNumber": "2010",
"class":"js one"
},
{
"admissionNumber": "2020",
"class":"ss one"
}
],
"appDomain":"www.example.com"
}
Here's my code:
if(isset($_POST['submit'])){
$sql = "SELECT * FROM students";
while($row = mysqli_fetch_array($sql){
$admissionNumber = $row['admNo'];
$class = $row['class'];
$data = array('students' => array(['admissionNumber' => $admNo, 'class' => $class]),
'appDomain' => "http://example.com",
);
echo $data;
$url = 'https://the-end-point';
$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(
"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 "<script>
alert(' Student Created Successfully!');
window.location = '.../students.php';
</script>";
}
}
}

Cannot recieve header information via PHP but with Postman [duplicate]

This question already has answers here:
Can PHP cURL retrieve response headers AND body in a single request?
(16 answers)
Closed 3 years ago.
I'm trying to get a Token in the header of an POST request. With Postman it works but when I run this in PHP I get the right content but cannot extract the header information.
I have copied the PHP code generated in Postman but I cannot extract the header information. I only get the content.
The code I used:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://xxxx.yyyy.xy/xxxxxx/xxxxxxxxxxx",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"Authorization: Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"Content-Type: application/x-www-form-urlencoded",
"Postman-Token: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
The header should include "Token".
I cannot recieve any header information.
I found a solution on the problem:
<?php
$curl = curl_init();
$Username = "XXXXXXXXX";
$Password = "YYYYYYYYYY";
$Credentials = base64_encode($Username.':'.$Password);
$Credentials_Auth = "Authorization: Basic ".$Credentials;
// echo "<br>Cred-auth: ".$Credentials_Auth."<br>";
curl_setopt_array($curl, array(
CURLOPT_URL => "https://XXXXXXXXX/YYYYYYYYYYY/ZZZZZZZZZZZ",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
**CURLOPT_HEADER => 1,**
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
$Credentials_Auth,
"Content-Type: application/x-www-form-urlencoded",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) { echo "cURL Error #:" . $err;}
else { echo $response; }
**$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);**
curl_close($curl);
**header("Content-Type:text/plain; charset=UTF-8");
echo $headers;
echo $body;**
?>

Woocommerce REST API incorrect signature

I currently want to make a plugin for Woocommerce for some personal stuff I was trying to connect through the API but I get:
{"code":"woocommerce_rest_authentication_error","message":"Invalid
signature - provided signature does not match.","data":{"status":401}}
Would anyone know where the signature isn't valid?
my curl request:
$curl = curl_init();
$cnonce = hash('sha256', makeRandomString());
$requesturl = "http://my-marketplace.test/wp-json/wc/v2/products";
$timestamp = time();
$signature = createSignature($requesturl,$consumerKey, $consumerSecret, $timestamp, $cnonce);
echo $signature;
curl_setopt_array($curl, array(
CURLOPT_URL => $requesturl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"authorization: OAuth oauth_consumer_key=\"".$consumerKey."\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"".$timestamp."\",oauth_nonce=\"".$cnonce."\",oauth_signature=\"".$signature,
"cache-control: no-cache",
"content-type: multipart/form-data",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
And my createSignature() function:
function createSignature($myurl, $consumerKey, $consumerSecret, $timestamp, $cnonce){
$sig = "GET&".rawurlencode($myurl)."&";
$sig = $sig.rawurlencode("oauth_consumer_key=".$consumerKey."&
oauth_signature_method=HMAC-SHA1&
oauth_timestamp=".$timestamp."&
oauth_nonce=".$cnonce);
return hash_hmac ( "sha1",$sig, $consumerSecret);
}

ALM SaaS REST API 12.50 not working in PHP

I have tried below code in PHP to get the defect details from ALM but its not showing any response in browser. But the same is working in POSTMAN . Can someone help me here
Here is the document of REST API USAGE REST DOCUMENT FROM ALM
I have already tried existing posts from Stackoverflow
HP ALM REST API login using PHP CURL
ALM REST API v12.50 error 401
Nothing is helping so posted a new question
Note : Due to security purpose header value is kept as encoded value
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://hostname/qcbin/api/domains/domainname/projects/projectname/defects/?limit=10",
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(
"authorization: Basic encoded value",
"cache-control: no-cache",
"postman-token: a8a2398d-7a0a-0ebd-a586-58a40e524a9a"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
I have finally found the solution and below is the approach
First we need get to LWSSO_COOKIE_KEY,QCSession,ALM_USER,XSRF_TOKEN values from the ALM Authentication link then we should use the values for subsequent calls
Below is the complete working code to get the list of defects by entering ALM Credentials
<?php
$curl = curl_init();
Header('Content-type: application/json');
$credentials = "username:password";
curl_setopt_array($curl, array(
CURLOPT_URL => "https://host:port/qcbin/api/authentication/sign-in",
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADER => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode($credentials) ,
"cache-control: no-cache"
) ,
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
}
else
{
// If there is no error then get the response to form the array of headers to get the different values required
$array_start = explode(';', $response);
foreach ($array_start as $key => $value) {
$remove_from_string = ['HTTP/1.1 200 OK','Path=/','HTTPOnly','HttpOnly','Content-Length',': 0'];
$replace_array = ['','','','','',''];
$value = str_replace($remove_from_string,$replace_array,$value);
$value = trim(preg_replace(('/Expires: [a-zA-Z]+, [0-9]+ [a-zA-Z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+ [a-zA-Z]+/'), '', $value));
$value = trim(preg_replace(('/Server: [a-zA-Z0-9.\(\)]+/'),'',$value));
if (!empty($value)) {
$almheaders[trim(explode('=',$value)[0])] = explode('=',$value)[1];
}
}
$LWSSO_COOKIE_KEY = $almheaders['Set-Cookie: LWSSO_COOKIE_KEY'];
$QCSession = $almheaders['Set-Cookie: QCSession'];
$ALM_USER = $almheaders['Set-Cookie: ALM_USER'];
$XSRF_TOKEN = $almheaders['Set-Cookie: XSRF-TOKEN'];
// Now form the Cookie value from the above values.
$cookie = "Cookie: JSESSIONID=33eyr1y736486zcnl0vtmo12;XSRF-TOKEN=$XSRF_TOKEN;QCSession=$QCSession;ALM_USER=$ALM_USER;LWSSO_COOKIE_KEY=$LWSSO_COOKIE_KEY";
// echo $cookie;
$curl = curl_init();
Header('Content-type: application/json');
curl_setopt_array($curl, array(
CURLOPT_URL => "https://host:port/qcbin/api/domains/CET_NTD/projects/BILLING_OPERATIONS/defects",
// CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode($credentials) ,
"cache-control: no-cache",
"Accept: application/json",
$cookie
) ,
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
}
else
{
echo $response;
}
}
?>

Categories