How can I get email from Google People API? - google-people-api

I am using Google people API client library in PHP.
After successfully authenticating, I want to get email
Help me to find out the problem from my code below.
Can i use multiple scopes to get email, beacuse when i m using different scope it gives me error
function getClient() {
$client = new Google_Client();
$client->setApplicationName('People API');
$client->setScopes(Google_Service_PeopleService::CONTACTS);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$str = file_get_contents('credentials.json');
$json = json_decode( $str, true );
$url = $json['web']['redirect_uris'][0];
if (isset($_GET['oauth'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = $url;
header('Location: ' . filter_var($redirect_uri,FILTER_SANITIZE_URL));
} else if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$people_service = new Google_Service_PeopleService($client);
} else {
$redirect_uri = $url.'/?oauth';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
return $people_service;
}
$optParams = array(
'pageSize' => 100,
'personFields' => 'addresses,ageRanges,biographies,birthdays,braggingRights,coverPhotos,emailAddresses,events,genders,imClients,interests,locales,memberships,metadata,names,nicknames,occupations,organizations,phoneNumbers,photos,relations,relationshipInterests,relationshipStatuses,residences,sipAddresses,skills,taglines,urls,userDefined',
);
$people_service = getClient();
$connections = $people_service->people_connections-
>listPeopleConnections('people/me', $optParams);

Related

how to add product to cart in opencart

Below is add to product code . But I am not getting where the values are storing . Kindly help to find out solution for this . I want to know logic behind this code
public function add($product_id, $qty = 1, $option = array(), $recurring_id = 0) {
$this->data = array();
$product['product_id'] = (int)$product_id;
if ($option) {
$product['option'] = $option;
}
if ($recurring_id) {
$product['recurring_id'] = (int)$recurring_id;
}
$key = base64_encode(serialize($product));
if ((int)$qty && ((int)$qty > 0)) {
if (!isset($this->session->data['cart'][$key])) {
$this->session->data['cart'][$key] = (int)$qty;
} else {
$this->session->data['cart'][$key] += (int)$qty;
}
}
}
The product details with options are stored in $key = base64_encode(serialize($product));. Where $this->session->data['cart'][$key] contains the number of quantity added by the customer.
For more details check the getProducts() function on the same page. Where you can find
foreach ($this->session->data['cart'] as $key => $quantity) {
....
$product = unserialize(base64_decode($key));
....
}

Undefined index: action error in facebook api

I am using php api's in my website (to make a profile page)
I am using the below code:
$action = $_REQUEST["action"];
switch($action){
case "fblogin":
include 'facebook.php';
$appid = "**********";
$appsecret = "*************************";
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => TRUE,
));
$fbuser = $facebook->getUser();
if ($fbuser) {
try {
$user_profile = $facebook->api('/me');
}
catch (Exception $e) {
echo $e->getMessage();
exit();
}
$user_fbid = $fbuser;
$user_email = $user_profile["email"];
$user_fnmae = $user_profile["first_name"];
$user_image = "https://graph.facebook.com/".$user_fbid."/picture?type=large";
$check_select = mysql_num_rows(mysql_query("SELECT * FROM `fblogin` WHERE email = '$user_email'"));
if($check_select > 0){
mysql_query("INSERT INTO `fblogin` (fb_id, name, email, image, postdate) VALUES ('$user_fbid', '$user_fnmae', '$user_email', '$user_image', '$now')");
}
}
break;
}
It gives an error saying : Undefined index: action
I am using wamp server as localhost. Please provide a solution

facebook registration plugin location field not writing to mysql

