Hello stackoverflow members.
I'm not a person who likes to ask for a help but in this case it's IMO the only way to solve my problem. Google didn't help me much.
So. My problem:
I want to get some data using Twitch API. Sounds easy? I wish it was. Below I'm posting my actual code (it's small but it was modified various of times and now it look like...):
$user = json_decode(file_get_contents('https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=MY_CORRECT_CLIENT_ID&redirect_uri=http://localhost/php/twitch.php&scope=user_read'), true);
print_r($user); // returns nothing
$token = $user['access_token'];
print_r($token); // same as above
$ch = curl_init();
// some stupid curls
curl_setopt($ch, CURLOPT_URL, 'https://api.twitch.tv/kraken/streams/followed');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Authorization: OAuth '.$token );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$retval = curl_exec($ch);
curl_close($ch);
$result = json_decode($retval, true);
It returns... Nothing. So I used ready solution from discussions.twitch. (I wish I could write the name of the author of this code but I'm too tired to search it again. Either way thanks!):
$ch = curl_init("https://api.twitch.tv/kraken/oauth2/token");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
'client_id' => 'blablabla_correct',
'client_secret' => 'blablabla_also_correct',
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://localhost/php/twitch.php',
'code' => $_GET['code']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$data = curl_exec($ch);
$response = json_decode($data, true);
//var_dump($response);
$access_token = $response["access_token"];
echo $access_token;
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$returnobj = curl_exec($ch);
curl_close($ch);
return $returnobj;
}
$testobj = json_decode(get_data("https://api.twitch.tv/kraken/user?oauth_token=".$access_token."&client_id=".$fields['client_id']));
echo "<br>Data: ";
print_r($testobj);
This code above is a bit better. Only a bit. It returns Error 401. Why? Because it can't get auth token. Well, it's something but not what I wanted to get. What should I do now? Maybe it's fault of localhost address?
FAQ(?):
Yes, I'm using correct data from my Twitch application settings page.
Yes, I'm confused
You're making two calls to the Twitch API, and you need to debug them independently.
For now, just skip the second call. Focus on the one where you grab your access token.
Try this:
// to start, just use the code you've already got:
$ch = curl_init("https://api.twitch.tv/kraken/oauth2/token");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
'client_id' => 'blablabla_correct',
'client_secret' => 'blablabla_also_correct',
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://localhost/php/twitch.php',
'code' => $_GET['code']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$data = curl_exec($ch);
// Now, here we believe the first error comes into play, so let's check it out
print_r($data); // confirm that this is not what we want
$info = curl_getinfo($ch); // let's get some details about that last request
// print it out and see what we get
echo '<pre>';
print_r($info);
echo '</pre>';
... that should give you a starting point to figure out what's going on. If you see an auth token, then you're not accessing it in the right way. If you don't, the info will give you some information about why.
I don't know what redirect_uri is (can you link to docs that explain it?) so I can't know if the localhost reference is a problem there.
Related
I was wondering if you could help me out with a bit of code for a cCURL request using PHP, I'm trying to retrieve data from the fpl api that would show my league standings. The url for the league standings api is - https://fantasy.premierleague.com/api/leagues-classic/my_league_id/standings/?page_new_entries=1&page_standings=1 I can see the data via the browser but when I try to retrieve it with a curl request with PHP it comes back with a 403 error with the message "Authentication credentials were not provided". That would mean that I would need login credentials to retrieve it.
After looking into it using dev tools and postman, I now know that I need to get a csrf token by logging in then save the token to use when I make the request for the league standings. I have no idea how to go about this, I kind of do but I would really appreciate if someone could give it a go for me.
What I would need to do is make a POST request to https://users.premierleague.com/accounts/login/ with this form data -
"login" => "my_email",
"password" => "my_password",
"app" => "plfpl-web",
"redirect_uri" => "https://fantasy.premierleague.com/",
After making the request I would need to capture the csrf token cookie, which I believe would be in the hidden input with the name - "csrfmiddlewaretoken" and save it in a variable.
Once getting the token and saving it, I would then make a GET request to https://fantasy.premierleague.com/api/leagues-classic/my_league_id/standings/ with placing the csrf token variable that I saved into the headers and then json decode that data so I'm able to echo out the league details.
I'm pretty sure that's how to do it but I'm not that great at PHP and was wondering if there is any savour out there that could help a brother out. Any help would be much appreciated :)
I've started with the first part, making the initial post request, but have had no luck in returning the token. Here's my code so far -
<?php
$cookie = "cookies.txt";
$url = 'https://users.premierleague.com/accounts/login/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
// var_dump($response);
$dom = new DOMDocument;
#$dom->loadHTML($response);
$tags = $dom->getElementsByTagName('input');
for($i = 0; $i < $tags->length; $i++) {
$grab = $tags->item($i);
if($grab->getAttribute('name') === 'csrfmiddlewaretoken') {
$token = $grab->getAttribute('value');
}
}
echo $token;
?>
<?php
// id of the league to show
$league_id = "your_league_id";
// set the relative path to your txt file to store the csrf token
$cookie_file = realpath('your_folder_dir_to_the_txt_file/cookie.txt');
// login url
$url = 'https://users.premierleague.com/accounts/login/';
// make a get request to the official fantasy league login page first, before we log in, to grab the csrf token from the hidden input that has the name of csrfmiddlewaretoken
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$dom = new DOMDocument;
#$dom->loadHTML($response);
// set the csrf here
$tags = $dom->getElementsByTagName('input');
for($i = 0; $i < $tags->length; $i++) {
$grab = $tags->item($i);
if($grab->getAttribute('name') === 'csrfmiddlewaretoken') {
$token = $grab->getAttribute('value');
}
}
// now that we have the token, use our login details to make a POST request to log in along with the essential data form header fields
if(!empty($token)) {
$params = array(
"csrfmiddlewaretoken" => $token,
"login" => "your_email_address",
"password" => "your_password",
"app" => "plfpl-web",
"redirect_uri" => "https://fantasy.premierleague.com/",
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
/**
* using CURLOPT_SSL_VERIFYPEER below is only for testing on a local server, make sure to remove this before uploading to a live server as it can be a security risk.
* If you're having trouble with the code after removing this, look at the link that #Dharman provided in the comment section.
*/
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//***********************************************^
$response = curl_exec($ch);
// set the header field for the token for our final request
$headers = array(
'csrftoken ' . $token,
);
}
// finally, we now have everything we need to make the GET request to retrieve the league standings data. Enjoy :)
$fplUrl = 'https://fantasy.premierleague.com/api/leagues-classic/' . $league_id . '/standings/';
curl_setopt($ch, CURLOPT_URL, $fplUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
if(!empty($token)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$response = curl_exec($ch);
$league_data = json_decode($response, true);
curl_close($ch);
echo '<pre class="card">';
print_r($league_data);
echo '</pre>';
?>
Today I tried to post a like via PHP (Curl) without luck. The output is that a token is required but I used a working token. I tried the same token with JS and it works.
Did Instagram changed some things bout PHP?
Here is my code:
<?php
$media_id = '615839918291043487_528338984';
$url = "https://api.instagram.com/v1/media/615839918291043487_528338984/likes?";
$access_token_parameters = array(
'access_token' => '191573449.9e262d9.ff708911edcd4f809ca31dd76d08c0ba',
'action' => 'like'
);
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_GET,true);
curl_setopt($curl,CURLOPT_GETFIELDS,$access_token_parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($curl);
?>
Output.:
{"meta":{"error_type":"OAuthParameterException","code":400,"error_message":"Missing client_id or access_token URL parameter."}}
I tried it on several server, with several proxies, several client and token. Hopefully you know what's going on.
To add a like to a photo you need to do it via POST. The following is an modified version of your code to do this.
<?php
$url = "https://api.instagram.com/v1/media/615839918291043487_528338984/likes";
$fields = array(
'access_token' => '191573449.9e262d9.ff708911edcd4f809ca31dd76d08c0ba'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
My code, which actually perfectly works with Linkedin and Meetup APIs, doesn't work with Eventbrite API and I definitely don't understand why :
$params = array(
'grant_type' => 'authorization_code',
'client_id' => EVENTBRITE_CONSUMER_KEY,
'client_secret' => EVENTBRITE_CONSUMER_SECRET,
);
// Eventbrite API access token request
$url = 'https://www.eventbrite.com/oauth/token?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(array('http' => array('method' => 'POST')));
// Retrieve access token information
$response = file_get_contents($url, false, $context);
I precise that the API login part to get the authorization code seems to work perfectly well.
Here is the PHP error :
Warning: file_get_contents(https://www.eventbrite.com/oauth/token?grant_type=authorization_code&client_id=ZZ6PPQOMTKSXIHEKLR&client_secret=QQDDIS4RBZXI6ONO7QEYEUZ4JB2ABQQG6K3H7CBD6M5QWK5GSK&code=O63YZASRAYMOUHRMH5AH): failed to open stream: HTTP request failed! HTTP/1.1 400 BAD REQUEST in /var/www/include/actions.php on line 102
Thanks by advance if anybody has a clue :)
UPDATE :
I finally found where is the problem (even if I don't understand why) :
file_get_contents doesn't seem to be a good method to access the oauth page, I used curl instead :
$request_url = 'https://www.eventbrite.com/oauth/token';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);
I hope it will help anybody encountering the same issue ;)
Just so that this question doesn't continue to show up as unanswered in an auto-email, I'm going to add your answer from your update here -- hope that's alight!
file_get_contents doesn't seem to be a good method to access the oauth page, I used curl instead:
$request_url = 'https://www.eventbrite.com/oauth/token';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);
Thanks for making it easy by answering your own question! ;)
I'm following this guide to make a server side Youtube web app in PHP. I can't get past step 4. Everything up to that is good, it redirects to my script and I can obtain the authorization code no problem. However, when I try to exchange that code for an authorization token (as demonstrated in step 4), absolutely NOTHING happens. I can't find any errors, just nothing happens on my browser. My PHP script is this (private info removed):
<?php
$data = array(
'code' => $_GET['code'],
'client_id' => '[REMOVED]',
'client_secret' => '[REMOVED]',
'redirect_uri' => '[REMOVED]',
'grant_type' => 'authorization_code');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec($ch);
curl_close($ch);
echo $return;
?>
Maybe I'm just way over my head here, but can anyone tell me why it's not working?
try adding,
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
after CURLOPT_RETURNTRANSFER
I have a news form on my website. After creating this news message I want to publish it on Facebook. I tried alot of things, but nothing was working. Here is my class:
<?php
class Facebook {
const FACEBOOK_APP_ID = 'MY_APP_ID';
const FACEBOOK_APP_SECRET = 'MY_APP_SECRET';
const FACEBOOK_ACCESS_TOKEN_URI = 'https://graph.facebook.com/oauth/access_token';
const FACEBOOK_FEED_URI = 'https://graph.facebook.com/app/feed';
private function getAccessToken() {
$params = array(
'client_id' => self::FACEBOOK_APP_ID,
'client_secret' => self::FACEBOOK_APP_SECRET,
'grant_type' => 'client_credentials',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::FACEBOOK_ACCESS_TOKEN_URI);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$data = curl_exec($ch);
curl_close($ch);
return substr($data, strpos($data, '=') + 1);
}
public function sendFeed() {
$params = array(
'access_token' => $this->getAccessToken(),
'message' => $message,
'name' => $name,
'link' => $url,
'description' => $description,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::FACEBOOK_FEED_URI);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close ($ch);
return $data;
}
}
If I call the method sendFeed() it returns the following:
{"id":"404322099626551_404397542952340"}
I think the submit was successfull, but when I visit my page on facebook, there is no new feed. What am I doing wrong? I searched the complete day and couldn't get it to work. I thank you for your help.
What you are doing here is posting it on your user's feed. You are using a user access token. What you want to use is a page access token.
You'll need the manage_pages permission to perform tasks on behalf of your page.
In addition you should consider using the official PHP SDK, it'll make accessing Facebook's API much easier and improve readability.