Send POST Request & Get JSON Response in PHP? - php

I'm trying to send a POST request via PHP from AJAX. I checked the API with Postman. It is working fine. But it is not getting executed in PHP. It is not showing up in Network Tab also.
I saw a lot of samples for making a POST Request in Stack Overflow & tried it. But I can't figure out where I'm going wrong ?
I have attached both the JS Code & PHP Code here
JavaScript CODE
function editUser(toid, name, mobile, mail, pin, addr, state, dis, subdis, role, user) {
$.ajax({
type: "POST",
url: "edituser.php",
dataType: 'html',
data: {
id: toid,
fullname: name,
phone: mobile,
email: mail,
address1: addr,
state: state,
district: dis,
subdistrict: subdis,
pincode: pin,
usertype: user,
role: role,
token: apptoken,
},
success: function (response) {
visibility(false);
console.log("Response > > " + response);
if (response.status == "SUCCESS") {
swal("Updated User", " Information Updated Successfully!", "success");
}
loadData();
}
});
}
PHP CODE
<?php
// where are we posting to?
$url = 'http://api.tech.com/api/UpdateUser';
// what post fields?
$fields = array(
'id' => $_POST['id'],
'fullname' => $_POST['fullname'],
'phone' => $_POST['phone'],
'email' => $_POST['email'],
'address1' => $_POST['address1'],
'state' => $_POST['state'],
'district' => $_POST['district'],
'subdistrict' => $_POST['subdistrict'],
'pincode' => $_POST['pincode'],
'usertype' => $_POST['usertype'],
'role' => $_POST['role'],
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
$token = $_POST['token'];
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("AppToken: $token",
"Content-Type: application/x-www-form-urlencoded"));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// execute post
$result = curl_exec($ch);
echo $result;
// close connection
curl_close($ch);
?>
UPDATE:
The request sent to the API ($url) is not showing in the Network Tab. But the request to edituser.php is shown.

I feel like a lot of context is missing here but I have done a lot of stuff like this so I will try to help out with what I do understand.
Here is what I have gathered so far from your question.
You are calling an ajax function in JavaScript that triggers the given PHP code.
The JavaScript is successful in calling this code "per the network screenshot."
The network tab indicates the PHP script returns nothing.
Here are my thoughts on how to move forward.
You appear to be sending all data from your client side JavaScript including a secure pin and token. This is a very bad idea as it mean your users can all see this secure pin and steal it for their own nefarious purposes. Instead store constants like the secure pin in the php code.
If you are expecting to see the curl request in the network tab you are mistaken. The curl request is going from server to server and will never be seen by the client.
If the response tab is empty you may have something as simple as a syntax error or some kind of curl error that you are not capturing.
Add some of this to your request for debugging:
$result = curl_exec($request);
$response_code = curl_getinfo($request, CURLINFO_HTTP_CODE);
echo 'Response code: ' . $response_code;
if(curl_error($request))
{
echo '<br />Curl error: ' . curl_error($request);
}
You should see the response code at least in the "response" tab of the ajax call.
If you still see nothing make sure your PHP configuration is set up to show all warnings and errors, etc and isn't suppressing the information you need.

Related

How do I send info to this API using cURL and PUT?

I am working with an API that is documented here: https://cutt.ly/BygHsPV
The documentation is a bit thin, but I am trying to understand it the best I can. There will not be a developer from the creator of the API available before the middle of next week, and I was hoping to get stuff done before that.
Basically what I am trying to do is update the consent of the customer. As far as I can understand from the documentation under API -> Customer I need to send info through PUT to /customers/{customerId}. That object has an array called "communicationChoices".
Going into Objects -> CustomerUpdate I find "communicationChoices" which is specified as "Type: list of CommunicationChoiceRequest". That object looks like this:
{
"choice": true,
"typeCode": ""
}
Doing my best do understand this, I have made this function:
function update_customer_consent() {
global $userPhone, $username, $password;
// Use phone number to get correct user
$url = 'https://apiurlredacted.com/api/v1/customers/' . $userPhone .'?customeridtype=MOBILE';
// Initiate cURL.
$ch = curl_init( $url );
// Specify the username and password using the CURLOPT_USERPWD option.
curl_setopt( $ch, CURLOPT_USERPWD, $username . ":" . $password );
// Tell cURL to return the output as a string instead
// of dumping it to the browser.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// Data to send
$data = [
"communicationChoices" => [
"communicationChoiceRequest" => [
"choice" => true,
"typeCode" => "SMS"
]
]
];
$json_payload = json_encode($data);
print_r($json_payload);
// Set other options
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($json_payload)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_payload);
// Execute the cURL request
$response = curl_exec($ch);
// Check for errors.
if( curl_errno( $ch ) ) :
// If an error occured, throw an Exception.
throw new Exception( curl_error( $ch ) );
endif;
if (!$response)
{
return false;
} else {
// Decode JSON
$obj = json_decode( $response );
}
print_r($response);
}
I understand that this is very hard to debug without knowing what is going on within the API and with limited documentation, but I figured asking here was worth a shot anyway.
Basically, $json_payload seems to be a perfectly fine JSON object. The response from the API however, is an error code that means unknown error. So I must be doing something wrong. Maybe someone has more experience with APIs and such documentation and can see what I should really be sending and how.
Any help or guidance will be highly appreciated!
before you test your code, you can use the form provided on the API Documentation.
when you navigate to API > Customers > /customers/{customerId} (GET), you will see a form on the right side of the page (scroll up). you need to provide the required values on the form then hit Submit button. you will surely get a valid data for communicationChoices based on the result from the Response Text section below the Submit button.
now, follow the data structure of communicationChoices object that you get from the result and try the same on API > Customers > /customers/{customerId} (PUT) form.
using the API forms, you may be able to instantly see a success or error from your input (data structure), then translate it to your code.

