Curl GET Request to the spotify Authorization API - php

I need some help with my Curl GET Request to the Spotify API.
The API has three different ways/endpoints to get an authorization.
I read some articles, to find the correct syntax to send the request. But i always get an error. If i post the url into my brwoser it works perfectly, also with the redirect uri.
But it doesnt work with the Curl GET Request.
It sounds stupid, but i spend the last three days with this Problem.
My code:
<?php
$client_id = 'myClientID';
$redirect_url = 'http://mywebsite/first/page.php';
$scope = 'user-read-private%20user-read-email';
$data = array(
'client_id' => $client_id,
'response_type' => 'code',
'redirect_uri' => $redirect_url,
'state' => stateHash(), // Create a random hash
'scope' => $scope,
'show_dialog' => 'true'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/authorize' . http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
$result=curl_exec($ch);
echo $result;
The error from the API Shows me this:
or i got an "1" as response.
I hope that i get some nice tips :)

There is a package for Spotify web API try using that
composer require jwilsson/spotify-web-api-php
Before using the Spotify Web API, you'll need to create an app at Spotify’s developer site.
Simple example displaying a user's profile:
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'CLIENT_ID',
'CLIENT_SECRET',
'REDIRECT_URI'
);
$api = new SpotifyWebAPI\SpotifyWebAPI();
if (isset($_GET['code'])) {
$session->requestAccessToken($_GET['code']);
$api->setAccessToken($session->getAccessToken());
print_r($api->me());
} else {
$options = [
'scope' => [
'user-read-email',
],
];
header('Location: ' . $session->getAuthorizeUrl($options));
die();
}
For more instructions and examples, check out the documentation.

Related

snapchat login kit web: invalid grant, invalid code verifier

I am using Snapchat login kit web in my PHP project. I successfully connected the user-authorization page. After giving authorization I am getting code and state GET variables in my redirect_uri page. I need an access token, but when I proceed next step, I got an error in response,
1.invalid_grant
2.invalid code_verifier
here are my login page and redirect page code:
--Login page---
<?php
if(isset($_POST['login']))
{
$url="https://accounts.snapchat.com/accounts/oauth2/auth";
$clientId="my_client_id_get_from_snapchat_app_setting";
$client_secret="my_client_secrect_get_from_snapchat_app_setting";
$redirectUri="https://Snapreport.org/Redirect.php";
$method= "GET";
$str = 'arifusingsnapchat';
$state= base64_encode($str);
$code_verifier = "arifusingsnapchat225678909fghh8df777634567890";
$code_verifier_hash = hash("sha256",$code_verifier);
$code_challenge = base64_encode($code_verifier_hash);
$scopeList= array("https://auth.snapchat.com/oauth2/api/user.display_name",
"https://auth.snapchat.com/oauth2/api/user.bitmoji.avatar",
"https://auth.snapchat.com/oauth2/api/user.external_id"
);
$scope = implode($scopeList," ");
$stringArr = array(
"client_id" => $clientId,
"client_secret" => $client_secret,
"redirect_uri" => $redirectUri,
"code_challenge" => $code_challenge,
"code_challenge_method"=> "S256",
"response_type" => "code",
"scope" => $scope,
"state" => $state );
$query= http_build_query($stringArr, '', '&');
$request = $url."?".$query;
header("Location:".$request);
}
?>
--Redirect_uri page--
<?php
if(isset($_GET['code']) && isset($_GET['state']))
{
$code= $_GET['code'];
$state=$_GET['state'];
$url="https://accounts.snapchat.com/accounts/oauth2/token";
$clientId="my_client_id_get_from_snapchat_app_setting";
$client_secret="my_client_secrect_get_from_snapchat_app_setting";
$redirect_uri="https://Snapreport.org/Redirect.php";
$header = base64_encode($clientId.":".$client_secret);
$code_verifier = "arifusingsnapchat225678909fghh8df777634567890";
$payloaded_url=$url."?client_id=".$clientId."&client_secret=".$client_secret."&grant_type=authorization_code&redirect_uri=".$redirect_uri."&code=".$code."&code_verifier=".$code_verifier;
$ch = curl_init($payloaded_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type' => 'application/json',
'Authorization'=> 'Basic '.$header
));
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
$res= json_decode($response);
// do anything you want with your response
echo "<pre>";
var_dump($res);
echo "</pre>";
}
Snapchat Login Kit Web Documentation
Snapchat Login Kit Web Documentationhttps://kit.snapchat.com/docs/login-kit-web
On your login page:
$code_verifier_hash = urlencode(pack('H*', hash('sha256', $code_verifier)))
You should probably also use a B64 safe url encoder like the one here:
https://github.com/F21/jwt/blob/master/JWT/JWT.php#L120

