How to send parameters in curl in php - php

How would I write below command in curl php:
curl -XPOST https://apiv2.unificationengine.com/v2/message/send
–data
“{ \"message\”: { \“receivers\”: [{\“name\”: \“TO_NAME \”,
\“address\”: \“TO_EMAILADDRESS\” ,
\“Connector\”: \“UNIQUE_CONNECTION_IDENTIFIER\”,
\“type\”: \“to\”}],\“sender\”: {\“address\”: \“EMAIL_ADDRESS\”},
\“subject\”:\“Hello\”,\“parts\”: [{\“id\”: \“1\”,
\“contentType\”: \“text/plain\”,
\“data\”:\“Hi welcome to UE\” ,
\“size\”: 100,\“type\”: \“body\”,\“sort\”:0}]}}“
-u USER_ACCESSKEY:USER_ACCESSSECRET -k
if this is the right way to execute and write curl in php:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://abcproject.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
Here is more sample code SO question.
But I am finding problem that where to mentions -u, --data options in php curl.

curl -u is equivalent to CURLOPT_USERPWD in php-curl.
You set it with curl_setopt, as the others.
--data is CURLOPT_POSTFIELDS, which you are already sending. But in your case you'd want to populate with the json you want to send.
If you are sending a JSON, you'd do well in setting the Content-type header (and content-length wouldn't be amiss either)
Be careful, in your example call there are some weird characters. But the JSON you posted is equivalent to:
$yourjson = <<<EOF
{
"message": {
"receivers": [
{
"name": "TO_NAME ",
"address": "TO_EMAILADDRESS",
"Connector": "UNIQUE_CONNECTION_IDENTIFIER",
"type": "to"
}
],
"sender": {
"address": "EMAIL_ADDRESS"
},
"subject": "Hello",
"parts": [
{
"id": "1",
"contentType": "text/plain",
"data": "Hi welcome to UE",
"size": 100,
"type": "body",
"sort": 0
}
]
}
}
EOF;
But usually you'd start with your data in array form and json_encode it.
So you'd start with something like:
$array = [
'message' =>
[
'receivers' =>
[
0 =>
[
'name' => 'TO_NAME ',
'address' => 'TO_EMAILADDRESS',
'Connector' => 'UNIQUE_CONNECTION_IDENTIFIER',
'type' => 'to',
],
],
'sender' =>
[
'address' => 'EMAIL_ADDRESS',
],
'subject' => 'Hello',
'parts' =>
[
0 =>
[
'id' => '1',
'contentType' => 'text/plain',
'data' => 'Hi welcome to UE',
'size' => 100,
'type' => 'body',
'sort' => 0,
],
],
],
];
... convert that using $yourjson = json_encode($array), and that's it.
E.g.:
// you already have your json inside of $yourjson,
// plus your username and password in their respective variables.
curl_setopt($ch, CURLOPT_USERPWD, "$user:$pass");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_POSTFIELDS, $yourjson);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($yourjson)
]
);

