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.
Related
Does anyone have any code about both getting and setting users OOF messages using Garethp/php-ews library by any chance?
(https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/aa563465(v=exchg.140))
(https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/aa493825(v=exchg.140))
I have tried the following
use garethp\ews\API\Type;
use garethp\ews\MailAPI;
use garethp\ews\API\Enumeration\DistinguishedFolderIdNameType;
use garethp\ews\API\Enumeration\UserConfigurationPropertyType;
use garethp\ews\API\Enumeration\GetUserOofSettingsRequestType;
$email = 'me#mycompany.com';
$host = 'myexchserver'; $username = 'myusername'; $password = 'mypassword';
$api = MailAPI::withUsernameAndPassword($host,$username,$password,["version" => 'Exchange2010_SP1', 'impersonation' => $email]);
$response = $api->getClient()->GetUserOofSettingsRequest(['Address' => 'someuser#mycompany.com']);
But get the following error.
Fatal error: Uncaught SoapFault exception: [Client] Function ("GetUserOofSettingsRequest") is not a valid method for this service in /Scripts/vendor/garethp/php-ews/src/API/NTLMSoapClient.php:119 Stack trace: #0 /Scripts/vendor/garethp/php-ews/src/API/NTLMSoapClient.php(119): SoapClient->__call() #1 /Scripts/vendor/garethp/php-ews/src/API/ExchangeWebServices/MiddlewareFactory.php(18): garethp\ews\API\NTLMSoapClient->__call() #2 /Scripts/vendor/garethp/php-ews/src/API/ExchangeWebServices.php(510): garethp\ews\API\ExchangeWebServices->garethp\ews\API\ExchangeWebServices\{closure}() #3 /Scripts/vendor/garethp/php-ews/src/API/ExchangeWebServices/MiddlewareFactory.php(32): garethp\ews\API\ExchangeWebServices->garethp\ews\API\{closure}() #4 /Scripts/vendor/garethp/php-ews/src/API/ExchangeWebServices.php(510): garethp\ews\API\ExchangeWebServices->garethp\ews\API\ExchangeWebServices\{closure}() #5 /Scripts/vendor/garethp/php-ews/src/API/ExchangeWebServices/MiddlewareFactory.php(48): garethp\ews\API\ExchangeWebServices->garethp\ew in /Scripts/vendor/garethp/php-ews/src/API/NTLMSoapClient.php on line 119
Thanks
I started with facebook business sdk for php. Was following this doc: https://developers.facebook.com/docs/business-sdk/getting-started/
installed without trouble, then tried testing as they instructed,
created src/test.php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;
$app_id = "{app-id}";
$app_secret = "{appsecret}";
$access_token = "{access-token}";
$account_id = "act_{{adaccount-id}}";
Api::init($app_id, $app_secret, $access_token);
$account = new AdAccount($account_id);
$cursor = $account->getCampaigns();
// Loop over objects
foreach ($cursor as $campaign) {
echo $campaign->{CampaignFields::NAME}.PHP_EOL;
}
filled in the required values. and ran the file. Getting this:
FacebookAds\CrashReporter : Enabled
FacebookAds\CrashReporter : Exception detected!
FacebookAds\CrashReporter : Successfully sent report
Fatal error: Uncaught FacebookAds\Http\Exception\AuthorizationException: Invalid OAuth access token. in C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Http\Exception\RequestException.php:174
Stack trace:
#0 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Http\Client.php(215): FacebookAds\Http\Exception\RequestException::create(Object(FacebookAds\Http\Response))
#1 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Http\Request.php(286): FacebookAds\Http\Client->sendRequest(Object(FacebookAds\Http\Request))
#2 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Api.php(165): FacebookAds\Http\Request->execute()
#3 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Api.php(214): FacebookAds\Api->executeRequest(Object(FacebookAds\Http\Request))
#4 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\ApiRequest.php(187): FacebookAds\Api->call('/act_3667840345...', 'GET', Array, Array)
#5 in C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Http\Exception\RequestException.php on line 174
Not sure what I am doing wrong. Didnt find much by searching. Can anyone please help?
The error you get is pretty explicit: "Invalid OAuth access token"
you can check the token you supplied using Facebook's token-debbuger # https://developers.facebook.com/tools/debug/accesstoken/
most probably you are missing the "ads_management" permission.
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.
I have been struggling to write a PHP script that will reboot a server using the 1.6.0 version of the Rackspace API (I can't install Composer on my server needed for 1.7.0). Unfortunately it does not want to recognize my credentials and keeps throwing this error:
Fatal error: Uncaught exception 'OpenCloud\Common\Exceptions\CredentialError' with message 'Unrecognized credential secret' in /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/OpenStack.php:694 Stack trace: #0 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/Rackspace.php(66): OpenCloud\OpenStack->credentials() #1 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/OpenStack.php(714): OpenCloud\Rackspace->Credentials() #2 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/OpenStack.php(591): OpenCloud\OpenStack->authenticate() #3 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/OpenStack.php(652): OpenCloud\OpenStack->checkExpiration() #4 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/Common/Service.php(337): OpenCloud\OpenStack->serviceCatalog() #5 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/Common/Service.php(68): OpenCloud\Common\Service->getEndpoint('compute', 'cloudServersOpe...', 'ORD', 'publicURL') #6 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/ in /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/OpenStack.php on line 694
Here is my PHP script (I did not include my credentials)
require_once "php-opencloud.php";
// The AUTHURL used for the US was: https://identity.api.rackspacecloud.com/v2.0/
putenv("RAX_USERNAME=$username");
putenv("RAX_API_KEY=$apikey");
putenv("RAX_TENANT_NAME=$tenantname");
putenv("RAX_AUTH_URL=$authurl");
define('USERNAME', $_ENV['RAX_USERNAME']);
define('APIKEY', $_ENV['RAX_API_KEY']);
define('TENANT', $_ENV['RAX_TENANT_NAME']);
define('AUTHURL', 'RAX_AUTH_URL');
$rackspace = new \OpenCloud\Rackspace(AUTHURL,
array( 'username' => USERNAME,
'apiKey' => APIKEY ));
$cservers = $rackspace->Compute('cloudServersOpenStack', 'ORD');
$list = $cservers->ServerList();
while($server = $list->Next()) {
if ($server->name == 'My_Server')
$server->Reboot('hard');
}
echo "Reboot sequence complete.";
Any help anyone can offer would be greatly appreciated.
I have PHP code that Google PHP Mirror API to insert user account.
if(isset($_GET['userToken'])){
$userToken=$_GET['userToken'];
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
'service-email-here',
array('https://www.googleapis.com/auth/glass', 'https://www.googleapis.com/auth/glass.thirdpartyauth'),
$key
);
$client->setAssertionCredentials($cred);
$mirrorService = new Google_Service_Mirror($client);
$_SESSION['access_token'] = $client->getAccessToken();
insert_account($mirrorService, $userToken, $email, $api_email);
exit();
}
function insert_account($service,$userToken, $email, $api_email)
{
$accountType='package-name-here';
$accountName='service-email-here';
$authtoken=null;
$postBody = new Google_Service_Mirror_Account();
$postBody->setAuthTokens($authtoken);
$userdata=array("email"=>$email);
$postBody->setUserData($userdata);
try {
$account = $service->accounts->insert($userToken, $accountType, $accountName, $postBody);
return $account;
} catch (Exception $e) {
echo "exception: ".$e;
return null;
}
}
I get an error which says:
exception: exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/mirror/v1/accounts/usertokenhere/package-name-here/service-email-here: (403) Insufficient Permission' in app-path/Google/Http/REST.php:79
Stack trace:
#0 app-path/Google/Http/REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 app-path/Google/Client.php(508): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 app-path/Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 app-path/Google/Service/Mirror.php(409): Google_Service_Resource->call('insert', Array, 'Google_Service_...')
#4 app-path/util.php(52): Google_Service_Mirror_Accounts_Resource->insert('8ce7d2ffbe6f693...', 'com.tenpearls.l...', '568533774877-an...', Object(Google_Service_Mirror_Account))
#5 app-path/add-your-own-camera.php(59): insert_account(Object(Google_Service_Mirror), '8ce7d2ffbe6f693...', 'safdar.tp#gmail...', '568533774877-an...')
#6 {main}
Why am I getting the insufficient permission error? I added the scope https://www.googleapis.com/auth/glass.thirdpartyauth which is required to add accounts using mirror api.
I need to insert user account using mirror API.
You do not need the scope https://www.googleapis.com/auth/glass. In fact, this is not a valid scope at all.
The only scope you need for adding an account on the device using a service account is https://www.googleapis.com/auth/glass.thirdpartyauth.
Calling insert account method required separate service client object. Code can be viewed here: http://goo.gl/DVggO6