Google Contacts API - getting image - google-api

I'm having a simple problem while retrieving user's contact's images. So I make a request to
$url = 'https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=9999&oauth_token=' . $accessToken;
And then I get huge JSON from which I have extracted full name and email. Then I tried getting contact's image, and haven't had any success.
I get with all contacts, and everyone has following structure:
entry [id, updated, category, title, link, gd$email].
In the link section, I got four links, of which first two are some kind of link to an image content but I cannot retrieve it.
Any body had any success in doing this kind of work !?
Tnx alot!
BTW: If some data from my case is missing, please report and I'll add it too!
EDIT: I have also tried to reach the image with URL
http://profiles.google.com/s2/photos/profile/" + userid + "?sz=" + size;
but the problem is I cannot get userId from contacts JSON.

You must call the photo endpoint and append to it a valid access token as a query parameter.
Example:
https://www.google.com/m8/feeds/photos/media/name.surname%40gmail.com/0?access_token=ACCESS_TOKEN
Docs:
https://developers.google.com/google-apps/contacts/v3/#contact_photo_management

Make a request again if the mentioned tags are available as given below.
$add = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/default/full?alt=json&v=3.0&max-results=500&access_token='.$token->access_token");
$add->setRequestMethod("GET");
$add->setRequestHeaders(array('GData-Version' => '3.0', 'content-type' => 'application/atom+xml; charset=UTF-8; type=feed'));
$submit = $client->getIo()->authenticatedRequest($add);
$sub_response = $submit->getResponseBody();
$temp = json_decode($sub_response, true);
foreach ($temp['feed']['entry'] as $image) {
$google_contact_id = $image['link'][2]['href'];
if (isset($image['link'][0]['href'])) {
$photo = new Google_HttpRequest($image['link'][0]['href']);
$photo_val = $client->getIo()->authenticatedRequest($photo);
$photo_return = $photo_val->getResponseBody();
$imgData = base64_encode($photo_return);
$pro_image = 'data:image/jpeg;base64, ' . $imgData . '';
}
}

Related

Laravel return after post is null with stored procedure