to send data as JSON add header content-type and set as JSON and add the option CURLOPT_USERPWD, something like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://apiv2.unificationengine.com/v2/message/send");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS,
“{ \"message\”: { \“receivers\”: [{\“name\”: \“TO_NAME \”, \“address\”: \“TO_EMAILADDRESS\” , \“Connector\”: \“UNIQUE_CONNECTION_IDENTIFIER\”, \“type\”: \“to\”}],\“sender\”: {\“address\”: \“EMAIL_ADDRESS\”},\“subject\”:\“Hello\”,\“parts\”: [{\“id\”: \“1\”,\“contentType\”: \“text/plain\”, \“data\”:\“Hi welcome to UE\” ,\“size\”: 100,\“type\”: \“body\”,\“sort\”:0}]}}“);
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$server_output = curl_exec ($ch);
curl_close ($ch);

Related

I want to recive long url from instamojo payment respose script option in a php

I'm integrating the Instamojo payment gateway into a website using core PHP.
I wrote some script that is working well enough on the test.instamojo.com (Which is a test version of their portal) but When I changed the credentials for the live testing (means I have removed test level credentials and put all real-time credentials like their live URL, Private key, Auth Key of our account) It's started showing error in the variable where I want to receive the long URL to redirect for the payment.
The Instamojo response is
{
"success": true,
"payment_request": {
"id": "47a321d9*****************bbb55f64",
"phone": "+9170******55",
"email": "a*******#gmail.com",
"buyer_name": "Aman",
"amount": "100.00",
"purpose": "FIFA",
"expires_at": null,
"status": "Pending",
"send_sms": true,
"send_email": true,
"sms_status": "Pending",
"email_status": "Pending",
"shorturl": null,
"longurl": "https://www.instamojo.com/#EXAMPLE/47a321d95c5c4d7f8e0e7742bbb55f64",
"redirect_url": "http://www.example.com/thankyou.php/",
"webhook": null,
"allow_repeated_payments": false,
"created_at": "2022-09-10T09:16:12.104302Z",
"modified_at": "2022-09-10T09:16:12.104336Z"
}
}
This is my Php Code
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.instamojo.com/api/1.1/payment-requests/');
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array("X-Api-Key:*****************************************",
"X-Auth-Token:**************************************"));
$payload = Array(
'purpose' => 'FIFA',
'amount' => '100',
'phone' => '70*****55',
'buyer_name' => 'Aman',
'redirect_url' => 'http://www.example.com/thankyou.php/',
'send_email' => true,
'send_sms' => true,
'email' => 'a******#gmail.com',
'allow_repeated_payments' => false
);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
$response = curl_exec($ch);
curl_close($ch);
header('location:'.$response->payment_request->longurl);
?>
I'm getting an error (red line within $ response) at
header('location:'.$response->payment_request->longurl);
The use of json_decode() and traverse to data you want
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.instamojo.com/api/1.1/payment-requests/');
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array("X-Api-Key:*****************************************",
"X-Auth-Token:**************************************"));
$payload = Array(
'purpose' => 'FIFA',
'amount' => '100',
'phone' => '70*****55',
'buyer_name' => 'Aman',
'redirect_url' => 'http://www.example.com/thankyou.php/',
'send_email' => true,
'send_sms' => true,
'email' => 'a******#gmail.com',
'allow_repeated_payments' => false
);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
$response = curl_exec($ch);
curl_close($ch);
header('location:'.json_decode($response, true)['payment_request']['longurl']);
?>

How to pass an object into the http client request?

I have tried making a HTTP request using CURL as below:
$rawQuery = '{
"CUSTNAME" : "1970188",
"CURDATE":"2020-12-28T00:00:00+02:00",
"BOOKNUM":"Test BookNum",
"DETAILS":"Test Details"
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://somelink.co.de");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "username:password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $rawQuery);
$curl_response = curl_exec($ch);
This one is returning me result. But when I try to implement the same using Symfony HTTP Client, I am getting 400 error.
This is the code, I have tried.
$response = $this->client->request('POST', $url, [
'auth_basic' => [
'username',
'password'
],
'headers' => [
'Accept' => 'application/json',
],
'json' => $rawQuery
]);
I am not sure what I am missing in Client
Can anybody please help me ?
Your Raw query is incorrect.. This should be a php array, Symfony is trying to json_encode() this for you when you use the 'json' key in the request. Reformat your $rawQuery to be
$rawQuery = [
"CUSTNAME" => "1970188",
"CURDATE" => "2020-12-28T00:00:00+02:00",
"BOOKNUM" => "Test BookNum",
"DETAILS" => "Test Details"
];

How to Create Shopify Order Via Api using Php?

I am trying to Create a Shopify Order using Api this is my code :
$arrOrder= array(
"email"=> "foo#example.com",
"fulfillment_status"=> "fulfilled",
"send_receipt"=> true,
"send_fulfillment_receipt"=> true,
"line_items"=> array(
array(
"product_id"=>875744960642,
"variant_id"=> 3558448932592,
"quantity"=> 1
)
),
"customer"=> array(
"id"=> 458297751235
),
"financial_status"=> "pending"
); echo json_encode($arrOrder);
echo "<br />";
$url = "https://AkiKey:Password#Store.myshopify.com/admin/api/2021-01/orders.json";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($arrOrder));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
curl_close($curl);
echo "<pre>";
print_r($response);
and the response is :
{"errors":{"order":"Required parameter missing or invalid"}}
I think there is some data mismatch that is sent using API Call, according to the documentation this the format to create an order.
So I think your request is something like this one demo code
$arrOrder= [
"order" =>[
"email" => "foo#example.com",
"fulfillment_status" => "fulfilled",
"send_receipt" => true,
"send_fulfillment_receipt" => true,
"line_items" => [
[
"product_id" => 875744960642,
"variant_id" => 3558448932592,
"quantity" => 1
]
],
"customer" => [
"id"=> 458297751235
],
"financial_status"=> "pending"
]
];

Error on PHP cURL with POST Method [duplicate]

