GET api for Parse Server with Where clause PHP - php

I am having the following code to make a GET statement to the REST API of Parse server using PHP:
$query = json_encode(
array(
'where' => array( 'userid' => "8728792347239" )
));
echo $query;
$ch = curl_init('https://*hidden*.herokuapp.com/parse/classes/computers?'.$query);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
'X-Parse-Application-Id: *hidden*',
'X-Parse-REST-API-Key: *hidden*',
'Content-Type: application/json'
)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
print_r($response);
However I am getting the following error:
{"code":102,"error":"Invalid parameter for query: {\"where\":{\"userid\":\"8728792347239\"}}"}
What am I doing wrong?

without having read the documentation, i bet it's supposed to be url-encoded, not json-encoded -OR- that the data is supposed to be in the POST body, not the URL query.
if guess #1 is correct, then your problem is that you're using json_encode instead of http_build_query eg
$query = http_build_query(
array(
'where' => array( 'userid' => "8728792347239" )
));
if guess #2 is correct, then your problem is that you're adding the data to the url query instead of adding it to the request body, eg
$ch = curl_init('https://*hidden*.herokuapp.com/parse/classes/computers');
curl_setopt($ch,CURLOPT_POSTFIELDS,$query);

Related

GoToTraining API rejecting json?

OK, I'm using the GoToTraining API to try to create a new Training. The docs say to "post" JSON to the endpoint.
So I have my array of data in PHP (this is a WordPress site, and here I'm grabbing stuff from Advanced Custom Fields data)
$my_data_array = array(
'name' => get_the_title( $_POST['acf']['field_5ab508b853122'] ),
'description' => $_POST['acf']['field_5ab50b2406457'],
'timeZone' => 'America/Los_Angeles',
'times' => array(
array(
'startDate' => date( 'Y-m-d', strtotime( $_POST['acf']['field_5ab50908347ef'] ) ) . 'T' . $_POST['acf']['field_5ab50bc6af8df'] . 'Z',
'endDate' => date( 'Y-m-d', strtotime( $_POST['acf']['field_5ab50908347ef'] ) ) . 'T' . $_POST['acf']['field_5abbd96c6ff8d'] . 'Z',
),
),
'registrationSettings' => array(
'disableConfirmationEmail' => false,
'disableWebRegistration' => true,
)
);
and then I'm just doing:
$payload = json_encode( $my_data_array )
to create the payload, which looks like this, if I print_r the value of $payload:
{"name":"Today’s Class","description":"We can add some default content here","timeZone":"America\/Los_Angeles","times":[{"startDate":"2018-04-24T06:00:00Z","endDate":"2018-04-24T09:00:00Z"}],"registrationSettings":{"disableConfirmationEmail":false,"disableWebRegistration":true}}
If I make the curl request, posting $payload, I get back:
Array
(
[errorCode] => InternalError
[description] => We have encountered an internal error. The request may
be retried, but it may have the same result.
[incident] => 5102160953111715072
)
Could be lots of things, right? But here is thing that's driving me crazy:
If cut and paste that dumped value of $payload above into the "body" field in the sandbox thing on the API reference page (see the link above), it works fine and I get an ID for the new Training back as the response.
Moreover, if I cut and paste that same string and just hardcode it as a string value of my $payload variable in my script (using the exact same code for the curl stuff) -- only difference being I'm hardcoding the value of $payload, like this
$payload = '{"name":"Today’s Class","description":"We can add some default content here","timeZone":"America\/Los_Angeles","times":[{"startDate":"2018-04-24T06:00:00Z","endDate":"2018-04-24T09:00:00Z"}],"registrationSettings":{"disableConfirmationEmail":false,"disableWebRegistration":true}}';
... and make the request that way, it also works and gives me a successful response!
protected function make_request( $url, $method, $fields ) {
// $payload = json_encode( $fields );
$payload = '{"name":"Getting to Know Today’s Electric Utility Industry","description":"We can add some default content here","timeZone":"America\/Los_Angeles","times":[{"startDate":"2018-04-24T06:00:00Z","endDate":"2018-04-24T09:00:00Z"}],"registrationSettings":{"disableConfirmationEmail":false,"disableWebRegistration":true}}';
$http_headers = array(
'Accept: application/json',
'Content-Type: application/json',
'Authorization: OAuth oauth_token=' . $this->access_token,
);
$ch = curl_init();
if ( 'post' == $method ) {
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload ); // define what you want to post
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); // return the output in string format
curl_setopt( $ch, CURLOPT_HTTPHEADER, $http_headers );
}
$response = curl_exec( $ch );
curl_close( $ch ); // close curl handle
return $response;
}
But what's assigned to $payload here is exactly the same thing I'm getting if I print_r what json_encode() returns. Whaa??
I do notice, if I run
mb_detect_encoding( $payload );
I get 'ASCII' from the json_encode version and I get 'UTF-8' on the version where I hardcode the string as the value of the variable. Would that make any difference?
Am I missing something simple? Anyone have any idea what I might be doing wrong here? Been beating my head against the wall for too many hours.
So for posterity: Turns out that apostrophe in the name of the Training was causing GTT to choke on the data getting sent over. But it had something to do with the get_the_title() function, which handles apostrophes and quotes differently than just grabbing the value from $post->post_title. When I changed the code that was assembling the data for the API call to $post->post_title instead of get_the_title(), it worked.