Everything else works fine except for the location. The actual city/state does not come across. Instead the word Array is displayed. My field type in the database is text but I've tried every field type through mysql. The HTML file is JSON where it comes to the field names. I am very new at this so any help is appreciated.
This is my php file:
<? ob_start(); ?>
<?php
define('FACEBOOK_APP_ID', '');
define('FACEBOOK_SECRET', '');
// No need to change function body
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
if ($_REQUEST) {
$response = parse_signed_request($_REQUEST['signed_request'],
FACEBOOK_SECRET);
/*
echo "<pre>";
print_r($response);
echo "</pre>"; // Uncomment this for printing the response Array
*/
$name = $response["registration"]["name"];
$email = $response["registration"]["email"];
$gender = $response["registration"]["gender"];
$prosecutor = $response["registration"]["prosecutor"];
$location = $response["registration"]["location"];
// Connecting to Database
$con = mysql_connect("my_hosting_site","Database","password");
if (!$response)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Database", $con);
mysql_query("INSERT INTO my_table (name, email, gender, prosecutor, location)
VALUES ('$name', '$email', '$gender', '$prosecutor', '$location')");
mysql_close($con);
}
$URL="https://www.facebook.com";
header ("Location: $URL");
?>
<? ob_flush(); ?>
Facebook
Basically, it's an array.
[location] => Array
(
[name] => Delhi, India
[id] => 1.1604xxxxxx286E+14
)
Use this for getting location stored in your db, like I have written below:
$location = $response["registration"]["location"]["name"];

Cakephp Geocoding Behaviour

I have been following this tutorial. Basically I want to take an address from a table I have and place that address on a google map. The tutorial seems pretty straight forward, create the table places, put the behavior in and model and what not.
Just kind of confused how I'd actually use that with my existing tables. I've read through the section in the cookbook about behaviors but am still a little confused about them. Mostly about how I'd integrate the tutorial into other views and controllers that aren't within place model?
first you need to add latitude / longitude coordinates to your address table...
you can do that with a writing parser around this google maps api call:
http://maps.google.com/maps/api/geocode/xml?address=miami&sensor=false
once your addresses contain the coordinates, all you need is to pass the coordinates
to a javascript google maps in your view, just copy the source :
http://code.google.com/apis/maps/documentation/javascript/examples/map-simple.html
here is a cakephp 2.0 shell to create latitude / longitude data
to run: "cake geo"
GeoShell.php :
<?php
class GeoShell extends Shell {
public $uses = array('Business');
public function main() {
$counter = 0;
$unique = 0;
$temps = $this->Business->find('all', array(
'limit' => 100
));
foreach($temps as $t) {
$address = $this->geocodeAddress($t['Business']['address']);
print_r($address);
if(!empty($address)) {
$data['Business']['id'] = $t['Business']['id'];
$data['Business']['lat'] = $address['latitude'];
$data['Business']['lng'] = $address['longitude'];
$this->Business->save($data, false);
$unique++;
}
}
$counter++;
$this->out(' - Processed Records: ' . $counter . ' - ');
$this->out(' - Inserted Records: ' . $unique . ' - ');
}
public function geocodeAddress($address) {
$url = 'http://maps.google.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=false';
$response = #file_get_contents($url);
if($response === false) {
return false;
}
$response = json_decode($response);
if($response->status != 'OK') {
return false;
}
foreach ($response->results['0']->address_components as $data) {
if($data->types['0'] == 'country') {
$country = $data->long_name;
$country_code = $data->short_name;
}
}
$result = array(
'latitude' => $response->results['0']->geometry->location->lat,
'longitude' => $response->results['0']->geometry->location->lng,
'country' => $country,
'country_code' => $country_code,
'googleaddress' => $response->results['0']->formatted_address,
);
return $result;
}
}

Is there any way to get facebook user email with django-facebookconnect?

I already integrate django-facebookconnect on my project, but when user login email field stay empty, i mean this app does not save user email ??
It seems like it does:
user = User(username=request.facebook.uid,
password=sha.new(str(random.random())).hexdigest()[:8],
email=profile.email)
But when i check it does not saves email, is this an error or a facebook restriction?
You need to get the extended permission from facebook.
<?php
$app_id = "YOUR_APP_ID";
$app_sec = "APP_SEC";
$canvas_page = "APP_CANVAS_PAGE_URL";
$scope = "&scope=user_photos,email,publish_stream"; $auth_url"http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page).$scope;
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode(".", $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, "-_", "+/")), true);
if (empty($data["user_id"])) {
echo(""); }
$access_token = $data["oauth_token"];
$user_id = $data["user_id"];
$user = json_decode(file_get_contents( "https://graph.facebook.com/me? access_token=" . $access_token));
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($COOKIE["fbs" . $app_id], "\""), $args);
ksort($args);
$payload = "";
foreach ($args as $key => $value) {
if ($key != "sig") {
$payload .= $key . "=" . $value;
}
}
if (md5($payload . $application_secret) != $args["sig"]) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie($app_id, $app_sec);
?>