perform an asynchronous query in PHP using "Guzzle" - php

make an asynchronous query with PHP using Guzzle and not wait for the result.
how to retrieve JSON content into another PHP file?
<?php
require '/tools/guzzle-master/vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
$url = 'https://xxxxxxx/receive.php;
/*creating a client*/
$client = new Client();
/*JSON formatting */
$param = array(
'order_id' => 4544,
'type' => 0,
'amount' => 1266,
'fullname' => 'qdxeq',
'account' => 'dqad',
'callback_url' => 'http://yuexingy.top/Withdraw/WithdrawCallback.aspx',
'device_type' => 'dqd',
'device_id' => 'dafwe',
'device_ip' => 'dwe',
);
$json = json_encode($param);//json encoding
$data = array('json'=>$json);
$req = new Request('POST',$url, $data);
//sending the asynchronous request
$promise = $client->sendAsync($req,['timeout' => 10])->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
?>

Related

How to use Laravel Http Async result?

I am new to using Laravel http and changed my code to use a async request. Can someone help me expand on my current code to access the result of each request. I am a little unsure how to use the following
fn (Response|TransferException $result) =>
$this->handleResult($result)
$date = new DateTime;
$date->modify('-15 minutes');
$formatted_date = $date->format('Y-m-d H:i:s');
$twitter_accounts = TwitterAccount::where('last_tweet_fetch','<=',$formatted_date)
->orWhere('last_tweet_fetch', '=', null)
->orderBy('id')
->limit(40)
->get();
foreach ($twitter_accounts as $twitter_account) {
$promise = Http::withToken('__TOKEN__')
->async()->get("https://api.twitter.com/2/users/".urlencode($twitter_account->twitter_id)."/tweets",[
'expansions' => 'attachments.media_keys,author_id,referenced_tweets.id',
'media.fields' => 'type,preview_image_url,url',
'user.fields' => 'profile_image_url,url,description,public_metrics,verified',
'tweet.fields' => 'created_at,text',
'max_results' => '5',
'exclude' => 'replies',
'since_id' => $twitter_account->last_tweet_id
])
->then(
fn (Response|TransferException $result) => $this->handleResult($result)
);
}
Make use of Guzzle Client request
$headers = [];
$body = [
'expansions' => 'attachments.media_keys,author_id,referenced_tweets.id',
'media.fields' => 'type,preview_image_url,url',
'user.fields' => 'profile_image_url,url,description,public_metrics,verified',
'tweet.fields' => 'created_at,text',
'max_results' => '5',
'exclude' => 'replies',
'since_id' => $twitter_account->last_tweet_id
];
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', "https://api.twitter.com/2/users/".urlencode($twitter_account->twitter_id)."/tweets", $headers, $body);
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();

make the variable as string in laravel

