Laravel OAuth Authorization Header for FitBit API - php

I have been struggling for days now to find a decent solution for Laravel but to no avail.
There are many libraries out there that at one point may have worked to provide a Laravel - FitBit API OAuth integration however after trying over 15 different ones and none of them working I am stuck.
Reading the FitBit Documentation I see that once you receive a token you must swap the authorization code with an access token. To do this you need to send an authorization header like this:
POST https://api.fitbit.com/oauth2/token
Authorization: Basic Y2xpZW50X2lkOmNsaWVudCBzZWNyZXQ=
Content-Type: application/x-www-form-urlencoded
client_id=22942C&grant_type=authorization_code&redirect_uri=http%3A%2F%2Fexample.com%2Fcallback&code=1234567890
I have tried using guzzle and a few other libraries for sending the requests but none of them support the format that FitBit require.
I've seen sites with FitBit API integrated so there must be a solution for this.
If anyone has managed to integrate the FitBit API please let me know where I am going wrong.
Thanks.

I don't have a fitbit account, so I can't test this and it will probably need some tweaking, but I would start with something like:
class FitbitConnection{
public function getToken($request_url, $client_id, $client_secret, $code, $redirect_uri){
// base64 encode the client_id and client_secret
$auth = base64_encode("{$client_id}:{$client_secret}");
// urlencode the redirect_url
$redirect_uri = urlencode($redirect_uri);
$request_url .= "?client_id={$client_id}&grant_type=authorization_code&redirect_uri={$redirect_uri}&code={$code}";
// Set the headers
$headers = [
"Authorization: Basic {$auth}",
"Content-Type: application/x-www-form-urlencoded",
];
// Initiate curl session
$ch = curl_init();
// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Options (see: http://php.net/manual/en/function.curl-setopt.php)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_POST, 1);
// Execute the curl request and get the response
$response = curl_exec($ch);
// Throw an exception if there was an error with curl
if($response === false){
throw new Exception(curl_error($ch), curl_errno($ch));
}
// Get the body of the response
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$responseBody = substr($response, $header_size);
// Close curl session
curl_close($ch);
// Return response body
return $responseBody;
}
}
You should note that I've commented out
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
You can put this option back in if you get an SSL certificate problem on your localhost, but you shouldn't use it in production .
You can then just do something like:
try{
$fitbitConnection = new FitbitConnection();
$token_response = $fitbitConnection->getToken("https://api.fitbit.com/oauth2/token","22942C","client_secret","1234567890","http://www.example.com");
echo $token_response;
}catch(Exception $e){
// curl error
echo $e->getMessage();
}

Related

2ba web API post request with php curl

Im using 2ba its API to receive product information which I later on want to store inside my database. I am trying to create a post request for receiving the data I need. This is the request I want to get to working. And this is my code:
postApiData.php
<?php
/**
* Posts API data based on given parameters at index.php.
*/
// Base url for all api calls.
$baseURL = 'https://api.2ba.nl';
// Version number and protocol.
$versionAndProtocol = '/1/json/';
// All parts together.
$url = $baseURL . $versionAndProtocol . $endPoint;
// Init session for CURL.
$ch = curl_init();
// Init headers. Security for acces data.
$headers = array();
$headers[] = "Authorization: Bearer " . $token->access_token;
// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
echo "<br>";
echo "Error location: postApiData";
exit();
}
// Ends the CURL session, frees all resources that belongs to the curl (ch).
curl_close($ch);
// String to array.
$data = json_decode($data);
?>
index.php
// Specified url endpoint. This comes after the baseUrl.
$endPoint = 'Product/forGLNAndProductcodes';
// Parameters that are required or/and optional for the endPoint its request.
$parameters = [
'gln' => '2220000075756',
'productcodes' => ['84622270']
];
// Get Supplier info
include("postApiData.php");
print_r($data);
exit();
My API key does for sure work since I have done alot of different GET requests already, also im not getting an access denied error.
The error I get with this code is: The requested URL returned error: 500 Internal Server Error
I also receive a "Bad request" 400 error when I remove the curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); part
Is there anyone who knows what im doing wrong?
PS: It's not really possible to try this code yourself unless you have a 2ba account with working key's etc.
Okey I fixed it already...
I had to add some extra headers and change the $parameters values like this:
postApiData.php
// Added this above the authorization.
$headers[] = "Connection: close";
$headers[] = "Accept-Encoding: gzip,deflate";
$headers[] = "Content-Type: application/json";
// Removed the http_build_query part.
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
index.php
// Encoded in a json way as asked by 2ba request.
$parameters = json_encode($parameters);

Xamarin Forms does not recieve firebase notification send from php

