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"];
Related
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);
I need to automatically update the prestashop->customers->customer->id_default_group value using PHP via the Prestashop webservice. The script knows the new value and it is done before/as the page loads.
I can get a customer record, or I can get just the "id_default_group" of a customer record but I run into trouble when I try changing the record value and updating the webservice. I get back "HTTP/1.1 400 Bad Request".
It seems like I am incorrectly trying to update the xml or object.
It would be preferable to do all this by only getting and updating the "id_default_group" and not having to retrieve the complete customer record.
I have:
define('DEBUG', true);
define('PS_SHOP_PATH', 'http://www.site.com/');
define('PS_WS_AUTH_KEY', 'yuyiu');
require_once('../PSWebServiceLibrary.php');
// First : We always get the customer's list or a specific one
try
{
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$opt = array('resource' => 'customers'); // Full customer record
//$opt = array('resource'=>'customers','display'=> '[id_default_group]','filter[id]' => '['.$_SESSION["iemIdCustomer"].']'); // Customer id_default_group value
if (isset($_SESSION['iemIdCustomer'])){
$opt['id'] = $_SESSION['iemIdCustomer'];
}
$xml = $webService->get($opt);
// The elements from children
$resources = $xml->children()->children();
// $resources = $xml->children()->children()->children(); // If just getting id_default_group
}
catch (PrestaShopWebserviceException $e)
{
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error';
}
// Second : We update the data and send it to the web service
if (isset($_SESSION['iemIdCustomer'])){
// Update XML with new values
$xml->customers->customer->id_default_group = 4;
//$resources = $xml->children()->children()->children();
// And call the web service
try
{
$opt = array('resource' => 'customers');
//$opt = array('resource'=>'customers','display'=> '[id_default_group]','filter[id]' => '['.$_SESSION["iemIdCustomer"].']');
$opt['putXml'] = $xml->asXML();
$opt['id'] = $_SESSION['iemIdCustomer'];
//$opt['display'] = 'id_default_group';
$xml = $webService->edit($opt);
// if WebService succeeds
echo "Successfully updated.";
}
catch (PrestaShopWebserviceException $ex)
{
// Dealing with errors
$trace = $ex->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$ex->getMessage();
}
}
This is basic for those in the know so I hope you can help.
Thanks in advance,
Lance
Ok I go the following to work.
The following line seem to do the trick:
$xml->children()->children()->id_default_group = 4;
Follows is the line with the rest of the code to do the task.
// Get the customer's id_default_group
try
{
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$opt = array('resource' => 'customers');
$opt['id'] = $_SESSION["iemIdCustomer"];
$xml = $webService->get($opt);
// Get the elements from children of customer
$resources = $xml->children()->children()->children();
}
catch (PrestaShopWebserviceException $e)
{
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error';
}
// Update the data and send it to the web service
// Update XML with new value
$xml->children()->children()->id_default_group = 4;
// And call the web service
try
{
$opt = array('resource' => 'customers');
//$opt = array('resource'=>'customers','display'=> '[id_default_group]','filter[id]' => '['.$_SESSION["iemIdCustomer"].']');
$opt['putXml'] = $xml->asXML();
$opt['id'] = $_SESSION['iemIdCustomer'];
//$opt['display'] = 'id_default_group';
$xml = $webService->edit($opt);
// if WebService don't throw an exception the action worked well and we don't show the following message
echo "Successfully updated.";
}
catch (PrestaShopWebserviceException $ex)
{
// Here we are dealing with errors
$trace = $ex->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$ex->getMessage();
}
Hope that it assists someone.
i think you have this error because you are editing the bad node ;)
try with
$xml->customer->id_default_group = 4;
That should be OK :)
If I try to create a record with something like
var myObject = App.ModelName.createRecord( data );
myObject.get("transaction").commit();
the id of myObject is never set.
This says that id generation should be handled by EmberData (first response). So what should be happening? Where is the new id determined. Shouldn't there be a callback to the API to get valid id?
ID is the primary key for your record which is created by your database, not by Ember. This is JSON structure submit to REST post, notice no ID.
{"post":{"title":"c","author":"c","body":"c"}}
At your REST Post function you must get the last insert ID and return it back with the rest of the model data to Ember using this following JSON structure. Notice the ID, that is the last insert ID. You must get that last insert ID manually using your DB api.
{"post":{"id":"20","title":"c","author":"c","body":"c"}}
This is my sample code for my REST post. I coded this using PHP REST Slim framework:
$app->post('/posts', 'addPost'); //insert new post
function addPost() {
$request = \Slim\Slim::getInstance()->request();
$data = json_decode($request->getBody());
//logging json data received from Ember!
$file = 'json1.txt';
file_put_contents($file, json_encode($data));
//exit;
foreach($data as $key => $value) {
$postData = $value;
}
$post = new Post();
foreach($postData as $key => $value) {
if ($key == "title")
$post->title = $value;
if ($key == "author")
$post->author = $value;
if ($key == "body")
$post->body = $value;
}
//logging
$file = 'json2.txt';
file_put_contents($file, json_encode($post));
$sql = "INSERT INTO posts (title, author, body) VALUES (:title, :author, :body)";
try
{
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("title", $post->title);
$stmt->bindParam("author", $post->author);
$stmt->bindParam("body", $post->body);
$stmt->execute();
$insertID = $db->lastInsertId(); //get the last insert ID
$post->id = $insertID;
//prepare the Ember Json structure
$emberJson = array("post" => $post);
//logging
$file = 'json3.txt';
file_put_contents($file, json_encode($emberJson));
//return the new model back to Ember for model update
echo json_encode($emberJson);
}
catch(PDOException $e)
{
//$errorMessage = $e->getMessage();
//$data = Array(
// "insertStatus" => "failed",
// "errorMessage" => $errorMessage
//);
}
}
With some REST adapters, such as Firebase, you can define the id as a variable of the record you are going to create.
App.User = DS.Model.extend({
firstName: DS.attr('string')
});
var sampleUser = model.store.createRecord('user', {
id: '4231341234891234',
firstName: 'andreas'
});
sampleUser.save();
JSON in the database (Firebase)
"users": {
"4231341234891234": {
"firstName": "andreas"
}
}
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;
}
}
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);
?>