How to call local api using curl in laravel? - laravel

Using laravel api in local API fetch and display data in the view file:
$url = 'http://demo.local:8000/api/category12';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec ($ch);
$err = curl_error($ch); //if you need
curl_close ($ch);
return $response;

If it's a local API, you can treat your controller as a Real Time Facade
Using real-time facades, you may treat any class in your application
as if it were a facade.
For example, let's assume our CategoryController controller has a detail method:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Category;
class CategoryController extends Controller
{
/**
* return the category object for the given id.
*
* #param int $id
* #return response
*/
public function detail($id)
{
return response()->json(['data' => Category::findOrFail($id)]);
}
}
Then you can use it like :
use Facades\App\Http\Controllers\CategoryController;
$category = CategoryController::detail(5);
When the real-time facade is used, the CategoryController
implementation will be resolved out of the service container using the
class name that appears after the Facades prefix

Try this:
$hit = "http://demo.local:8000/api/category12";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $hit,
CURLOPT_USERAGENT => 'http://YOUR-DOMAIN'
));
$resp = curl_exec($curl);
curl_close($curl);
return $resp;

Related

How to send data from controller to rest api in laravel?

How can I send data from controller to external api in Laravel?
public function syncData(Request $request)
{
$datas = Data::all();
$newDatas = NewData::all();
$url = 'mydomain.com/api/sync-data';
}
I want to send $datas and $newDatas to $url through Laravel controller and perform some actions on those data. How can I achieve that?
You could use the Laravel HTTP Client (which is a wrapper for Guzzle HTTP Client) to perform a request to that API.
use Illuminate\Support\Facades\Http;
$response = Http::post('mydomain.com/api/sync-data', [
'data' => Data::all(),
'newdata' => NewData::all(),
]);
public function syncData(Request $request)
{
$datas = Data::all();
$newDatas = NewData::all();
$url = 'mydomain.com/api/sync-data';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($datas));
$output = curl_exec($ch);
curl_close($ch);
}
let me know if it is helpful.
important things to notice here.
you have to know what your external API type is. is it POST or in GET method.
my example above is just a sample code to make you understand how you will use curl it is not tested in regard to your context

Laravel - How to access Array inside Collection