how to send a json request in php?

i have a register page for allow users to register. before register i need to validate their phone number. i have given a web-service address along with its parameters.
the parameters i have given:
http://*********
Method:POST
Headers:Content-Type:application/json
Body:
the following in:
{
"mobileNo":"0*********",
"service":"****",
"Code1":"*****",
"content":"hi",
"actionDate":"2017/09/26",
"requestId":"1"
}
and here the code i found in the Internet:
$data = array(
'mobileNo' => '****',
'service' => '***',
'Code1' => '*****',
'content' => '55',
'actionDate' => '2017/09/26');
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json" .
"Accept: application/json"
)
);
$url = "******";
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
and here is error i face with when i test local:
file_get_contents(http://********/sms-gateway/sms-external-zone /receive): failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
and there is no error and no result(receive SMS) in response when i test online(cpanel server)
According to the given parameters, where do i wrong?
thanks in advance.
According to your Error, it seems your service did not respond. Have you tried to open it in a browser, to check if any response there?
Maybe the service you try to call requires you to provide a Static IP from your Webserver, as they only grant access on a IP based level. Means, your IP is blocked until they allow it.
I suggest you use cURL to do your request. This way you get future data to use for debugging, if anything fails. Still here, if the service does not respond, you want get any other information.
$data = array(
'mobileNo' => '****',
'service' => '***',
'Code1' => '*****',
'content' => '55',
'actionDate' => '2017/09/26');
$url = "******";
$ch = curl_init( $url );
// set data as json string
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data));
// define json as content type
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
// tell curl to fetch return data
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// follow location if redirect happens like http to https
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
// send request
$result = curl_exec($ch);
// gives you the result - most of the time you only want this
var_dump($result);
// for debugging purpose, gives you the whole connection info
var_dump(curl_getinfo($ch));
// gives back any occurred errors
var_dump(curl_error($ch));
curl_close($ch);
Edit: I added the CURLOPT_FOLLOWLOCATION, as a request may gets redirected. We want to catch that as well. And I added the curl_close at the end. If it is closed, error or info data can be fetched.

I need help creating an endpoint that can receive json data

