Convert Curl in Laravel Http facade - laravel

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

Related

Mailchimp API 3.0 batch/bulk untag

I have a problem with untag the subscribers in a bulk with the Mailchimp API.
In the documentation https://mailchimp.com/developer/guides/how-to-use-tags/#Tag_multiple_contacts_in_bulk is the example:
{
"members_to_remove": [
"john.smith#example.com",
"brad.hudson#example.com"
]
}
Below can you see my PHP code where I with the $methode variable give the value members_to_remove and the $email value is an array with email addresses.
But the script does only add tags with a bulk to the subscriptions instead of remove.
What do I wrong?
public function tag_mailchimp($list_id, $email, $tag, $method) {
$authToken = 'HERE MY KEY';
// The data to send to the API
$postData = array(
$method => $email
);
// Setup cURL
$ch = curl_init('https://us2.api.mailchimp.com/3.0/lists/'.$list_id.'/segments/'.$tag);
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: apikey '.$authToken,
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
return $response;
}
It works, but I don't know what I do else.., the code:
foreach($members as $member) {
$list[] = $member->email;
}
$Mailer->tag_mailchimp('12345678', $list, 123456, 'members_to_remove');
And in the class I have the next function:
public function tag_mailchimp($list_id, $email, $tag, $method) {
$authToken = 'HERE MY KEY';
// The data to send to the API
$postData = array(
$method => $email
);
// Setup cURL
$ch = curl_init('https://us2.api.mailchimp.com/3.0/lists/'.$list_id.'/segments/'.$tag);
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: apikey '.$authToken,
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
return $response;
}

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

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']);
}

How to submit multiple file images in API Laravel with using CURLOPT?

I'm trying to upload multiple images in the API of Laravel but it keeps getting 500 errors.
I'm using CURLOPT PHP for the API here are the codes below.
If you have an alternative way to do this in PHP that's ok for me.
$data = array(
"images" => $request->file('input_images'),
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://sample/api/name",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
),
));
$response = curl_exec($curl);
curl_close($curl);
$result = json_decode($response);
print_r($result);

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

Login a User in laravel application after API endpoint authentication

I am working on this application where i created an API to do the business logic and using Laravel as the core part of my application that calls the API endpoints for resources.
Authentication is been done by the API which only returns a JSON resource. I am a bit confused as to what is the best way to log a user into my laravel application after successful authentication from the API.
//
public function login(Request $request)
{
$data = [
'username' => $request->username,
'password' => $request->password,
];
$data = Json_encode($data, TRUE);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://localhost:8080/api/v1/auth/login",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$response = Json_decode($response);
// var_dump($response);
if ($err) {
echo "cURL Error #:" . $err;
} else {
if ($response->status === 'failed') {
if ($response->message === "Incorrect login details") {
return redirect()->back()->with('error' , $response->message);
}elseif ($response->message === "User's account has not been activated") {
return view('activation', ['email' => $response->data]);
}
}elseif ($response->status === 'success' && $response->message === "Ok") {
$user = $response->data;
Auth::login($user , true);
return view('dashboard', ['user' => $user]);
}
}
After getting the required response from the API, intend logging the user straight into the application.
What is the best way for this?
If you have same database to connect with on the user. you can just simply call
Auth::loginUsingId($id);
this will automatically log in user with that id.

Resources