I want to extract data from this URL with Php Curl:
https://www.traveloka.com/en/flight/fullsearch?ap=JKTA.DPS&dt=14-10-2017.NA&ps=1.0.0&sc=ECONOMY
But I got the following error:
"{"errorType":"SERVER_ERROR","userErrorMessage":"Unexpected server error occurred. We apologize for the inconvenience. Please try again later.","errorMessage":"Exception occurred in server."}".
How I can extract the data from that link with php curl?
Here is my code
$url = 'https://api.traveloka.com/en/v2/flight/search/oneway';
$params = [
'context' => [
'tvLifetime' => 'eTq6r7InDN+j0vrg5Bujah9yFLWfBGsNGWxzjTBUa/jvVfn8fy/IF40U7OQl0vjmoqMJwuSocopqxISYLLi6YlngzuFViHSWhNHdFgs+49yydWXm5gSjBRwDBFuO0UKHd+B69Ip0Tk1qnKH+oyzW43f2GdS7QOd10yBpqoCOyOk73cVe4oyqCjYUR7X72PoHr14UQNQEUjl1NP5Mcxp+1Gw6RzKF7uV7jMRzmsYbGfGKpYLfsYtxaSx1t35KGWOO605YN9Mj2n5kP5fOD7j2KA9adtfLBtEymWXf6tEt3ug8oBVyzj5c2/pp/hboYilQnDRCih+RwhV5WX7hPTw9IsKapSNtWZ1NX8biH7UyYuhNLgcLK03OS4WNpoO+NphjOPKh09oBpUgrEJ0UqeY+1rfj98lWMAdpMO5rp2E5pvmP7HRuW6CqBwSchPLtVPQAi7ceDGYgYneH+AfodZMd5A==',
'tvSession' => '9tCFUug+5pqBk0WdAmwAbThaxD2lAm75JaxFJenJTB2MkEWW7bwVa5FW83NZnCLnlL2TAAijDDIDfD9YbC7NhRws3r5fKxPj62n1bJ+Nck309g3Rkogk+dtxsoMRpFHbkVkEJbYuNFbd9Ckp9iEBGg==',
'nonce' => '5eebdd23-2574-4465-afa7-cecc94b8f909'
],
'clientInterface' => 'desktop',
'data' => [
'currency' => 'IDR',
'destinationAirportOrArea' => 'DPS',
'flightDate' => [
'day' => '14',
'month' => '10',
'year' => '2017'
],
'isReschedule' => 'false',
'locale' => 'en_ID',
'newResult' => 'true',
'numSeats' => [
'numAdults' => '1',
'numChildren' => '0',
'numInfants' => '0'
],
'seatPublishedClass' => 'ECONOMY',
'seqNo' => 'null',
'sortFilter' => [
'filterAirlines' => [],
'filterArrive' => [],
'filterDepart' => [],
'filterTransit' => [],
'selectedDeparture' => '',
'sort' => 'null'
],
'sourceAirportOrArea' => 'JKTA',
'searchId' => 'null',
'usePromoFinder' => 'false',
'useDateFlow' => 'false'
],
'fields' => []
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_REFERER, "https://www.traveloka.com/en/flight/fullsearch?ap=JKTA.DPS&dt=14-10-2017.NA&ps=1.0.0&sc=ECONOMY");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Host: api.traveloka.com",
"Accept: application/json, text/javascript, */*; q=0.01",
"Accept-Language: en-us,en;q=0.5",
"X-Requested-With: XMLHttpRequest",
"Connection: keep-alive",
"Pragma: no-cache",
"Cache-Control: no-cache")
);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
Actually I'm not doing screen crawling, but I want to crawl its json data. I open the "Network" Tab in browser and see the XHR section, and then I want to grab the response from that XHR section. So how to do it and what's wrong with my code?
As per the URL you have given using the below code, you would get nothing rather the redirection link:
Replace with the link and parameters with the correct api:
General format of using CURL is given here:
$ch = curl_init();
$params = urldecode('{"ap":"' . 'JKTA.DPS' . '","dt":"' . '14-10-2017.NA' . '","ps":"' . '1.0.0'. '","sc":"' . 'ECONOMY'. '"}');
$url = 'https://www.traveloka.com/en/flight/fullsearch?JsonData=' . $params;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0");
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
if (!empty($output)) {
$x = json_decode($output, true);
var_dump($x);
}else{
return FALSE;
}
What you want to do is called Web scraping, there are plenty of tools that you can use to do that.
For now, go for:
https://github.com/FriendsOfPHP/Goutte
or https://github.com/duzun/hQuery.php.

Error on cURL with POST data

