How to use Laravel Http Async result? - php

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();

Related

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 Get time for response

I'm playing around with guzzle and trying to build a simple page, that i can add my domains to - and have it check if they are currently online/accessible.
I can currently check if an array/list of domain's is online, or if it gets rejected for some reason. I would love to also be able to see in my log/DB how long it takes from i send a the HTTP request to [mydomain.com] until the response arrives back.
Current Code:
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
if(!empty($aDomains))
{
$oClient = new Client(['expect' => false]);
$aAcceptedResponse = [];
$aRejectedResponses = [];
$aCreatedRequests = [];
foreach ($aDomains as $iDomainKey => $sDomain)
{
array_push($aCreatedRequests, new Request('GET', $sDomain));
}
$pool = new Pool($oClient, $aCreatedRequests,
[
'concurrency' => 50,
'options' => ['timeout' => 10],
'fulfilled' => function ($response, $index) use (&$aAcceptedResponse)
{
$aAcceptedResponse[] = $index;
},
'rejected' => function ($reason, $index) use(&$aRejectedResponses)
{
$aRejectedResponses[] = $index;
},
]);
$promise = $pool->promise();
$promise->wait();
}
I figured i would be able to find something in the guzzle response object, but so far i have been unable to find anything - am i blind or is it not possible to see this?
Thanks to El_Vanja's answer i figured it out by just using a global timestamp:
$iStartExecutionTime = microtime(true);
$oClient = new Client(['expect' => false]);
$aAcceptedResponse = [];
$aRejectedResponses = [];
$aCreatedRequests = [];
foreach ($aDomains as $iDomainKey => $oDomain)
{
array_push($aCreatedRequests, new Request('GET', $oDomain->sDomainName));
update_domain_uptime_monitor($oDomain->iID, 1, date('Y-m-d H:i:s', strtotime('NOW')+$oDomain->iInterval), date('Y-m-d H:i:s', strtotime('NOW')));
}
$pool = new Pool($oClient, $aCreatedRequests,
[
'concurrency' => 50,
'options' => ['timeout' => 10],
'fulfilled' => function ($response, $index) use (&$aAcceptedResponse)
{
$aAcceptedResponse[$index] = (microtime(true)-$GLOBALS['iStartExecutionTime']);
},
'rejected' => function ($reason, $index) use(&$aRejectedResponses)
{
$aRejectedResponses[] = $index;
},
]);
$promise = $pool->promise();
$promise->wait();

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

Request to RingCentral API

I am trying to send a request to RingCentral API. The link to documentation is https://developers.ringcentral.com/api-reference/Fax/createFaxMessage If I don't specify faxResolution or coverIndex everything goes well, fax could be sent. But if I add faxResolution param like in the code below, I receive error "Parameter [faxResolution] value is invalid", "errorCode" : "CMN-101". The same thing with coverIndex param. My client is GuzzleHttp 6.3
$token = $this->ringcentral->platform()->auth()->data()['access_token'];
$a = array();
foreach ($destination_numbers as $number) {
$a[] = [
'name' => 'to',
'contents' => $number,
'headers' => ['Content-Type' => 'multipart/form-data']
];
}
$a[] = [
'name' => 'faxResolution',
'contents' => 'High',
'headers' => ['Content-Type' => 'multipart/form-data']
];
foreach ($attachments as $attachment) {
$file_pointer = fopen($attachment, 'r');
$mime = mime_content_type($attachment);
$a[] = [
'name' => 'attachment',
'contents' => $file_pointer,
'headers' => ['Content-Type' => $mime]
];
}
$client = new Client();
try {
$response = $client->request('POST', url(config('services.ringcentral.app_url')) . '/restapi/v1.0/account/~/extension/~/fax', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token
],
'multipart' => $a
]);
$response = json_decode($response->getBody(), true);
} catch (\GuzzleHttp\Exception\ClientException $e) {
echo($e->getResponse()->getBody()->getContents());
}
Here's what RingCentral suggests when using PHP. I included all of what they suggested, but just look at the part about faxResolution (2/3 of the way down)
<?php
// https://developers.ringcentral.com/my-account.html#/applications
// Find your credentials at the above url, set them as environment variables, or enter them below
// PATH PARAMETERS
$accountId = '<ENTER VALUE>';
$extensionId = '<ENTER VALUE>';
$recipient = '<ENTER VALUE>';
require('vendor/autoload.php');
$rcsdk = new RingCentral\SDK\SDK(getenv('clientId'), getenv('clientSecret'), getenv('serverURL'));
$platform = $rcsdk->platform();
$platform->login(getenv('username'), getenv('extension'), getenv('password'));
$request = $rcsdk->createMultipartBuilder()
->setBody(array(
'to' => array(array('phoneNumber' => $recipient)),
'faxResolution' => 'High',
))
->add(fopen('fax.jpg', 'r'))
->request("/restapi/v1.0/account/{$accountId}/extension/{$extensionId}/fax");
$r = $platform->sendRequest($request);
?>

perform an asynchronous query in PHP using "Guzzle"

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();
?>

Categories