PHP : generate a token using a Post method

Good day,
Before getting back on Stackoverflow, I have been googling the entire afternoon without being really successful.
What I am trying to do is to get a token from myfox api by referring to their doc which says
A fresh token must be generated to be able to perform API calls. The
token can be requested by calling the following method
https://api.myfox.me/oauth2/token and providing the parameters below
(through POST): client_id, client_secret, username, password and
grant_type set to password.
Hence my code :
function getToken()
{
$clientID = "a65000ee0c57f2e37260e90c375c3";
$clientSecret = "MyLongSecretCode";
$exportFile = "myfile.txt";
$userName = "somebody#somewhere.com";
$userPass = "myPassword123";
$sourceWebsite = "https://api.myfox.me/oauth2/token?client_id=" . $clientID . "&client_secret=" . $clientSecret . "&username=" . $userName . "&password=" . $userPass . "&grant_type=password";
file_put_contents($exportFile, fopen($sourceWebsite , 'r'));
}
All I'm getting is a PHP error which says that the method is not allowed.
Any idea what I am missing here?
Many thanks for your kind help on this subject.
Edit 17.03.2017 :
I have been told by other users that I might be able to achieve this by using curl and it looks like, again, by reading the documentation that this is something that I can do :
A fresh token must be generated to be able to perform API calls. The
token can be requested by calling the following method
https://api.myfox.me/oauth2/token and providing the parameters below
(through POST): client_id, client_secret, username, password and
grant_type set to password. curl -u CLIENT_ID:CLIENT_SECRET
https://api.myfox.me/oauth2/token -d
'grant_type=password&username=YOUR_USERNAME&password=YOUR_PASSWORD'
or curl https://api.myfox.me/oauth2/token -d
'grant_type=password&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&username=YOUR_USERNAME&password=YOUR_PASSWORD'
Now, for my question : is there a way to translate this curl -u query into a php instruction and to output the contents to a file out of it that would look like :
{"access_token":"********************************","expires_in":3600,"token_type":"Bearer","scope":null,"refresh_token":"********************************"}
Thanks again for your help.
Thanks all a lot for your hints, here is a script that is working :
I hope that this script (and this post) can at some point be helpful to someone else. I wish you a very nice week-end.
<?php
$clientID = 'b85036758c385c3cd0c57f2e37260f91';
$clientSecret = 'MyLongSecretCode';
$username = 'myemailaddress#provider.net';
$passwd = 'mypassword';
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://api.myfox.me/oauth2/token',
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'grant_type' => 'password',
'client_id' => $clientID,
'client_secret' => $clientSecret,
'username' => $username,
'password' => $passwd
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
echo $resp;
// Close request to clear up some resources
curl_close($curl);
?>

Google Admin SDK: You are not authorized to access this API

