How would I make the same curl request in something like Guzzle? - laravel

I've got this php curl request that I stumbled onto that works but would like to use something like Guzzle instead and cant quite figure out how to make the conversion. Anything I try is giving me status code 400, Bad Authentication data.
Any help or references would be much appreciated.
$header = array($this->oauth, 'Expect:' );
$header['Content-Type'] = $multipart ? 'multipart/form-data' : 'application/x-www-form-urlencoded';
$options = [
CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => $return,
CURLOPT_TIMEOUT => 30,
];
if (!is_null($this->postFields)){
$options[CURLOPT_postFields] = http_build_query($this->postFields, '', '&');
}
else if ($this->getField !== ''){
$options[CURLOPT_URL] .= $this->getField;
}
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
// $this->httpStatusCode = curl_getinfo($feed, CURLINFO_HTTP_CODE);
if (($error = curl_error($feed)) !== '')
{
curl_close($feed);
throw new \Exception($error);
}
curl_close($feed)

First install guzzle, and use code like this
$client = new \GuzzleHttp\Client();
$header = array($this->oauth, 'Expect:' );
$header['Content-Type'] = $multipart ? 'multipart/form-data' :
'application/x-www-form-urlencoded';
try
{
$response = $client->request('GET', $url, [ 'headers' => $header]);
}
catch(\GuzzleHttp\Exception\ClientException $e)
{
return response(['status' => 0, 'error' => $e->getMessage()]);
}
catch(\GuzzleHttp\Exception\ServerException $e)
{
return response(['status' => 0, 'error' => 'Something went wrong']);
}

Related

Convert Curl in Laravel Http facade

i want refactor curl method which is work with laravel Http facade and now i'm encounter some error
public function get($data)
{
$post_data = http_build_query($data, '', '&');
$sign = hash_hmac('sha512', $post_data, env('INDODAX_SECRET_KEY'));
$response = Http::withHeaders([
'Key' => env('INDODAX_API_KEY'),
'Sign' => $sign,
])->withOptions([
'form_params' => $data,
])
->withBody('post_data', $post_data)
->post(config('indodax.private.endpoint'), [
'CURLOPT_POSTFIELDS' => $post_data,
]);
return $response->collect();
}
public static function curl($data)
{
$post_data = http_build_query($data, '', '&');
$sign = hash_hmac('sha512', $post_data, env('INDODAX_SECRET_KEY'));
$headers = ['Key:'.env('INDODAX_API_KEY'),'Sign:'.$sign];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_HTTPHEADER => $headers,
CURLOPT_URL => config('indodax.private.endpoint'),
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($curl);
return json_decode($response, true);
}
i think i'm missing CURLOPT_POSTFIELDS part, how to set CURLOPT_POSTFIELDS in Http facade
i'v tried with withOptions and still same
reff PHP Curl proxy option in Laravel Http Facade

$request->header('Authorization') return null using laravel

