I am using Guzzle with the following code:
try {
$client = new Client();
$result = $client->get("http://{$request->ES_HOST}:{$request->ES_PORT}", [
'headers' => ['Content-Type' => 'application/json'],
'auth' => [$request->ES_LOGIN, $request->ES_PASSWORD],
'allow_redirects' => false,
]);
$response['status'] = $result->getStatusCode();
$response['message'] = json_decode($result->getBody()->getContents());
} catch (RequestException $e) {
$response['status'] = $e->getResponse()->getStatusCode();
$response['message'] = $e->getMessage();
}
And it works well however when an user gives the wrong URL for guzzle to process it instead of getting catched in RequestException it gives an 500 error in the server and returns a regular Exception with the message of cURL error 7: Failed to connect to [host] port [port]: Connection refused. Hoe can I make it so that I can catch the error and status code as well to return to the user?
Having tried your code, it seems to be throwing an instance of GuzzleHttp\Exception\ConnectException, so change the catch to
} catch (ConnectException $e) {
$response['status'] = 'Connect Exception';
$response['message'] = $e->getMessage();
}
( Adding the appropriate use statement...
use GuzzleHttp\Exception\ConnectException;
)
Also noticed that it doesn't have $e->getResponse()->getStatusCode(), which is why I've just set it to a fixed string.
Since Guzzle has so many Exceptions, i ended up checking which type of exception that guzzle has thrown and constructing a response accordingly:
try {
$client = new Client();
$result = $client->get("http://{$request->ES_HOST}:{$request->ES_PORT}", [
'headers' => ['Content-Type' => 'application/json'],
'auth' => [$request->ES_LOGIN, $request->ES_PASSWORD],
'allow_redirects' => false,
]);
$response['status'] = $result->getStatusCode();
$response['message'] = json_decode($result->getBody()->getContents());
} catch (ConnectException $e) {
$response['status'] = 404;
$response['message'] = $e->getMessage();
} catch (RequestException $e) {
$response['status'] = $e->getResponse()->getStatusCode();
$response['message'] = $e->getMessage();
} catch (\Exception $e) {
$response['status'] = 0;
$response['message'] = $e->getMessage();
}
Related
We are using ListObjects with specific prefixes to return keys to process. Some of the prefixes don't exist all the time. Our previous working environment was PHP 7.3 and aws-sdk 3.142.0 and the code worked as expected. If the prefix has data the result would be parsed, if the prefix didn't exist it returned nothing without issue. We have recently upgraded to PHP 8.1.8 and aws-sdk 3.231.8. ListObjects returns the data as expected when the prefix exists, if the prefix doesn't exist the call fails and the code fails and it is not handled by the exception code. The below code processes the listObjects prefix acr/ and then fails on acr_processed/ because the prefix doesn't currently exist in the bucket.
Has anyone seen this or have a workaround? thank you in advance
$prefixarray = array('acr/','acr_processed/'); // NOTE: acr_processed/ doesn't exist
foreach ($prefixarray as $prefix) {
$bucketName = 'abc';
try {
$objects = $s3->ListObjectsV2(['Bucket' => $bucketName,
'Prefix' => $prefix
]);
} catch (S3Exception $e) {
echo "there was a S3 exception";
} catch (Exception $e) {
echo 'there was an exception';
}
foreach ($objects['Contents'] as $contents) {
echo $contents['Key'] . "<br>";
}
}
The issue is Addressed, call it a workaround because the error 500 still returns if a prefix doesn't exist when you try and list it. With these current versions of PHP and Asw-sdk.
To fix create a dummyobject in the prefix being listed prior to the listing of the prefix. The process is HeadObject to see if the dummyobject is there, if not putObject in the prefix and then list the prefix. The dummyobject will be returned but it is easy to skip when processing the list results.
$tagstring = 'status=placeholder';
$dummykeyName = $prefix . 'placeholder.prefix';
try {
// head a s3 object:
$result = $s3->headObject([
'Bucket' => $bucketName,
'Key' => $dummykeyName
]);
// found
$NoResults = 'no';
} catch (S3Exception $e) {
die('s3 Error:' . $e->getMessage());
} catch (Exception $e) { // placeholder.prefix was not found put it
try {
$s3->putObject(
array(
'Bucket' => $bucketName,
'Key' => $dummykeyName,
'ContentType' => 'text/xml',
'Tagging' => $tagstring,
'StorageClass' => $strgclass
)
);
} catch (S3Exception $e) {
echo 'there was an S3 exception ' . $dummykeyName . '<br>';
$NoResults = 'yes';
} catch (Exception $e) {
echo 'there was an exception ' . $dummykeyName . '<br>';
$NoResults = 'yes';
}
}
// get the list of objects from the bucket
try {
$objects = $s3->ListObjectsV2(['Bucket' => $bucketName,
'Prefix' => $prefix
]);
} catch (S3Exception $e) {
$e->getMessage();
echo "<tr><td>list-enduser error" . $e . "</td></tr>";
$NoResults = 'yes';
} catch (Exception $e) {
echo 'there was an exception';
$NoResults = 'yes';
}
I tried the below code though I am not sure whether these are the required set of scripts, but it didn't work and gives
SOAP-ERROR: Parsing WSDL: Couldn't load from : Start tag expected, '<' not found
$wsdlUrl = 'http://localhost/magento20_0407/soap/default?wsdl_list=1';
$apiUser = 'testUser';
$apiKey = 'admin123';
$token = 'xioxnuuebn7tlh8ytu7781t14w7ftwmp';
$opts = array('http' => array('method' => "GET", 'header' => "Accept-language: en\r\nConnection: close\r\n"));
$context = stream_context_create($opts);
stream_context_set_option($context, "http", "protocol_version", 1.1);
fpassthru(fopen($wsdlUrl, 'r', false, $context));
$opts = array('http'=>array('header' => 'Authorization: Bearer '.$token));
$serviceArgs = array("id"=>1);
try{
$context = stream_context_create($opts);
$soapClient = new SoapClient($wsdlUrl, array('version' => SOAP_1_2, 'context' => $context));
$soapResponse = $soapClient->customerCustomerAccountServiceV1($serviceArgs);
}catch(Exception $e){
$e->getMessage();
}
var_dump($soapResponse);exit;
Can anyone share the code to make SOAP connection in Magento2.x
In Magento1.x the below code works fine to connect SOAP
$apiUrl = 'http://localhost/magento_28_03/index.php/api/soap?wsdl';
$apiUser = 'testUser';
$apiKey = 'admin123';
ini_set("soap.wsdl_cache_enabled", "0");
try{
$client = new SoapClient($apiUrl, array('cache_wsdl' => WSDL_CACHE_NONE));
} catch (SoapFault $e) {
echo 'Error in Soap Connection : '.$e->getMessage();
}
try {
$session = $client->login($apiUser, $apiKey);
if($session) echo 'SOAP Connection Successful.';
else echo 'SOAP Connection Failed.';
} catch (SoapFault $e) {
echo 'Wrong Soap credentials : '.$e->getMessage();
}
But the above doesn't work for Magento 1. Can anyone say, what changes the above code needs to work fine for Magento 2?
For SOAP API call follow the below
test.php
<?php
$token = 'YOUR_ACCESS_TOKEN';
require('vendor/zendframework/zend-server/src/Client.php');
require('vendor/zendframework/zend-soap/src/Client.php');
require('vendor/zendframework/zend-soap/src/Client/Common.php');
$addArgs = array('num1'=>2, 'num2'=>1);// Get Request
$sumArgs = array('nums'=>array(2,1000));// Post request
//$wsdlUrl = YOUR_BASE_URL."soap?wsdl&services=customerAccountManagementV1,customerCustomerRepositoryV1,alanKentCalculatorWebServiceCalculatorV1";//To declar multiple
$wsdlUrl = YOUR_BASE_URL."soap?wsdl&services=alanKentCalculatorWebServiceCalculatorV1";
try{
$opts = ['http' => ['header' => "Authorization: Bearer " . $token]];
$context = stream_context_create($opts);
$soapClient = new \Zend\Soap\Client($wsdlUrl);
$soapClient->setSoapVersion(SOAP_1_2);
$soapClient->setStreamContext($context);
}catch(Exception $e){
echo 'Error1 : '.$e->getMessage();
}
try{
$soapResponse = $soapClient->alanKentCalculatorWebServiceCalculatorV1Add($addArgs);print_r($soapResponse);
$soapResponse = $soapClient->alanKentCalculatorWebServiceCalculatorV1Sum($sumArgs);print_r($soapResponse);
}catch(Exception $e){
echo 'Error2 : '.$e->getMessage();
}
?>
http://YOUR_BASE_URL/test.php
SOAP-ERROR: Parsing WSDL: Couldn't load from : Start tag expected, '<' not found
Tells you all you need to know; the URL you're trying to load isn't a proper WSDL.
What are the contents of: http://localhost/magento20_0407/soap/default?wsdl_list=1
Trying below code for deleting files from google storage but getting the error "An error occurred: (delete) missing required param: 'object'". I am sending the filesId like this $fileId = 1458180875815000.
$google-api-php-client :- getting the google service
// code for delete
$bucketName = "bucketname";
$googleServiceStorage = new Google_Service_Storage($this->client);
//$googleServiceStorage = new Google_Service_Storage_StorageObject();
try
{
$googleServiceStorage->objects->delete($bucketName,$companyId,
[
'object' => $companyId."/".$objectName,
'generation' => $fileId,
'alt' => "media"
]
);
//$bucketName,$companyId,$objectName,$fileId);
}
catch (Exception $e)
{
print "An error occurred: " . $e->getMessage();
}
}
Here is how I am deleting files from GCS
$bucket = 'my_main_bucket';
$file = 'path/to/file/image.jpg';
$this->service = new Google_Service_Storage($this->client);
try
{
$this->service->objects->delete($bucket, $file);
}
catch (Google_Service_Exception $e)
{
syslog(LOG_ERR, $e);
}
am using the php api sdk found here: https://github.com/paypal/PayPal-PHP-SDK but am having trouble issuing a refund.
This is the code I am using:
// CAPTURE THE ORIGINAL AUTHORIZATION
try
{
$amount = new Amount();
$amount->setCurrency("USD");
$amount->setTotal($amount_authorized);
$capture = new Capture();
$capture->setId($authorization_id);
$capture->setAmount($amount);
$authorization = Authorization::get($transaction_id, $apiContext);
$capt = $authorization->capture($capture, $apiContext);
if ($capt->state == 'completed')
{
$capture_id = $capt->id;
}
}
catch (PayPal\Exception\PayPalConnectionException $e)
{
$response = json_decode($e->getData());
die('Error capturing funds: '.$response->message);
}
catch (Exception $e)
{
die('Error capturing funds: '.$e->getMessage());
}
// REFUND THE CAPTURE
try
{
$amount = new Amount();
$amount->setCurrency("USD");
$amount->setTotal($refund_amount);
$refund = new Refund();
$refund->setId($capture_id);
$refund->setAmount($amount);
$capture = Capture::get($capture_id, $apiContext);
$captureRefund = $capture->refund($refund, $apiContext);
if ($captureRefund->state == 'completed')
{
die('REFUNDED');
}
}
catch (PayPal\Exception\PayPalConnectionException $e)
{
$response = json_decode($e->getData());
die('There was an error refunding the funds: '.$response->message);
}
catch (Exception $e)
{
die('There was an error refunding the funds: '.$e->getMessage());
}
I get this error everytime: The requested resource ID was not found
I believe I am following the sample code on the developer site but I'll pulling my hair out. It's probably something pretty easy I hope.
Any ideas?
Thanks
how do I catch my custom soap fault ProductoInexistente when requesting a soap web service operation? my code is the following, but it's not working:
$_WSDL_URI = 'http://joaquinlrobles.redirectme.net:8080/Pelopincho/PelopinchoService?WSDL';
$ws = new Zend_Soap_Client($_WSDL_URI, array('soap_version' => SOAP_1_1));
try {
$resultado = $ws->getStockProducto(array('idProducto' => $idProducto));
$this->view->resultado = $resultado->result;
}
catch (ProductoInexistente $ex) {
$this->view->resultado = 'Producto Inexistente';
}
thanks!
Is there the exception of type ProductoInexistente thrown?
Try changing the code to
$_WSDL_URI = 'http://joaquinlrobles.redirectme.net:8080/Pelopincho/PelopinchoService?WSDL';
$ws = new Zend_Soap_Client($_WSDL_URI, array('soap_version' => SOAP_1_1));
try {
$resultado = $ws->getStockProducto(array('idProducto' => $idProducto));
$this->view->resultado = $resultado->result;
}
catch (Exception $ex) {
var_dump($ex);
}
And see what's the name of exception class.
Unless the exception of ProductoInexistente it cannot be caught by catch(ProductoInexistente $ex)