Since the Google Login Auth is disabled since last week I'm trying to get oAuth 2.0 working with a service account. We want to give users on our internal web application the oppurtunity to set there Out of Office.
I downloaded the lastest Google APIs Client Library for PHP. In the Google Developer Console, I have created a new project for my application and created a Service account credentials. I have also enabled the API service: Admin SDK in the Developer Console.
I have granted the account user ID access to the correct scopes (I think):
When I use the service-account.php example and change the details, I recieve an JSON with an access token, but when I do an CURL request (same as before) to get the e-mail settings from a user, the error "You are not authorized to access this API." occur.
My code:
<?php
include_once "templates/base.php";
require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php');
$client_id = '124331845-DELETEDPART-hbh89pbgl20citf6ko.apps.googleusercontent.com'; //Client ID
$service_account_name = '124331845-DELETEDPART-89pbgl20citf6ko#developer.gserviceaccount.com'; //Email Address
$key_file_location = 'globaltext-4ce09b20cb73.p12'; //key.p12
$client = new Google_Client();
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://apps-apis.google.com/a/feeds/emailsettings/2.0/'),
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$aOutput = json_decode($client->getAccessToken());
$strEmailAdresSplit = explode('#', "FIRSTNAME.LASTNAME#DOMAIN.EXTENSION");
$strDomein = $strEmailAdresSplit[1];
$strAlias = $strEmailAdresSplit[0];
$resConnectionJobs = curl_init();
$aHeader = array();
$aHeader[] = 'Authorization: Bearer '.$aOutput->access_token;
$aHeader[] = 'Content-Type: application/atom+xml';
curl_setopt($resConnectionJobs, CURLOPT_URL, "https://apps-apis.google.com/a/feeds/emailsettings/2.0/DOMAIN.EXTENSION/FIRSTNAME.LASTNAME/vacation");
curl_setopt($resConnectionJobs, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($resConnectionJobs, CURLOPT_HTTPHEADER, $aHeader);
curl_setopt($resConnectionJobs, CURLOPT_RETURNTRANSFER, true);
curl_setopt($resConnectionJobs, CURLOPT_HEADER, false);
$oCurlData = curl_exec($resConnectionJobs);
curl_close($resConnectionJobs);
echo $oCurlData;
?>
Are you certain your credentials are OK?
Please try the following procedure to make sure you have the right credentials.
Creating your API keys
Go to the developer's console and follow these steps:
Select your project
Choose menu item "APIs & auth"
Choose menu item "Registered app"
Register an app of type "web application"
Choose one of the following options, depending on what kind of app you're creating. Server side languages should use this option :
Key for server apps (with IP locking)
Getting access token & refresh token
Create a file that contains the following code :
<?php
if (isset($_GET['code'])) {
// try to get an access token
$code = $_GET['code'];
$url = 'https://accounts.google.com/o/oauth2/token';
$params = array(
"code" => $code,
"client_id" => YOUR_CLIENT_ID,
"client_secret" => YOUR_CLIENT_SECRET,
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"grant_type" => "authorization_code"
);
$ch = curl_init();
curl_setopt($ch, constant("CURLOPT_" . 'URL'), $url);
curl_setopt($ch, constant("CURLOPT_" . 'POST'), true);
curl_setopt($ch, constant("CURLOPT_" . 'POSTFIELDS'), $params);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] === 200) {
header('Content-Type: ' . $info['content_type']);
return $output;
} else {
return 'An error happened';
}
} else {
$url = "https://accounts.google.com/o/oauth2/auth";
$params = array(
"response_type" => "code",
"client_id" => YOUR_CLIENT_ID,
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"scope" => "https://www.googleapis.com/auth/plus.me"
);
$request_to = $url . '?' . http_build_query($params);
header("Location: " . $request_to);
}
Now, replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your client ID and client secret.
Make sure your scope is correct. For example, it should be https://www.googleapis.com/auth/analytics if you want to get access to Analytics.
If you run the file, you should get an OAuth2 approval screen.
If you now press Accept, you should get a result that looks like this:
{
"access_token" : YOUR_ACCESS_TOKEN,
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : YOUR_REFRESH_TOKEN
}
The result may contain additional fields, depending on which scope you're applying for.
Connecting with Google's systems in background
Once you get the above to work, your application needs to implement the following workflow:
1) Check if your input contains a GET parameter named "code". If "code" is present, get a new access token and repeat this step (refresh your page)
If "code" is not present, go to step 2.
2) Check if you have credentials stored for your service. If credentials are present, check if your access token has expired or will expire soon. Then go to step 3. If credentials are not present, go to the auth path of your service to get the auth code and go back to step 1 (make sure Google redirects to your current URL).
3) If refresh is needed, refresh your page and go back to step 1.
If refresh is not needed, you're ready to actually do what you wanted to do in the first place.
Google's PHP library takes care if the oAuth2 flow for you, however. If you're using their library, each of the steps in the 3-step process are taken care of by the library and you should just be able to do whatever you want to do with Google's services straight away. I use this strategy myself in my Google Adwords dashboard.
You can, however, just write your custom library and connect with the service directly. Herebelow is some dev code from a project I wrote a few months ago. While it doesn't work out of the box (since it's a controller that's part of a larger application), it should help you understand the flow that Google's library takes care of under the hood.
namespace Application;
class Controller_API_Google_Youtube extends Controller_API {
public function read() {
$scope = "https://www.googleapis.com/auth/youtube";
$this->doOauth($scope);
}
function doOauth($scope) {
$oauth2Credentials = JSON_File::load(__DIR__ . DIRECTORY_SEPARATOR . 'Config.json');
$paths = array(
'token' => 'https://accounts.google.com/o/oauth2/token',
'auth' => "https://accounts.google.com/o/oauth2/auth"
);
$refreshtime = 300;
if (isset($_GET['code'])) {
// Get access code
$query = $_GET;
unset($query['code']);
if (count($query) > 0) {
$query = '?' . http_build_query($query);
} else {
$query = '';
}
$client = \PowerTools\HTTP_Client::factory(
array(
'maps' => array(
'url' => $paths['token'],
'returntransfer' => 1,
'post' => true,
'postfields' => array(
'code' => $_GET['code'],
"client_id" => $oauth2Credentials['client_id'],
"client_secret" => $oauth2Credentials['client_secret'],
"redirect_uri" => HTTP_PROTOCOL . URL_PATH . $query,
"grant_type" => "authorization_code"
)
)
)
)->execute();
$responses = $client->getResponses();
$response = array_pop($responses);
$info = $response['maps']->getInfo();
$content = $response['maps']->getContent();
if ($info['http_code'] === 200) {
$output = JSON::decode($content);
$oauth2Credentials[$scope] = array();
$oauth2Credentials[$scope]['expires'] = time() + $output['expires_in'];
$oauth2Credentials[$scope]['access_token'] = $output['access_token'];
$oauth2Credentials[$scope]['refresh_token'] = $output['refresh_token'];
file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Config.json', JSON::encode($oauth2Credentials));
header("Location: " . HTTP_PROTOCOL . URL_PATH . $query);
} else {
echo "Something went wrong";
}
} elseif (!isset($oauth2Credentials[$scope])) {
// Get auth code
header("Location: " . $paths['auth'] . '?' . http_build_query(
array(
"response_type" => "code",
"client_id" => $oauth2Credentials['client_id'],
"redirect_uri" => HTTP_PROTOCOL . DOMAIN_PATH,
"scope" => $scope
)
));
} elseif ($oauth2Credentials[$scope]['expires'] - $refreshtime < time()) {
// Refresh access code
$client = \PowerTools\HTTP_Client::factory(
array(
'maps' => array(
'url' => $paths['token'],
'returntransfer' => 1,
'post' => true,
'postfields' => array(
"client_id" => $oauth2Credentials['client_id'],
"client_secret" => $oauth2Credentials['client_secret'],
"refresh_token" => $oauth2Credentials[$scope]['refresh_token'],
"grant_type" => "refresh_token"
)
)
)
)->execute();
$responses = $client->getResponses();
$response = array_pop($responses);
$info = $response['maps']->getInfo();
$content = $response['maps']->getContent();
if ($info['http_code'] === 200) {
$output = JSON::decode($response['maps']->getContent());
$oauth2Credentials[$scope]['expires'] = time() + $output['expires_in'];
$oauth2Credentials[$scope]['access_token'] = $output['access_token'];
file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Config.json', JSON::encode($oauth2Credentials));
$this->read();
} else {
$this->output = array("error" => "Something went wrong");
}
} else {
$this->doSomethinguseful($oauth2Credentials, $scope);
}
return $this;
}
function doSomethinguseful($oauth2Credentials, $scope) {
// https://developers.google.com/youtube/v3/sample_requests?hl=nl
$client = \PowerTools\HTTP_Client::factory(
array(
'maps' => array(
'useragent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13',
'url' => 'https://www.googleapis.com/youtube/v3/channels?part=contentDetails&mine=true',
'returntransfer' => true,
'httpheader' => array(
'Authorization: Bearer ' . $oauth2Credentials[$scope]['access_token'],
'Accept-Encoding: gzip, deflate'
)
)
)
)->execute();
$responses = $client->getResponses();
$response = array_pop($responses);
$content = $response['maps']->getContent();
$this->output = JSON::decode(gzdecode($content));
}
}
It looks like you may be running into a problem I had as well.
The call to Google_Auth_AssertionCredentials actually requires more parameters than you're sending to work with a service account. (At least, it did in my case.)
You need to pass enough parameters to include sub (which user to take actions on account of).
Without that, I always got an access denied. This clearly isn't obvious, since there's even been a function added to the php library, loadServiceAccountJson, which is supposed to set up a service account client connection, but breaks because it doesn't set sub either.
See working code here: Google php client library loadServiceAccountJson broken - fix enclosed