I have created a php file that sends json data to an external url. Their API requires that I have a page on my website that receives the json responses for processing. The one that sends json data works well. I need help with the second php page that should process it
$Url="http://example.com/submit.php";
$date = date_create();
$UserID=7;
$Password='';//<-password written here
$Timestamp=date_timestamp_get($date);
$token=$UserID.$Password.$Timestamp;
$data_string = array();
$data_string = array(
"AuthDetails" => array(
array(
"UserID" => $UserID,
"Token" => md5($token),
"Timestamp"=>$Timestamp
)
),
"MessageType"=> array(
"3"
),
"BatchType"=>array(
"0"
),
"SourceAddr"=>array(
"Example"
),
"MessagePayload"=> array(
array(
"Text" => "Sample text message by Example :)"
)
),
"DestinationAddr" => array(
array(
'MSISDN'=>'254701000000',
'LinkID'=>''
)
),
"DeliveryRequest" => array(
array(
'EndPoint'=>'',//<-URL that receives the response
'Correlator'=>md5(uniqid())
)
)
);
$data_string=json_encode($data_string);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
)
);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$output = curl_exec($ch);
if(curl_errno($ch)){
echo 'Request Error:' . curl_error($ch);
}
curl_close($ch);
return $output;
Ok this is going to be a bit generic but it should put you on the right path.
So you have to write a script that will process the response from them i.e. your end-point for this circle of events.
So lets call it my-enpoint.php
So in the message you send to them you put the address of this new script into this parameter
"DeliveryRequest" => array(
array(
'EndPoint'=>'http://www.example.com/my-endpoint.php',
'Correlator'=>md5(uniqid())
Now your script my-endpoint.php I am assuming they have said how they will return their reply, probably as POST variable. You process their reply basically like you would a submitted form from your own site.
So for example if their reply is POSTed
<?php
// initial testing to see what comes back from them
// as this wont be associated with a browser
// dump their reply to a file so you can see whats there
file_put_contents('reply.txt', print_r($_POST, true), FILE_APPEND);
?>
With the info you have provided this is about a much as I can do.

Posting to a file using CURL... Not taking variables

Posting to a file using Curl
I'm trying to post to a file as soon as user enters a website assuming they have clicked from an ad.
Example url = http://myFabSite.com/?tr=213
This is what I'm trying but its not capturing the tr URL variable or the referrer:
if($_GET['tr']){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://myFabSite.com/actions/tracksAds.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'referrer' => $_SERVER['HTTP_REFERER'],
'track_code' => $_GET['tr']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
}
trackAds.php:
$mysqli = dbConnect();
$referrer = $mysqli->real_escape_string(urldecode(trim($_REQUEST['referrer'])));
$track_code = $mysqli->real_escape_string($_REQUEST['track_code']);
$query = "insert into ad_tracking ( tracking_code, referrer ) VALUES ( '$track_code', '$referrer' )";
$result = $mysqli->query($query);
Anything obvious?
UPDATE
This is from print_r($data);
Array
(
[referrer] => none
[track_code] => fb1
)
This is $query from trackAds.php
insert into ad_tracking ( tracking_code, referrer ) VALUES ( '', '' )
So, the array is not being passed, either at all or correctly, to trackAds.php
You're missing quotes in $_GET[tr] on the first line. Change it to $_GET['tr'].
Also, use $_POST instead of $_REQUEST in trackAds.php. There's a great chance here that you are inadvertently getting a cookie value instead of a POST value, or simply have the wrong data in $_REQUEST. See this page in the documentation.
Actually found a different method which works ok, still no clue why the other doesn't.
This assumes PHP 5+
$url = 'http://myFabSite.com/actions/tracksAds.php';
$data = array('referrer' => $_SERVER['HTTP_REFERER'], 'track_code' => $_GET['tr']);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

Value is empty in PHP Array

I am developing an Instagram application. Nevermind, my questions isn't focused on the API.
Its a simple php question. However. Everytime I try to run the the output is that the TOKEN is empty.
$token = 'XxXXXXXXXXX.XXXXXXX.XXXXXX';
$access_token_parameters = array(
'access_token' => $token,
'action' => 'like'
);
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_GET,true);
curl_setopt($curl,CURLOPT_GETFIELDS,$access_token_parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($curl);
}
Is there a way to set a value externally the Array? (Between, I tried it with include file.php. which works.) But I would like to call this without using an external php file.
Hope you understand my problem and may help me :)
$token = 'XxXXXXXXXXX.XXXXXXX.XXXXXX';
$access_token_parameters = array(
'access_token' => $token,
'action' => 'like'
);
$curl = curl_init($url."?".http_build_query($access_token_parameters ));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($curl);
}

Categories