How to send cURL request in json by using php - arrays

I need to curl following input string for GoGoVan API
curl -X GET \
-H 'GoGoVan-API-Key: 3af4ba76-3767-4963-9680-327bb6d391d1' \
-H 'GoGoVan-User-Language: en-US' \
-F 'order[name]=John' \
-F 'order[phone_number]=61577364' \
-F 'order[pickup_time]=2016-01-20T18:00:00H' \
-F 'order[service_type]=delivery' \
-F 'order[vehicle]=motorcycle' \
-F 'order[title_prefix]=Corporate Order' \
-F 'order[extra_requirements][express_service]=true' \
-F 'order[extra_requirements][remark]=Please confirm the following 3 items' \
-F 'order[locations]=[[1.333948, 103.840142,"Toa Payoh, Singapore"],[1.353945, 103.843884,"5G Jalan Berjaya, Singapore"]]' \
'https://gogovan-staging-sg.herokuapp.com/api/v0/orders/price.json'
I'm using Following code to create query
$query = urlencode(json_encode(array(
'order' => array(
'name' => 'john',
'phone_number' => '61577364' ,
'pickup_time' => '2017-07-18T18:00:00H',
'service_type' => 'delivery',
'vehicle' => 'motorcycle',
'title_prefix' => 'Corporate Order',
'extra_requirements' => array(
'express_service' => 'true',
'remark'=> 'Please confirm the following 3 items'
),
'locations' => array(
'1.333948, 103.840142,"Toa Payoh, Singapore"',
'1.353945, 103.843884,"5G Jalan Berjaya, Singapore"'
)
)
))));
$apifullurl = "https://gogovan-staging-sg.herokuapp.com/api/v0/orders/price.json";
$apifullurl = $apifullurl . '?json=' . $query;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $apifullurl);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'GoGoVan-API-Key: 3af4ba76-3767-4963-9680-327bb6d391d1',
'GoGoVan-User-Language: en-US'
)
);
$response = curl_exec($curl);
echo print_r($response);
$err_status = curl_error($curl);
curl_close($curl);
Response output that I get is null
{
"breakdown": {
"fee": {
"title": "Fee",
"value":null
}
},
"base": null,
"total": 0,
"payment_method": "cash"
}1
whereas there should be output like :
{
"base" : 10,
"total" : 35,
"breakdown" : {
"fee" : {
"title" : "Fee",
"value" : 30
},
"extra_charge_for_express":{
"title":"Express service",
"value":3
},
"multi_point_concession":{
"title":"Promotional Discount",
"value":-3
},
},
}
}

I also have same query. I think something wrong in query generation for following curl
order[locations] = [
[
1.333948,
103.840142,
"Toa Payoh, Singapore"
],
[
1.353945,
103.843884,
"5G Jalan Berjaya, Singapore"
]
]
It is an array of array. means multidimensional array .

Related

Capture data from CSV file contain variable for API request to save in new CSV file