Slack Dialog gives an error

I am working on a small slack app development. I stuck in one situation. I am using slack dialog to get data from the user and when user enter data
and click on submit button I get an alert message. I don't know what
is it and why it gives an alert. What to do with this? Please note I get
payload response in my interactive component script. And respond to the server with 200. Here is my Response code :
if($type == "dialog_submission")
{
http_response_code(200);
return json_encode(array(
'status' => 200,
'message' => 'ok'
));
$ch = curl_init("https://slack.com/api/chat.postMessage");
$dataSet = http_build_query([
"token" => $authToken,
"channel" => $data['channel']['name'],
"text" => "123",
]);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataSet);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
}
Screenshot of alert message
Try something like:
if($type == "dialog_submission") {
return json_encode(array(
'status' => 200,
'message' => ''
));
}
You need to return an empty response to the Slack Dialog, or you will get the error
We had some trouble connecting. Try again?
So you must somewhere have an echo that returns something to the Slack dialog causing the error. You need to remove those. Like the echo $result; at the end.
This error will also occur if your script has a run-time error, since it will then create an automatic response like "error in test.php line 101....". To check for that make sure you have error logging activated and check if there are any errors in the logfile.
You activate error logging by putting these commands at the beginning of your script:
ini_set("log_errors", 1);
ini_set("error_log", "php-errors.log");
You can however return validation errors to Slack, but those must be in a specific format. See this documentation for details.

Returning data from Google's Geocoding API with PHP curl

