Right now i am working on spotify api, When i hit url for first time it is giving me all playlist but when i refresh page again it is giving me exception error, here is my code,
require '../../../vendor/autoload.php';
$session = new SpotifyWebAPI\Session('******', '*******', 'http://localhost:8080/spotify/vendor/jwilsson/spotify-web-api-php/demo.php');
$api = new SpotifyWebAPI\SpotifyWebAPI();
if (isset($_GET['code'])) {
$session->requestAccessToken($_GET['code']);
$data = $api->setAccessToken($session->getAccessToken());
$artistData = $api->me();
$artistId = $artistData->id;
$playlists = $api->getUserPlaylists($artistId, array(
'limit' => 5
));
foreach ($playlists->items as $playlist) {
echo '' . $playlist->name . ' <br>';
}
} else {
$scopes = array(
'scope' => array(
'user-read-email',
'user-library-modify',
),
);
header('Location: ' . $session->getAuthorizeUrl($scopes));
}
Here is my exception error
Fatal error: Uncaught exception 'SpotifyWebAPI\SpotifyWebAPIException' with message 'Invalid authorization code' in D:\xampp\htdocs\spotify\vendor\jwilsson\spotify-web-api-php\src\Request.php:156 Stack trace: #0 D:\xampp\htdocs\spotify\vendor\jwilsson\spotify-web-api-php\src\Request.php(26): SpotifyWebAPI\Request->send('POST', 'https://account...', Array, Array) #1 D:\xampp\htdocs\spotify\vendor\jwilsson\spotify-web-api-php\src\Session.php(233): SpotifyWebAPI\Request->account('POST', '/api/token', Array) #2 D:\xampp\htdocs\spotify\vendor\jwilsson\spotify-web-api-php\demo.php(31): SpotifyWebAPI\Session->requestAccessToken('AQAaVZvpXUExKg2...') #3 {main} thrown in D:\xampp\htdocs\spotify\vendor\jwilsson\spotify-web-api-php\src\Request.php on line 156
Can anyone please tell me why it cause error ? If anyone have experiance with spotify
Creator of the library here.
The only thing I can think of which would yield that error message is if you try to request a access token twice with the same code. Try visiting the URL to your PHP file again but remove any ?code=... parts.
Related
I am building an API, but I get an Uncaught error when creating my token with JWT, when I run a post man call, I get in my error log Stack trace:
#0 [internal function]: Api->generateToken()
#1 /home/osconliz/public_html/Osconlizapicall/rest.php(42): ReflectionMethod->invoke(Object(Api))
#2 /home/osconliz/public_html/Osconlizapicall/index.php(4): Rest->processApi()
#3 {main}
thrown in /home/osconliz/public_html/Osconlizapicall/api.php on line 36
[19-May-2018 02:04:47 UTC] PHP Fatal error: Uncaught Error: Class 'JWT' not found in /home/osconliz/public_html/Osconlizapicall/api.php:36
Stack trace:
#0 [internal function]: Api->generateToken()
#1 /home/osconliz/public_html/Osconlizapicall/rest.php(42): ReflectionMethod->invoke(Object(Api))
#2 /home/osconliz/public_html/Osconlizapicall/index.php(4): Rest->processApi()
#3 {main}
but when I check my jwt file on my PHP server it has class JWT in it.
**jwt.php** page with class jwt screen shot
Then the page I am using to create the token which is **api.php**
//SECRETE_KEY is a constant for creating a pass for JWT
<?php
class Api extends Rest {
public $dbConn;
public function __construct(){
parent::__construct();
$db = new DbConnect;
$this->dbConn = $db->connect();
}
public function generateToken(){
$client_id_key = $this->validateParameter('client_id_key', $this->param['client_id_key'], STRING);
//$client_secret_key = $this->validateParameter('client_secret_key', $this->param['client_secret_key'], STRING);
//client_secret_key should be commented out it is not used for validation for security purposes, only id key
$stmt = $this->dbConn->prepare("SELECT * FROM `api_clients_properties` WHERE client_id = :client_id_key");
$stmt->bindParam(":client_id_key", $client_id_key);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!is_array($user)){
$this->returnResponse(API_NAME_REQUIRED, "Invalid Client Id Key");
}
if ($user['property_status'] == "not verified"){
$this->returnResponse(API_NAME_REQUIRED, "Property not verified, please contact admin, to verify it");
}
$payload = [
'iat' => time(),
'iss' => 'localhost',
'exp' => time() + (60),
'userId' => $user['id']
];
$token = JWT::encode($payload, SECRETE_KEY);
echo $token;
}
}
?>
The JWT class is in the namespace Firebase\JWT, so you will either need to use it:
use \Firebase\Jwt\Jwt;
Jwt::encode(...);
Or use its full namespace when invoking:
\Firebase\Jwt\Jwt::encode();
If you copied the file from GitHub rather than using composer to install it, you will need to comment out the namespace lines at the top of the file. so from my snapshot at the very top of the first line of jwt.php screenshot, you will comment out //namespace Firebase\JWT; and you would not get the 500 internal server error again.
I am getting following error in Azure Authentication. Kindly help me understand the same.
Fatal error: Uncaught exception
'League\OAuth2\Client\Provider\Exception\IdentityProviderException'
with message 'invalid_client' in
/var/www/html/active/vendor/league/oauth2-client/src/Provider/GenericProvider.php:216
Stack trace: #0
/var/www/html/active/vendor/league/oauth2-client/src/Provider/AbstractProvider.php(644):
League\OAuth2\Client\Provider\GenericProvider->checkResponse(Object(GuzzleHttp\Psr7\Response),
Array) #1
/var/www/html/active/vendor/league/oauth2-client/src/Provider/AbstractProvider.php(560):
League\OAuth2\Client\Provider\AbstractProvider->getResponse(Object(GuzzleHttp\Psr7\Request))
2 /var/www/html/active/src/Delegates/Receive.php(82): League\OAuth2\Client\Provider\AbstractProvider->getAccessToken('authorization_c...',
Array) #3 /var/www/html/active/src/ActiveDirectory.php(180):
Magium\ActiveDirectory\Delegates\Receive->execute() #4
/var/www/html/active/index.php(25):
Magium\ActiveDirectory\ActiveDirectory->authenticate() #5 {main}
thrown in
/var/www/html/active/vendor/league/oauth2-client/src/Provider/GenericProvider.php
on line 216
I have the following code
<?php
ini_set('display_errors', 1);
require_once 'vendor/autoload.php';
session_start();
$config = [
'authentication' => [
'ad' => [
'client_id' => 'xxx',
'client_secret' => 'xxx',
'enabled' => '1',
'directory' => 'common'
]
]
];
$request = new \Zend\Http\PhpEnvironment\Request();
$ad = new \Magium\ActiveDirectory\ActiveDirectory(
new \Magium\Configuration\Config\Repository\ArrayConfigurationRepository($config),
Zend\Psr7Bridge\Psr7ServerRequest::fromZend(new \Zend\Http\PhpEnvironment\Request())
);
$entity = $ad->authenticate();
echo $entity->getName() . '<Br />';
// echo $entity->getOid() . '<Br />';
echo $entity->getPreferredUsername() . '<Br />';
URL : https://github.com/magium/active-directory
Kindly help.
Microsoft automatically signs in using the client id which is used first time. If it is a wrong one, it will always throw this error even if it is updated in .env file. How to overcome this?
Go to Apps & Services page
Click on Edit against the app you are trying to sign in
Click on Remove these permissions button
Try to authenticate again
I am at the stage of the OAuth flow where I get the OAuth verifier and have to use it to get the permanent token, however I encounter the error "Invalid oauth_verifier parameter".
// I get a valid oauth verifier
$oauth_verifier = filter_input(INPUT_GET, "oauth_verifier");
// I am able to run var_dump($connection) and the response seems valid
$connection = new TwitterOAuth(
$config["consumer_key"],
$config["consumer_secret"],
$_SESSION["oauth_token"],
$_SESSION["oauth_token_secret"]
);
// I believe this is where the problem lies, if I try var_dump($token) nothing shows but my original error message
$token = $connection->oauth(
"oauth/access_token", [
"oauth_verifier" => $oauth_verifier
]
);
$twitter = new TwitterOAuth(
$config["consumer_key"],
$config["consumer_secret"],
$token["oauth_token"],
$token["oauth_token_secret"]
);
The full error message is:
Fatal error: Uncaught Abraham\TwitterOAuth\TwitterOAuthException: Invalid request token. in C:\xampp\htdocs\twitteroauth-master\src\TwitterOAuth.php:158 Stack trace: #0 C:\xampp\htdocs\twitter_callback.php(34): Abraham\TwitterOAuth\TwitterOAuth->oauth('oauth/access_to...', Array) #1 {main} thrown in C:\xampp\htdocs\twitteroauth-master\src\TwitterOAuth.php on line 158
If you are running this on a local server then check your url_callback, its not be in form of google tiny url, it must be in the form of "http://localhost:80/file_name" OR "http://localhots:8080/file_name". If you still have this problem then write your throw statement in try catch block.
e.g.
try {
throw new TwitterOAuthException($result);
}
catch(Exception $e) {
}
If you are running on server in spite of always check your url_callback should not be in the form of google tiny url because new twitter oauth didn't verify your google tiny url.
I'm trying to post on my Facebook page with PHP.
I have set up the Facebook API (version 4) and collected all the data I need, like AppId, Secret Key, Access Token and now when I try to post on my page like this:
require 'vendor/autoload.php';
define('FACEBOOK_SDK_V4_SRC_DIR', '/vendor/facebook/php-sdk-v4/src/Facebook/');
define("FACEBOOK_CONSUMER_KEY", "{myKey}");
define("FACEBOOK_CONSUMER_SECRET", "{mySecret}");
define("FACEBOOK_ACCESS_KEY", "{myToken}");
Facebook\FacebookSession::setDefaultApplication(FACEBOOK_CONSUMER_KEY, FACEBOOK_CONSUMER_SECRET);
$session = new Facebook\FacebookSession(FACEBOOK_ACCESS_KEY);
$message = array(
"message" => "It works!",
"link" => "http://www.google.de",
//"picture" => "url to picture",
//"name" => "Picture title",
//"description" => "Description",
);
$response = ( new Facebook\FacebookRequest( $session, 'POST', '/{myPageId}/feed', $message ) )->execute()->getGraphObject();
echo $response->getProperty('id');
Unfortunately I get the following error evertime I execute it:
PHP Fatal error: Uncaught exception 'Facebook\FacebookPermissionException' with message '(#200) The user hasn't authorized the application to perform this action' in {myPath}/FacebookRequestException.php:128
Stack trace:
#0 {myPath}/FacebookRequest.php(280): Facebook\FacebookRequestException::create('{"error":{"mess...', Object(stdClass), 403)
#1 {myPath}/test.php(21): Facebook\FacebookRequest->execute()
#2 {main}
thrown in {myPath}/FacebookRequestException.php on line 128
How can I setup the Facebook App that it work correctly?
You have to do the login flow to authorize your app first. https://developers.facebook.com/docs/php/howto/example_facebook_login/4.0.0
I'm creating a simple page to display my current photos from my Instragram account. I'm using cosenary's Instagram PHP API (instagram.class.php) from https://github.com/cosenary/Instagram-PHP-API
Upon successful login the success page displayed correctly. But when I refresh the page again, it displayed this error message:
Fatal error: Uncaught exception 'Exception' with message 'Error: _makeCall() | users/self/media/recent - This method requires an authenticated users access token.' in /home/teammond/public_html/projects/amacc/it321/final/instagram.class.php:432
Stack trace: #0 /home/teammond/public_html/projects/amacc/it321/final/instagram.class.php(148): Instagram->_makeCall('users/self/medi...', true, Array) #1 /home/teammond/public_html/projects/amacc/it321/final/success/index.php(40): Instagram->getUserMedia() #2 {main} thrown in /home/teammond/public_html/projects/amacc/it321/final/instagram.class.php on line 432
I tried placing what I think were the tokens in PHP sessions but still to no avail.
This the PHP code from my success page (redirect_uri):
<?php
session_start();
require_once '../instagram.class.php';
// initialize class
$instagram = new Instagram(array(
'apiKey' => '010d47aaccf945559ae9ded9d0aa7459',
'apiSecret' => '{omitted}',
'apiCallback' => 'http://projects.teammondestars.com/amacc/it321/final/success'
));
// receive OAuth code parameter
$code = $_GET['code'];
if (!isset($_SESSION['oauth'])) {
$_SESSION['oauth'] = $code;
}
// check whether the user has granted access
if (isset($_SESSION['oauth'])) {
// receive OAuth token object
$data = $instagram->getOAuthToken($_SESSION['oauth'], true);
$username = $username = $data->user->username;
// store user access token
$instagram->setAccessToken($data);
if (!isset($_SESSION['token'])) {
$_SESSION['token'] = $instagram->getAccessToken();
}
// now you have access to all authenticated user methods
$result = $instagram->getUserMedia();
} else {
// check whether an error occurred
if (isset($_GET['error'])) {
echo 'An error occurred: ' . $_GET['error_description'];
}
}
?>