Laravel - How to access Array inside Collection - laravel

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)

Related

How to call local api using curl in 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;

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

Magento - Online refund with PayPal

Currently we have a Magento ver. 1.8.1.0 with installed PayPal Website Payments Standard option enabled. However when I want to do an online refund it doesn't show an 'Refund' button but only 'Offline refund'.
Is it actually possible to create an online refund with PayPal Standard?
Impossible with Paypal standard, you must overload the paypal standard model to implement the refund method, or you can install a module.
As luigifab said, that functionality isn't part of the Paypal module - I've implemented a small add-on for it that can be seen here:
https://gist.github.com/bubach/ed86611c634b401e5d66392cf32c2f6e
The most important part being this class:
<?php
class Namespace_Modulename_Model_Paypal extends Mage_Paypal_Model_Standard
{
protected $_canRefund = true;
protected $_canRefundInvoicePartial = true;
protected $_canVoid = true;
/**
* https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/RefundTransaction_API_Operation_NVP/
*/
public function tryRefund(Varien_Object $payment, $amount)
{
$transactionId = $payment->getLastTransId();
if ($transactionId) {
$order = $payment->getOrder();
$storeId = $order->getStoreId();
$refundType = "Partial";
$invoiceFee = $payment->getMethodInstance()->getInfoInstance()->getAdditionalInformation('invoice_fee');
$remaining = $order->getTotalInvoiced() - ($order->getTotalOfflineRefunded() + $order->getTotalOnlineRefunded()) - $invoiceFee;
if (abs($remaining - $amount) < 0.00001) {
$refundType = "Full";
}
$currencyCode = $order->getBaseCurrencyCode();
$invoiceId = $order->getIncrementId();
$params = array(
"METHOD" => "RefundTransaction",
"VERSION" => "72.0",
"TRANSACTIONID" => $transactionId,
"INVOICEID" => $invoiceId,
"REFUNDTYPE" => $refundType,
"AMT" => $amount,
"CURRENCYCODE" => $currencyCode,
"USER" => Mage::getStoreConfig('paypal/wpp/api_username', $storeId),
"PWD" => Mage::getStoreConfig('paypal/wpp/api_password', $storeId),
"SIGNATURE" => Mage::getStoreConfig('paypal/wpp/api_signature', $storeId)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api-3t.paypal.com/nvp");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
$response = curl_exec($ch);
if (curl_errno($ch)) {
curl_close($ch);
throw new Mage_Core_Exception('Impossible to issue a refund transaction because of cURL error.');
} else {
curl_close($ch);
$responseArray = array();
parse_str($response, $responseArray); // Break the NVP string to an array
if ($responseArray['ACK'] == "Success") {
return array(0, "Paypal refunded successfully");
} else {
return array(-1, "Paypal refund failed!");
}
}
} else {
Mage::throwException(Mage::helper('paypal')->__('Impossible to issue a refund transaction because the capture transaction does not exist.'));
}
}
}

How to Redirect a login request to an external domain using PHP (Using Laravel 4)

I have two webs (Client side and Admin side) but are independent, I mean are in different domains but both using the same DB. I want to allow the Admins to login from Client side but once I recognize that isn't a normal user I want to redirect the login request to the other web and parse everything from the Admin side, just if I was trying to login from the admin web.
$credentials = array(
'username' => Input::get('username'),
'password' => Input::get('password'),
);
$message = "Wrong Data";
try {
if(Auth::attempt($credentials)) {
if(Auth::user()->role_id < 4) {
$url = 'http://externaldomain.info/login';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$credentials);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
return $response;
}
return Redirect::to('/');
}
} catch( \Toddish\Verify\UserNotFoundException $e ) {
$message = _("User not found");
} catch( \Toddish\Verify\UserUnverifiedException $e ) {
$message = _("User not found");
} catch( \Toddish\Verify\UserDisabledException $e ) {
$message = _("User disabled");
}
Instead of the dashboard I get the login screen, I checked it with fiddler and didn't see any post request to the external domain, I just saw the login page request(GET).
EDIT
$credentials = array(
'username' => Input::get('username'),
'password' => Input::get('password'),
);
$message = "Wrong Data";
try {
if(Auth::attempt($credentials)) {
if(Auth::user()->role_id < 4) {
$url = 'http://externaldomain.info/login';
$html = new \Htmldom($url);
$token = "";
foreach($html->find('input') as $element) {
if($element->name == "_token") {
$token = $element->value;
}
}
$credentials['_token'] = $token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$credentials);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
return $response;
}
return Redirect::to('/');
}
} catch( \Toddish\Verify\UserNotFoundException $e ) {
$message = _("User not found");
} catch( \Toddish\Verify\UserUnverifiedException $e ) {
$message = _("User not found");
} catch( \Toddish\Verify\UserDisabledException $e ) {
$message = _("User disabled");
}
I'm using "yangqi/htmldom": "dev-master" to get the "_token", but I can't see the Request in fiddler, it keeps redirecting me to the login page instead of the dashboard.
It's probably because you forgot to add "_token" and "remember" fields.
The post you need to make should contain those for default login panel:
_token JB6nC85wLkFQtTglpiuoWk06YxI3Jx3no0xVQx0K
email admin#blabala.com
password 123456
remember on
Token is created by Laravel automatically for protecting your application from CSRF attacks.
You have two ways, first make request to your login page scrap the token. Then make a second request for post with that token.
Second you can disable the token for login page.
Ok, after your edit missing thing to do adding COOKIEJAR in curl request. Your current request is working like a browser with cookies disabled.
$url = 'http://externaldomain.info/login';
$file = "cookiefile.txt";
$fp = #fopen($file, "x");
if($fp)
fclose($fp);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $file);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_token = curl_exec ($ch);
curl_close ($ch);
$html = new \Htmldom();
// Load HTML from a string
$html->load($response_token);
$token = "";
foreach($html->find('input') as $element) {
if($element->name == "_token") {
$token = $element->value;
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $file);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$credentials);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
BTW, your first request to page should also need to use same cookie file. I suggest you to use curl for making the first request too.

retrieve google image search using foreach

I used the following function to get google search images
function get_images($query){
$url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=';
$url .= urlencode($query);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
//decoding request
$result = json_decode($data, true);
return $result;
}
It works good when I output all results using print_r()
$images = get_images("porsche");
print_r($images);
But when I want to get a specific value using foreach()
foreach ($images->responseData->results as $result) {
echo $result->url;
}
I got an error:
Notice: Trying to get property of non-object
How can I get any specific value separetly using foreach()?
Try this :
<?php
function get_images($query){
$url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=';
$url .= urlencode($query);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
//decoding request
$result = json_decode($data, true);
return $result;
}
$images = get_images("porsche");
//print_r($images);
foreach ($images['responseData']['results'] as $result) {
echo $result['url']. "<br>";
}
?>
Output
http://upload.wikimedia.org/wikipedia/commons/e/e7/2012_NAIAS_Red_Porsche_991_convertible_(world_premiere).jpg
http://www.inautonews.com/wp-content/uploads/2012/05/porsche-911-club-coupe-1.jpg
http://o.aolcdn.com/hss/storage/adam/6e58b30fb96bf0d28d10fa6d290682e7/porsche-exclusive-911t-cab.jpg
http://media.caranddriver.com/images/media/510773/porsche-960-updated-inline-photo-514518-s-original.jpg

Resources