I have created a custom action that I want to allow users to post to their timeline with e.g. {User} read {Article}. I can get this to work fine when I do a post using the sample URL like this :
FB.api('/me/fbsite:actionname' +
'?object=http://samples.ogp.me/356694057772404&access_token=abc','post'
But when I replace the sample URL with my own URL I get the error 'The session was invalidated explicitly using an API call'. Can anybody please advise?
EDIT : Changed my Javascript to this, but I now get 'Invalid OAuth Access Token' :
<script type="text/javascript">
function redeem() {
FB.api('/me/fbsite:actionname' +
'?object=http://samples.ogp.me/356694057772404&access_token=\' + <%=UserManager.Current.FB.accessToken %> + \'', 'post',
function (response) {
var msg = 'Error occured';
if (!response || response.error) {
if (response.error) {
msg += "\n\nType: " + response.error.type + "\n\nMessage: " + response.error.message;
}
alert(msg);
}
else {
alert('Post was successful! Action ID: ' + response.id);
}
});
}
That might be because you are using the same access token in same session. So try logging out and log back in, get a new FB access token, and try the query using the new access token you got, that should work as expected.
Related
i created a login.php file where the user can will be navigated to instamojo payment page . After completing the transaction the user is getting the success message from instamojo , but i need to display the successful transaction in my domain or in own php file . so how can i get the transation related information to my webpage or to my login.php file
Ex: Redirecting from our login.php to instamojo(payment gateway)and response back (success message)to our login.php intimating the user that payment is success
var rootURL = "cgshealthcare.com/HealthCareSystem/";;
$(document).ready(function() {
$('#login').click(function() {
if ($('#username').val() == "" || $('#password').val() == "") {
alert("Please enter username or password");
return false;
}
cardloginUser($('#username').val(), $('#password').val());
});
});
function forwardtoRegister() {
window.location = "login.php?page=register";
}
function cardloginUser(userName, password) {
console.log('userName: ' + userName);
console.log('password: ' + password);
if (userName.length < 1) {
$('#errorlist').html("<font color='red'><b> Please enter User ID</b></font>");
return false;
}
if (password.length < 1) {
$('#errorlist').html(" <font color='red'><b> Please enter Password</b></font>");
return false;
}
console.log(rootURL + '/authenticate/' + userName + '/' + password);
$.ajax({
type: 'GET',
url: rootURL + '/authenticate/' + userName + '/' + password,
dataType: "json",
success: function(data) {
console.log("hello" + data.responseMessageDetails);
var list = data == null ? [] : (data.responseMessageDetails instanceof Array ? data.responseMessageDetails : [data.responseMessageDetails]);
console.log("List : " + list);
if ((list).length < 1) {
$('#errorlist').html("<font color='red'><b> Invalid User Name and Password Combination </b></font>");
$('#errorblock').css("visibility") == "visible";
}
$.each(list, function(index, responseMessageDetails) {
console.log("Status " + responseMessageDetails);
var message = responseMessageDetails.message;
if (message.indexOf("]:") > 0) message = message.substring(0, message.indexOf("]:") + 2);
console.log("message" + message);
console.log("USer Data" + responseMessageDetails.status);
console.log("USer Data" + responseMessageDetails.message);
if (responseMessageDetails.status == "Success") {
window.location = "imjo.in/NpKxN";;
} else if (responseMessageDetails.status == "Fail") {
window.location = "www.google.com";
console.log("Fail1");
$('#errorlist').html("<font color='red'><b>" + message + "</b></font>");
} else {
console.log("Fail111");
$('#errorlist').html("<font color='red'><b> We are sorry some intermittent Issue. Please try after some time. </b></font>");
}
});
},
error: function(data) {
console.log("data...." + data);
var list = data == null ? [] : (data.responseMessageDetails instanceof Array ? data.responseMessageDetails : [data.responseMessageDetails]);
console.log("data...." + data);
$.each(list, function(index, responseMessageDetails) {
console.log(responseMessageDetails);
var message = responseMessageDetails.message;
if (message.indexOf("]:") > 0) message = message.substring(0, message.indexOf("]:") + 2);
$('#errorlist').html("<font color='red'><b>" + message + "</b></font>");
});
}
});
}
function showLogin() {
window.location = "login.php";
}
Please look at the integration guide here.
After user enters payment information on instamojo, they are redirected to a redirect-url which you specify (and is a url on your website). Instamojo appends transaction results to this url. You can make it a php url on your website and read the results using GET method. Depending upon the results, you can process your payment and display results to the end-user. More on GET method here...
Instamojo also provides for webhooks, which are like silent POSTs in the background and can be used as backups in case redirect urls in front-end fail for some reason. This way if end-users' redirection failed for any reason, the webhook will still receive information in the background which can be used you to update your database for success/failure of transaction. Of course you webserver has to be up and running to receive webhooks notifications. If that's the point of failure, nothing will work :)
The API link I shared has all those details.
Thanks
I am implementing Google log in for the first time as described here and here.
I am using HTML with Javascript.
The problem that needs solving is as follows: How can I, after the initial login, on a different page (say a landing page, or portal that the user sees after logging in), check if the user is logged in? Is there a service I can call to check the user's login in status with my app key or something similar?
I assume I would have to include the google API on each page.
Login Page Code:
Script In Head (Code from Google's tutorial listed above):
<head>
....
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script>
function onSignIn(googleUser)
{
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
alert(profile.getName());
}
function logout()
{
alert('logging out');
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
...
</head>
Code In Body (1st line from Google's tutorial listed above, 2nd line to trigger logout test)
<body>
...
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<div onmousedown="logout()">Logout</div>
...
</body>
Is there some way I can include the google API on another page, and then call some check login status function? Or another way to concretely tell if the user is logged in or out?
You do not need to store anything on local storage. The library allows you to check if the user is logged in or not using the isSignedIn.get() on the auth2 of the gapi object.
Load the JavaScript library, make sure you are not deferring the load :
<script src="https://apis.google.com/js/platform.js"></script>
Then initialize the library and check if the user is logged in or not
var auth2;
var googleUser; // The current user
gapi.load('auth2', function(){
auth2 = gapi.auth2.init({
client_id: 'your-app-id.apps.googleusercontent.com'
});
auth2.attachClickHandler('signin-button', {}, onSuccess, onFailure);
auth2.isSignedIn.listen(signinChanged);
auth2.currentUser.listen(userChanged); // This is what you use to listen for user changes
});
var signinChanged = function (val) {
console.log('Signin state changed to ', val);
};
var onSuccess = function(user) {
console.log('Signed in as ' + user.getBasicProfile().getName());
// Redirect somewhere
};
var onFailure = function(error) {
console.log(error);
};
function signOut() {
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
var userChanged = function (user) {
if(user.getId()){
// Do something here
}
};
Don't forget to change the app id
You can stringify a custom userEntity object and store it in sessionStorage where you can check it anytime you load a new page. I have not tested the following but it should work (doing something similar with WebAPI tokens in the same way)
function onSignIn(googleUser)
{
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
var myUserEntity = {};
myUserEntity.Id = profile.getId();
myUserEntity.Name = profile.getName();
//Store the entity object in sessionStorage where it will be accessible from all pages of your site.
sessionStorage.setItem('myUserEntity',JSON.stringify(myUserEntity));
alert(profile.getName());
}
function checkIfLoggedIn()
{
if(sessionStorage.getItem('myUserEntity') == null){
//Redirect to login page, no user entity available in sessionStorage
window.location.href='Login.html';
} else {
//User already logged in
var userEntity = {};
userEntity = JSON.parse(sessionStorage.getItem('myUserEntity'));
...
DoWhatever();
}
}
function logout()
{
//Don't forget to clear sessionStorage when user logs out
sessionStorage.clear();
}
Of course, you can have some internal checks if the sessionStorage object is tampered with. This approach should work with modern browsers like Chrome and Firefox.
To check is user Signed-in use:
gapi.auth2.getAuthInstance().isSignedIn.get()
Adding on to Joseph's answer above, you can then get information about the user by calling auth2.currentUser.get().getBasicProfile().
if (auth2.isSignedIn.get()) {
googleUserProfile = auth2.currentUser.get().getBasicProfile()
console.log('ID: ' + googleUserProfile.getId());
console.log('Full Name: ' + googleUserProfile.getName());
console.log('Given Name: ' + googleUserProfile.getGivenName());
console.log('Family Name: ' + googleUserProfile.getFamilyName());
console.log('Image URL: ' + googleUserProfile.getImageUrl());
console.log('Email: ' + googleUserProfile.getEmail());
}
From the docs: https://developers.google.com/identity/sign-in/web/people
according to the link from Phyrik post (https://developers.google.com/identity/sign-in/web/people) -
google stopped supporting the Sign-In Javascript web auth API:
We are discontinuing the Google Sign-In JavaScript Platform Library for web. The library will be unavailable for download after the March 31, 2023 deprecation date. Instead, use the new Google Identity Services for Web.
By default, newly created Client IDs are now blocked from using the older Platform Library, existing Client IDs are unaffected. New Client IDs created before July 29th, 2022 can set plugin_name to enable use of the Google Platform Library.
I am already using this script but I didn't get hometown and location when I use API the hometown and location is undefined message appears please give example code and how to get user mobile number in Facebook API:
function login() {
FB.login(function(response) {
if (response.authResponse) {
// connected
testAPI();
} else {
// cancelled
}
}, { scope: 'email,user_birthday,user_location,user_hometown' });
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.' + ' Email: ' + response.email + ' Facebook ID: ' + response.id);
//console.log('Good to see you, ' + response.name + '.');
var userfirstName=response.first_name;
var lastName=response.last_name;
var useremail=response.email;
var usersex=response.gender;
var userbithday=response.birthday;
var hometown= response.hometown.name;
var location= response.location.name;
alert(hometown);
});
}
<fb:login-button show-faces="false" width="200" max-rows="1" scope="email,user_birthday,user_location,user_hometown" onclick="testAPI();" onlogin="Log.info('onlogin callback')">
Sign Up with Facebook
</fb:login-button>
but can't get hometown and location, please help give any example.
You are using wrong permissions, try this:
{ scope: 'email,user_birthday,user_location,user_hometown' }
Another thing, to access the hometown use this:
var hometown= response.hometown.name;
Also, instead of /me; mention explicitly the fields you want using the fields parameter; just like: /me?fields=hometown
Graph API Explorer
I'm using the reddit API and can successfully login and receive a cookie value in return. The code I use is as follows
loginPost = $.ajax({
type: 'POST',
url: 'http://www.reddit.com/api/login/' + username + '?user=' + username + '&passwd=' + password + '&api_type=json',
xhrFields: {
withCredentials: true
},
dataType: "json",
success: function() {
console.log("Define response variables");
var header = loginPost.getAllResponseHeaders();
var responseText = loginPost.responseText;
var match = header.match(/(Set-Cookie|set-cookie): reddit_session=(.+?);/);
if (match) {
reddit_session = match[2];
window.localStorage.setItem("reddit_session", reddit_session);
window.localStorage.setItem("reddit_username", username);
window.localStorage.setItem("reddit_password", password);
console.log("Logged in!");
//alert(responseText);
$('.loginWrapper').slideUp('fast', function() {
$('#feedWrapper').css("top", "44px");
$('#feedWrapper').css("bottom", "0");
// Animation complete.
});
}
else {
reddit_session = null;
window.localStorage.setItem("reddit_session", null);
navigator.notification.alert('Your username or password is incorrect. Please try again.');
console.log("Login Failed");
}
},
});
I am storing the cookie using
var header = loginPost.getAllResponseHeaders();
var match = header.match(/(Set-Cookie|set-cookie): reddit_session=(.+?);/);
if(match){
reddit_session = match[2];
window.localStorage.setItem("reddit_session", reddit_session);
But the cookie isn't sent with a simple request to http://www.reddit.com/api/me.json. All that is returned is an empty JSON response like this {}. If I browse to that link in my browser (and am, of course, logged into reddit) it returns a JSON string with all the user data.
Any idea how I can store the cookie so that it is usable in a UIWebView?
Any idea how I can store the cookie so that it is usable in a UIWebView?
It appears that iOS cookies have been problematic since phonegap 2.5; please see [Handling cookies in PhoneGap/Cordova
I can't see any more current (phonegap 3.3) info [http://docs.phonegap.com/en/3.3.0/_index.html]
In this script
function fql(){
FB.api('/me', function(response) {
var query = FB.Data.query('select uid, name, email from user where uid={0}', response.id);
query.wait(function(rows) {
document.getElementById('name').innerHTML =
'Your name: ' + rows[0].name + "<br />" +
+ rows[0].email + "<br />" + rows[0].uid;
});
});
}
Function returns name and pic, but email value is NaN. App requires basic data and email (it was set in app properties/Auth dialog) but i cant get user email.
When I tested this query in Facebook test console, I've got email field with correct value.
Check that in Test Console and on your site you use the same application id and ensure that user have granted the email permission to your application!
This can be done with simple Graph API call:
FB.api('/me/permissions', function(response){
if (response && response.data){
var userPermissions = response.data.shift();
if (userPermissions.email){
alert('User is granted email permission');
} else {
alert('User is NOT granted email permission');
}
} else {
// No response or results from the Graph API
}
});
Couple of things you should be aware of!
FB.Data.* is gone! It's deprecated, undocumented and should not be used anymore! It's just a matter of time for it to disappear from the JavaScript SDK code...
You just doesn't want extra call just to figure the id of current user (most chances that you already have it, just check FB.getUserID()), in FQL use me() to refer to current user.
Rewrite your usage of FB.Data.* and query.wait with:
FB.api('/fql', {q:'YOUR_FQL_QUERY_HERE'}, function(response){
var rows = response.data;
});
In your case same results may be received by Graph API call without usage of FQL:
FB.api('/me', {fields: 'id,name,email'}, function(response){
// response -> {id: UID, name: 'User Name', email: 'user#email.dz'}
console.log(response);
});