post data to api using json - php

This code i wrote to send data to an api using post method in JSON but in response i am getting invalid can anyone tell me what is wrong in the code.
$post = array(
"operatorCode"=>"9",
"scheduleCode"=>"84W92XC8LOBAF3KZP4",
"travelDate"=>"2015-03-20",
"fromStationCode"=>"84",
"toStationCode"=>"76",
"boardingPointCode"=>"191933",
"droppingPointCode"=>"0000",
"email"=>"*********",
"mobile"=>"*******",
"passenger"=>array(
"seatNumber"=>"40",
"name"=>"*****",
"age"=>"20",
"gender"=>"Male"
)
);
$data_string = json_encode($post);
echo $data_string;
$ch=url_init('http://api?username=*****');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,array('data'=>$data_string));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);
echo'<pre>';
print_r($result);
Response From api
stdClass Object
(
[code] => 0
[errorCode] => ER30
[errorDesc] => Invalid Data
[message] => Failure
)
Sample URL:
http://<ServerName>/bookbustickets/rest/json/2.0/tempbooking?username=****&password‌​=******
Sample Input data:
data={"operatorCode":"2586",
"scheduleCode":"7Q52586C3YG8KJ350F2F5V264",
"travelDa‌​te":"2015-03-10",
"fromStationCode":"76",
"toStationCode":"75",
"boardingPointCode":‌​"284936",
"droppingPointCode":"0000",
"email":"test#gmail.com",
"mobile":"9876543210‌​",
"passenger":[
{
"seatNumber":"3",
"na 9 me":"Test",
"age":20,
"gender":"Male"},
{
"seatNumber":"4",
"name":"Test",
"age":20,
"g‌​ender":"Male"}
]
}

Ok so the problem is that "passenger" should be an array of objects so try changing your code to
$passenger1 = new stdClass();
$passenger1->seatNumber = "40";
$passenger1->name = "*****";
$passenger1->age = "20";
$passenger1->gender = "Male";
$passenger2 = new stdClass();
$passenger2->seatNumber = "41";
$passenger2->name = "*****";
$passenger2->age = "21";
$passenger2->gender = "Female";
$post = array(
"operatorCode"=>"9",
"scheduleCode"=>"84W92XC8LOBAF3KZP4",
"travelDate"=>"2015-03-20",
"fromStationCode"=>"84",
"toStationCode"=>"76",
"boardingPointCode"=>"191933",
"droppingPointCode"=>"0000",
"email"=>"*********",
"mobile"=>"*******",
"passenger"=>array( $passenger1, $passenger2 )
);
This will generate the following result
{
"operatorCode":"9",
"scheduleCode":"84W92XC8LOBAF3KZP4",
"travelDate":"2015-03-20",
"fromStationCode":"84",
"toStationCode":"76",
"boardingPointCode":"191933",
"droppingPointCode":"0000",
"email":"*********",
"mobile":"*******",
"passenger":[
{
"seatNumber":"40",
"name":"*****",
"age":"20",
"gender":"Male"
},
{
"seatNumber":"41",
"name":"*****",
"age":"21",
"gender":"Female"
}
]
}
Also I am note sure why you are using
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
Would not
curl_setopt($ch, CURLOPT_POST, true);
be a better option?

Related

How do I return specific array data from php?