I am trying to get some feeds from online api through Laravel. I have this in my laravel:
{
"assetCount,": "96",
"title": "testing",
"description": "Users feedback",
"articles": {
"id": "206",
"publishedTime": "234663266",
"teaser": "*REI and VDC DEC teams to..."
}
}
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SmsFeed extends Model
{
protected $table = 'sms_feeds';
protected $fillable = ['asset_count', 'title', 'description', 'published_time', 'teaser', 'smskey', 'category'];
}
The question is, how do I complete articles that is a collection of array.
$array_content=[];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.test.com/monk/1xhxiluh826bt7?_fmt=json&_rt=b&ctg=english%20football%20sms&_fld=tsr,pt&kwd=arsenal");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //Important
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$result = curl_exec($ch);
//$array = json_decode($result, true);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
$plainXML = self::mungXML($result);
$arrayResult = json_decode(json_encode(SimpleXML_Load_String($plainXML, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
$i=0;
foreach($arrayResult['monk'] as $value)
{
$record=SmsFeed::where('id', $value['articles']['id'])->first();
if (!isset($record)) {
SmsFeed::create([
'sms_key' => $value['#attributes']['id'],
'category' => 'arsenal',
'asset_count' => $value['assetCount'],
'title' => $value['title']
]);
}
$i++;
}
I need help in the foreach statement. How do I complete it for article that has (id, publishedTime, teaser)

codeigniter: how do you declare sendsms( '919918xxxxxx', 'test message from spring edge' );

sendsms( '919918xxxxxx', 'test message from spring edge' ); how do you declare this function in codeigniter?
Codeigniter have a good functionality Helpers. Helper functions are available in all controllers(if auto-load). You can use codeigniter helper to declare this function.
Open a file in Application/Heplers/sendsms_helper.php
/*Start sendsms_helper.php file */
function sendsms($number, $message_body, $return = '0'){
$sender = 'SEDEMO'; //Use sender name here
$smsGatewayUrl = 'SMS_GATEWAY_URL_HERE';
$apikey = '62q3z3hs49xxxxxx'; // Use API key here
$textmessage = urlencode($textmessage);
$api_element = '/api/web/send/';
$api_params = $api_element.'?apikey='.$apikey.'&sender='.$sender.'&to='.$mobileno.
'&message='.$textmessage;
$smsgatewaydata = $smsGatewayUrl.$api_params;
$url = $smsgatewaydata;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
if($return == '1'){
return $output;
}
}
/* * End sendsms_helper.php file */
How to use in controller:
Load sendsms helper in controller using $this->load->helper('sendsms_helper');
Call sendsms function Ex. sendsms( '919918xxxxxx', 'test message from spring edge' );

Refreshing an access token (offline access) for Google Drive API in PHP

I am writing an app that performs routine updates to a database with data gathered from a single account's Google Drive using the Google Drive API and Google Sheets API.
Using the answer found in this How do I authorise an app (web or installed) without user intervention? (canonical ?) question, I have been able to create my own PHP function to get the access token.
function get_access_token() {
$request_url = "https://www.googleapis.com/oauth2/v4/token";
$refresh_token = "1/XgTqiwrGHJ3LOh-verververververv-q2qIF3Aq_ENrzhH6IQA4u4X";
$params = [
'client_id' => "1073411048819-vergewrgergergewrgerwgewr.apps.googleusercontent.com",
'client_secret' => "b8oPhmVrevervvreverviA37aipaB",
'refresh_token' => $refresh_token,
'grant_type' => "refresh_token"
];
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HEADER,'Content-Type: application/x-www-form-urlencoded');
$postData = "";
//This is needed to properly form post the credentials object
foreach($params as $k => $v) {
$postData .= $k . '='.urlencode($v).'&';
}
$postData = rtrim($postData, '&');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
$json_response = curl_exec($curl);
$response = (array) json_decode( $json_response );
$response["refresh_token"] = $refresh_token;
$date = new DateTime();
$response["created"] = $date->getTimestamp();
return $response;
}
Which works and produces an access token that looks like this:
array(5) {
["access_token"]=>
string(129) "ya29.GlsEBWfC-cdO1F80MjNB_oNVp87fojEWILclEfbgbgbgbbgbgbgbgzXNFV3xSmMSI733HvdTrXd6wgbDB0u3ACLfRaNkitIQPOdF3T2jSH3NTjCEndH0fBYXy"
["token_type"]=>
string(6) "Bearer"
["expires_in"]=>
int(3600)
["refresh_token"]=>
string(45) "1/XgTqiwrGHJ3LOh-verververververv-q2qIF3Aq_ENrzhH6IQA4u4X"
["created"]=>
int(1510654966)
}
I can use this access_token to make requests such as...
GET https://www.googleapis.com/drive/v3/files
Authorization: Bearer ya29.GlsEBWfC-cdO1F80MjNB_oNVp87fojEWILclEfbgbgbgbbgbgbgbgzXNFV3xSmMSI733HvdTrXd6wgbDB0u3ACLfRaNkitIQPOdF3T2jSH3NTjCEndH0fBYXy
... so the function definitely produces a valid token.
However, I cannot figure out how to use the Google Drive API Client library with this.
Here is the PHP Quickstart for the Google Drive API.
And here is my broken code:
define('APPLICATION_NAME', 'My Plugin');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('SCOPES', implode(' ', array(
Google_Service_Drive::DRIVE_METADATA_READONLY)
));
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
$accessToken = get_access_token();
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode(get_access_token()));
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* #param string $path the path to expand.
* #return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
$client = getClient();
$driveService = new Google_Service_Drive($client);
That produces:
$client = NULL;
$driveService = NULL;
Is it possible to use this approach with the PHP library? If so, what is wrong with my example?
If not, how can I turn this:
$response = $driveService->changes->getStartPageToken();
Into a HTTP/REST call (similar to GET https://www.googleapis.com/drive/v3/files)?
$token='access_token_here';
$url="https://www.googleapis.com/upload/drive/v3/files?uploadType=media";
$method='POST';
$filepath='file_to_upload_path.pdf'
$data['name']='file_title_here.pdf';
$data['title']='file_title_here.pdf';
$p1=(object)[];
$p1->id='parent_folder_id_here';
$data['parents'][]=$p1;
$body=file_get_contents($filepath);
$timeout=30;
$verify_ssl = false;
$headers = array(
'Content-Type: application/pdf',
'Cache-Control: no-cache',
'Authorization: Bearer '.$token ,
'Content-Length: '.strlen($body)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_ssl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
echo $result = curl_exec($ch);
//echo $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

how to make Pagination in laravel to return values in json format

I have client controller that sends request and server controller that processes the request and sends response.
How to paginate the response json data in laravel.
Server Controller
public function index() {
$data = languages::where('is_active','1')->orderBy('id','desc')->get();
$response = Response::json($data,200);
return $response;
}
Client Controller
public function index()
{
$url = url('languagesService');
$data = json_encode(array("username" => $this -> username,"password" => $this -> password));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER,false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = CURL_EXEC($ch);
$data = json_decode($response);
return View::make("languages.index")->with("data",$data);
}
I guess, this is quite simple. Have you tried something like :
public function index() {
$data = languages::where('is_active','1')->orderBy('id','desc')->paginate($perPage);
$response = Response::json($data,200);
return $response;
}
UPD:
In case you want to paginate elsewhere of index() action, then you should create manually the paginator object via native Paginator class. You can find additional info here. As quick example, you should do on your client controller:
$paginator = Paginator::make($data, count($data), $perPage);
And then use the $paginator object to achieve what you want.
You can simply return the collection, it will convert to JSON itself.
public function index() {
return languages::where('is_active','1')->orderBy('id','desc')->paginate();
}
// If you add `page` param into URL, Eloquent gets you content for specified page.
$url = url('languagesService', ['page'=>0]);
// $url = url('languagesService', ['page'=>20]);
I advice you send links for previous/next page together with total count of items so that API consumer can retrieve more elements if needed.
public function index() {
$data [
'data' => languages::where('is_active','1')->orderBy('id','desc')->paginate()->toArray(),
'total' => getNumberOfAllEntitiesThatFitFilter(),
'nextPage' => getUrlForNextPage(),
'previousPage' => getUrlForPreviousPage(),
];
return Response::json($data);
}

Resources