public function productData(Request $request)
{
$product_no = $request->product_no;
$response = array();
if($request->product_no)
{
try
{
$header = $request->header();
$Authorization = $request->header('Authorization');
dd($Authorization);
if (empty($Authorization))
{
$data = "Authorization key invalid";
return $data;
}
else
{
$sp_token = str_replace("Bearer ", "", $Authorization);
$varify_token = 'ZQWmRjUyNDJDQUFGRjBBOUMzMUZGQUVEOTA4QkYzOEU2RENBNEQ4OTIwMzRGQzY1NDA0QzIyMjk3RkJENkRzdsg=====';
if($sp_token == $varify_token)
{
$response = array(
'status' => 200,
'message' => 'success',
);
}
else
{
$response = array(
'status' => 300,
'message' => 'Invalid Bearer Token',
);
}
}
}
catch (\Exception $e)
{
$response = array(
'status' => 500,
'message' => 'Data Not Found',
'msgErr' => 'Something went wrong',
'result' => '0');
}
}
else
{
$response = array(
'status' => 0,
'message' => 'product Number Empty',
);
}
return response()->json($response);
}
Above code working in local server and when print $Authorization then it return Bearer Token but same code not working on production server when I hit API using production URL using postman then it return Authorization key invalid and when I print or dd $Authorization then it return null. I don't know why?. Please help me.
Thank you
The Authorization header might be stripped by your webserver or reverse proxy. Try renaming it to anything that isn't a default HTTP header. For example: Token.
Any route or url that uses Auth() must be encapsulated in the web middleware.
Let me explain using e.g
Route::group(['middleware' => '['web','auth']', function () {
Auth::user();
//Other auth routes
});

Laravel Mqtt's subscription doesn't end

I receive an Mqtt message from Laravel and try to do some action, but if you subscribe, you only get one message and it takes about a minute to delay.
I referred to this at https://github.com/salmanzafar949/MQTT-Laravel.
Implementing Mqtttt motion was made by creating a separate controller.
My code is
<?php
namespace App\Http\Controllers;
use Salman\Mqtt\MqttClass\Mqtt;
use Illuminate\Http\Request;
class MqttController extends Controller{
public $token = "";
public function SendMsgViaMqtt(Request $request)
{
$mqtt = new Mqtt();
//$client_id = Auth::user()->id;/
$topic = $request->topic;
$token = $request->token;
$message = $request->message;
$output = $mqtt->ConnectAndPublish("test", $message, "");
if ($output === true)
{
if($token == "none" || !$token){
return "End";
}else{
$this->SubscribetoTopic($token);
}
}else{
return "Failed";
}
}
public function SubscribetoTopic($token)
{
$topic = 'test';
$this->token = $token;
$message = [];
$mqtt = new Mqtt();
$client_id = "";
$mqtt->ConnectAndSubscribe($topic, function($topic, $msg){
if($msg == "end"){
$message = [
'title' => '魚が釣れました',
'body' => '釣竿を確認してください',
'click_action' => 'Url'
];
}else if($msg == "no"){
$message = [
'title' => '測定できません',
'body' => '波が強すぎると測れません',
'click_action' => 'Url'
];
}else{
return "end";
}
return $this->sendCrul($this->token, $message);
}, "");
}
public function sendCrul($token, $message){
define('SERVER_API_KEY', 'APIKEY');
$tokens = $token;
$header = [
'Authorization: Key=' . SERVER_API_KEY,
'Content-Type: Application/json'
];
$payload = [
'to' => $tokens,
'notification' => $message
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://fcm.googleapis.com/fcm/send",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode( $payload ),
CURLOPT_HTTPHEADER => $header
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err){
echo "cURL Error #:". $err;
}else{
return $response;
}
// return "ok";
}
}
If you're in trouble like me, let me know how.

Laravel - How to pass the result of Post Request

I have this code I have written and tested. The first phase
mokkle_test(Request $request)
is working. I have issue with how to pass the result of the request to the second phase
First phase:
public function mokkle_test(Request $request)
{
$telco_match=['name'=>'Icell'];
$telco=Telco::where($telco_match)->first();
try{
$client = new Client();
$response = $client->request(
'POST', $telco->send_call, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->cpPwd,
'text' =>$request->text,
'correlator' =>$request->correlator,
'serviceid' =>$request->serviceid,
'shortcode' => $request->shortcode
],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
$noti=new Notification_log();
$noti->error_message= (string)$response->getBody();
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
return $result;
}catch(\Exception $e)
{
return $e->getMessage();
}
}
... and its working very well.
How do I pass the result of the response into another function shown below.
Second phase:
function subscribe($request,$telco)
{
try{
$client = new Client();
$response = $client->request(
'POST', $telco->billing_callback_2, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->password,
'amount' =>$request->amount,
'shortcode' => $request->shortcode
],
'headers' => [
'auth' => $telco->authorization,
'key' => $telco->key,
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
$amount = $request->amount;
$shortcode = $request->shortcode;
$noti=new Notification_log();
$noti->error_message=(string)$response;
$noti->msisdn=$request->msisdn;
$noti->product_id=$request->productid;
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
$request = array();
$request->text= "Weldone";
$request->amount = $amount;
$request->serviceid="100010";
$request->correlator="876543ghj";
$result_sms=self::mokkle_test($request);
return $result;
}catch(\Exception $e)
{
return $e;
}
}
I tried this, but nothing is happening
$result_sms=self::mokkle_test($request);
Kindly assist. How do I achieve my goal. Kindly assist me.
Here you can pass it to the other method
public function mokkle_test(Request $request)
{
$telco_match = ['name' => 'Icell'];
$telco = Telco::where($telco_match)->first();
try {
$client = new Client();
$response = $client->request(
'POST', $telco->send_call, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->cpPwd,
'text' => $request->text,
'correlator' => $request->correlator,
'serviceid' => $request->serviceid,
'shortcode' => $request->shortcode
],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
// Here you can pass it to the other method
this.subscribe($response, $telco); // <--- $response will be your "$request" parameter
$noti = new Notification_log();
$noti->error_message = (string)$response->getBody();
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
return $result;
} catch (\Exception $e) {
return $e->getMessage();
}
}

Creating laravel service class

My Uptime.php
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.uptimerobot.com/v2/getMonitors",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "Your Api Key",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$data = json_decode($response);
$custom_uptime = ($data->monitors[0]->custom_uptime_ratio);
$uptime = explode("-",$custom_uptime);
}
?>
ApiCommand.php
public function handle()
{
//include(app_path() . '/Includes/Uptime.php')
$this->showMonitors();
}
public function showMonitors(UptimeRobotAPI $uptime_api)
{
$monitors = $uptime_api->getMonitors();
return $monitors;
}
Hello everyone. I just want to ask how can I turn this to a service class? Do I need to use service providers or service containers? Thanks in advance.
Someone convert it to service class and here was my command looks like.
In your terminal, require the guzzle package as you will use it as an HTTP client: composer require guzzlehttp/guzzle
Then you can make a class for your UptimeRobotAPI at app/Services/UptimeRobotAPI.php:
<?php
namespace App\Services;
use GuzzleHttp\Client;
class UptimeRobotAPI
{
protected $url;
protected $http;
protected $headers;
public function __construct(Client $client)
{
$this->url = 'https://api.uptimerobot.com/v2/';
$this->http = $client;
$this->headers = [
'cache-control' => 'no-cache',
'content-type' => 'application/x-www-form-urlencoded',
];
}
private function getResponse(string $uri = null)
{
$full_path = $this->url;
$full_path .= $uri;
$request = $this->http->get($full_path, [
'headers' => $this->headers,
'timeout' => 30,
'connect_timeout' => true,
'http_errors' => true,
]);
$response = $request ? $request->getBody()->getContents() : null;
$status = $request ? $request->getStatusCode() : 500;
if ($response && $status === 200 && $response !== 'null') {
return (object) json_decode($response);
}
return null;
}
private function postResponse(string $uri = null, array $post_params = [])
{
$full_path = $this->url;
$full_path .= $uri;
$request = $this->http->post($full_path, [
'headers' => $this->headers,
'timeout' => 30,
'connect_timeout' => true,
'http_errors' => true,
'form_params' => $post_params,
]);
$response = $request ? $request->getBody()->getContents() : null;
$status = $request ? $request->getStatusCode() : 500;
if ($response && $status === 200 && $response !== 'null') {
return (object) json_decode($response);
}
return null;
}
public function getMonitors()
{
return $this->getResponse('getMonitors');
}
}
You can then add more functions beneath, I created getMonitors() as an example.
To use this in a controller, you can simply dependency inject it into your controller methods:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\Promises\UptimeRobotAPI;
class ExampleController extends Controller
{
public function showMonitors(UptimeRobotAPI $uptime_api)
{
$monitors = $uptime_api->getMonitors();
return view('monitors.index')->with(compact('monitors'));
}
}
This is just an example, this does not handle any errors or timeouts that can occur, this is simply for you to understand and extend. I don't know what you want to do with it, but I can't code your whole project, this will definitely answer your question though. :)

Resources