I try to use GuzzleHttp with Magento to update my product catalog.
I use a pool request to get data from database and I try to post them into magento trought API
$apiUrl = 'http://xxx.xxxxx.xxx';
$middleware = new Oauth1([
'consumer_key' => '-------------------------------',
'consumer_secret' => '-------------------------------',
'token' => '-------------------------------',
'token_secret' => '-------------------------------'
]);
$stack->push($middleware);
$client = new Client();
$clientUpdate = new Client([
'base_uri' => $apiUrl,
'handler' => $stack,
'auth' => 'oauth'
]);
$mapper = new JsonMapper();
$requests = function ($total) {
$uri = 'http://10.0.0.114:15021/myservice';
for ($i = 1; $i <= $total; $i++) {
yield new Request('GET', $uri.$i);
}
};
$pool = new Pool($client, $requests(3), [
'concurrency' => 3,
'fulfilled' => function ($response, $index) {
global $clientUpdate, $mapper;
$productsArray = $mapper->mapArray(
json_decode($response->getBody($asString = TRUE)), new ArrayObject(), 'ProductGo'
);
$product = new Product();
$stock = new StockData();
foreach($productsArray as &$value){
$product->type_id = "simple";
$product->attribute_set_id = 4;
$product->sku = $value->xxxxxxxxxxxxxxx;
$product->weight = 1;
$product->name = $value->xxxxxxxx;
$product->price = $value->xxxxxxxx;
$product->status = 1;
$product->visibility =4;
$product->tax_class_id = 4;
$product->description = $value->xxxxxxx;
$product->short_description = $value->xxxxxx;
$stock->qty = $value->xxxxx;
$stock->min_qty = "0";
$stock->is_qty_decimal = 0;
$stock->is_in_stock = 1;
$product->stock_data = (object) array_filter((array) $stock);
$productIn = (object) array_filter((array) $product);
try{
$response = $clientUpdate->request('POST', '/api/rest/products', ['json' => json_encode($productIn)]);
echo $response;
}catch (RequestException $e) {
echo GuzzleHttp\Psr7\str($e->getRequest());
if ($e->hasResponse()) {
echo GuzzleHttp\Psr7\str($e->getResponse());
}
}
}
},
'rejected' => function ($reason, $index) {
echo $reason;
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
Pool request works ok. If I debug I will put a break point where I make a request but after I get ever the same error
PHP Fatal error: Uncaught exception 'GuzzleHttp\Exception\ServerException' with message 'Server error: 500' in /home/xxxxxxxxxxx/PhpstormProjects/xxxxxxxxxxx/vendor/guzzlehttp/guzzle/src/Middleware.php:68
Stack trace:
#0 /home/xxxxxxxxxxx/PhpstormProjects/xxxxxxxxxxx/vendor/guzzlehttp/promises/src/Promise.php(199): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response))
#1 /home/xxxxxxxxxxx/PhpstormProjects/xxxxxxxxxxx/vendor/guzzlehttp/promises/src/Promise.php(152): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), Array)
#2 /home/xxxxxxxxxxx/PhpstormProjects/xxxxxxxxxxx/vendor/guzzlehttp/promises/src/TaskQueue.php(60): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise\{closure}()
#3 /home/xxxxxxxxxxx/PhpstormProjects/xxxxxxxxxxx/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php(96): GuzzleHttp\Promise\TaskQueue->run()
#4 /home/xxxxxxxxxxx/PhpstormProjects/xxxxxxxxxxx/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php(123): GuzzleHttp\Handler\CurlMultiHandler->tick()
#5 /home/xxxxxxxxxxx/PhpstormPr in /home/xxxxxxxxxxx/PhpstormProjects/xxxxxxxxxxx/vendor/guzzlehttp/guzzle/src/Middleware.php on line 68
I can't understand what's the problem, I've tried to post with postman this json as product and it works.
Any suggestions???
http://docs.guzzlephp.org/en/latest/request-options.html#jso
Summary:
The json option is used to easily upload JSON encoded data as the body
of a request. A Content-Type header of application/json will be added
if no Content-Type header is already present on the message.
Here's an example on how to set up the header on request:
$client->request('POST', $url, [
'headers' => [
'Accept' => 'application/json',
],
'body' = $body
]);
Related
<?php
$time = time();
$name = $_GET['cname'];
$invoiceNumber = $_GET['invoice'];
$date = $_GET['date'];
$percentage = $_GET['percentage'];
$taxableValue = $_GET['taxableValue'];
$discount = $_GET['discount'];
$invoictotoal = $_GET['total'];
$sgst = $percentage*$taxableValue/100;
echo $discount;
require __DIR__ . '/vendor/autoload.php';
/**
* Returns an authorized API client.
* #return Client the authorized client object
*/
function getClient()
{
$client = new \Google_Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAuthConfig('C:\Users\mitta\Desktop\Seagull\form\credentials.json');
$client->setAccessType('offline');
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$client->addScope(Google\Service\Drive::DRIVE);
$client->setScopes(['https://www.googleapis.com/auth/spreadsheets']);
$service = new Google\Service\Sheets($client);
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
try{
$spreadsheetId = '1H6EHEHGsHyRZTE-j8er9DrZjj-b9TkRg0p96K-h90Pc';
$range = 'Form Responses 1';
$valuetoinsert = [
[$time,$name,$invoiceNumber,$date,$percentage,$invoictotoal,$taxableValue,$discount,$sgst,$sgst],
];
$body = new Google_Service_Sheets_ValueRange([
'values' => $valuetoinsert
]);
$params = [
'valueInputOption' => 'RAW'
];
$inset = [
"insertDataOption" => "INSERT_ROWS"
];
$result = $service->spreedsheets_values->append(
$spreadsheetId,
$range,
$body,
$params
);
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
printf($e->getMessage());
}
?>
I am getting this error on line 53 i.e; "$result = $service->spreedsheets_values->append(
$spreadsheetId,
$range,
$body,
$params
);"
I am getting the following error:
Warning: Undefined property: Google\Service\Sheets::$spreedsheets_values in D:\xamp\htdocs\form\insert.php on line 53
Fatal error: Uncaught Error: Call to a member function append() on null in D:\xamp\htdocs\form\insert.php:53 Stack trace: #0 {main} thrown in D:\xamp\htdocs\form\insert.php on line 53
i'm running script(svc/rest services) that request a server which response me a XML string.. this request is going through an intermediate server.
My aim is to fetch the details of guests o.e. rooms which will be response..
but after certain number of request i am getting 504 gateway out and only about 40 rooms are able to retreived
1: file...source hots
$ROOMS = ["301","302","304","305","306","307","308","309","310",
"311","312","314","315","316","317","318","319","320",
"401","402","403","404","405","406","407","408","409",
"410","411","412","414","415","416","802","802","802",
"802","802","802","802","802","802","802","802","802",
"802","802","802","802","802","802","802","802","802",
"802","802","802","802","802","802","802","802"
];
// all rooms more than 75
for ($x = 0; $x < count($ROOMS); $x++){
$end_point = "https://www.innkeyapp.com/SerRest.svc/GetOccupiedRoomData";
$sharedkey = "2diSq8bjZ4N3ZR4XB5KXXXXXXXXXXXXXXXXXXXXXXX";
$url = 'https://eastern-services.com/innkeyPMS_room_ststus.php';
$room_no = $ROOMS[$x];
$postdata = http_build_query([
'end_point' => $end_point,
'room_no' => $room_no,
'sharedkey' => $sharedkey
]);
$opts = [
'http' => [
'method' => 'POST',
'content' => $postdata
]
];
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
$arrayData = json_decode($result,true);
if (empty($arrayData)) {
// Redirect('failure.php?msg=Error in service');
echo "Error in Service";
exit();
}
print_r($arrayData);
echo $room_no."Added";
}
2: file.... innkeyPMS_room_ststus.php i.e. intermediate host.
$room_no = $post_var['room_no'];
$end_point = $post_var['end_point'];
$sharedkey = $post_var['sharedkey'];
$registerno = '';
$prprtxt = '';
$validunit = '';
// echo $post_var;
function curl_get_file_contents($URL)
{
return file_get_contents($URL);
}
$xmlString = curl_get_file_contents(
$end_point.'sharedkey='.$sharedkey.'=&roomno='.$room_no
);
$xml = simplexml_load_string($xmlString);
header("Content-Type: application/json");
echo json_encode($xml);
why this connection is getting lost or why its showing 504 gateway time out?
I'm trying to make 4 async search calls (POST HTTP request) to search 4 database tables at the same time, then wait for all of them to finish (asynchronously), combine the results and return them to the user.
Here is my code:
public static function async_search($search_words)
{
$curl = new CurlMultiHandler();
$client = new Client([
'base_uri' => 'https://mytestapi.com/',
'timeout' => 0,
]);
$finished_promisesArr = array(
'search1' => 0,
'search2' => 0,
'search3' => 0,
'search4' => 0,
);
$bodyArr = array(
'search_words' => $search_words,
);
$search1_promise = $client->requestAsync('POST', 'search1', array(
'form_params' => $bodyArr,
))->then(
function(ResponseInterface $response) {
echo 'got response';
$finished_promisesArr['search1'] = 1;
},
function (RequestException $e) {
$finished_promisesArr['search1'] = 1;
}
);
$search2_promise = $client->requestAsync('POST', 'search2', array(
'form_params' => $bodyArr,
))->then(
function(ResponseInterface $response) {
$finished_promisesArr['search2'] = 1;
},
function (RequestException $e) {
$finished_promisesArr['search2'] = 1;
}
);
$search3_promise = $client->requestAsync('POST', 'searchCompanies', array(
'form_params' => $bodyArr,
))->then(
function(ResponseInterface $response) {
$finished_promisesArr['search3'] = 1;
},
function (RequestException $e) {
$finished_promisesArr['search3'] = 1;
}
);
$search4_promise = $client->requestAsync('POST', 'searchCompaniesByIndustries', array(
'form_params' => $bodyArr,
))->then(
function(ResponseInterface $response) {
$finished_promisesArr['search4'] = 1;
},
function (RequestException $e) {
$finished_promisesArr['search4'] = 1;
}
);
$promisesAggregate = GuzzleHttp\Promise\all([$search1_promise, $search2_promise, $search3_promise, $search4_promise]);
foreach ($promisesAggregate as $agg) {
$curl->tick();
}
$keep_running = true;
while ($keep_running) {
$all_processes_finished = true;
foreach ($finished_promisesArr as $promise => $status) {
if (!$status) {
$all_processes_finished = false;
}
}
if ($all_processes_finished) {
$keep_running = false;
}
}
return array();
}
Please ignore the empty array in the result and the fact that I'm not doing anything with the response.
I've got logs on the server methods and they're not even being called, and the loop continues to run infinitely.
Note that when I use the request method instead of requestAsync I do get the correct result.
Any ideas here?
Thank's!
Just call $promisesAggregate->wait() after you get it from GuzzleHttp\Promise\all function.
It means the same as your code, but does it right (your wait code calls ->tick() only once and this is the mistake).
I have this function that connects to an external API:
function ICUK_Request($url, $method = 'GET', $body = NULL) {
$client = new IcukApiClient();
$client->username = "user";
$client->key = "pass";
$client->encryption = "SHA-512";
$req = new IcukApiRequest();
$req->url = $url;
$req->method = $method;
if(!is_null($body)) {
$req->body = $body;
}
$res = $client->send($req);
if ($res->success) {
$obj = json_decode($res->response);
}
else {
throw new Exception('There was an error contacting the API.');
}
return $obj;
}
the API docs are telling me to send the POST request like this:
POST /domain/registration/new/
{
"domain_name": "domain.co.uk",
"hosting_type": "NONE",
"registration_length": 1,
"auto_renew": false,
"domain_lock": false,
"whois_privacy": false,
"contact_registrant_id": 1
}
so i tried this:
$arr = array(
"domain_name" => "domain.co.uk",
"hosting_type" => "NONE",
"registration_length" => 1,
"auto_renew" => false,
"domain_lock" => false,
"whois_privacy" => false,
"contact_registrant_id" => 1
);
ICUK_Request("/domain/registration/new", "POST", $arr);
but thats giving me a response in the API Logs saying:
{
"exception_message": "Internal API exception occured",
"exception_type": "InternalApiException"
}
im not sure if this would be anything generic and if anyone can help on how to POST the data?
Send it as json:
$values = json_encode($arr);
ICUK_Request("/domain/registration/new", "POST", $values);
All the question about examples are like 2 years old, and I can't find ANY working example for current API client version (https://github.com/google/google-api-php-client). Every single one is missing something or throwing exception....
Could anybody provide working example? There is no documentation AT ALL, anywhere.
This is the most working one:
<?php
require_once 'inc/google-api/autoload.php'; // or wherever autoload.php is located
$client = new Google_Client();
$client->setApplicationName("whatever");
$client->setDeveloperKey("some key");
$service = new Google_Service_Bigquery($client);
$postBody = "[
'datasetReference' => [
'datasetId' => $datasetId,
'projectId' => $projectId,
],
'friendlyName' => $name,
'description' => $description,
'access' => [
['role' => 'READER', 'specialGroup' => 'projectReaders'],
['role' => 'WRITER', 'specialGroup' => 'projectWriters'],
['role' => 'OWNER', 'specialGroup' => 'projectOwners'],
],
]";
$dataset = $service->datasets->insert($projectId, new Google_Dataset($postBody));
$postBody = "[
'tableReference' => [
'projectId' => 'test_project_id',
'datasetId' => 'test_data_set',
'tableId' => 'test_data_table'
]
]";
$table = $service->tables->insert($projectId, $datasetId, new Google_Table($postBody));
?>
But I am getting Fatal errors about Google_Dataset and Google_Table not defined...
Here is a code that
properly creates a Google_Client
runs a job async
displays the running job ID and status
You need to have:
service account created (something like ...#developer.gserviceaccount.com)
your key file (.p12)
service_token_file_location (writable path to store the JSON from the handshake, it will be valid for 1h)
code sample:
function getGoogleClient($data = null) {
global $service_token_file_location, $key_file_location, $service_account_name;
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$old_service_token = null;
$service_token = #file_get_contents($service_token_file_location);
$client->setAccessToken($service_token);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name, array(
'https://www.googleapis.com/auth/bigquery',
'https://www.googleapis.com/auth/devstorage.full_control'
), $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
$service_token = $client->getAccessToken();
}
return $client;
}
$client = getGoogleClient();
$bq = new Google_Service_Bigquery($client);
/**
* #see https://developers.google.com/bigquery/docs/reference/v2/jobs#resource
*/
$job = new Google_Service_Bigquery_Job();
$config = new Google_Service_Bigquery_JobConfiguration();
$config->setDryRun(false);
$queryConfig = new Google_Service_Bigquery_JobConfigurationQuery();
$config->setQuery($queryConfig);
$job->setConfiguration($config);
$destinationTable = new Google_Service_Bigquery_TableReference();
$destinationTable->setDatasetId(DATASET_ID);
$destinationTable->setProjectId(PROJECT_ID);
$destinationTable->setTableId('table1');
$queryConfig->setDestinationTable($destinationTable);
$sql = "select * from publicdata:samples.github_timeline limit 10";
$queryConfig->setQuery($sql);
try {
// print_r($job);
// exit;
$job = $bq->jobs->insert(PROJECT_ID, $job);
$status = new Google_Service_Bigquery_JobStatus();
$status = $job->getStatus();
// print_r($status);
if ($status->count() != 0) {
$err_res = $status->getErrorResult();
die($err_res->getMessage());
}
} catch (Google_Service_Exception $e) {
echo $e->getMessage();
exit;
}
//print_r($job);
$jr = $job->getJobReference();
//var_dump($jr);
$jobId = $jr['jobId'];
if ($status)
$state = $status['state'];
echo 'JOBID:' . $jobId . " ";
echo 'STATUS:' . $state;
You can grab the results with:
$res = $bq->jobs->getQueryResults(PROJECT_ID, $_GET['jobId'], array('timeoutMs' => 1000));
if (!$res->jobComplete) {
echo "Job not yet complete";
exit;
}
echo "<p>Total rows: " . $res->totalRows . "</p>\r\n";
//see the results made it as an object ok
//print_r($res);
$rows = $res->getRows();
$r = new Google_Service_Bigquery_TableRow();
$a = array();
foreach ($rows as $r) {
$r = $r->getF();
$temp = array();
foreach ($r as $v) {
$temp[] = $v->v;
}
$a[] = $temp;
}
print_r($a);
You can see here the classes that you can use for your other BigQuery calls. When you read the file, please know that file is being generated from other sources, hence it looks strange for PHP, and you need to learn reading it in order to be able to use the methods from it.
https://github.com/google/google-api-php-client/blob/master/src/Google/Service/Bigquery.php
like:
Google_Service_Bigquery_TableRow