I need the tracking number and order number when every line of Unique ID send the API request to the URL, and capture it to save in the new CSV file altogether with the API response.I really need help for this :/
packet.csv (CSV file contains variable for API request)
- Tracking #,Order #,Unique ID
- AB74832493,0dajKDhsa,478324
- CD78437294,kDHIdsan98,768542
track.csv (API response)
delivered,"2020-04-21 13:10:12"
delivered,"2020-02-29 12:55:51"
delivered,"2020-04-21 12:42:16"
desired track.csv (API response) :
Tracking #,Order#,Status,Date ((get the tracking and order from packet.csv)
0CS7lPuyKzO6,YT2010421266182766,delivered,"2020-04-21 13:10:12"
327231739327,YT7328729173217832,delivered,"2020-02-29 12:55:51"
743287493274,YT7438749327489324,delivered,"2020-04-21 12:42:16"
Controller :
public function getstatusbyid()
{
$csv_file = file('C:\wamp64\www\tetsing\application\csv\packet.csv');
$csv_data = [];
foreach ($csv_file as $line) {
$csv_data[] = str_getcsv($line);
}
$order_no = json_encode(array_column($csv_data, '0'));
$tracking = json_encode(array_column($csv_data, '1'));
$unique_id = array_column($csv_data, '2');
$access_key = 'SOMETHING';
if (FALSE === ($fp = fopen('C:\wamp64\www\testing\application\csv\track.csv', 'w'))) {
die("Error opening CSV file."); // TO DO: handle this better
}
foreach ($unique_id as $i => $id) {
$url = "https://track.my/api/getstatusbyid/$id";
$data = array(
'unique_id' => $id,
'access_key' => $access_key
);
$data_string = json_encode($data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 120);
$result = curl_exec($curl);
curl_close($curl);
$resultinfo = json_decode($result, true);
echo '<pre>';
print_r($resultinfo);
$status = $resultinfo["status"];
$date = $resultinfo["last_action_date_time"];
$resultdata = array();
$resultdata[] = array(
'status' => $status,
'date' => $date
);
if ($status == 'delivered') {
foreach ($resultdata as $fields) {
fputcsv($fp, $fields);
}
}
}
fclose($fp);
}
See this updated code, with comments to describe what's happening. Basically, you need to loop through each line in packet.csv, make the appropriate cURL call, and output the results:
public function getstatusbyid()
{
$access_key = 'SOMETHING';
$url = "https://track.my/api/getstatusbyid/$id";
if (FALSE === ($fp = fopen('C:\wamp64\www\testing\application\csv\track.csv', 'w'))) {
die("Error opening CSV file."); // TO DO: handle this better
}
$csv_file = file('C:\wamp64\www\tetsing\application\csv\packet.csv');
// Loop through each line in packet.csv:
foreach ($csv_file as $line) {
$csv_data = str_getcsv($line); // Get the next line
list( $order_no, $tracking, $id ) = $csv_data; // Split it up
$data = array(
'unique_id' => $id,
'access_key' => $access_key
);
$data_string = json_encode($data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 120);
$result = curl_exec($curl);
curl_close($curl);
$resultinfo = json_decode($result, true);
echo '<pre>';
print_r($resultinfo);
$status = $resultinfo["status"];
$date = $resultinfo["last_action_date_time"];
// Create the array of data to output:
$resultdata = array(
'tracking' => $tracking,
'order' => $order_no,
'status' => $status,
'date' => $date
);
if ($status == 'delivered') {
fputcsv($fp, $resultdata);
}
}
fclose($fp);
}

Is this the correct way to create and post a mutipart form data in CakePhp3?

I am trying to post a mutipart form data in CakePhp3. The form should contain a few information about the user (text fields) and an image.
I'm doing something like this:
$request = [
'fistname'=>$user->firstname,
'lastname'=>'$user->lastname',
'_session'=>'$session'
];
$form = new FormData();
foreach ($request as $key => $value) {
$form->add($key,$request);
}
$file = $form->addFile('upload',fopen(WWW_ROOT.'img/picture.png','r'));
$file->contentId('mypicture'); // <-- not sure what this is
$file->disposition('attachment');
$response = $http->post(
$url,
(string)$form,
['headers' => ['Content-Type' => $form->contentType()]]
);
Is this the correct way to create and post a mutipart form data in CakePhp3?
Thanks for your help.
EDIT
If I post to my own server it seems to be working (thanks #Mary), but I get firstname and lastname replicated (this might be the problem):
object(Cake\Http\ServerRequest) {
trustProxy => false
...
[protected] data => [
'fistname' => [
'fistname' => 'Test',
'lastname' => 'Test'
],
'lastname' => [
'fistname' => 'Test',
'lastname' => 'Test'
],
'upload' => [
'tmp_name' => '/private/var/folders/g5/jjd1vc557bs21hq805lcxjk80000gn/T/phpAVXNqK',
'error' => (int) 0,
'name' => 'SELL5BAE2B6348272_gallery_1.png',
'type' => 'image/png',
'size' => (int) 200231
]
]
...
If I post to the API server it doesn't work.
I did the same with CURL and it works:
$filename = WWW_ROOT.'ufiles/medium/'.$img['image_1'];
$cFile = curl_file_create($filename);
$request = [
'_operation'=>'uploadFile',
'id'=>$ticket_id,
'_session'=>$session,
'file' => $cFile
];
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL,$this->crm['endpoint']);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$response=curl_exec($ch);
curl_close ($ch);
}catch(\Exception $e){
$response = null;
}
Counterquestion: Does it work?
As you can see here, $file->contentId() sets the Content ID or part in a multipart form data request body:
https://github.com/cakephp/cakephp/blob/master/src/Http/Client/FormDataPart.php#L114
I’m not sure about this, but I don’t think you have to set it as it doesn’t seem to be required for multipart/form-data:
https://www.w3.org/TR/2006/REC-xforms-20060314/slice11.html#serialize-form-data
Edit
I did some testing and: It. works. Here is what I tried:
use Cake\Http\Client;
use Cake\Http\Client\FormData;
public function test() {
$request = [
'fistname'=>'Test',
'lastname'=>'Test'
];
$form = new FormData();
$http = new Client();
foreach ($request as $key => $value) {
$form->add($key,$request);
}
$file = $form->addFile('upload',fopen(WWW_ROOT.'img/awards.png','r'));
$file->contentId('mypicture'); // <-- not sure what this is
$file->disposition('attachment');
$response = $http->post(
'http://www.testurl.dev/test',
(string)$form,
['headers' => ['Content-Type' => $form->contentType()]]
);
var_dump($response);
exit;
}
Output of var_dump($response):
object(Cake\Http\Client\Response)#150 (12) {
["code":protected]=>int(200)
…
["headers":protected]=>array(12) {
["Date"]=>array(1) {
[0]=>string(29) "Fri, 28 Sep 2018 12:44:31 GMT"
}
…
}
}
Server access log output:
[28/Sep/2018:14:44:31 +0200] "POST /test HTTP/1.1" 200 6852 "-" "CakePHP"

