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.
Related
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'm trying to embed Server Side conversion in a website (due to iOS 14 update) but I'm experiencing issues with the PHP SDK so everytime I try a conversion code in a page it turns out Fatal Error.
So my question is, how can I use/embed correctly these conversions code?
Thanks in advance to who will answer
EDIT: To explain better
I Downloaded the Facebook Php SDK from here https://php-download.com/package/facebook/php-sdk-v4 and then I uploaded in my website root, after that I've included the following code(from https://developers.facebook.com/docs/marketing-api/conversions-api/payload-helper ) in a thank you page to track "purchase" conversion:
<?php
define('SDK_DIR', __DIR__ . '/..'); // Path to the SDK directory
$loader = include SDK_DIR . '/vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
use FacebookAds\Object\ServerSide\Content;
use FacebookAds\Object\ServerSide\CustomData;
use FacebookAds\Object\ServerSide\DeliveryCategory;
use FacebookAds\Object\ServerSide\Event;
use FacebookAds\Object\ServerSide\EventRequest;
use FacebookAds\Object\ServerSide\Gender;
use FacebookAds\Object\ServerSide\UserData;
// Configuration.
// Should fill in value before running this script
$access_token = null;
$pixel_id = null;
if (is_null($access_token) || is_null($pixel_id)) {
throw new Exception(
'You must set your access token and pixel id before executing'
);
}
// Initialize
Api::init(null, null, $access_token);
$api = Api::instance();
$api->setLogger(new CurlLogger());
$events = array();
$user_data_0 = (new UserData())
->setEmail("hashed email");
$custom_data_0 = (new CustomData())
->setValue(142.52)
->setCurrency("USD");
$event_0 = (new Event())
->setEventName("Purchase")
->setEventTime(1620379012)
->setUserData($user_data_0)
->setCustomData($custom_data_0)
->setActionSource("email");
array_push($events, $event_0);
$request = (new EventRequest($pixel_id))
->setEvents($events);
$request->execute();
Of course this code do not contain token and pixel ID but in the website I filled all the variables with the right values.
I also adjusted the require on top with the right path and then i got the following error in the page:
Fatal error: Uncaught Error: Class 'FacebookAds\Api' not found in mywebsite/public_html/template/includes/analyticstracking2.inc.php:60 Stack trace: #0 /mywebsite/public_html/it/thankyou_page.php(134): require() #1 {main} thrown in mywebsite/public_html/template/includes/analyticstracking2.inc.php on line 60
On line 60 there's the following: Api::init(null, null, $access_token);
Onestly I do not understand where the issue it's coming from.
Now to answer to 'why do not use composer' I can't from a shared hosting server, if someone knows howo to do maybe I can start from there.
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'm new one on Odoo, and I don't have experience with the system and try to follow the documentation how they do it.
For my first thing what I need is to connect external PHP web application whit our Odoo system.
I see this is possible and I follow the steps on that documentation: Odoo Documentation
So I'm stick here:
$common = ripcord::client("$url/xmlrpc/2/common");
$common->version();
When I execute that lines of code I get that error:
[faultString] => Traceback (most recent call last):
File "/home/odoo/src/odoo/12.0/odoo/addons/base/controllers/rpc.py", line 63, in xmlrpc_2
response = self._xmlrpc(service)
File "/home/odoo/src/odoo/12.0/odoo/addons/base/controllers/rpc.py", line 42, in _xmlrpc
params, method = loads(data)
File "/usr/lib/python3.5/xmlrpc/client.py", line 1000, in loads
p.close()
File "/usr/lib/python3.5/xmlrpc/client.py", line 447, in close
parser.Parse(b"", True) # end of data
xml.parsers.expat.ExpatError: no element found: line 1, column 0
I use demo URL (https://demo.odoo.com/) which their recommend. And from first example I get username, password, database name, successfully. But after that I cannot do anything.
UPDATE:
That is my PHP class which I call for testing:
require_once(__DIR__ . '/Ripcode/ripcord.php');
class Ripcode
{
private $_url = 'https://demo.odoo.com/';
private $_server = [];
private $_connection = null;
private $_common = null;
public function __construct()
{
$this->_server = \ripcord::client($this->_url . 'start')->start();
$common = \ripcord::client($this->_url . "xmlrpc/2/common");
$common->version();
$models = \ripcord::client($this->_url . "xmlrpc/2/object");
$uid = $common->authenticate(
$this->_server['database'],
$this->_server['user'],
$this->_server['password'],
array()
);
showArray([
'server' => $this->_server,
'uid' => $uid
]);
showArray([
'server' => $this->_server,
'models' => $models,
'uid' => $uid
'common' => $common->version()
]);
}
}
The problem is ripcord. I tested one cloned from https://github.com/poef/ripcord with an Odoo v12 running locally and debugged from the reception of the request all the way through until the response is sent. Everything works seamlessly until it gets to ripcord.
May I suggest using another XML-RPC client?
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.