Prestashop REST API returning bad HTTP response with PHP client - prestashop

This code:
try {
// creating webservice access
$webService = new PrestaShopWebservice('https://149.28.159.206/', '6DE5PU9M9SC7RZCRFF4VK3MFDVVTGRJT', false);
// call to retrieve all customers
$xml = $webService->get(['resource' => 'products']);
} catch (PrestaShopWebserviceException $ex) {
// Shows a message related to the error
echo 'Other error: <br />' . $ex->getMessage();
}
Is returning the following error:
Other error: <br />Bad HTTP response
And I have activated the key with the appropriate permissions (please see attached screenshot). Yet, it's giving this error.
May I know why, and how I can solve this?
I am using Prestashop 1.7.6.5 on Ubuntu 18.04 x64, from a vultr.com cloud instance.

Prestashop use Domain/api for webservics.
try "https://149.28.159.206/api/"

Related

Magento Soap API 1.9 - failed to load external entity

when i tried to connect to Soap Api, i'm getting this error :
SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://www.lignedublanc.fr/index.php/api/soap/?wsdl' : failed to load external entity "https://www.lignedublanc.fr/index.php/api/soap/?wsdl
i tried with soap UI and same errors.
i tried everything on the net but nothing helped.
Maybe someone here can help me ?
<?php
ini_set('soap.wsdl_cache_enabled',0);
ini_set('soap.wsdl_cache_ttl',0);
$url = 'https://www.lignedublanc.fr/index.php/api/soap/?wsdl=1';
$MagentoAPILogin = '';
$MagentoAPIPass = '';
$context = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]);
try {
echo "Connecting to : $url\n";
//$client = new SoapClient($url);
$client = new SoapClient($url, ['stream_context' => $context]);
echo $client->login($MagentoAPILogin, $MagentoAPIPass)."\n";
echo 'Login successful';
} catch (Exception $e) {
echo 'Login fail'."\n";
echo $e->getMessage()."\n";
echo $e->getTraceAsString()."\n";
}
I believe the problem is caused by the server not being able to access the API from the local machine. It is actually the .htaccess file that blocking any hosts except the development machines. Hence, it results in a 403 Forbidden error which is actually the SOAP error. For more reference, have a look:
Unable to connect to Magento SOAP API v2 due to "failed to load external entity"

how to handle error 500 when requesting a distant server with guzzle?

i am requesting a webservice using :
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
try {
$client = new Client();
$response = $client->request('GET', $url); //it crashes at this line
$content = json_decode($response->getBody(), true);
}
catch (ConnectException $e) {
\Drupal::logger('amu_hal')->error('incorrect_url'.$url);
}
today the distant server return a error 500.
How can i modify my code not to crash my site when it happens?
I assume that by distant server you mean a server that takes a long time to connect. You can specify a timeout for the request.
Or perhaps the server returned error 500 and it fails during json_decode? You can check the status code returned by the request.
Or even perhaps the code is failing the line that you indicate but the exception ConnectException is not being caught? Try using Exception as a catch-all to debug this situation.
Instead of using Guzzle directly, I recommend that you use the Drupal wrapper (which uses Guzzle under the hood).
$client = Drupal::httpClient();
$request = $client->get($uri, ['connect_timeout' => 5]);
if ($request->getStatusCode() === 200) {
echo 'Connection Success';
} else {
echo sprintf('Error %d occurred', $request->getStatusCode());
}

Google API Client Libraries -PHP : Google Game Services occurs error (code : 500) without any message

I'm using Google API Client Libraries - PHP and using Service accounts issuing on Google API Console.
I want to get Leaderboards list but error occurs code 500 without any message.
Enabled Google Play Game Management, Google Play Game Services, Google+ API on API Console.
And, Android application using this Leaderboards proper.
What can I do resolve this problem?
request codes(PHP)
set_include_path(get_include_path().PATH_SEPARATOR.'/path/to/google-api-php-client/src');
require_once realpath(dirname(__FILE__).'/google-api-php-client/src/Google/autoload.php');
$client_email = 'myaccount#developer.gserviceaccount.com';
$private_key = file_get_contents('/path/to/my_key_file.p12');
$scopes = array(
Google_Service_Games::GAMES,
Google_Service_Games::PLUS_LOGIN
);
$client = new Google_Client();
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service = new Google_Service_Games($client);
$response = $service->leaderboards->listLeaderboards();
echo json_encode($response) . "\n";
error occours
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/games/v1/leaderboards: (500) {
"error": {
"code": 500,
"message": null
}
}
Additional, It is works simple query - like Book API, returned proper results without error...
$service = new Google_Service_Books($client);
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Korea', $optParams);
var_dump($results) ;
Let me know your any advice.
Thank you for your help. :)

Codeigniter API error returning