I want to extract data from this URL with Php Curl:
https://www.traveloka.com/en/flight/fullsearch?ap=JKTA.DPS&dt=14-10-2017.NA&ps=1.0.0&sc=ECONOMY
But I got the following error:
"{"errorType":"SERVER_ERROR","userErrorMessage":"Unexpected server error occurred. We apologize for the inconvenience. Please try again later.","errorMessage":"Exception occurred in server."}".
How I can extract the data from that link with php curl?
Here is my code
$url = 'https://api.traveloka.com/en/v2/flight/search/oneway';
$params = [
'context' => [
'tvLifetime' => 'eTq6r7InDN+j0vrg5Bujah9yFLWfBGsNGWxzjTBUa/jvVfn8fy/IF40U7OQl0vjmoqMJwuSocopqxISYLLi6YlngzuFViHSWhNHdFgs+49yydWXm5gSjBRwDBFuO0UKHd+B69Ip0Tk1qnKH+oyzW43f2GdS7QOd10yBpqoCOyOk73cVe4oyqCjYUR7X72PoHr14UQNQEUjl1NP5Mcxp+1Gw6RzKF7uV7jMRzmsYbGfGKpYLfsYtxaSx1t35KGWOO605YN9Mj2n5kP5fOD7j2KA9adtfLBtEymWXf6tEt3ug8oBVyzj5c2/pp/hboYilQnDRCih+RwhV5WX7hPTw9IsKapSNtWZ1NX8biH7UyYuhNLgcLK03OS4WNpoO+NphjOPKh09oBpUgrEJ0UqeY+1rfj98lWMAdpMO5rp2E5pvmP7HRuW6CqBwSchPLtVPQAi7ceDGYgYneH+AfodZMd5A==',
'tvSession' => '9tCFUug+5pqBk0WdAmwAbThaxD2lAm75JaxFJenJTB2MkEWW7bwVa5FW83NZnCLnlL2TAAijDDIDfD9YbC7NhRws3r5fKxPj62n1bJ+Nck309g3Rkogk+dtxsoMRpFHbkVkEJbYuNFbd9Ckp9iEBGg==',
'nonce' => '5eebdd23-2574-4465-afa7-cecc94b8f909'
],
'clientInterface' => 'desktop',
'data' => [
'currency' => 'IDR',
'destinationAirportOrArea' => 'DPS',
'flightDate' => [
'day' => '14',
'month' => '10',
'year' => '2017'
],
'isReschedule' => 'false',
'locale' => 'en_ID',
'newResult' => 'true',
'numSeats' => [
'numAdults' => '1',
'numChildren' => '0',
'numInfants' => '0'
],
'seatPublishedClass' => 'ECONOMY',
'seqNo' => 'null',
'sortFilter' => [
'filterAirlines' => [],
'filterArrive' => [],
'filterDepart' => [],
'filterTransit' => [],
'selectedDeparture' => '',
'sort' => 'null'
],
'sourceAirportOrArea' => 'JKTA',
'searchId' => 'null',
'usePromoFinder' => 'false',
'useDateFlow' => 'false'
],
'fields' => []
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_REFERER, "https://www.traveloka.com/en/flight/fullsearch?ap=JKTA.DPS&dt=14-10-2017.NA&ps=1.0.0&sc=ECONOMY");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Host: api.traveloka.com",
"Accept: application/json, text/javascript, */*; q=0.01",
"Accept-Language: en-us,en;q=0.5",
"X-Requested-With: XMLHttpRequest",
"Connection: keep-alive",
"Pragma: no-cache",
"Cache-Control: no-cache")
);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
Actually I'm not doing screen crawling, but I want to crawl its json data. I open the "Network" Tab in browser and see the XHR section, and then I want to grab the response from that XHR section. So how to do it and what's wrong with my code?
As per the URL you have given using the below code, you would get nothing rather the redirection link:
Replace with the link and parameters with the correct api:
General format of using CURL is given here:
$ch = curl_init();
$params = urldecode('{"ap":"' . 'JKTA.DPS' . '","dt":"' . '14-10-2017.NA' . '","ps":"' . '1.0.0'. '","sc":"' . 'ECONOMY'. '"}');
$url = 'https://www.traveloka.com/en/flight/fullsearch?JsonData=' . $params;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0");
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
if (!empty($output)) {
$x = json_decode($output, true);
var_dump($x);
}else{
return FALSE;
}
What you want to do is called Web scraping, there are plenty of tools that you can use to do that.
For now, go for:
https://github.com/FriendsOfPHP/Goutte
or https://github.com/duzun/hQuery.php.

Categories