I have a thingsuno board. There is one led on the board I want to turn on via a POST request (http integrations) if I do this command in my CLI it works:
curl -i -X POST --data '{"dev_id":"myid","port": 1,"confirmed": false, "payload_raw": "MDA="}' https://integrations.thethingsnetwork.org/ttn-eu/api/v2/down/myapplication/test?key=ttn-account-v2.thekey
But now I want to do it in PHP so I have this code:
<?php
//API Url
$endpoint_url = 'https://integrations.thethingsnetwork.org/ttn-eu/api/v2/down/myapp/test?key=ttn-account-v2.mykey';
$data_to_post = [
'dev_id' => 'mydevice',
'port' => 1,
'confirmed' => false,
'payload_raw' => 'MDA='];
$options = [
CURLOPT_URL => $endpoint_url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data_to_post,`enter code here`
CURLOPT_SSL_VERIFYPEER=> false
];
$curl = curl_init();
curl_setopt_array($curl, $options);
curl_exec($curl);
var_dump(curl_getinfo($curl));
curl_close($curl);
And it only returns HTTP400 badrequest. what am I doing wrong ?
Try to encode the data using json_encode:
$data_to_post = json_encode([
'dev_id' => 'mydevice',
'port' => 1,
'confirmed' => false,
'payload_raw' => 'MDA=']);
Related
I am trying to submit a php response to the following PlayFab API: https://learn.microsoft.com/en-us/rest/api/playfab/admin/account-management/reset-password?view=playfab-rest
This is my first ever php script and I have been working with this for quite some time and being able to run my script without errors but it seems like I have no payload.
The echo in the code:
echo ' The resp: ' .$resp;
...response from the above echo is:
The resp: string(0) ""
Unfortunately I really do not know what is wrong and how to fix it as there is not error messages. I have tried to echo $options array to control if there is a payload but not succeeded. I realise I need help and would really appreciate that.
$url = "https://titleId.playfabapi.com/Admin/ResetPassword/json/";
$data = array('Password' => $pw1, 'Token' => $params['token']);
$options = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data),
'header' => 'X-SecretKey: xxxxxxxxxxxx\r\n',
'ignore_errors' => true
)
);
$context = stream_context_create($options);
$resp = file_get_contents($url, false, $context);
echo ' The resp: ' .$resp;
var_dump($resp);
Ok here is the solution. I was able to get this to work in Postman and when I test the code it works.
Here is the snippet that work:
echo '>>>>>>>>>> TEST <<<<<<<<<<';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://99999.playfabapi.com/Admin/ResetPassword?Password=pekapeka&Token=1B5A9C01EFD5DB69',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'X-SecretKey: xxxxxxx',
'Content-Type: application/json\\'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
print_r($response);
echo '<br>========== END ==========';
How to pass client certificate (2 files .key and .pem) through http client request?
I need to include those files in the below http post request to be able to talk with the server.
$response = Http::post('https://domainname.com/api/client/session', array('xxx' => array('xx' => 'xxxx')));
I am able to do it using phpCurl like below:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $type,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => $header,
CURLOPT_SSLKEY => $pemPath,
CURLOPT_SSLCERT => $crtPath,
// CURLOPT_NOSIGNAL => 1
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
echo (json_encode($response));
echo ("\n\n");
if ($err) {
return ["success" => false, "message" => $err];
} else {
return ["success" => true, "data" => json_decode($response)];
}
But I need to do it using Http Client for many other purposes. Any suggestion?
You can use Guzzle options provided by http client
$response = Http::withOptions([
'ssl_key' => ['/path/to/cert.pem', 'password.key']
])->post('https://domainname.com/api/client/session');
It would be same as using ssl_key request option for guzzle http client instance directly.
use GuzzleHttp\Client;
$client = new Client();
$client->request('POST', 'https://domainname.com/api/client/session', [
'ssl_key' => ['/path/to/cert.pem', 'password.key']
]);
I am busy sending a HTTP curl request for request token , When i send the below code to get access token , when i receive the responds i would like the access token value and not entire responds.
$params = array(
'username' => 'nuser',
'password' => 'password',
);
$curlSecondHandler = curl_init();
curl_setopt_array($curlSecondHandler, [
CURLOPT_URL => 'https://localhost/api/v3/authentication/usernamepassword',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Content-Type: multipart/form-data',
'Authorization: Bearer '
],
CURLOPT_POSTFIELDS => $params,
]);
$response2 = curl_exec($curlSecondHandler);
curl_close($curlSecondHandler);
$arr = json_decode($response2);
echo $response2->data -> accessToken ;
I get this error
Trying to get property of non-object
I'm trying to get latitude and longitude from cell tower info using Google's geolocation api.
It requires a valid JSON with information like MCC, MNC, cellId, lac etc.., My PHP post request looks like this.
<?php
header("Access-Control-Allow-Origin: *");
$mcc = $_POST["mcc"];
$mnc = $_POST["mnc"];
$cellId = $_POST["cellId"];
$lac = $_POST["lac"];
$post_array = array(
"cellId" => (int) $cellId,
"locationAreaCode" => (int) $lac,
"mobileCountryCode" => (int) $mcc,
"mobileNetworkCode" => (int) $mnc,
);
$post_data = json_encode(array('cellTowers' => array($post_array)));
echo $post_data;
$url = "https://www.googleapis.com/geolocation/v1/geolocate?key=".$api_key; // not including api key here but its there in my code
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => $post_data
));
$result = curl_exec($ch);
echo "Result: ".$result;
curl_close($ch);
?>
However I get an error saying bad request in the response. The error is shown below.
Result: {
"error": {
"errors": [
{
"domain": "geolocation",
"reason": "invalidRequest",
"message": "Bad Request"
}
],
"code": 400,
"message": "Bad Request"
}
}
I thought my JSON was not in the correct format but it was working with the following command line execution, so that can't be the issue.
$ curl -d #your_filename.json -H "Content-Type: application/json" -i "https://www.googleapis.com/geolocation/v1/geolocate?key=API_KEY"
The above command in terminal gives lattitude and longitude properly with the same JSON in a file. What am I doing wrong ?
Try this
$DadosLBS['homeMobileCountryCode'] = $data['MCC'];
$DadosLBS['homeMobileNetworkCode'] = $data['MNC'];
$DadosLBS['radioType'] = 'gsm';
$DadosLBS['carrier'] = $data['MNCOperator'];
$DadosLBS['cellTowers'] = [
[
'mobileCountryCode' => $data['MCC'],
'mobileNetworkCode' => $data['MNC'],
'age' => $data['Age'],
'timingAdvance' => $data['TA'],
'locationAreaCode' => $data['LAC'],
'cellId' => $data['CELL_ID'],
'signalStrength' => $data['SIGNAL'],
],
];
//Ver detalhes da API no https://developers.google.com/maps/documentation/geolocation/intro?hl=pt-br
$service_url = "https://www.googleapis.com/geolocation/v1/geolocate";
//Chave de acesso
$Curl_Data = array(
'key' => <YOUR KEY HERE>
);
$CurlQueryString = http_build_query($Curl_Data);
//Preparando o método a ser enviado os dados
$Metodo = array(
CURLOPT_URL => $service_url.'?'.$CurlQueryString // Define URL to be called
);
//Criando s string de dados
$DadosPost = json_encode($DadosLBS);
//Preparando as opções padrões do CUrl
$Curl_Adicional_Options = array(
CURLOPT_CUSTOMREQUEST => "POST"
,CURLOPT_POSTFIELDS => $DadosPost
,CURLOPT_RETURNTRANSFER => true // return web page
,CURLOPT_CONNECTTIMEOUT => 15 // time-out on connect
,CURLOPT_TIMEOUT => 15 // time-out on response
,CURLOPT_FAILONERROR => true //
,CURLOPT_HEADER => false // don't return headers
,CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Content-Length: ' . strlen($DadosPost)
) // Dados para o cabeçalho do post
,CURLOPT_FOLLOWLOCATION => true // follow redirects
,CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
,CURLOPT_SSL_VERIFYPEER => false
,CURLOPT_SSL_VERIFYHOST => false
);
$Curl_Options = array_replace_recursive($Metodo,$Curl_Adicional_Options);
$cURLConn = curl_init();
curl_setopt_array($cURLConn, $Curl_Options);
$vDados['Curl']['Output'] = curl_exec($cURLConn);
$vDados['Curl']['Error'] = curl_error($cURLConn);
$vDados['Curl']['ErrorNum'] = curl_errno($cURLConn);
$vDados['Curl']['ErrorMsg'] = curl_strerror($vDados['Curl']['ErrorNum']);
$vDados['Curl']['Info'] = curl_getinfo($cURLConn);
curl_close($cURLConn);
if ($vDados['Curl']['ErrorNum'] != 0) {
$Dados['loc'] = array(
'status' => 'ERROR',
'error' => array(
'error_cod' => $vDados['Curl']['ErrorNum'],
'error_msg' => $vDados['Curl']['ErrorMsg']
)
);
return $Dados['loc'];
}
//Tratando as respostas
$vDados['Curl']['Dados'] = json_decode($vDados['Curl']['Output']) or die("Error: Cannot create object");
print_r($vDados['Curl']['Dados']);
Don't forget to create our key on google console.
I'm using the LinkedIn REST API to post updates to a users timeline.
Since a few days I get an Internal server error response from LinkedIn but the code worked before.
PHP:
$postTitle = "hello";
$postDesc = "world ";
$submitted-url = "http://example.com";
$submitted-image-url = "http://images.example.com/img/hello.jpg";
$comment = "foobar";
$postData = array('visibility' => array('code' => 'connections-only'),
'content' => array('title' => $postTitle,'description' => $postDesc,'submitted-url' => $postURL,'submitted-image-url' => $postImage), 'comment' => $postComment);
$ch = curl_init('https://api.linkedin.com/v1/people/~/shares?oauth2_access_token='.$oauthToken.'&format=json'
);
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('x-li-format: json', "Content-Type: application/json"),
CURLOPT_POSTFIELDS => json_encode($postData)
));
$response = curl_exec($ch);
How to fix that error?
Your code is invalid PHP (perhaps because of some edits you made before posting?); modifying it to:
$postTitle = "hello";
$postDesc = "world ";
$postURL = "http://example.com";
$postImage = "http://images.example.com/img/hello.jpg";
$postComment = "foobar";
$oauthToken = "<token>";
$postData = array(
'visibility' => array('code' => 'connections-only'),
'content' => array(
'title' => $postTitle,
'description' => $postDesc,
'submitted-url' => $postURL,
'submitted-image-url' => $postImage
),
'comment' => $postComment
);
$ch = curl_init('https://api.linkedin.com/v1/people/~/shares?oauth2_access_token='.$oauthToken.'&format=json');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('x-li-format: json', "Content-Type: application/json"),
CURLOPT_POSTFIELDS => json_encode($postData)
));
$response = curl_exec($ch);
works if only $oauthToken is set to a valid token. Assuming your real code is correct the only possiblity left is that your OAuth token has expired and you need to obtain a new one first. By adding CURLOPT_VERBOSE => TRUE to the cURL options you would find out more about the error that LinkedIn returns.
You may considering using the LinkedIn PHP SDK (provided by the community) instead: https://github.com/Happyr/LinkedIn-API-client
We faced similar issue with Linkedin API recently. Finally figured out the fix by changing the url.
New URL : "https://api.linkedin.com/v1/people/~/shares"
Instead of specifying 'oauth2_access_token' in the query string,
add it in the header - specify :
"Authorization", "Bearer " + accessToken.
And finally in the request body parameter, add your json/xml data to post
You have to Use your Authentication Token in Request Headers.
This is the working code. Try it.
$postTitle = "hello";
$postDesc = "world ";
$submitted-url = "http://example.com";
$submitted-image-url = "http://images.example.com/img/hello.jpg";
$comment = "foobar";
$oauthToken = "TokenHere";
$postData = array('visibility' => array('code' => 'connections-only'),
'content' => array('title' => $postTitle,'description' => $postDesc,'submitted-url' => $postURL,'submitted-image-url' => $postImage), 'comment' => $postComment);
$ch = curl_init('https://api.linkedin.com/v1/people/~/shares?format=json');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('x-li-format: json', "Content-Type: application/json", "Bearer: ".$oauthToken.""),
CURLOPT_POSTFIELDS => json_encode($postData)
));
$response = curl_exec($ch);