PHP HTTP CURL PUT request for LIFX Power On/Off - php

I'm trying to power all of my Lifx bulbs on/off using PHP.
The API documentation, http://developer.lifx.com/, says to use a PUT request:
curl -u "c87c73a896b554367fac61f71dd3656af8d93a525a4e87df5952c6078a89d192:" \
-X PUT \
-d "state=on" \
"https://api.lifx.com/v1beta1/lights/all/power"
Now using that curl command works in the command line. It prompts me for my password unless I add it after the colon in the "username".
The trouble is when I try to translate that command into PHP like so:
$authToken = 'c87c73a896b554367fac61f71dd3656af8d93a525a4e87df5952c6078a89d192:myFakePassword';
$ch = curl_init('https://api.lifx.com/v1beta1/lights/all/power');
$headers = array("selector=all&state=on",'Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
This goes through, but I get a 404 Not Found which the Lifx documentation says is probably a malformed selector.
Note: I was able to make a successful call with PHP to toggle the power with this POST:
$authToken = 'c87c73a896b554367fac61f71dd3656af8d93a525a4e87df5952c6078a89d192';
$ch = curl_init('https://api.lifx.com/v1beta1/lights/all/toggle');
$headers = array("selector=all",'Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
But I don't want to just toggle the lights, I want to be able to specify on or off. What could be wrong with my PUT request?
Thank you for any suggestions.

Solved this by setting some other curl options:
$ch = curl_init($link);
$headers = array('Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = "state=on";
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
$link is https://api.lifx.com/v1beta1/lights/all/power
$authToken is my api key

Related

Php cURL with calling an API with GRAPHQL

I am trying to call an api called Wave I have used cURL before but never with GRAPHQL queries. I am wondering what is wrong with the below when using cURL. I get an error Bad Request Below is an exmple of my code.
This is what the API cURL is
curl -X POST "https://reef.waveapps.com/graphql/public" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Content-Type: application/json" \
-d '{ "query": "query { user { id defaultEmail } }" }'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://reef.waveapps.com/graphql/public');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{ "query": "query { user { id defaultEmail } }');
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer 1212121';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
Any help would be helpful.
For those wanting to query a GraphQL service WITHOUT a third party library, I basically took Brian's code and tested against a GraphCMS service I had already written Node.js code for. So I knew the url, authorization token, and query all worked.
<?php
$endpoint = "https://api-euwest.graphcms.com/v1/[[your id number here]]/master";//this is provided by graphcms
$authToken = "[[your auth token]]";//this is provided by graphcms
$qry = '{"query":"query {products(where:{status:PUBLISHED}){title,img,description,costPrice,sellPrice,quantity,sku,categories {name},brand {name}}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$authToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
?>
All worked fine.
The auth token is a big long character string provided by GraphCMS and only needs to be passed in the header. So no real tricky authentication process - as long as you have the token.
I can recommend using https://github.com/softonic/graphql-client, it has worked great for us.
A way easier way to go about doing this is by using an API platform. I often use Postman, the platform have the functionality to give you the PHP cURL code for a GraphQL request in the GraphQl tools part of the application.
You can create your own client passing whatever middleware you'd like:
$clientWithMiddleware = \MyGuzzleClientWithMiddlware::build();
$graphQLClient = new \Softonic\GraphQL\Client(
$clientWithMiddleware,
new \Softonic\GraphQL\ResponseBuilder()
);
For an example how to build a Guzzle client with middleware you can check this out:
https://github.com/softonic/guzzle-oauth2-middleware/blob/master/src/ClientBuilder.php
If there is no authentication
You can use file_get_contents instead of curl
$url = http://myapi/graphql?query={me{name}}
$html =file_get_contents($url);
echo $html;
use json in query paramter for graphql;
Bit late but I made this code
$endpoint = "https://gql.waveapps.com/graphql/public";
$authToken = ""; //Your Bearer code
$qry = '{"query": "query {user {id firstName lastName defaultEmail createdAt modifiedAt}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$authToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}

Posting to API with curl not working

$headers = array();
$headers[] = 'Authorization: hmac ' .$websiteKey.':'.$hmac .':'.$nonce . ':'.$time;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl,CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
var_dump($result);
curl_close($curl);
I have the code above, i want to post to an api. Somehow its not working. I tried using a var_dump on the result variable. The result is:
string(117) "{"Message":"The request entity's media type 'application/x-www-form-urlencoded' is not supported for this resource."}"
Any idea why its not posting to the api?
The value of the $post=
{"AmountDebit":10,"Currency":"EUR","Invoice":"testinvoice 123","Services":{"ServiceList":[{"Action":"Pay","Name":"ideal","Parameters":[{"Name":"issuer","Value":"ABNANL2A"}]}]}}
Headers:
$headers[] = 'Authorization: hmac ' .$websiteKey.':'.$hmac .':'.$nonce . ':'.$time;
If you don't specify a Content-Type header when making a POST call with Curl, it will add one in with the value application/x-www-form-urlencoded.
From the Everything Curl book:
POSTing with curl's -d option will make it include a default header that looks like Content-Type: application/x-www-form-urlencoded. That's what your typical browser will use for a plain POST.
Many receivers of POST data don't care about or check the Content-Type header.
If that header is not good enough for you, you should, of course, replace that and instead provide the correct one.
Judging by your request, I imagine you'll need to add the following to the top of your script:
$headers[] = 'Content-Type: application/json';
But depending on the exact API you're posting to, this might need to be different.
Have You installed curl before using it.
If it not install try google for Curl installation
and use my curl function for post request its 100% working-
public function curlPostJson() {
$headers = [];
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-Length: ' .strlen(json_encode($paramdata));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paramdata));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
$server_output = curl_exec($ch);
curl_close($ch);
return json_decode($server_output);
}

How to declare CURL body for CoinBase API call in php

I want use php curl to interact with coinbase api. Simple API calls that does not require data to be passed are successful. What I want to do is create address.
CLI curl works. The command line curl command sample is below:
curl https://api.coinbase.com/v2/accounts/82de7fcd-db72-5085-8ceb-bee19303080b/addresses \
-X POST \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c' \
-d '{"name": "New receive address"}'
}
My php code excerpt
$apiurl = "https://api.coinbase.com";
$secret = "coinbase api secret";
$method = "POST";
$requestPath = "/v2/accounts/actualAccountID/addresses";
$body = "";
$url = $apiurl.$requestPath;
$data["name"] = "curl smj6 ary";
$body=json_encode($data);
$string = $timestamp.$method.$requestPath.$body;
$sig = hash_hmac('sha256', $string, $secret);
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
if($method == "POST"){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
$headers = [
"CB-ACCESS-KEY: xxx",
"CB-ACCESS-SIGN:$sig",
"CB-ACCESS-TIMESTAMP: $timestamp",
"CB-VERSION: 2018-03-21",
"accept: application/json;charset=utf-8"
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute
$result_json = curl_exec($ch);
It returns
{"errors":[{"id":"authentication_error","message":"invalid signature"}]}
Since it works with listing user. I guess th error occurs the way iam passing post data to curl.
Similar Questions that I found on SO but none solves my issue. Please help!
Invalid Signature Coinbase
CoinBase "invalid signature" PHP Buy API Request
How to declare CURL body for CoinBase API call
Api key authentication for coinbase
UPDATE:
$apiurl = "https://api.coinbase.com/v2/";
$requestPath = "accounts/$accountid/addresses";
returns same error
There are sites that convert the command line cURL syntax to PHP, like https://incarnate.github.io/curl-to-php/
I just pasted your command and:
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.coinbase.com/v2/accounts/82de7fcd-db72-5085-8ceb-bee19303080b/addresses");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"name\": \"New receive address\"}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c";
$headers[] = "CB-ACCESS-KEY: <your api key>";
$headers[] = "CB-ACCESS-SIGN: <the user generated message signature>";
$headers[] = "CB-ACCESS-TIMESTAMP: <a timestamp for your request>";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

Post the data with header in curl not working in php?

I'm trying to create the box app users using PHP. The curl for create user as follows, and it is working on terminal
curl https://api.box.com/2.0/users \
-H "Authorization: Bearer <Access token>" \
-d '{"name": "New User", "is_platform_access_only": true}' \
-X POST
Same thing I have tried with php But it is giving the following error
{"type":"error","status":400,"code":"invalid_request_parameters","help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Invalid input parameters in request","request_id":"6688622675982fb5339a37"}
The following one I have tried
$developer_token = "TOKEN" ;
$access_token_url = "https://api.box.com/2.0/users";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $access_token_url);
//Adding Parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'name'=>'NEW USER',
'is_platform_access_only'=>'true',
));
//Adding Header
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$developer_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response1 = curl_exec($ch);
If I remove the Post parameters, and run with only headers it is give the result of users. But with post it is throws error.
I have rise the same question in Perl tag with Perl code. There I got answer by user #melpomene.
We should encode the data as JSON. It is working,
Then the final code is
$data = array(name=>SOMENAME,is_platform_access_only=>true);
$data = json_encode($data);
$header = array("Authorization: Bearer <TOKEN>");
$ch = curl_init("https://api.box.com/2.0/users/");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response1 = curl_exec($ch);
curl_close($ch);

cURL Output in PHP

I have this curl output where I replace with my id, secret and url. It gives correct response.
curl -XPOST -H "Cache-Control:no-cache" -H "Content-Type:application/json" --user 'id:secret' 'url'
But when I'm trying to write it in php in the following way, it's giving error for invalid cleint. How to rewrite curl from the above output in the same way in php? Thanks!
$url = 'https://test.api.neteller.com/v1/oauth2/token?grant_type=client_credentials';
$clientId = 'client_id;
$clientSecret = 'secret_id';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERPWD, $clientId . ":" . $clientSecret);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
It's giving error - 'invalid cleint', but when I run it in console, it returns access token. This code is only for access token, not for payment.
Edited: My current code is:
$url ='https://test.api.neteller.com/v1/oauth2/token?grant_type=client_credentials';
$clientId = NETELLER_CLIENT_ID;
$clientSecret = NETELLER_CLIENT_SECRET;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
'Authorization: Basic '. base64_encode($clientId) . ':' . base64_encode($clientSecret),
'Content-Type:application/json'
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
if (curl_error($curl)) {
curl_close($curl);
throw new \Exception('System error. Can not get neteller token');
}
curl_close($curl);
Tried to add the credentials as part of the headers.
$headers = array(
'Authorization: Basic '. base64_encode($clientID . ':' . $clientSecret),
'Content-Type:application/json'
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
Ok I found out.
Update:
There are 4 reasons why you may get { "error": "invalid_client" } when trying to run your code.
You are using client_id + client_secret from your test account on the production environment or vice versa.
Your client_id or client_secret values are wrong.
The IP address from which your application is making outgoing requests is not white-listed in your merchant account.
You are not sending the Authorization header properly.
You missed curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type:application/json", "Cache-Control:no-cache")); from your code.

Categories