facebook.login() is not working in Corona SDK - facebook

I have went threw all the steps, creating a key hash for android for my game build in corona. I have create a Button for user login Facebook account. But don't have any error message and response when user touch the Button. Only have print output.
What am I missing? Please help.
I have create the Key Hashes using OPENSSL
Enter App ID from Facebook Developers
Enter Key Hashes to Facebook Developers
Enable "Single Sign On" and "Deep Linking"
Enter Class Name "com.ansca.corona.CoronaActivity" on Facebook Developers
include "android.permission.INTERNET" in build.settings
local facebook = require ("facebook")
local fbAppID = "49911xxxxxx"
local function onClick( event )
if ( "ended" == event.phase ) then
print( "Button was pressed and released" )
facebook.login( fbAppID, facebookListener, { "publish_actions, email" } )
end
end
-- Facebook Button
FacebookButton = widget.newButton
{
defaultFile = "images/fb.png" ,
width = 240,
height = 120,
onEvent = onClick,
}
FacebookButton.x = display.contentWidth / 2
FacebookButton.y = display.contentHeight / 2

I am unsure if you have fixed this problem but I too have been having problems with this. When you go to log in through Facebook and it gives you an error saying:
"invalid key hash code, it does not match xxxxxxxxxxxxx configure it in (your website here)" I copied the hash code and checked it over and over again...
Only to FINALLY realize that the lowercase "L" was actually an uppercase "i" o.0 it fixed it! Good luck to ya!
Also, here is a little code snippit that helped me a little
local function facebookListener(event)
if (event.type == "session") then
if (event.phase == "login") then
sessionToken = event.token
local response = event.response
native.showAlert("My Response", response)
--facebook.request("me", "GET", {fields = "email"})
elseif (event.type == "request") then
local response = event.response
native.showAlert("My Response", response)
end
end
end
facebook.login( appId, facebookListener, {"publish_actions, email, public_profile"})

Related

Should I notify user if link has been expired?

I'm creating logic for password recovery. User will submit request by providing their email address. Then email will be sent with more information that includes the link with the url parameter. This parameter is token created with ColdFusion createUUID() method. When user clicks on the link first thing to check is if url parameter exist then if it's valid token. The next step is to check if token exists in Database and pull Expiration value/timestamp. Here is example of my code:
<cfscript>
if (structKeyExists(url,"token") AND isValid("uuid", url.token) AND len(trim(url.token)) EQ 35){
cfstoredproc( procedure="ckToken", datasource=dsn ) {
cfprocparam( maxlength=35, null=!len(trim(url.token)), cfsqltype="cf_sql_varchar", dbvarname="#Token", value=trim(url.token) );
cfprocresult( name="Result" );
}
if( dateCompare(now(), Result.Expires, "s") == -1 ){
writeOutput("Link Valid Current: " & now() & " Expires: " & Result.Expires);
//include = "form.html";
}else{
writeOutput("Link Invalid Current: " & now() & " Expires: " & Result.Expires);
}
}else{
}
</cfscript>
If link is valid and not expired user will be directed to .html that has form with the password input field. If link has been expired I'm wondering should notify the user with the message or kick them back to the login page? I'm not sure if there is standard process for this kind of situation. If anyone have any suggestions please let me know.

Google Analytics OAuth2: How to solve error: "redirect_uri_mismatch"?

