I am trying to get my id via the Facebook API 2.1
https://graph.facebook.com/v2.1/me&fields=id&access_token="+accesstoken
I get error 200 but no data.
Does anyone have an example how to get and extract my id, name, or any data from query 2.1?
that's because of me&field=id must be me?field=id
https://graph.facebook.com/v2.1/me?fields=id&access_token=accesstoken
for all public user information
https://graph.facebook.com/v2.1/me?access_token=accesstoken
i would recommend you to use Facebook SDK. see Using the Graph API
Example graph api me request with facebook sdk:
new Request(
Session.getActiveSession(),
"/me",
null,
HttpMethod.GET,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
if (graphObject != null) {
if (graphObject.getProperty("id") != null) {
String fbId = graphObject.getProperty("id").toString();
String userName = graphObject.getProperty("name").toString();
}
}
}
}
).executeAsync();
Related
i am trying to send json using postman to Lavavel but i facing this error.
enter image description here
this is my json code:
{
"email":"test#test.com",
"password":"testtest"
}
and this is Laravel codes :
Route::get('/r','test#store');
and
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Log;
class test extends Controller
{
public function store(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
Log::info('test');
Log::info($email);
Log::info($password);
DB::table('login')->insert([
['email' => $email],
['password' => $password]
]);
}
}
also i trying using android for send data using volley and so checked Laravel logs :
Column 'email' cannot be null (this is Laravel logs)
and on android Logs:
E/Volley: [299] BasicNetwork.performRequest: Unexpected response code 500 for http://192.168.1.4:8000/r
D/error: com.android.volley.ServerErro
my android code is :
public class ApiService {
private final Context context;
public ApiService(Context context){
this.context=context;
}
public void loginUser(String email, String password, final OnLoginResponse onLoginResponse){
JSONObject requestJsonObject=new JSONObject();
try {
requestJsonObject.put("email",email);
requestJsonObject.put("password",password);
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, "http://192.168.1.4:8000/r",requestJsonObject , new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("response",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
}) {
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
return headers;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(18000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(context).add(request);
} catch (JSONException e) {
Log.e(TAG, "loginUser: "+e.toString());
}
}
public interface OnLoginResponse{
void onResponse(boolean success);
}
}
I hope this helps people trying to search on how to send JSON data to laravel not only specific to android applications but to all. The goal of this solution is to identify whether you can send a JSON data to laravel or not.
First of all you have to download postman from https://www.getpostman.com/ to test if your API is really working or not.
Create a post request using postman. Be sure that you follow the example data below
Be sure that you set your Routes that would associate to the controller
This is the controller part that will show the JSON data you sent if it was successfully accepted or not.
And also, if ever you are trying to send POST data to laravel, by default they provided a CSRF Token which is applicable for the forms if you are going to use the MVC of laravel. For the meantime, we are going to take this down and comment it out. Just go to app/http/kernel.php
and now you'll get the following result from the code earlier
$json = json_decode($request['json']);
echo $json->{'email'};
echo "\n";
echo $json->{'password'};
We tested that we were able to send data to laravel. I hope this truly helps.
Wen you want to send data, you will want to use POST or PUT method on your postman, specially if you are sending a body, that means that you are sending data. Get method is used to retrieve data from a service.
Take a look into CRUD functions for more information.
Your postman should look something like this
Last in your android code try to change this line
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, "http://192.168.1.4:8000/r",requestJsonObject , new Response.Listener<JSONObject>() {
to use Request.Method.POST
I'm trying to run a query to search for locations using search query facebok graf api for android.
If I try to run this query in the Graph API Explorer, I get this result.
But programmatically it is impossible. I try to make so:
new GraphRequest(AccessToken.getCurrentAccessToken(),"/search?q=coffee&type=place¢er=37.76,-122.427",null,HttpMethod.GET,new GraphRequest.Callback()
{
public void onCompleted(GraphResponse response)
{
Log.v("HelloFacebook", response.toString());
}
}).executeAsync();
}
i get nothing (param distance must be number)
if I try without distance i get too nothing, but another message (An access token is required to request this resourse and too)
What could be the problem?
Right syntax for search in Facebook graph API:
GraphRequest request = GraphRequest.newGraphPathRequest(
accessToken,
"/search",
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
// Insert your code here
}
});
Bundle parameters = new Bundle();
parameters.putString("type", "place");
parameters.putString("center", "53,27");
parameters.putString("distance", "30000");
request.setParameters(parameters);
request.executeAsync();
The syntax that Vadim Korzun provided did unfortunately not directly work for me. But it gave me some ideas. I wanted to search for people by names. Here the code I impelemted according to the newPlacesSearchRequest(...)-method of the official GraphRequest-class:
AccessToken accessToken = AccessToken.getCurrentAccessToken();
Bundle parameters = new Bundle(2);
parameters.putString("type", "user");
parameters.putString("q", "Albert Einstein");
GraphRequest.Callback wrapper = new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
try {
JSONObject jso = response.getJSONObject();
JSONArray arr = jso.getJSONArray( "data" );
for (int i = 0; i < (arr.length()); i++) {
JSONObject json_obj = arr.getJSONObject(i);
// START: Your code goes here
String id = json_obj.getString("id");
String name = json_obj.getString("name");
// ...
// END: Your code goes here
}
} catch (JSONException e) {
Log.e("name: ", e.getMessage());
}
}
};
GraphRequest gr = new GraphRequest(accessToken, "search", parameters, HttpMethod.GET, wrapper);
gr.executeAsync();
hope this helps...
Ok, I've figured this one out already, but I wanted to put it out there in case anyone else is running into issues. Basically, what I needed to do was have post as a Facebook user's owned page (i.e. I'm John Doe and I'm an admin for page Rum Ham; I want to post to the Rum Ham page).
So, basically the answer looks like this
First, you need to log the user in with this line
LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions", "manage_pages", "publish_pages"));
Then, you need to fetch the access token of the page we wish to publish to
Bundle params = new Bundle();
//ok so access token here is "app_ID|app_secret"
params.putString("access_token", accessToken);
params.putString("fields", "id");
GraphRequest request = new GraphRequest(null, "me", params, HttpMethod.GET, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
FacebookRequestError error = response.getError();
if (error != null) {
Log.e("Error", error.getErrorMessage());
} else {
JSONObject values = response.getJSONObject();
try {
//so I have to get the user ID first
String id = values.getString("id");
Bundle p = new Bundle();
p.putString("access_token", accessToken);
//yay nest the graph requests
//once we get the id we can get their pages
GraphRequest pagesRequest = new GraphRequest(null, "/" + id + "/accounts", p, HttpMethod.GET, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
FacebookRequestError error = response.getError();
if (error != null) {
Log.e("Error", error.getErrorMessage());
} else {
//ok so here, we're getting the pages back in a few JSON wrappers
JSONObject values = response.getJSONObject();
JSONArray array = null;
try {
array = values.getJSONArray("data");
//ok, so here we're just iterating through the pages a user has, obviously you can handle this accordingly..
for (int i = 0; i < array.length(); i++) {
//ok, here's how to actually get the token
String access_token = array.getJSONObject(i).getString("access_token")
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
GraphRequest.executeAndWait(pagesRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
GraphRequest.executeAndWait(request);
}
Ok, so once we've got the access token page, here's where the real f***kery comes into play that Facebook refuses to tell you about in their reference pages.
So, forget anything you've read about needing to submit your app for review with them. All I had to do was create a new access token like so
//create a new access token, facebook refers to this as a page access token
AccessToken token = new AccessToken("page_access_token", AccessToken.getCurrentAccessToken().getUserId(), Arrays.asList("publish_actions", "manage_pages", "publish_pages"), null, AccessTokenSource.FACEBOOK_APPLICATION_SERVICE,
AccessToken.getCurrentAccessToken().getExpires(), AccessToken.getCurrentAccessToken().getLastRefresh());
//then we simply update our current access token
AccessToken.setCurrentAccessToken(token);
Now, we're still not done yet. Finally, we need to actually make the API call to create the post:
Bundle params = new Bundle();
params.putString("message", "Contents of message");
//here, token is our newly created AccessToken object
GraphRequest request = new GraphRequest(token, "/pageid/feed", params, HttpMethod.POST, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
FacebookRequestError error = response.getError();
if (error != null) {
Log.e("Error", error.getErrorMessage());
} else {
//do your own processing here for success
}
}
});
GraphRequest.executeAndWait(request);
}
}
And that's pretty much it. Hopefully this helps someone!
So I have an app which uses Google App Engine and Google Cloud Endpoints as it's backend in Java. I'm currently working on User authentication and here is what I'm trying to do:
When user first opens the app, they'll have option to either "Login through Facebook" or signup using their email address. Then this data would be stored in a user object and after registration would direct them to the app homepage. It will be saved in their preferences so that they don't need to login every time they open the app (if ever).
Now I heard you can use a custom authenticator for Facebook, but there's not much documentation regarding this. How can I get the email registration and Facebook Login options to be implemented with Google Cloud Endpoint's Authenticator? Or should I make a different approach?
Thanks.
My approach is using the Facebook login method (Facebook SDK for Android). The Facebook authentication process returns (on success) an object from which I can get the user's email then I save it in my Endpoints class using Datastore API. To check if user already logged in I chose the SharedPreferences approach with GSON library to parse objects into JSON String and save them in the prefs.
Links and my sample codes below :
Regarding the Authenticator I found this SO answer
More info about Facebook login method
Saving custom objects in SharedPreferences
Getting user's email through Facebook auth
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
if (isSessionCalled == false) {
Log.i(TAG, "Logged in...");
System.out.println("Token=" + session.getAccessToken());
new Request(
session,
"/me",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
if (response != null) {
GraphObject object = response.getGraphObject();
String email = (String) object.getProperty("email");
Log.i(TAG, "user email : " + email);
String firstName = (String) object.getProperty("first_name");
String lastName = (String) object.getProperty("last_name");
mUserTask = new UserAsyncTask();
mUserTask.execute(email);
}
}
}
).executeAsync();
isSessionCalled = true;
}
else {
Log.w(TAG, "session called twice");
}
}
else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
Storing the user in my backend :
#ApiMethod(name = "storeUserModel")
public UserModel storeUserModel(UserModel userModel) throws UserAlreadyExistsException, UserNotFoundException {
logger.info("inside storeUser");
String email = userModel.getEmail();
UserModel checkUser = getUserModel(email);
logger.info("after getUserModel with email " + email);
if (checkUser == null) {
logger.info("inside checkUser is NULL");
DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
Transaction txn = datastoreService.beginTransaction();
try {
Entity userEntity = new Entity(UserModel.class.getSimpleName(), email);
userEntity.setProperty("nickname", userModel.getNickname());
// TODO save the pheromones with the key of userEntity
datastoreService.put(userEntity);
txn.commit();
storePheromoneList(userModel.getPheromoneList(), userEntity.getKey(), datastoreService);
} finally {
if (txn.isActive()) {
logger.severe("rolled back with email : " + email);
txn.rollback();
}
}
}
else {
throw new UserAlreadyExistsException();
}
return userModel;
}
A class that triggers calls to my backend
public class EndpointsServer implements Server {
private static final String TAG = "EndpointsServer";
final UserModelApi userEndpointsApi;
public EndpointsServer() {
UserModelApi.Builder builder = new UserModelApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
userEndpointsApi = builder.build();
}
#Override
public User getUser(String email) {
User user = null;
try {
Log.d(TAG, "in getUser with email " +email);
// get user from db
UserModel userModel = userEndpointsApi.getUserModel(email).execute();
if (userModel != null) {
Log.d(TAG, "user != null with email " + email);
user = new User(userModel);
}
} catch (IOException e) {
e.printStackTrace();
}
return user;
}
}
Storing user on successful login :
String userString = gson.toJson(user, User.class);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(USER_KEY, userString);
editor.commit();
There's more to it like another client side class to build the api call to the backend and lots of other details. I can post it if you want.
I can't speak on Java but I started with Python by looking at this repo on Github:
https://github.com/loudnate/appengine-endpoints-auth-example
This shows you an example on how to write a custom authenticator with Facebook Login. Writing your own authentication I think you should be able to find some examples. The only thing you need to do after is to use the same User entity.
And I suggest you do some reading on how OAUTH 2.0 works so you don't get too confused on the task you need to do.
Basically:
On your client side, whether web or android, get a facebook access token, sends it to your endpoint service. Exchange for a access token of your own. At the same time, create your User object in datastore and associate the access token.
Then all your subsequent request should use this access token to get access to your endpoint backend. (Do a user check on your endpoint API method.)
im trying to get the users group list.
before i ask how to extract that information from the "response" this is my code:
permissions:
this.login = (LoginButton)findViewById(R.id.login_button);
login.setReadPermissions(Arrays.asList("user_groups", "friends_groups"));
request:
Request share = Request.newGraphPathRequest(session, "/me/groups", new Request.Callback() {
#Override
public void onCompleted(Response response) {
GraphObject go = response.getGraphObject();
Log.d("getting groups", go.toString());
}
});
first of all a few issues:
1. the log.d line not showing. meaning the app dosent get to that call back.
is the code ok?
how to handle the response, meaning how to extract the information?
thank you !