I am using async/await to fetch a file (createCharge.php) that contains arrays with data inside when <button> is clicked on checkout.html
If I use print_r I can see all the results in the console such as the name, description, amount and even a new generated 'hosted_url'
that the customer will use to continue to their payment.
The problem is that I can't figure out how to fetch the hosted_url result into the checkout page and into the Pay now!.
This is what I have on my checkout.html...
<button id="btn">Pay with Crypto?</button>
<p id="pay"></p>
<script>
btn.addEventListener('click', async (e) => {e.preventDefault();
const response = await fetch('coinbasePHPtest/createCharge.php/');
if (!response.ok) {
const errorMessage = await response.text();
console.error(response.status, response.statusText, errorMessage);
alert('There was an error creating the charge.');
return;
}
const newurl = await response.text();
console.log(newurl);
pay.innerHTML = `Pay Now! - Coinbase`;
});
</script>
You can see I'm trying to bring the hosted_url into the <a> tag within the <script>.
And here is my createCharge.php that actually creates the hosted_url... (Example: https://commerce.coinbase.com/charges/xxxxx)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.commerce.coinbase.com/charges');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(
array (
'name' => 'My-Company',
'description' => 'Selected Product',
'local_price' =>
array (
'amount' => '147.00',
'currency' => 'GBP',
),
'pricing_type' => 'fixed_price',
'metadata' =>
array (
'customer_id' => 'id_1',
'customer_name' => 'Satoshi Nakamoto',
),
'redirect_url' => 'https://www.my-site.co.uk/Checkout/payment_successful.php',
'cancel_url' => 'https://www.my-site.co.uk/Checkout/payment_cancelled.php',
)
));
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'X-Cc-Api-Key: MY-API-KEY';
$headers[] = 'X-Cc-Version: 2018-03-22';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
$response = json_decode($result, true);
return $response->data->hosted_url;
?>
I also tried..
pay.innerHTML = `Pay Now!`
pay.innerHTML = `Pay Now!`
pay.innerHTML = `Pay Now!`
pay.innerHTML = `Pay Now!`
with no luck.
and...
btn.onclick = async() => {
const response = await fetch('coinbasePHPtest/charge.php/hosted_url');
const data = await response.json();
&
btn.onclick = async() => {
const resp = await fetch(`coinbasePHPtest/createCharge.php/${hosted_url}`);
const data = await resp.json();
Solution:
$result = curl_exec($ch);
curl_close($ch);
$response = json_decode($result, true);
echo $response['data']['hosted_url'];
This code within the createCharge.php worked for me! :)
I think you want to just output the data instead of using return. replace
return $response->data->hosted_url;
with
echo $response['data']['hosted_url'];

CURL Post Request to API Looping Through Database

I've been trying to select values (students data) from mysql database table and looping through database to send to an API using PHP CURL Post request but it's not working.
This is the API body:
{
"students":[
{
"admissionNumber": "2010",
"class":"js one"
},
{
"admissionNumber": "2020",
"class":"ss one"
}
],
"appDomain":"www.schooldomain.com"
}
Parameters I want to send are "admissionNumber" and "class" parameters while "appDomain" is same for all. Here's my code:
if(isset($_POST['submit'])){
$body = "success";
$info = "yes";
class SendDATA
{
private $url = 'https://url-of-the-endpoint';
private $username = '';
private $appDomain = 'http://schooldomain.com/';
// public function to commit the send
public function send($admNo,$class)
{
$url_array= array('admissionNumber'=>$admNo,'class'=>$class,'appDomain'=>$this-> appDomain);
$url_string = $data = http_build_query($url_array);
// using the curl library to make the request
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $this->url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $url_string);
curl_setopt($curlHandle, CURLOPT_POST, 1);
$responseBody = curl_exec($curlHandle);
$responseInfo = curl_getinfo($curlHandle);
curl_close($curlHandle);
return $this->handleResponse($responseBody,$responseInfo);
}
private function handleResponse($body,$info)
{
if ($info['http_code']==200){ // successful submission
$xml_obj = simplexml_load_string($body);
// extract
return true;
}
else{
// error handling
return false;
}
}
}
$sms = new SendDATA();
$result = mysqli_query( $mysqli, "SELECT * FROM school_kids");
while ($row = mysqli_fetch_array($result)) {
$admNo = $row['admNo'];
$class = $row['class'];
$sms->send($admNo,$class,"header");
echo $admNo. " ".$class;
}
}
The question is rather unclear; when you say "this is the API body", I presume this JSON fragment is what the REST API at https://url-of-the-endpoint expects. If so, you are building your request body wrong. http_build_query creates an URL-encoded form data block (like key=value&anotherKey=another_value), not a JSON. For a JSON, here's what you want:
$data = array('students' => array
(
array('admissionNumber' => $admNo, 'class' => $class)
),
'appDomain':$this->appDomain
);
$url_string = $data = json_encode($data);
Also, you probably want to remove the HTTP headers from the response:
curl_setopt($curlHandle, CURLOPT_HEADER, false);