This question is similar to another one answered, however the solution in that case was to use a country code, which is not feasible for this particular use, as the address is being provided by the user through an input field (so a country may not be provided).
Here is the content of my current request
Request coming from AngularJS:
function getCoordinatesFromApi(address) {
addressApiResponse = $http({
url: 'php/coordinates.php',
method: 'get',
params: {
address: address
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
return addressApiResponse;
}
Request handled in PHP:
$api_maps = 'https://maps.googleapis.com/maps/';
$address = urencode($_GET['address']);
$api_key = 'API_key_here';
$url = $api_maps . 'api/geocode/json?address=' . $address . '&key=' . $api_key;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($curl);
curl_close($curl);
echo ($curl_response);
When this is called, I consistently get back a valid response with status: 200, but data is an empty string.
I've checked the validity of the $url being build in PHP and it is ok, accessing that url directly in the browser displays a valid API response with data.
I've also tried using Angular's $http method and that too returns a valid response from the API:
function getCoordinatesFromApi(address) {
addressApiResponse = $http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=API_key_here');
return addressApiResponse;
}
For some reason, it's ony the curl method that does not behave as expected. Has any one dealt with this problem?
If you are saying that echo ($curl_response); return nothing even if status is 200, it's because it's encoded JSON!
Please try this :
$decodedresponse = json_decode($curl_response);
//send me what var_dump return so I can hellp you accessing the array!
echo var_dump($decodedresponse);
//You would use as an array DEPENDING ON HOW THE ARRAY IS BUILD OF COURSE
echo $decodedresponse['response']['lat'];
echo $decodedresponse['response']['long'];
try again
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false

How PHP get the content from web service?

I have a problem in getting the content/array from web service to my php code. When I type in the url in browser like http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD, then the result in the browser is displayed like this: [ 1.20MYR , 0.39SGD ]. My PHP code looks like this:
$ch = curl_init('http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
echo $content;
Unfortunately, I get nothing use the code above. Looking for help.
Thanks.
UPDATED
$data=array(
'amount'=>1.2,
'fromCurrency'=>'MYR',
'toCurrency'=>'SGD'
);
$data_string = json_encode($data);
$ch = curl_init('http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-type: application/json'));
$content= curl_exec($ch);
curl_close($ch);
$obj = json_decode($content);
echo $obj;
This page contains dynamic content, loaded by JavaScript. You can see it in Google Chrome for example by access view-source:http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD.
If you look closer to the source code of the page (file http://server1-xeon.asuscomm.com/currency/JQuery/app_converter.js) you'll see, that it uses this code to get exchange data under the hood:
$.ajax({type: "POST",
url: "WebService.asmx/YaHOO_CurrencyEx", // important: it's a relative URL!
data: "{amount:" + amount + ",fromCurrency:'" + from + "',toCurrency:'" + to + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {},
success: function (data) {
$('#results').html(' [ ' + amount + from + ' , ' + data.d.toFixed(2) + to + ' ] ');
});
So, actually you can make such request in PHP to avoid access dynamic content on the http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD page.
UPD:
I've added a more complete explanation.
By the time the page on http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD is loaded, a JavaScript code on this page (it means that it's executed on the client side, in a browser, not on your server) parses URL parameters and makes AJAX POST request to the URL http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx. It passes a JSON payload {amount:1.20,fromCurrency:'MYR',toCurrency:'SGD'} and gets a response like this {"d":0.390360}. So, you can just make a direct POST request to the http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx via curl, passing an amount, fromCurrency and toCurrency in JSON body and then decode received JSON response using json_decode($content);.
How data should look? Add this to your code from "UPDATED" and run:
$array["MYR"] = 1.2;
$array["SGD"] = doubleval($obj->d)
// Print simple array (print source for example)
echo "<pre>";
print_r($array);
echo "</pre>";
// Print true JSON-array
print_r(json_encode($array));
In web browser you will see:
Array
(
[MYR] => 1.2
[SGD] => 0.39036
)
{"MYR":1.2,"SGD":0.39036}
Can't understand your problem at this moment.
If you want print only returned value (digits), do it: echo $obj->d;

PHP GCM error message MismatchSenderId

I am facing the problem with GCM push notification. I am getting the following error.
{
"multicast_id":4630467710672911593,
"success":0,
"failure":1,
"canonical_ids":0,
"results":[{
"error":"MismatchSenderId"
}]
}
Following is the code. Any help would be really appreciated. Thanks in Advance.
public function gcmPush()
{
$regId = "APA91bHFcgOssQZEqtdUk3EC1ojwC5-LVG3NPV2bMqKyC9rPymR6StmAbz-N7Ss8fnvruZhWWNrR3lmBqpjQItlu00AKHPbltBclUJF-EfC5qG4CF2xiuYYC0NCf8u5rbiYFk8ARhIT4lY2AEPWzGpl1OtTvQEC0gA";
$registatoin_ids = array($regId);
$message = array("msg" => 12345);
$this->send_notification($registatoin_ids, $message);
}
public function send_notification($registatoin_ids, $message)
{
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
define('GOOGLE_API_KEY', 'AIzaSyBavsIgQKo1Nf9wKZ5o_fGvE_6MI52LFR0');
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch)
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
"MismatchSenderId" is the obvious problem that we are getting nowadays.
Here are the possible cases that cause this problem.
Case 1: Mismatching Sender ID ->
Please check the Project number which you are using. If it's is correct or not.
Case 2: Wrong API Key ->
Please be sure that you are using the same API_Key or not. And in most of the cases, we need to generate Server_Key instead of Android_Key.
Case 3: Wrong Device's ID ->
Most of the time the problem is due to the wrong Device ID(Registration ID generated by GCM).
Please be ensure that that Whenever you generate new API key, the device id's of your device gets changed. Then it will take almost 5 five minutes to get an effect.
Note : Your device id is bound with the API KEY.
So....
--New Key created.
--GCM for Android Turned "on" in Google Dev. Console.
--Device registered with backend fine (Android Project is doing its job). Device key on the server.
--Send to device. Fail! The same message is returned from GCM everytime.
To Recap. This is NOT an Android Studio, Android OS, or Device issue. The GCM servers are not even trying to send the message to the device. My server sends to GCM, it returns the message...
{"multicast_id":6047824495557336291,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
to the server. As far as I can tell this means the Device's ID (the one returned to the device when it registered for a push, and the one saved on the backend (in the control panel) does not match, or is somehow not associated with the API Key used when sending the message.
Sending, of course, starts on my server, goes to GCM, then goes to the device.
This is what's not happening. The message goes from my server to GCM and back to my server - with the error.
Super frustrating as all of you can imagine - we've all been through this nightmarish stuff before :-)
Reference : https://www.buzztouch.com/forum/thread.php?tid=C3CED924C86828C2172E924
Hope it will solve your problem.

Categories