Hi has anyone any experience using Phil Sturgeons RESTFUL libraries for codeigniter. I've decided to create a web service for our database in order to supply access to the database from multiple applications. The website is currently developed in Codeigniter therefore it was a simple solution to use the rest API libraries.
The problem I have is that I am trying to return specific errors in the event of a problem.
At the moment I am purposely returning an error like so:
require(APPPATH . 'libraries/REST_Controller.php');
class Settings_api extends REST_Controller {
function settings_get()
{
$this->response(NULL, 404);
}
}
If I access the url directly then I am just receiving a blank page, I can return a message if I replace the 'NULL' with a message but there is nothing to say its a 404 error whereas If I call the page via php using the following
$user = json_decode(file_get_contents('http://www.example.co.uk/api/settings_api/settings/'));
echo $user;
then it shows the following line
Message: file_get_contents(http://www.example.co.uk/api/settings_api/settings/) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 404
In both instances I would like to return a 404 error along with a message I provide. Is this possible and if so could you point me in the right direction.
Thanks
The error message being generated by PHP, as far as I know, there's nothing you can do about this (other than using the # operator, which I do NOT recommend). So, your only option is to manually check file_get_content()'s return value:
$response = file_get_contents('http://...');
if ($response === false) {
// return whatever you feel is appropriate
} else {
$user = json_decode($response);
echo $user;
}
EDIT
Found this answer here on Stackoverflow which is what you are looking for.

Error while using REST api in magento

I have set up magento locally in my system using XAMPP
I have created a file in root directory named dm.php with the contents
<?php
/**
* Example of products list retrieve using Customer account via Magento REST API. OAuth authorization is used
*/
$callbackUrl = "http://localhost/dm.php";
$temporaryCredentialsRequestUrl = "http://localhost/mage2/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://localhost/mage2/oauth/authorize';
$accessTokenRequestUrl = 'http://localhost/mage2/oauth/token';
$apiUrl = 'http://localhost/mage2/api/rest';
$consumerKey = 'enhksf7u33p3snubewb6zcq0z9c63bvv';
$consumerSecret = 'p7e835cdcxofokeep749jgzz4l1e306p';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
try {
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
exit;
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = "$apiUrl/products";
$oauthClient->fetch($resourceUrl);
$productsList = json_decode($oauthClient->getLastResponse());
print_r($productsList);
}
} catch (OAuthException $e) {
print_r($e);
}
But this is giving me the following error
Fatal error: Class 'OAuth' not found in D:\Webserver\xampp\htdocs\dm.php on line 19
Can anybody shed some light on this
Thanks
Since oauth is not possible to install in xampp windows i changed the contents of my dm.php file to this.
<?php
$ch = curl_init('http://localhost/mage2/api/rest/customers');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$customers = curl_exec($ch);
echo $customers;
?>
Now i am getting an error like this
{"messages":{"error":[{"code":403,"message":"Access denied"}]}}
What am i doing wrong?
First of all
Go to magento admin panel System->Webservice->RESt Roles->Guest->Resources Access ->SET ALL
Similarly Go to System->Webservice->RESt Attribute->Guest->Resources Access ->SET ALL
Then Hit this url http://****/chanchal/magento/api/rest/products in web Browser and check what error it shows....
According to me it must show product in your website in xml format.
Please let me know..
EDIT:
I configured a localhost just now and got this output refer the Screenshot. Be sure there is product in your magento.
Similarly follow the above steps for admin,customer then create a Ouath consumer from admin panel , Install RESTClient For Mozilla Firefox And follow Here
These for steps are necessary for the setup..the link might help you..
Authentication Endpoints
1./oauth/initiate - this endpoint is used for retrieving the Request Token.
2./oauth/authorize - this endpoint is used for user authorization (Customer).
3./admin/oauth_authorize - this endpoint is used for user authorization (Admin).
4./oauth/token - this endpoint is used for retrieving the Access Token.
Let me know if you have any issues.
Best of luck
A bit of code modifications will easily solve this error 403 forbidden.
What magento engine does is that it uses the default guest user to provide access to the REST api methods. The guest user does not have much powers so it should be better to change this functionality of magento. There are 2 ways of doing this:
1) Quick and dirty fix: in the file /app/code/core/Mage/Api2/Model/Auth.php, change the value of: DEFAULT_USER_TYPE = 'guest' to DEFAULT_USER_TYPE = 'admin'. In the file /app/code/core/Mage/Api2/Model/Auth/Adapter.php, change this line from return (object) array('type' => Mage_Api2_Model_Auth::DEFAULT_USER_TYPE, 'id' => null); to this:
return (object) array('type' => Mage_Api2_Model_Auth::DEFAULT_USER_TYPE, 'id' => '1');
This way the authentication system will not be broken.
2) Proper and long run fix: Override the two functionalities using the magento overriding mechanism to have a better solution in accordance to magento standards. This way the core files will be intact.
We use this link to install oauth for php. Its good and easy to add extension for php.
install oauth php
I hope it helps to all and would solved 'OAuth' not found fatal error.
I had the same issue and was struggling for a week but just try insatlling new version of xammp or wamp with supports ouath.The better solution was ,I installed Ammps 1.9 and in php5.4 I resolved the extension of oauth but still make sure that you select the proper php for extension oauth is supported (php5.4)
For installing Oauth : http://www.magentocommerce.com/api/rest/authentication/oauth_authentication.html
Installing PHP Extension for Oauth :
1. Download php_oauth.dll file and add it under C:\xampp\php\ext\
2. add [PHP_OAUTH] extension=php_oauth.dll in php.ini