I'm trying to get this example to work: https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php#enable
The error I'm getting is "Error: redirect_uri_mismatch" .
In order to install the google api resources, I used composer with this command:
php composer.phar require google/apiclient:^2.0.0#RC
This installed the "vendor" folder in my root site folder. My index.php and oauth2callback.php files are located in the "public_html" folder.
Here's a screenshot of my error when going to my site:
The weird thing is that if I navigate to the link above that's included in the error message "Visit ...... to update the authorized..", I get this error message: " The OAuth Client Does Not Exist "
If I click on my only available Client ID, I can navigate to see the URI's which I'll screenshot below as well:
As you can see, under Authorized Javascript origins, I have http://localhost listed, and under authorized redirect URIs, I have my live site followed by the "oauthc2callback.php" file extension.
I don't understand how to get rid of the error I'm getting. I've tried replacing the URI's and putting in different JavaScript origins.
Also, for some reason on that last screenshot, it says that I don't have permission to edit this OAuth client, but I can make edits.
The code I have for index.php:
<?php
// Load the Google API PHP Client Library.
require_once '../vendor/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfigFile('../config/client_secrets.json');
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Create an authorized analytics service object.
$analytics = new Google_Service_Analytics($client);
// Get the first view (profile) id for the authorized user.
$profile = getFirstProfileId($analytics);
// Get the results from the Core Reporting API and print the results.
$results = getResults($analytics, $profile);
printResults($results);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
function getFirstprofileId(&$analytics) {
// Get the user's first view (profile) ID.
// Get the list of accounts for the authorized user.
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
// Get the list of properties for the authorized user.
$properties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($properties->getItems()) > 0) {
$items = $properties->getItems();
$firstPropertyId = $items[0]->getId();
// Get the list of views (profiles) for the authorized user.
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstPropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
// Return the first view (profile) ID.
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No properties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
function getResults(&$analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
}
function printResults(&$results) {
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {
// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();
// Get the entry for the first entry in the first row.
$rows = $results->getRows();
$sessions = $rows[0][0];
// Print the results.
print "<p>First view (profile) found: $profileName</p>";
print "<p>Total sessions: $sessions</p>";
} else {
print "<p>No results found.</p>";
}
}
The code I have for "oauth2callback.php":
<?php
require_once '../vendor/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfigFile('../config/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
All of this code was taken from the first website example, except with a few minor additions to make it match my system.
Anyone know how I can get rid of this error? What am I doing wrong?
Remember, as far as Google is concerned, "your" server is hostile until you name it "friendly", you must explicitly whitelist every possible source of an OAuth call TO Google.
Google is a clubbouncer, a big, ugly, unmovable bouncer with a a guest list saying to your application: "I will only deal with your request if your exact name OR id is on the list"
Have you tried including, not only localhost, but all other possible origins?
You must list every possible variation of url "root", including explicit IPs.
http://www.example.com
http://example.com
https://example.com
https://www.example.com
http://222.111.0.111
...
dont forget to include
https://accounts.google.com:443
The redirect Uri in the request MUST be exactly the same as one Uri you stored.
I see a / at the end of the stored one you missed in your request.
just copy the request URI on which error is occurring from error screen and paste it to OAuth credentials "Authorised redirect URIs"
now run the app.
this works for me. Hope I answered your query.

CORONA SDK - facebook.showDialog() appears and disappears after a while

I've added Facebook to my application.
The login is ok, except that facebook.login() opens the browser instead of the native Facebook App, but then, when I call Facebook.showDialog() the popup pops up, but after a second or two it disappears.
Note that I get this behavior on iOS only, while on Android it is working fine.
I'm using the code below in my game.lua file:
local function facebookListener( event )
if ( "session" == event.type ) then
if ( "login" == event.phase ) then
local access_token = event.token
facebook.showDialog( "feed", { name = "SuperCool Game Coming soon", description = "Trying to figure out how to get my game to rule the world.", picture = "http://omnigeekmedia.com/wp-content/uploads/2011/05/omniblaster_promo-300x300.png", link = "http://www.omnigeekmedia.com/"})
end
elseif ( "request" == event.type ) then
print("facebook request")
if ( not event.isError ) then
local response = json.decode( event.response )
end
elseif ( "dialog" == event.type ) then
print( "dialog", event.response )
end
end
fbAppID = "my app ID" --replace with your Facebook App ID
function logOnFacebook(event)
if(event.phase=="ended")then
facebook.login( fbAppID, facebookListener, { "user_friends", "publish_actions" } )
end
end
["facebook"] =
{
publisherId = "com.coronalabs",
supportedPlatforms = { iphone = true, ["iphone-sim"] = true },
},
I'm running on build 2015.2729.
How can I manage to get Facebook work?
I would suggest updating to the v4 version of the plugin. While it's technically still in beta, it's required for iOS 9 builds. See:
https://coronalabs.com/blog/2015/07/24/facebook-v4-plugin-android-beta/
https://coronalabs.com/blog/2015/09/01/facebook-v4-plugin-ios-beta-improvements-and-new-features/
Browsing through the source code of the old Facebook plugin, this error will occur in the event that a permission requested wasn't granted!
In the source code for the old Facebook plugin, this can be seen in the FBSessionReauthorizeResultHandlers.
for ( int i = 0; i < [publishPermissions count]; i++)
{
if ( ![publishSession.permissions containsObject:[publishPermissions objectAtIndex:i]] )
{
release = true;
publishError = [[NSError alloc] initWithDomain:#"com.facebook" code:123 userInfo:nil];
break;
}
}
This will also occur for read permissions that were requested and not granted.
The issue has since been fixed in the Facebook-v4 plugin.

Yii REST POST is not working in POSTMAN but in Framework

how could i post the form to the rest api action. Or how can i test the rest api for creating a record in the db with all the field values. Should we add create aq queryStringUrl. if its comming from a POST form action its fine. But this yii rest api should also work when called on a android device. I have used $_Request on post of the form , will the same work else where. if i wanna test the same in POSTMAN how can i do it. http://localhost/basic/web/site/create?fname=deepika&uname=deeps&email=deep#gmail.com&pwd=deepika&pwd_confirm=deepika&gender=female says 404 in postman. But works in the yii controller url This is the action i have created.
public function actionCreate()
{
$params=$_REQUEST;
//echo $params;
$model= new UsersForm();
if(isset($params['fname']))
$fname=$params['fname'];
if(isset($params['uname']))
$uname=$params['uname'];
if(isset($params['email']))
$email=$params['email'];
if(isset($params['pwd']))
$pwd=$params['pwd'];
if(isset($params['gender']))
$gender=$params['gender'];
if($fname == "" || $uname == "" || $email == "" || $pwd == "" || $gender == ""){
$this->setHeader(400);
echo "<pre>".json_encode(array('status'=>0,'error_code'=>400,'errors'=>"Something went wrong"),JSON_PRETTY_PRINT)."</pre>";
}else{
$model->fname = $fname;
$model->uname = $uname;
$model->email = $email;
$model->pwd = $pwd;
$model->pwd_confirm = $pwd;
$model->gender = $gender;
if($model->save()){
if($model->status == 0){
$mailSent = Yii::$app->mailer->compose()
->setFrom("noreply#gmail.com")
->setTo($model->email)
->setSubject("Proceed by Verification")
->setTextBody('Plain text content')
->setHtmlBody('<b>HTML content</b>')
->send();
// VarDumper::dump($mailSent, 10, true);die();
}
$this->setHeader(200);
echo "<pre>".json_encode(array('status'=>1,'success_code' => 200,'verification_mail'=>$mailSent,'message'=>'Registered Successfully'),JSON_PRETTY_PRINT)."</pre>";
}else{
$this->setHeader(400);
echo "<pre>".json_encode(array('status'=>0,'error_code'=>400,'errors'=>$model->errors),JSON_PRETTY_PRINT)."</pre>";
}
}
// VarDumper::dump($params, 10, true);die();
}
Without code examples its hard to say what goes wrong in your app. I think first of all if you creat new item by GET method, its not REST. In REST API cretion of new item goes by POST method (I say nothing about URL appearance). When I was realized REST in some project, I create simple methods at the backend application and then on frontend (JavaScript app) create simple method for send request to API URLs, and when I preparing headers to send, and then depending of url I set method to headers GET, POST, or PUT (no DELETE because we not deletin items throgh API). So it may be little bit confusing... But I believe when you will get things about REST you will resolve your problem.

How to get the access token automatically in facebook

I'm trying to make some sort of dashboard of my facebook in R. Some basic stuff. I would like to automate the script so that it can periodically update itself. I use knitr and task manager to produce the dashboard, which works well.
I use the facebook code of romainfrancois' blog to get the facebook data:
facebook <- function( path = "me", access_token = token, options){
if( !missing(options) ){
options <- sprintf( "?%s", paste( names(options), "=", unlist(options), collapse = "&", sep = "" ) )
} else {
options <- ""
}
url <- sprintf( "https://graph.facebook.com/%s%s&access_token=%s", path, options, access_token )
# print(url)
data <- getURL( url )
fromJSON( data )
}
The only problem is to get the access token automatically.
I tried to webscrape the token of the webpage:
library(RCurl)
FBdevPage<-browseURL("http://developers.facebook.com/tools/explorer")
FBdevPage[21]
It should be on line 21, according to the source code of the page. However, in R it only shows a backslash. Does someone had any ideas to get the access token? Or otherwise, store the procedure, while it allows to retrieve the data each time?