Write Array to File:PHP

I'm trying to write the array $jsonDataInArray to an external csv file. Right now, my file only has the column headers without the data underneath. Could someone help me step through this PHP array, $jsonDataInArray, and write it to an external .csv file?
//set url for pipedrive data being pulled
$api_token="soemToken";
$url = "https://someURL.com;
$ch = curl_init(); //initialize connection with a URL
//check if cURL is enabled or not
if(is_callable('curl_init'))
{
echo "curl_init Enabled";
}
else
{
echo "curl_init Not enabled";
}
echo '<br/><br/><br/><br/><br/><br/>';
curl_setopt($ch, CURLOPT_URL, $url); //fetching URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //return queried data as string
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);//verify certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);//check the existence of a common name & verify that it matches the hostname provided
curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/permissingFile.pem");//name of file holding certificates to verify peer with
$json_response = curl_exec($ch);//perform cURL session. Returns ALL of JSON data if sucessful, false if not.
$info = curl_getinfo($ch);//gets array of info about cURL transfer.
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);//gets HTTP message about cURL transfer
if ( $status != 200 )
{
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch));
//die();
}
curl_close($ch);//close connection with URL
// create an array from the data that is sent back from the API
$response = json_decode($json_response, 1);
// Gets the count of records returned from the api. Used in the for loop to go through response 1 array element at a time.
$count = Count($response['data']);
for ($x=0; $x<$count; $x++)
{
$currentRecord = $response['data'][$x];
$jsonDataInArray = array
(
"id" => $response['data'][$x]['id'],
"user_id" => $response['data'][$x]['user_id']['id'],
"person_id" => $response['data'][$x]['person_id']['value'],
"org_id" => $response['data'][$x]['org_id']['value'],
"stage_id" => $response['data'][$x]['stage_id'],
"title" => $response['data'][$x]['title'],
"value" => $response['data'][$x]['value'],
"currency" => $response['data'][$x]['currency'],
"add_time" => $response['data'][$x]['add_time'],
"update_time" => $response['data'][$x]['update_time'],
"stage_change_time" => $response['data'][$x]['stage_change_time'],
"active" => $response['data'][$x]['active'],
"deleted" => $response['data'][$x]['deleted'],
"status" => $response['data'][$x]['status'],
);
ksort($currentRecord);
}
$test_array = $response['data'][0];//test_array = first row of data
if($startPos == 0){
$fp = fopen('cacheDeals3.csv', 'w');
fputcsv($fp, array_keys($response['data'][0]));
}else{
$fp = fopen('cacheDeals3.csv', 'a');
}
foreach ($jsonDataInArray as $fields)
{
fputcsv($fp, $fields);
}
$jsonDataInArray is being overwritten on every iteration of the for loop, therefore fputcsv is being passed a string as the $field parameter rather than an array.
You need to append a new array to $jsonDataInArray each time, change
$jsonDataInArray = array
to
$jsonDataInArray[] = array

Extract parts of a php array to client side