I am Working on Xamarin Forms Platform to Implement the Firebase Notification. I have add google-services.json and GoogleService-Info.plist in android and IOS applicaition respectively by setting appropriate property.I have generated token code natively and using dependency service I am getting the generated token for sending notification on same or different device. For sending the Notification I am using php since my application use php as mediator for communicating with database and xamarin forms.
class MyFirebaseIIDService : FirebaseInstanceIdService, IPushHelper
{
public string GetPushToken()
{
return FirebaseInstanceId.Instance.Token;
}
}
public interface IPushHelper
{
string GetPushToken();
}
This is how I am Accessing Token in Xamarin Forms
string token = DependencyService.Get<IPushHelper>().GetPushToken();
PHP Code For Sending Notification
$fields = array(
'to' => $token // Token Generated By Xamarin Forms
'data'=> array("message"=>$message) // Message For Notification
);
//Header Including API Key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$api_key
);
$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_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
Also, I have tried shell_exec() for running curl
$result =shell_exec('curl -X POST --header "Authorization: key='.$api_key.'" --header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"'.$token.'\",\"priority\":\"high\",\"notification\":{\"body\": \"'.stripslashes($message).'\"}}"');
Output for result:
"{"multicast_id":8563984716459935776,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1585669578263131%631c6722f9fd7ecd"}]}"
But My Application does not recieve push Notification and I could see the send notication in firebase console.
Please Help me for sending and getting Notification using Firebase

Does Marketo API block curl on a per account basis?

I am trying to connect to the Marketo.com REST API using curl.
I can't get a response from the identity service. I only get an error message
"[curl] 6: Couldn't resolve host 'MY_CLIENT_ENDPOINT.mktorest.com'
,
but I can print the constructed url and paste it into a browser address bar and this will provide the expected response with the access_token element.
I can use curl in php and in a terminal to access my gmail account so curl is able to access an https service.
I have tried sending the parameters in the curl url as a get request and also by declaring them with curl's -F option as a post request
My application uses dchesterton/marketo-rest-api available on github, but I have also tried a simple php curl request just to get the access token.
private function getToken() {
$url = "$this->client_url/identity/oauth/token?grant_type=client_credentials&client_id=$this->client_id&client_secret=$this->client_secret";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$errors = curl_error($ch);
curl_close($ch);
file_put_contents($this->logDir . 'access_token_response' . date('Y-m-d') . '.txt', $url . "\n" . $response . "\n", FILE_APPEND);
if ($errors) {
file_put_contents($this->logDir . 'access_token_errors' . date('Y-m-d') . '.txt', $errors . "\n", FILE_APPEND);
}
return $response['access_token'];
}
Again, this fails with the same error but produces a perfectly formed url that I can paste into the browser and get a valid response.
I have also tried this using post instead of get as I have for every other test mentioned, and these have been tried on my localhost and on a test server.
Can anyone explain to me why this would fail?
Does Marketo block curl on a per account basis?
I was trying to implement something similar but my code wasn't working. I'm not sure exactly what is failing but I tried your code and it seems to work perfectly after some slight modifications:
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($request_data));
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($curl);
$errors = curl_error($curl);
curl_close($curl);
I hope this helps.

Trying to make an API request using PHP with AWS Route53

I need to make one API request to AWS Route53 to create a reusable delegation set. You can't do this through the console web interface, it has to be through the API.
Here is the documentation for making this API request: http://docs.aws.amazon.com/Route53/latest/APIReference/api-create-reusable-delegation-set.html
<?php
$baseurl = "route53.amazonaws.com/2013-04-01/delegationset";
$body = '<?xml version="1.0" encoding="UTF-8"?>
<CreateReusableDelegationSetRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<CallerReference>whitelabel DNS</CallerReference>
</CreateReusableDelegationSetRequest>';
$ch = curl_init();
// Set query data here with the URL
curl_setopt($ch, CURLOPT_URL, $baseurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $body );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: route53.amazonaws.com','X-Amzn-Authorization: '));
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$rest = curl_exec($ch);
if ($rest === false)
{
// throw new Exception('Curl error: ' . curl_error($crl));
print_r('Curl error: ' . curl_error($ch));
}
curl_close($ch);
print_r($rest);
?>
I know the request isn't signed/authenticated, but I'm not even able to connect to the server. I would at least like to get an error message that says I'm not authenticated before I continue. Instead all I get is "connection refused".
I'm sure I'm doing something completely wrong here. But Google has been of no use.
scrowler was right. I changed:
$baseurl = "route53.amazonaws.com/2013-04-01/delegationset";
to
$baseurl = "https://route53.amazonaws.com/2013-04-01/delegationset";
I got the error message I was expecting and now I can work on the next step.

Showing Unauthorized in box api response

I am using the box api as mentioned in the documentation. I get the ticket from api_key and then auth_token from api_key and ticket.
But when i use this auth_token for getting information like folder list or file contents etc. I get unauthorized error in response.
Here is my code:
$auth_token = $_REQUEST["auth_token"];
//exit($auth_token);
$headers = array(
"Authorization: BoxAuth api_key=".$box_api_key."&auth_token=".$auth_token
);
$http_message = curl_init("https://www.box.com/api/2.0/folders/0");
curl_setopt($http_message, CURLOPT_RETURNTRANSFER, true);
curl_setopt($http_message, CURLOPT_HTTP_VERSION, "CURL_HTTP_VERSION_1_1");
curl_setopt($http_message, CURLOPT_HTTPHEADER, $headers);
curl_setopt($http_message, CURLINFO_HEADER, true);
curl_setopt($http_message, CURLINFO_HEADER_OUT, true);
curl_setopt($http_message, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($http_message);
print($response);
What may be the problem in the code?
Thanks!
Thank you very much in advance!!!
Make sure you're setting $box_api_key to the api_key you're using to get the ticket and auth token. Also, while this should have no bearing on your question, please use the hostname api.box.com for all API V2 requests (aka, https://api.box.com/2.0/folders/0)

Categories