I have store method with return like this :
return redirect()->route('hasil.transaksi', ["data" => $data]);
with the route like this :
ROUTE::GET('hasil-transaksi', [KasirRajalController::class, 'hasilTransaksi'])->name('hasil.transaksi');
And method return like this :
public function hasilTransaksi(Request $request)
{
$data["info"] = DB::select("EXEC spx_kasirirj_GetData
#sdata = 2,
#where = '" . $request->no_transaksi . "'
");
dd($data);
}
URL after store like this :
http://127.0.0.1:8000/hasil-transaksi?data%5B0%5D%5B%5D=0000260&data%5B0%5D%5Bno_transaksi%5D=KRJ22010001
I want to catch no_transaksi=KRJ22010001 to paste in the method return above. But i don't get it, the result is null.
enter image description here
Please, help?
Full dd($request) :
enter image description here
There are multiple things to review in your code:
return redirect()->route('hasil.transaksi', ["data" => $data]);
This will do a GET redirect, so the $data object will be added as GET parameter and encoded (from object to string). That is why your URL only parameter is "data" (http://127.0.0.1:8000/hasil-transaksi?data=) and then the encoded data.
Your decoded URL data looks like this data[0][]=0000260&data[0][no_transaksi]=KRJ22010001.
This format seems a bit strange, but I don't have enough code to confirm. You could do this (assuming you don't need your 0000260 parameter [that should be keyed]):
return redirect()->route('hasil.transaksi', ["no_transaksi" => $data[0]['no_transaksi']]);
This should generate a correct URL ?no_transaksi=xx and so $request->no_transaksi should work (that you should also sanitize).
#where = '" . $request->no_transaksi . "'
As #Joundill mentioned, this part of your raw query is opened to SQL injection. If you don't use Eloquent, Models or Requests, you should at least sanitize and validate the no_transaksi request param value.

How to retrieve respons status from Street View Image Metadata using guzzle

I am using guzzle to call to Street View Image API from my laravel application. I want to be able to retrieve the status code from my request as explained in the end of the docs.
I specifically want to catch the:
{
"status" : "ZERO_RESULTS"
}
here is my Guzzle code from my controller (am including guzzle correctly in namespace). The address in the get call is generating a "Sorry we have no imagery here":
$client = new Client();
$res = $client->get('https://maps.googleapis.com/maps/api/streetview?size=800x600&location=78.648401,14.194336&key=my-API-key&fov=120&heading=90');
$res->getStatusCode();
dd($res->getBody());
BUT. As u can see in the pic the meta-data is empty. When I dd the $res->getStatusCode(); it gives me a 200.
How do I catch the ZERO_RESULT ?
Sir, please note that there are two different endpoints; one for metadata and one for image retrieval. You only used the image retrieval. Here is an example method checking if a given coordinate has an image
private function coordinateHasImage($coordinate)
{
$client = new Client();
$res = $client->get( 'https://maps.googleapis.com/maps/api/streetview/metadata?size=600x300&location=' . $coordinate . '&fov=90&heading=235&pitch=10&key=YOUR_KEY_HERE');
return json_decode($res->getBody()->getContents())->status == "OK";
}

Storing a new post tag if it doesn't exist in the table?

I have a single input field (using select2 plugin) in a blog post form which allow user to insert post tags from existing tags in the table or create new ones and store them in the Tag table and also attach them to the post when they hit submit post button. I've managed to get this work by filtering the input with array_filter(), if the input is !is_numeric the input will first get stored in Tag table and then attach the id to the post.
The problem with this is that it's not working when the new tag from the input is in full numeric type, like 2017 tag. Is there a solution to get this working so the new tag is not limited to string only but also numeric type ? and if possible, I don't want to use any package for this.
The post store method :
public function store(PostsReq $request) {
$input = $request->all();
$post = Post::create($input);
//Handle the tags
$getTags = $request->input('tagspivot');
$oldTags = array_filter($getTags, 'is_numeric');
$newTags = array_filter($getTags, function($item) {
return !is_numeric($item);
});
foreach ($newTags as $newTag) {
if ($tag = Tag::create(['title' => strtolower(trim($newTag))])) {
$oldTags[] = $tag->id;
}
}
$post->tags()->attach($oldTags);
// Upload Image
if ($request->hasFile('image')) {
$input['image'] = $this->uploadImage($request, $post);
}
return redirect()->route('postindex')->with($this->postStoreSuccess);
}
Here is three lines of code would be more than enough:
$tag = Tag::firstOrCreate([
'title' => $request->input('tagspivot'),
]);
You don't need to check for !is_numeric. However, in your form don't use tag id as value. use the title.

How to get image url from tweets using the Twitter API

I'm using this code:
require_once ("twitteroauth.php");
define('CONSUMER_KEY', 'XXX');
define('CONSUMER_SECRET', 'XXX');
define('ACCESS_TOKEN', 'XXX');
define('ACCESS_TOKEN_SECRET', 'XXX');
$toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$query = array(
"q" => "#Misiones",
"result_type" => "recent",
"include_entities" => "true"
);
results = $toa->get('search/tweets', $query);
foreach ($results->statuses as $result) {
$user = $result->user->screen_name;
$text = $result->text;
To get tweets whit the hashtag #Misiones(the name of the place where i'm live). Works fine but i'm trying to get the image url (if the tweet have some).
I tryed with $result->media and $result->media->media_url and other convinations without succcess.
Tweet Entities are what you are looking for to access the pictures. Entities provide structured data from Tweets including expanded URLs and media URLs. They are located under the entities attribute in all Tweet objects from both Twitter REST and Streaming APIs.
As a result, to answer your question, if a Tweet contains one picture, its URL will be located here:
$media_url = $result->entities->media[0]->media_url;
Below is a PHP snippet you can add to your existing foreach loop, it is a bit more elaborate to handle whether or not the Tweet contains media URLs:
if (isset($result->entities->media)) {
foreach ($result->entities->media as $media) {
$media_url = $media->media_url; // Or $media->media_url_https for the SSL version.
}
}
To get the media_url back to twitter search pass tweet_mode=extended. Works across multiple endpoints (eg. /statuses/show, /statuses/user_timeline ..)
Example: https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=aneon&tweet_mode=extended
More here: https://developer.twitter.com/en/docs/tweets/tweet-updates.html
To get the image url of a Tweet with the new v2 api you must append expansions=attachments.media_keys&media.fields=url at your url.
For example to open a stream that returns tweets with their images(if any) create a get request like this
https://api.twitter.com/2/tweets/search/stream?tweet.fields=created_at&expansions=attachments.media_keys&media.fields=url
To get an image url of a tweet, you need a tweet object and a media object. The media object can be obtained with a tweet id.
https://developer.twitter.com/en/docs/twitter-api/data-dictionary/object-model/media

One list, two different thank you pages with Mailchimp

Mailchimp ties each form to one list.
I'd like to have a signup form on Page1.html that sends users to Page1ty.html and another form on Page2.html that sends users to Page2ty.html. But both forms need to feed users into the same list. As stated above, this isn't possible using their basic forms. I would need two list.
Mailchimp says this kind of routing might be possible using their API. Does any one know how to go about accomplishing the above kind of signups?
You would just create custom forms and tie into the MailChimp API, but as of their latest update you'll need to make sure you have administrator privileges.
You include (require) the MCAPI.class.php and config.inc.php files from their API downloads, and then write your process (I use PHP).
Once you have downloaded the files and set up your 'config.inc.php` file with the proper credentials, (API Key and list ID) you're ready to go.
Here's a sample in PHP that subscribes a user to a list, but you'll have to read the API docs to get the exact functionality you're looking for.
<?php
session_start();
// --- Sample fields - depends on your list
$mailChimpTIME = date('Y-m-d H:i:s');
$mailChimpFirstName = // First Name
$mailChimpLastName = // Last Name
$mailChimpEmailAddress = // Email Address
require_once 'MCAPI.class.php';
require_once 'config.inc.php'; //contains apikey
$api = new MCAPI($apikey);
$merge_vars = array(
'FNAME'=>$mailChimpFirstName,
'LNAME'=>$mailChimpLastName,
'EMAIL'=>$mailChimpEmailAddress,
'OPTIN_IP'=>$_SERVER['REMOTE_ADDR'],
'OPTIN_TIME'=>$mailChimpTIME
);
$email_type = 'html';
$double_optin = true;
$update_existing = true;
$replace_interests = false;
// By default this sends a confirmation email - you will not see new members
// until the link contained in it is clicked!
$retval = $api->listSubscribe( $listId, $mailChimpEmailAddress, $merge_vars, $email_type, $double_optin, $update_existing, $replace_interests);
if ($api->errorCode){
echo "Unable to load listSubscribe()!\n";
echo "\tCode=".$api->errorCode."\n";
echo "\tMsg=".$api->errorMessage."\n";
} else {
// Success
//echo "Subscribed - look for the confirmation email!\n";
}
?>

Resources