how are you ?
I'm using Guzzle to send post method but when i tried to send the post method with variable getting error so i tried to convert it to sting but still same
this is my current code
if $ mobile value is 55454545445 , them the 'numbers' => "{$mobile}" will be different not "55454545445"
$user = Auth::user();
$mobile = $user->mobile;
$client = new Client();
$booking = Booking::where('id', '=', e($id))->first();
if($booking)
{
$booking->booking_status_id = 3;
$booking->save();
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$data = array('userName' => "test",
'apiKey' => "1",
'numbers' => "{$mobile}",
'userSender' => "sender",
'msg' =>'msg',
'msgEncoding' => "UTF8",);
$dataJson = json_encode($data);
$response = $client->post('https://www.test.test',
['body' => $dataJson]
);
i used this
"0{$mobile}"
instead of
"{$mobile}"
and its work

HTTP Guzzle not returning all data

I have created a function that contacts a remote API using Guzzle but I cannot get it to return all of the data available.
I call the function here:
$arr = array(
'skip' => 0,
'take' => 1000,
);
$sims = api_request('sims', $arr);
And here is the function, where I have tried the following in my $response variable
json_decode($x->getBody(), true)
json_decode($x->getBody()->getContents(), true)
But neither has shown any more records. It returns 10 records, and I know there are over 51 available that it should be returning.
use GuzzleHttp\Client;
function api_request($url, $vars = array(), $type = 'GET') {
$username = '***';
$password = '***';
//use GuzzleHttp\Client;
$client = new Client([
'auth' => [$username, $password],
]);
$auth_header = 'Basic '.$username.':'.$password;
$headers = ['Authorization' => $auth_header, 'Content-Type' => 'application/json'];
$json_data = json_encode($vars);
$end_point = 'https://simportal-api.azurewebsites.net/api/v1/';
try {
$x = $client->request($type, $end_point.$url, ['headers' => $headers, 'body' => $json_data]);
$response = array(
'success' => true,
'response' => // SEE ABOVE //
);
} catch (GuzzleHttp\Exception\ClientException $e) {
$response = array(
'success' => false,
'errors' => json_decode($e->getResponse()->getBody(true)),
);
}
return $response;
}
By reading the documentation on https://simportal-api.azurewebsites.net/Help/Api/GET-api-v1-sims_search_skip_take I assume that the server is not accepting your parameters in the body of that GET request and assuming the default of 10, as it is normal in many applications, get requests tend to only use query string parameters.
In that function I'd try to change it in order to send a body in case of a POST/PUT/PATCH request, and a "query" without json_encode in case of a GET/DELETE request. Example from guzzle documentation:
$client->request('GET', 'http://httpbin.org', [
'query' => ['foo' => 'bar']
]);
Source: https://docs.guzzlephp.org/en/stable/quickstart.html#query-string-parameters

PHP Azure OCR - use local file

I'm using the Azure OCR Service to get the text of an image back (
https://learn.microsoft.com/de-de/azure/cognitive-services/Computer-vision/QuickStarts/PHP).
So far everything is up and running, but now I would like to use a local file instead of an already uploaded one.
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_POST);
// Request body
$request->setBody("{body}"); // Replace with the body, for example, "{"url": "http://www.example.com/images/image.jpg"}
Unfortunately I don't know how to pass the raw binary as the body of my POST request in PHP.
At first, when we refer local file, we should use 'Content-Type': 'application/octet-stream' in a header, then we can send requests that use a stream resource as the body.
Here's my working code using Guzzle for your reference:
<?php
require 'vendor/autoload.php';
$resource = fopen('./Shaki_waterfall.jpg', 'r');
$client = new \GuzzleHttp\Client();
$res = $client->request('POST', 'https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze', [
'query' => [
'visualFeatures' => 'Categories',
'details' => '',
'language' => 'en'
],
'headers' => [
'Content-Type' => 'application/octet-stream',
'Ocp-Apim-Subscription-Key' => '<Ocp-Apim-Subscription-Key>'
],
'body' => $resource
]);
echo $res->getBody();
Using HTTP_Request2:
<?php
require_once 'HTTP/Request2.php';
$request = new Http_Request2('https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze');
$url = $request->getUrl();
$headers = array(
'Content-Type' => 'application/octet-stream',
'Ocp-Apim-Subscription-Key' => '<Ocp-Apim-Subscription-Key>',
);
$request->setHeader($headers);
$parameters = array(
'visualFeatures' => 'Categories',
'details' => '',
'language' => 'en',
);
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->setBody(fopen('./Shaki_waterfall.jpg', 'r'));
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}

Can not fetch value of an element using Symfony Dom Crawler

I am fetching a URL using guzzle POST method . its working and returning the page that I want . but the problem is when I want to get the value of an input element in a form in that page, the crawler returns nothing . I don't know why .
PHP:
<?php
use Symfony\Component\DomCrawler\Crawler;
use Guzzle\Http\Client;
$client = new Client();
$request = $client->get("https://example.com");
$response = $request->send();
$getRequest = $response->getBody();
$cookie = $response->getHeader("Set-Cookie");
$request = $client->post('https://example.com/page_example.php', array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Cookie' => $cookie
), array(
'param1' => 5,
'param2' => 10,
'param3' => 20
));
$response = $request->send();
$pageHTML = $response->getBody();
//fetch orderID
$crawler = new Crawler($pageHTML);
$orderID = $crawler->filter("input[name=orderId]")->attr('value');//there is only one element with this name
echo $orderID; //returns nothing
What should I do ?
You don't have to create a Crawler:
$crawler = $client->post('https://example.com/page_example.php', array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Cookie' => $cookie
), array(
'param1' => 5,
'param2' => 10,
'param3' => 20
));
$orderID = $crawler->filter("input[name=orderId]")->attr('value');
This assumes your POST isn't being redirected, if it is redirected you should add before calling the filter function:
$this->assertTrue($client->getResponse()->isRedirect());
$crawler = $client->followRedirect();

Categories