Get access token using refresh token

I am currently implementing OAuth2 using thephpleague/oauth2 library. I have already added the refresh token grant and the access token response already contains the refresh token. However, I don't have any idea how to use that refresh token to get a new access token.
I checked the documentation but I don't see anything about it. The oauth2-client library has methods for it but I'm not going to use that.
My code for the refresh token grant:
$server->setRefreshTokenStorage(new RefreshTokenStorage);
$refreshTokenGrant = new \League\OAuth2\Server\Grant\RefreshTokenGrant();
$authCodeGrant = new \League\OAuth2\Server\Grant\AuthCodeGrant();
$server->addGrantType($authCodeGrant);
$server->addGrantType($refreshTokenGrant);
$response = $server->issueAccessToken();
My question is how can I test that using the refresh token, I can retrieve a new access token? Do I have to implement a new endpoint different from the one that's used by the authorization code grant?
Here is my code for getting the token. Any comments?
public function actionToken(){
$authCodeModel = new \app\models\OAuth_Auth_Codes;
if(!isset($_POST['code'])){
throw new \yii\web\HttpException(400,"Required parameter \'code\' is missing or invalid.");
}
$result = $authCodeModel->find()->where(['authorization_code' => trim($_POST['code'])])->one();
if(!empty($result)){
$user_id = $result->user_id;
$session2 = new Session();
$session2->open();
$server = new AuthorizationServer;
$server->setSessionStorage(new SessionStorage);
$server->setAccessTokenStorage(new AccessTokenStorage);
$server->setClientStorage(new ClientStorage);
$server->setScopeStorage(new ScopeStorage);
$server->setAuthCodeStorage(new AuthCodeStorage);
$server->setRefreshTokenStorage(new RefreshTokenStorage);
$refreshTokenGrant = new \League\OAuth2\Server\Grant\RefreshTokenGrant();
$authCodeGrant = new \League\OAuth2\Server\Grant\AuthCodeGrant();
$server->addGrantType($authCodeGrant);
$server->addGrantType($refreshTokenGrant);
$response = $server->issueAccessToken();
$model = new \app\models\OAuth_Access_Tokens();
$accessTokenModel = $model->find()->where(['access_token' => $response['access_token']])->one();
$accessTokenModel->setAttribute('user_id',''.$user_id);
$accessTokenModel->save(FALSE);
return json_encode($response);
}
else{
throw new \yii\web\UnauthorizedHttpException("You have provided an invalid authorization code.");
}
}
Using the cURL support in PHP it would be:
$postData = array(
"grant_type" => "refresh_token",
"client_id" => $clientID,
"client_secret" => $clientSecret,
"refresh_token" => $refreshToken
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenEndpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$response = curl_exec($ch);
curl_close($ch);
$r = json_decode($response);
echo $r->access_token;
Edit:
For server side examples see: https://github.com/thephpleague/oauth2-server/blob/master/tests/unit/Grant/RefreshTokenGrantTest.php, e.g.:
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$server->addGrantType($grant);
$server->issueAccessToken();

FACEBOOK GRAPH/rest api: how to LOGIN my OWN USER to update my STATUS with PHP

I want to update the status of a FAN-PAGE by PHP with the help of the Facebook graph api. google says: doesn't work.
Now I want to update my own user status by PHP. My main problem is how to login my own user to the graph api (with PHP), without using a browser and without funny PHP workarounds.
In both cases you need to get publish_stream permission http://developers.facebook.com/docs/authentication/permissions
This can be done with FB.login()
More information: http://developers.facebook.com/docs/authentication
After that you can just update status with graph api post: http://developers.facebook.com/docs/reference/api/post
my main problem is how to login my own
user to the graph api (with php),
without using a browser and without
funny php workarounds.
There's no way for you to act on behalf of a user (even your own user) without interacting with him through a browser at least once to get the offline_access.
How to get the offline_access permission and how to use it from there onward is explained in this answer.
EDIT:
Please read the comments! thanks #zerkms!
You need several things to update your facebook profile or a page's feed: a facebook application (client_id, client_secret), profile_id, and access_token (publish_stream, manage_pages, offline_access permissions)
You need offline_access because if not, then the access token will expire. If you've read that you don't need offline_access if you already have publish_stream specified, they just meant that you don't need it always.
To publish a post is easy:
$data = array(
'access_token' => $access_token,
'message' => 'status message',
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/{$profile_id}/feed");
Now how to get the profile_id and access_token, you can use my app post panda, or make your own script. I'll include it here:
# arvin castro
# http://codecri.me/
# January 16, 2011
$client_id = ''; # application id
$client_secret = ''; # application secret
$callbackURL = 'http://'; # the URL of this script
$extendedPermissions = 'publish_stream,manage_pages,offline_access';
session_name('facebookoauth');
session_start();
if(isset($_GET['logout']) and $_SESSION['loggedin']) {
$_SESSION = array();
session_destroy();
}
if(isset($_GET['signin'])) {
# STEP 1: Redirect user to Facebook, to grant permission for our application
$url = 'https://graph.facebook.com/oauth/authorize?' . xhttp::toQueryString(array(
'client_id' => $client_id,
'redirect_uri' => $callbackURL,
'scope' => $extendedPermissions,
));
header("Location: $url", 303);
die();
}
if(isset($_GET['code'])) {
# STEP 2: Exchange the code that we have for an access token
$data = array();
$data['get'] = array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'code' => $_GET['code'],
'redirect_uri' => $callbackURL,
);
$response = xhttp::fetch('https://graph.facebook.com/oauth/access_token', $data);
if($response['successful']) {
$var = xhttp::toQueryArray($response['body']);
$_SESSION['access_token'] = $var['access_token'];
$_SESSION['loggedin'] = true;
} else {
print_r($response['body']);
}
}
if($_SESSION['loggedin']) {
// Get Profile ID
$data = array();
$data['get'] = array(
'access_token' => $_SESSION['access_token'],
'fields' => 'id,name,accounts',
);
$response = xhttp::fetch('https://graph.facebook.com/me', $data);
echo '<pre>';
print_r(json_decode($response['body'], true));
echo '</pre>';
} else {
echo 'Sign in with Facebook';
}
?>
I'm using my cURL wrapper class, xhttp

Categories