calling a .net service from php - php

I'm trying to call a .NET api controller from php
$user = $ctl->getUser();
$client = $ctl->getCurrentClient();
$userid = $user->getID();
$clientid = $client->getID();
$data = array('userid' => $userid, 'clientid' => $clientid);
$data_string = json_encode($data);
$ch = curl_init('https://localhost:44346/api/participantapi/TransferParticipants');
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-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
My controller looks like
[HttpPost]
[Route("TransferParticipants")]
public IActionResult TransferParticipants(JObject data)
If I make the call from postman it works fine. But when I make this call from the php code, I don't see anything. Is there anyway for me to see what I'm missing. Any help would be much appreciated.
I tried the options from that post and still no luck. It seems like it isn't sending at all.

Related

How to access API in R with API documentation in PHP?

I am a complete beginner when it comes to APIs. I would like to access the API of https://foundico.com, I even received a public and a private key, however, the documentation is quite sparse and only provides the code in PHP (can be found here https://foundico.com/developers/)
The code is as follows:
$privateKey = 'privateKey';
$publicKey = 'publicKey';
$parameters = array('status' => 'upcoming');
$postData = json_encode($parameters);
$accessKey = base64_encode(hash_hmac('sha256', $postData, $privateKey, true));
$ch = curl_init('https://foundico.com/api/v1/icos/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'X-Foundico-Public-Key: '.$publicKey,
'X-Foundico-Access-Key: '.$accessKey
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
I would like to access the API in R so that I can directly use the data in my code. How would I translate this into R?

Uniquely identify iOS device with DeviceCheck API and server side php code not working

I'm getting error : Missing or incorrectly formatted payload
I'm generating device token from Apple DeviceCheck API in swift language with real device and also passing Transaction ID to this php api.
jwt token generating successfully with this code but further code not working with apple query bit api.
This is my server side code in php :
<?php
require_once "vendor/autoload.php";
use Zenstruck\JWT\Token;
use Zenstruck\JWT\Signer\OpenSSL\ECDSA\ES256;
use \Ramsey\Uuid\Uuid;
$deviceToken = (isset($_POST["deviceToken"]) ? $_POST["deviceToken"] : null);
$transId = (isset($_POST["transId"]) ? $_POST["transId"] : null);
function generateJWT($teamId, $keyId, $privateKeyFilePath) {
$payload = [
"iss" => $teamId,
"iat" => time()
];
$header = [
"kid" => $keyId
];
$token = new Token($payload, $header);
return (string)$token->sign(new ES256(), $privateKeyFilePath);
}
$teamId = "#####";// I'm passing My team id
$keyId = "#####"; // I'm passing my key id
$privateKeyFilePath = "AuthKey_4AU5LJV3.p8";
$jwt = generateJWT($teamId, $keyId, $privateKeyFilePath);
function postReq($url, $jwt, $bodyArray) {
$header = [
"Authorization: Bearer ". $jwt
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyArray); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$server_output = curl_exec($ch);
//$info = curl_getinfo($ch);
// print_r($info);
//echo 'http code: ' . $info['http_code'] . '<br />';
//echo curl_error($ch);
curl_close($ch);
return $server_output;
}
$body = [
"device_token" => $deviceToken,
"transaction_id" => $transId,
"timestamp" => ceil(microtime(true)*1000)
];
$myjsonis = postReq("https://api.development.devicecheck.apple.com/v1/query_two_bits", $jwt, $body);
echo $myjsonis;
?>
Where is problem in this code? Or any other solution in php code.
Is there anything that I'm missing.
I just checked the Docs. They don't want POST fields like a form, they want a JSON body instead. Here's a snippet of code that you should be able to tweak to do what you require:
$data = array("name" => "delboy1978uk", "age" => "41");
$data_string = json_encode($data);
$ch = curl_init('http://api.local/rest/users');
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-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
Actually, looking again at your code, it could be as simple as running json_encode() on your array.

How to query Github GraphQL API from PHP script?

I am querying Github API for some internal monitoring interface. I came across the new GraphQL implementation in the documentation and decided to use it for my interface.
Accordingly, I prepared this small PHP script to test the Github GraphQL API which I have pasted below. I always get ‘Problems parsing JSON’ error whenever I run the script. Am I doing something wrong here? Can somebody help me highlight any mistake I am doing?
<?php
//GRAPHQL request
$postData =<<<‘JSON’
{
“query”: query{
user(login:“tojochacko”) {
name
}
}
}
JSON;
$json = json_encode($postData);
$chObj = curl_init();
curl_setopt($chObj, CURLOPT_URL, ‘https://api.github.com/graphql’);
curl_setopt($chObj, CURLOPT_RETURNTRANSFER, true);
curl_setopt($chObj, CURLOPT_CUSTOMREQUEST, ‘POST’);
curl_setopt($chObj, CURLOPT_POSTFIELDS, $json);
curl_setopt($chObj, CURLOPT_HEADER, true);
curl_setopt($chObj, CURLOPT_VERBOSE, true);
curl_setopt($chObj, CURLOPT_HTTPHEADER,
array(
‘User-Agent: PHP Script’,
‘Content-Type: application/json’,
'Authorization: bearer '.GITHUB_TOKEN
)
);
$response = curl_exec($chObj);
echo $response;
?>
I found the fix myself. The JSON that I was passing to the Github API was not in correct expected format. Github unfortunately does not have correct documentation on the expected format. I had to read the GraphQL spec and dig through some php client library codes to understand the format. Below is the correct code to query Github GraphQL API. Hope this helps anyone who goes through the same issue.
//GRAPHQL request
$query = <<<'JSON'
query{
user(login:"tojochacko") {
name
}
}
JSON;
$variables = '';
$json = json_encode(['query' => $query, 'variables' => $variables]);
$chObj = curl_init();
curl_setopt($chObj, CURLOPT_URL, ‘https://api.github.com/graphql’);
curl_setopt($chObj, CURLOPT_RETURNTRANSFER, true);
curl_setopt($chObj, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($chObj, CURLOPT_HEADER, true);
curl_setopt($chObj, CURLOPT_VERBOSE, true);
curl_setopt($chObj, CURLOPT_POSTFIELDS, $json);
curl_setopt($chObj, CURLOPT_HTTPHEADER,
array(
'User-Agent: PHP Script',
'Content-Type: application/json;charset=utf-8',
'Authorization: bearer '.GITHUB_TOKEN
)
);
$response = curl_exec($chObj);
echo $response;

Passing JSON to PHP CURL [duplicate]

I have been working on building an Rest API for the hell of it and I have been testing it out as I go along by using curl from the command line which is very easy for CRUD
I can successfully make these call from the command line
curl -u username:pass -X GET http://api.mysite.com/pet/1
curl -d '{"dog":"tall"}' -u username:pass -X GET http://api.mysite.com/pet
curl -d '{"dog":"short"}' -u username:pass -X POST http://api.mysite.com/pet
curl -d '{"dog":"tall"}' -u username:pass -X PUT http://api.mysite.com/pet/1
The above calls are easy to make from the command line and work fine with my api, but now I want to use PHP to create the curl. As you can see, I pass data as a json string. I have read around and I think I can probably do the POST and include the POST fields, but I have not been able to find out how to pass http body data with GET. Everything I see says you must attached it to the url, but it doesn't look that way on the command line form. Any way, I would love it if someone could write the correct way to do these four operations in PHP here on one page. I would like to see the simplest way to do it with curl and php. I think I need to pass everything through the http body because my php api catching everything with php://input
PUT
$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
GET
See #Dan H answer
DELETE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
You can use this small library: https://github.com/ledfusion/php-rest-curl
Making a call is as simple as:
// GET
$result = RestCurl::get($URL, array('id' => 12345678));
// POST
$result = RestCurl::post($URL, array('name' => 'John'));
// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));
// DELETE
$result = RestCurl::delete($URL);
And for the $result variable:
$result['status'] is the HTTP response code
$result['data'] an array with the JSON response parsed
$result['header'] a string with the response headers
Hope it helps
For myself, I just encode it in the url and use $_GET on the destination page. Here's a line as an example.
$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
EDIT: Adding the destination snippet... (EDIT 2 added more above at OPs request)
<?php
if(!isset($_GET['json']))
die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>
I was Working with Elastic SQL plugin.
Query is done with GET method using cURL as below:
curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'
I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.
This code, works fine plus Basic Auth Header:
$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";
function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
if ($auth)
curl_setopt($ch, CURLOPT_USERPWD, $auth);
if (strlen($data) > 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$resp = curl_exec($ch);
if(!$resp){
$resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
}
curl_close($ch);
return $resp;
}
$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT
set one more property curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);

GCM Curl php send two push

I'm implementing GCM on my website from this tutorial
All work fine when I send a Curl query by command line on the dev windows, I see one call of the event listener.
But, when I send query by PHP, there are two call of the listener. I don't know where that from....
My PHP code :
<?php
//request url
$url = 'https://android.googleapis.com/gcm/send';
//your api key
$apiKey = $apiKey;
//registration ids
$registrationIDs = array('fwt_qmI-Rlo:A...eencfYg2_0WU');
$fields = array('registration_ids' => $registrationIDs);
//http header
$headers = array('Authorization: key=' . $apiKey,
'Content-Type: application/json');
//curl connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
And my JS code :
self.addEventListener('push', function(event) {
console.log('Push message', event);
});
I never realy used Curl on PHP, and maybe there are errors...
Can someone help me ?
Thanks.

Categories