Microsoft Graph Api displays insufficient privileges to complete the operation

I have an admin account that am trying to update its data using microsoft Graph API via php Curl but its showing error:
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"request-id": "110ac3f6-16d1-41a2-b2dc-add954514666",
"date": "2017-12-04T00:12:02"
}
}
}
below is the code for updating
<?php
session_start();
echo $acc= $_SESSION['access_token'];
$data_string = array("jobTitle" => 'Fibre ngineer', "officeLocation" => "SAMOLA");
$data = json_encode($data_string);
//$data = $data_string;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://graph.microsoft.com/v1.0/users/#mydata.onmicrosoft.com",
//CURLOPT_URL => "https://graph.microsoft.com/v1.0/me",
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
CURLOPT_CUSTOMREQUEST => "PATCH",
CURLOPT_POSTFIELDS => "$data",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"authorization: Bearer $acc",
"content-type: application/json; charset=utf-8"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
print_r($response);
$json = json_decode($response);
if ($err) {
echo "cURL Error #:" . $err;
} else {
//echo $response;
}
?>
I have also set all the required permission like Directory and Users read access but cannot get it to work

How to get success or failure response from paypal?

Iam trying to do the paypal payment.after completion of the payment how can we get the details of the transaction and how to get the success or failure response from paypal payment in angularjs?
I'm using this PHP Code to make it. So, after you complete a transaction in Paypal, they will return to you a response, (even if the transaction was a failure). Just check the the parameter "ACK" at the array.
This response is an array with the informations about your transaction.
If you want to confer the information of your transaction. Just use the method "GetTransactionDetails", and the paypal server will return you an array with all informations(you must the transaction ID to make your Query, not your token). Just adapt this code to angularJS
<?php
function verify_Transaction($idTrans,$show){
$nvp = array(
'METHOD' => 'GetTransactionDetails',
'VERSION' => '124.0',
'PWD' => 'YOUR PASS',
'USER' => 'YOUR USER',
'SIGNATURE' => 'YOUR SIGNATURE' ,
'TRANSACTIONID' => yourTransactionID
);
$curl = curl_init();
curl_setopt( $curl , CURLOPT_URL , 'https://api-3t.sandbox.paypal.com/nvp' );
curl_setopt( $curl , CURLOPT_SSL_VERIFYPEER , false );
curl_setopt( $curl , CURLOPT_RETURNTRANSFER , 1 );
curl_setopt( $curl , CURLOPT_POST , 1 );
curl_setopt( $curl , CURLOPT_POSTFIELDS , http_build_query( $nvp ) );
$response = urldecode( curl_exec( $curl ) );
$responseNvp = array();
if ( preg_match_all( '/(?<name>[^\=]+)\=(?<value>[^&]+)&?/' , $response , $matches ) ) {
foreach ( $matches[ 'name' ] as $offset => $name ) {
$responseNvp[ $name ] = $matches[ 'value' ][ $offset ];
}
}
if($show){
echo '<pre>';print_r($responseNvp);echo'</pre>';
}
if($responseNvp['ACK']=='Success'){
//echo "true";
return true;
}else{
//echo "false";
return false;
}
}
?>