So I'm trying to centralize products in one central php file and have my client side php just request info so I only have to edit the central php file to add and remove products
my server side
$varProduct= (
// [0] [1] [2] [3 4 5 6 7] [8]
array("Title" , 0001 , 100, 0,0,1,1,0, "/womens/tops/s/2.png", "/womens/tops/s/2.jpg", "/womens/tops/s/2.jpg", 50 )
)
In my html client side I want to display the title, the price [2] and the url [8]
basically
for(i=o, i< $varProduct.length(), i++){
//display $varProduct[i][0];
//display the Image for $varProduct[i][8];
//display $varProduct[i][2];
}
how can I put values in my server side file to my client side in within html tags? I need to display them inline will I be able to format the variables?
Try something like this
<?php
for ($i = 0; $i < count($varProduct); $i++) {
//full path -- then post pram
$return = sendPostData("http://stackoverflow.com/", array('parm1' => $varProduct[$i][0], 'parm2' => $varProduct[$i][0]));
print_r($return);
}
?>
<?php
//send data function
function sendPostData($url, Array $post) {
$data = "";
foreach ($post as $key => $row) {
$row = urlencode($row); //fix the url encoding
$key = urlencode($key); //fix the url encoding
if ($data == "") {
$data .="$key=$row";
} else {
$data .="&$key=$row";
}
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
}
?>

How to setup ios platform through code with apple push notification p12 certificate file?

I want to create an app with ios platform set up from the .p12 file. How do I do that?
This is the method for creating app:
class AppHandler
{
public $USER_AUTH_KEY = 'Insert your key here';
public function create($name, $apns_p12 = null, $apns_p12_password = null, $gcm_key = null, $android_gcm_sender_id = null)
{
$fields = array(
'name' => $name,
'apns_p12' => $apns_p12,
'apns_p12_password' => $apns_p12_password,
'gcm_key' => $gcm_key,
'android_gcm_sender_id' => $android_gcm_sender_id
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/apps");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
"Authorization: Basic " . $this->USER_AUTH_KEY));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
try {
$response = curl_exec($ch);
if (!$response) {
throw new Exception("App wasn't created");
}
} catch (Exception $e) {
echo 'Error: ', $e->getMessage(), "\n";
} finally {
curl_close($ch);
}
$response = json_decode($response, true);
$return = array(
'id' => $response['id'],
'basic_auth_key' => $response['basic_auth_key']
);
return $return;
}
...
And this is the method with 2 ways of getting the insides of .p12 file:
public function getP12($pkcs12, $password = NULL): string
{
/*
// Way 1:
$pkcs12 = file_get_contents($pkcs12);
$encoded = base64_encode($pkcs12);
return $encoded;
*/
// Way 2:
$cert_store = file_get_contents($pkcs12);
if (!$cert_store) {
echo "Error: can't read file.\n";
exit;
}
$pkcs12Read = openssl_pkcs12_read($cert_store, $cert_info, $password);
if ($pkcs12Read) {
$result = base64_encode($cert_info['cert']);
return $result;
} else {
echo "Error: can't read cert.\n";
exit;
}
}
According to onesignal's doc I have to send apns_p12 as my apple push notification p12 certificate file, converted to a string and Base64 encoded.
And I do that this way:
$obj = new AppHandler();
$response = $obj->create('TestName', $obj->getP12('cert.p12', 'password'), 'password')
It creates an app with given name, however, the platform is not set up.
What do you mean by "the platform is not set up"? What error are you getting and where?
By the way, I finally gave up trying code the intricacies of APNS programming and instead went with AWS' Simple Notification Service: https://aws.amazon.com/sns. It handles both Apple and Google notifications by using the API to set up topics and subscribers, plus you can send up to 1 million notifications per month free.
Ok, I got it. I simply needed to add apns_env parameter:
$fields = array(
'name' => $name,
'apns_env' => $apns_env,
'apns_p12' => $apns_p12,
'apns_p12_password' => $apns_p12_password,
'gcm_key' => $gcm_key,
'android_gcm_sender_id' => $android_gcm_sender_id
);
And I should've taken insides of the file and converted them to a string and Base64 encoded like that:
public function getP12($pkcs12): string
{
$apns_12 = base64_encode(file_get_contents($pkcs12));
return $apns_12;
}

Categories