I'm making a call to retrieve a user's latest tracks using the last.fm PHP api library. It works perfectly when I run it on my local webserver (localhost), but when I run it on a remote server it sends back an error code of 99, saying that permission has been denied.
Here is my code:
static function readRecentTracks() {
$authVars['apiKey'] = '#########';
$auth = new lastfmApiAuth('setsession', $authVars);
$apiClass = new lastfmApi();
$packageClass = $apiClass->getPackage($auth, 'user');
$method_vars = array(
'user' => 'liquidus219',
'limit' => 25
);
if ($tracks = $packageClass->getRecentTracks($method_vars)) {
echo json_encode($tracks);
} else {
echo '<b>Error '.$packageClass->error['code'].' - </b><i>'.$packageClass->error['desc'].'</i>';
}
}
You can see the code in action at http://liquidus219.freehostia.com/api/?q=readRecentTracks
UPDATE: I have checked/changed the application URL to no effect.
UPDATE: I have gone through the code for the last.fm PHP api, no sign of an error 99 defined anywhere.
I found out in the end that my hosting provider was blocking the call.
Related
I am new to firebase. I am testing a web application using the Firestore Database and PHP. https://github.com/googleapis/google-cloud-php-firestore. I have created a database "cities" and want to fetch the data only for the login User. I have set a rule on the database
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /cities/{city} {
allow read, write: if request.auth != null
}
}
}
Now after login is successful using email and password, I want to fetch the population of a city. I have checked firebase auth and it is showing me logged in.
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var uid = user.uid;
console.log("Logged In"+uid)
} else {
console.log("Please login");
}
});
I am using the following PHP code.
$firestore = new FirestoreClient([
'projectId' => 'XXXXXXXX',
]);
$collectionReference = $firestore->collection('cities');
$documentReference = $collectionReference->document('kolkata');
$snapshot = $documentReference->snapshot();
echo "Population is " . $snapshot['population'];
Now I am getting the following error:
Fatal error: Uncaught Google\Cloud\Core\Exception\ServiceException: {
"message": "Missing or insufficient permissions.", "code": 7,
"status": "PERMISSION_DENIED", "details": [] }
Now when I change the security rule to allow read and write for all users, data are fetching properly.
I have searched the document but have not found any suggestions about the error.
Also, when I am using the keyfile along with the project id, I can fetch the data, but there is another issue. The security rule is not working anymore. I can read the data without logging in.
How can I solve this issue. Thanks in advance and sorry for the bad English.
$firestore = new FirestoreClient([
'projectId' => 'XXXXXX',
'keyFile' => json_decode(file_get_contents(__DIR__.'/secret/XXXXXXXX.json'), true)
]);
While developing Recaptcha Enterprise for use of the V2 "I am not a robot" checkbox, I am stuck on this error:
Fatal error: Uncaught DomainException: Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information
I follow the link and have settled on this to authenticate:
use Google\Cloud\Storage\StorageClient;
$storage = new StorageClient([
'keyFile' => json_decode(file_get_contents($path_to_keyfile), true),
'projectId' => 'MY_PROJECT'
]);
I cannot find anything else that suggests I need to do anything more than this, and this link to the constructor API doesn't suggest I can pass it in as a parameter and then proceed. I do not want to use environment variables for this project, I want to connect manually in the code. What am I missing? I can confirm I have a working service account.
If it's helpful, the code I'm trying to run after I presumably authenticate is this:
// ==================== CAPTCHA ===================
use Google\Cloud\RecaptchaEnterprise\V1\RecaptchaEnterpriseServiceClient;
use Google\Cloud\RecaptchaEnterprise\V1\Event;
use Google\Cloud\RecaptchaEnterprise\V1\Assessment;
use Google\Cloud\RecaptchaEnterprise\V1\TokenProperties\InvalidReason;
$captcha_response = $_POST['g-recaptcha-response'];
$site_key = "123456789abc";
$client = new RecaptchaEnterpriseServiceClient();
define('SITE_KEY', $site_key);
define('TOKEN', $captcha_response);
define('PROTECTED_ACTION', 'signup');
define('PARENT_PROJECT', 'projects/MY_PROJECT');
$event = (new Event())
->setSiteKey(SITE_KEY)
->setExpectedAction(PROTECTED_ACTION)
->setToken(TOKEN);
$assessment = (new Assessment())
->setEvent($event);
try {
$response = $client->createAssessment(
PARENT_PROJECT,
$assessment
);
if ($response->getTokenProperties()->getValid() == false) {
printf('The CreateAssessment() call failed because the token was invalid for the following reason: ');
printf(InvalidReason::name($response->getTokenProperties()->getInvalidReason()));
} else {
if ($response->getEvent()->getExpectedAction() == PROTECTED_ACTION) {
printf('The score for the protection action is:');
printf($response->getRiskAnalysis()->getScore());
}
else
{
printf('The action attribute in your reCAPTCHA tag does not match the action you are expecting to score');
}
}
} catch (exception $e) {
printf('CreateAssessment() call failed with the following error: ');
printf($e);
}
Here's how I got it working. Thanks to John Hanley for the help in a previous answer. The documentation had lead me to believe that (for whatever reason) Storage was required, but that was not the case: it was as simple as providing the path to the key via the credentials parameter. Not the keyFile parameter.
if (empty($_POST['g-recaptcha-response']))
die("You have failed the not-a-robot check.");
$captcha_response = $_POST['g-recaptcha-response'];
require 'composer/vendor/autoload.php';
use Google\Cloud\RecaptchaEnterprise\V1\RecaptchaEnterpriseServiceClient;
use Google\Cloud\RecaptchaEnterprise\V1\Event;
use Google\Cloud\RecaptchaEnterprise\V1\Assessment;
use Google\Cloud\RecaptchaEnterprise\V1\TokenProperties\InvalidReason;
$path_to_keyfile = "MY_PROJECT-1234567890abc.json";
$site_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$client = new RecaptchaEnterpriseServiceClient([
'credentials' => $path_to_keyfile,
'projectId' => 'MY_PROJECT'
]);
define('SITE_KEY', $site_key);
define('TOKEN', $captcha_response);
define('PROTECTED_ACTION', 'signup');
define('PARENT_PROJECT', 'projects/MY_PROJECT');
$event = (new Event())
->setSiteKey(SITE_KEY)
->setExpectedAction(PROTECTED_ACTION)
->setToken(TOKEN);
$assessment = (new Assessment())
->setEvent($event);
try {
$response = $client->createAssessment(PARENT_PROJECT, $assessment);
if ($response->getTokenProperties()->getValid() == false) {
printf('The CreateAssessment() call failed because the token was invalid for the following reason: ');
printf(InvalidReason::name($response->getTokenProperties()->getInvalidReason()));
exit;
} else {
if ($response->getEvent()->getExpectedAction() == PROTECTED_ACTION) {
// Closer to 1 = human, to 0 = robot.
$bot_score = $response->getRiskAnalysis()->getScore();
// do what you want with the score here...
} else {
die('The action attribute in your reCAPTCHA tag does not match the action you are expecting to score');
}
}
} catch (exception $e) {
printf('CreateAssessment() call failed with the following error: ');
printf($e);
exit;
}
Your problem is that you are not specifying the service account to use in the client constructor and the system is falling back to using ADC (Application Default Credentials).
ADC will check the environment variable GOOGLE_APPLICATION_CREDENTIALS for the service account JSON key file.
You can set the environment variable before running your program:
Windows:
set GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
Linux:
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
Or modify your program by changing this line of code:
$client = new RecaptchaEnterpriseServiceClient();
To this:
$options = ['keyFile' => $path_to_keyfile];
$client = new RecaptchaEnterpriseServiceClient($options);
Note 1:
If you are running your program on a Google Cloud computer service such as Compute Engine, App Engine, Cloud Run, ... the default service account will be used if neither of the above methods are implemented.
Note 2:
While developing, another method is to use the CLI's application default credentials. Run the following command using the Google Cloud SDK CLI:
gcloud auth application-default login
However, I have not verified that the reCAPTCHA Enterprise library checks for this type of credential.
I want to connect Instagram Basic Display API with a website in order to display one user's post. But, when trying to authenticate the user (myself, for test purposes) I'm getting this error:
{"error_type": "OAuthException", "code": 400, "error_message": "Invalid redirect_uri"}
This is the PHP code I'm using for my request:
require_once 'ig_defines.php';
Class instagram_basic_display_api {
private $_appId = INSTAGRAM_APP_ID;
private $_appSecret = INSTAGRAM_APP_SECRET;
private $_redirectUrl = INSTAGRAM_APP_REDIRECT_URI;
private $_getCode = '';
private $_apiBaseUrl = 'https://api.instagram.com/';
public $authorizationUrl = '';
// called on class init
function __construct( $params ) {
// save instagram code
$this->_getCode = $params['get_code'];
// get an access token (code will follow)
// get authorization url
$this->_setAuthorizationUrl();
}
private function _setAuthorizationUrl() {
$getVars = array(
'app_id' => $this->_appId,
'redirect_uri' => $this->_redirectUrl,
'scope' => 'user_profile,user_media',
'response_type' => 'code'
);
// create url
$this->authorizationUrl = $this->_apiBaseUrl . 'oauth/authorize?' . http_build_query( $getVars );
}
}
private $_redirectUrl = INSTAGRAM_APP_REDIRECT_URI; is "http://google.com/" as suggested in this post. My OAuth Redirect URI in the facebook developer tools Instagram API settings is "http://google.com/" as well.
For testing I'm using my test webspace. The URL is something like http://mytestwebspace.de/instagram/news_ig_test.php. As you can see, it doesn't have SSL. The final page is going to, though. Could the lack of SSL be an issue?
EDIT: I forgot to add, I did try using http://mytestwebspace.de/instagram/news_ig_test.php as redirectUrl before, but I'm still getting the same error.
I'm not sure what the reason could be.
I can confirm, SSL is required. When using https://mytestwebspace.de/etc... , authentication works just fine. (Though it's not surprising, I didn't quite expect the solution to be that simple, thus why I opened a thread.)
The QuickBooks-V3-PHP-SDK is giving me a hard time.
I'm trying to use it to sync invoice data. I can successfully get authorization using OAuth 2.0 and connect my client PHP web application to QuickBooks Online. However, while I can successfully make a getCompanyInfo call and receive the results, I can't make a getUserInfo call (or most of the other API calls for that matter), as it will complain about the "access token object" not being set yet.
While connecting to QuickBooks and getting authorization, everything seems to work accurately - and the access token object is successfully placed in the PHP Session. But for some reason, it complains when I try to get the UserInfo data, or use any of the other API calls.
Here's the error that I receive:
Fatal error: Uncaught QuickBooksOnline\API\Exception\SdkException: [0]: Can't get OAuth 2 Access Token Object. It is not set yet.
thrown in /compiled/src/Core/OAuth/OAuth2/OAuth2LoginHelper.php on line 129
Here's how I try to get the UserInfo:
$dataService->updateOAuth2Token($accessToken);
$OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
$result = $OAuth2LoginHelper->getUserInfo();
Again, getting the CompanyInfo works without any problems.
Does anyone have any idea what's going on?
Below I'm including the code from apiCall.php (from the HelloWorld example package, further edited by myself). This file is used to make requests through Ajax after I already connected to and received authorization from QuickBooks Online.
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use QuickBooksOnline\API\Core\ServiceContext;
use QuickBooksOnline\API\DataService\DataService;
use QuickBooksOnline\API\Core\Http\Serialization\XmlObjectSerializer;
use QuickBooksOnline\API\Facades\Invoice;
session_start();
function makeAPICall()
{
// Create SDK instance
$config = include('config.php');
$dataService = DataService::Configure(array(
'auth_mode' => 'oauth2',
'ClientID' => $config['client_id'],
'ClientSecret' => $config['client_secret'],
'RedirectURI' => $config['oauth_redirect_uri'],
'scope' => $config['oauth_scope'],
'baseUrl' => "development"
));
/*
* Retrieve the accessToken value from session variable
*/
$accessToken = $_SESSION['sessionAccessToken'];
$dataService->throwExceptionOnError(true);
/*
* Update the OAuth2Token of the dataService object
*/
$dataService->updateOAuth2Token($accessToken);
//Get the requested data:
$action = filter_input(INPUT_GET, "action", FILTER_SANITIZE_SPECIAL_CHARS);
$method = "get$action";
switch($action){
case "CompanyInfo":
$result = $dataService->$method();
break;
case "UserInfo":
$OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
$result = $OAuth2LoginHelper->getUserInfo();
break;
case "InvoiceExample":
$allInvoices = $dataService->Query("SELECT * FROM Invoice");
$result = $allInvoices;
break;
}
var_dump($result);
return $result;
}
$result = makeAPICall();
?>
Anyone any idea what I'm doing wrong?
The Intuit (QuickBooks) support team provided the answer to me. In my ApiCall code above, I had to use the following code to make the UserInfo request:
$result = $OAuth2LoginHelper->getUserInfo($accessToken->getAccessToken(), 'development');
Obviously, if this would involve production keys, I would have to replace 'development' with 'production'.
I have created an XML-RPC User and I've assigned a role (with all resources) from admin panel: System/Web Services/XML-Rpc Users and Roles.
Now I want to dump all cart products and send them to an external server.
I'm using this code in app/design/frontend/default/theme/template/catalog/product/view.phtml:
$client = new Zend_XmlRpc_Client('http://mysite/api/xmlrpc/', 80);
$session = $client->call('login', array('myuser', 'myapi'));
$filterData = array('type' => array('in' => 'simple'));
$product = $client->call('call', array($session, 'category_product.list', array($filterData)));
var_dump($product);
$server = new Zend_XmlRpc_Client('/xmlServer.php','www.server-site.com', 80);
$result = $server->send($product);
The problem is that I receive this error:
Fatal error: Call to a member function getUri() on a non-object in /var/www/html/zzz/lib/Zend/XmlRpc/Client.php on line 265
This is the code from line 265:
if($http->getUri() === null) {
$http->setUri($this->_serverAddress);
}
I think that the problem comes from here:
$session = $client->call('login', array('myuser', 'myapi'));
But the user and api are valid. So I don't know what could it be.
What is wrong in my code?
Anticipated thanks!
The problem is my server configuration.
It returns false if I try this php command: file_get_contents
So host can't be accessed on port 80.
It's because of the firewall or some other settings.