Send file using multipart/form-data request in php

I have image resource stored in variable which I need to send to server using its http API and PHP. I have to send request with content type multipart/form-data. So, I need to make similiar request as when form with file input and enctype=multipart/form-data attribute is sent.
I tried this:
<?php
$url = 'here_is_url_for_web_API';
$input = fopen('delfin.jpg','r');
$header = array('Content-Type: multipart/form-data');
$resource = curl_init();
curl_setopt($resource, CURLOPT_URL, $url);
curl_setopt($resource, CURLOPT_USERPWD, "user:password");
curl_setopt($resource, CURLOPT_HTTPAUTH, CURLAUTH_ANYSAFE);
curl_setopt($resource, CURLOPT_HTTPHEADER, $header);
curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($resource, CURLOPT_BINARYTRANSFER, true );
curl_setopt($resource, CURLOPT_INFILESIZE, 61631);
curl_setopt($resource, CURLOPT_INFILE, $input);
$result = curl_exec($resource);
curl_close($resource);
var_dump($result);
?>
I don't know how exactly response should look like but this returns:
http status 405
and error report is: The specified HTTP method is not allowed for the requested resource ().
use multipart/form-data and boundaries in POST content with curl.
$filenames = array("/tmp/1.jpg", "/tmp/2.png");
$files = array();
foreach ($filenames as $f){
$files[$f] = file_get_contents($f);
}
// more fields for POST request
$fields = array("f1"=>"value1", "another_field2"=>"anothervalue");
$url = "http://example.com/upload";
$curl = curl_init();
$url_data = http_build_query($data);
$boundary = uniqid();
$delimiter = '-------------' . $boundary;
$post_data = build_data_files($boundary, $fields, $files);
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
//CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $post_data,
CURLOPT_HTTPHEADER => array(
//"Authorization: Bearer $TOKEN",
"Content-Type: multipart/form-data; boundary=" . $delimiter,
"Content-Length: " . strlen($post_data)
)
));
//
$response = curl_exec($curl);
$info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";
//print_r($info['request_header']);
var_dump($response);
$err = curl_error($curl);
echo "error";
var_dump($err);
curl_close($curl);
function build_data_files($boundary, $fields, $files){
$data = '';
$eol = "\r\n";
$delimiter = '-------------' . $boundary;
foreach ($fields as $name => $content) {
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="' . $name . "\"".$eol.$eol
. $content . $eol;
}
foreach ($files as $name => $content) {
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="' . $name . '"; filename="' . $name . '"' . $eol
//. 'Content-Type: image/png'.$eol
. 'Content-Transfer-Encoding: binary'.$eol;
$data .= $eol;
$data .= $content . $eol;
}
$data .= "--" . $delimiter . "--".$eol;
return $data;
}
See the full example here: https://gist.github.com/maxivak/18fcac476a2f4ea02e5f80b303811d5f
If you work with CURL, you have to just:
1, set header 'Content-Type' as 'multipart/form-data;'
2, set option 'RETURNTRANSFER' of curl to true (use option method of curl)
3, set option 'POST' of curl to true (use option method of curl)
4, get source of your file (what you get from fopen in PHP):
$tempFile = tempnam(sys_get_temp_dir(), 'File_');
file_put_contents($tempFile, $source);
$post = array(
"uploadedFile" => "#" . $tempFile, //"#".$tempFile.";type=image/jpeg",
);
5, use post method of CURL with parameter in $post variable

Resources