How to get email id twitter integration - android

i am using twitter integration using fabric, now issue is i am able to get all the details of user except email address. following is my code, can any one help me with that
public void login(Result<TwitterSession> result) {
//Creating a twitter session with result's data
TwitterSession session = result.data;
//Getting the username from session
final String username = session.getUserName();
//This code will fetch the profile image URL
//Getting the account service of the user logged in
Call<User> userResult = Twitter.getApiClient(session).getAccountService().verifyCredentials(true, false);
userResult.enqueue(new Callback<User>() {
#Override
public void failure(TwitterException e) {
}
#Override
public void success(Result<User> userResult) {
User user = userResult.data;
String twitterImage = user.profileImageUrl;
try {
Log.d("imageurl", user.profileImageUrl);
Log.d("name", user.name);
System.out.println("Twitter Email"+user.email);
//Log.d("email", user.email);
Log.d("des", user.description);
Log.d("followers ", String.valueOf(user.followersCount));
Log.d("createdAt", user.createdAt);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

This is how I fetched the user email of an user:
final TwitterSession twitterSession = result.data;
twitterAuthClient.requestEmail(twitterSession, new com.twitter.sdk.android.core.Callback<String>() {
#Override
public void success(Result<String> emailResult) {
String email = emailResult.data;
// ...
}
#Override
public void failure(TwitterException e) {
callback.onTwitterSignInFailed(e);
}
});
So you have to call TwitterAuthClient.requestEmail() once you got a successful Result<TwitterSession> upon authorization.
Be aware that you'll have to contact Twitter support to enable access to users' email for your app. An error message with this will show up.

Here is my code to get details from twitter:
private void intializeTwitterUI() {
loginButton = (TwitterLoginButton)
findViewById(R.id.twitter_login_button);
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// The TwitterSession is also available through:
// TWITTER.getInstance().core.getSessionManager().getActiveSession()
TwitterSession session = result.data;
// TODO: Remove toast and use the TwitterSession's userID
// with your app's user model
String msg = "Twitter: #" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
/**
*
*/
AccountService _AccountService = Twitter.getApiClient(result.data).getAccountService();
_AccountService.verifyCredentials(true, true).enqueue(new retrofit2.Callback<User>() {
#Override
public void onResponse(Call<User> call, retrofit2.Response<User> response) {
Log.d(TAG, "Twitter user is: " + response.toString());
Log.d(TAG, "Twitter-Email" + response.body().email);
Log.d(TAG, "Twitter-profileImage" + response.body().profileImageUrl);
Log.d(TAG, "Twitter-ID" + response.body().id);
twitterDetails = response.body().email + "," + response.body().profileImageUrl + "," + response.body().id;
}
#Override
public void onFailure(Call<User> call, Throwable t) {
Log.e(TAG, "verifyCredentials failed! " + t.getLocalizedMessage());
}
});
}

For those that want to do it with Kotlin can try in this way:
val session = TwitterCore.getInstance().sessionManager.activeSession as TwitterSession
val authClient = TwitterAuthClient()
authClient.requestEmail(session, object : Callback<String>(){
override fun failure(exception: TwitterException?) {
email.setText("Welcome to Twitter")
}
override fun success(result: Result<String>?) {
email.setText("Welcome " + result?.data)
}
})

It is possible to request an email address from users, but it requires your app to be whitelisted.
check here Is there a way to get an user's email ID after verifying his/her Twitter identity using OAuth?

Related

How to validate the Access Token in OAuth 2.0?

How can I validate the Access Token and how to get the information of token using Access Token?
Is this the url to validate the Access Token?
https://mydomain/oauth2/v1/tokeninfo?access_token=tYPJr7F6ArYkd1Vdlh1gbhWlnz8NLA9TZmky2NpvaHZxhw14udbmFNRG1pKMKVEY&token_type=bearer
Here is an example of the data taken from token (the example is from Azure auth - but it does not matter both use OAuth2).
That's how you extract the information from the Token:
in getAuthInteractiveCallback() or getAuthSilentCallback() methods:
private AuthenticationCallback getAuthSilentCallback() {
return new AuthenticationCallback() {
#Override
public void onSuccess(AuthenticationResult authenticationResult) {
/* Successfully got a token, call api now */
Log.d(TAG, "Successfully authenticated");
Log.d(TAG, "ID Token: " + authenticationResult.getIdToken());
Log.d(TAG, "ID Token: " + authenticationResult.getAccessToken());
try {
String token = authenticationResult.getIdToken();
String token2 = token.substring(token.indexOf('.') + 1, token.lastIndexOf('.'));
byte[] data = Base64.decode(token2, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);
JSONObject jsonObject = new JSONObject(text);
JSONArray jsonArray = new JSONArray(jsonObject.getString("emails"));
String eMail = jsonArray.get(0).toString();
Log.d(TAG, "eMail: " + eMail);
} catch (JSONException ex) { }
authResult = authenticationResult;
state.setAuthResult(authResult);
}
#Override
public void onError(MsalException exception) {
}
#Override
public void onCancel() {
}
};
}
In addition you can get iod, expiration time (exp), auth time (auth_time), versiov (ver)

Facebook Android SDK 4.14.0 get birthday

I'm currently creating a test application to test using the latest facebook SDK to update our existing application problem is that I need to get the user birthday. I'm confused on this since the the SDK3 and above provides more information than the updated SDK4 and I'm lost on how to get the birthday as all the answers I've seen so far doesn't provide the birthday on my end. Here's my code so far:
LoginButton CallBacks:
fbLogin = (LoginButton) findViewById(R.id.login_button);
fbLogin.setReadPermissions(Arrays.asList("email", "user_birthday"));
fbLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
if (object.has("id"))
id = object.getString("id");
if (object.has("name"))
userName = object.getString("name");
if (object.has("email"))
userEmail = object.getString("email");
if (object.has("gender"))
gender = object.getString("gender");
if (object.has("birthday"))
birthday = object.getString("birthday");
String profile_URL = "https://graph.facebook.com/" + id+ "/picture?type=large";
LogCat.show(id + "\n" + userName + "\n" + userEmail + "\n" + birthday + "\n" + profile_URL + "\n" + gender);
} catch (Exception e) {
e.printStackTrace();
LogCat.show("Error:" + e.getMessage());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Toast.makeText(SplashLogin.this, "CANCEL", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException exception) {
// App code
Toast.makeText(SplashLogin.this, "" + exception.toString(), Toast.LENGTH_SHORT).show();
}
});
The JSON response returns only the ID and name, email and gender of my account but doesn't include the birthday. Did I missed out something?
According to the latest sdk of facebook, to get birthday you need to first submit your application for review. On test applications you can just get the public profile which includes the following things
id
cover
name
first_name
last_name
age_range
link
gender
locale
picture
timezone
updated_time
verified
For more information you can read the following documentation from this link
If your app requests this permission Facebook will have to review how
your app uses it. link
Facebook don't give user birthday by default.You have to use extended permissions.
I solve this problem by enable permission of Birthday in my app from the Facebook Developer Console.
fbSignUp.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
Data.fbAccessToken = loginResult.getAccessToken().getToken();
LogCat.show(loginResult.getAccessToken().getToken());
if (object.has("id")) {
id = object.getString("id");
Data.fbId = object.getString("id");
}
if (object.has("name")) {
userName = object.getString("name");
;
Data.fbUserName = object.getString("name");
}
if (object.has("email")) {
userEmail = object.getString("email");
Data.fbUserEmail = object.getString("email");
}
if (object.has("birthday")) {
userBirthDay = object.getString("birthday");
}
else {
if (userEmail == null || "".equalsIgnoreCase(userEmail)) {
if (userName != null && !"".equalsIgnoreCase(userName)) {
userEmail = userName + "#facebook.com";
Data.fbUserEmail = Data.fbUserName + "#facebook.com";
} else {
userEmail = id + "#facebook.com";
Data.fbUserEmail = Data.fbId + "#facebook.com";
}
}
}
} catch (Exception e) {
e.printStackTrace();
LogCat.show("Error:" + e.getMessage());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email,birthday,gender");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Toast.makeText(RegisterScreen.this, "CANCEL", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException exception) {
// App code
Toast.makeText(RegisterScreen.this, "" + exception.toString(), Toast.LENGTH_SHORT).show();
}
});

How to get user details from twitter API in android application

I am doing an android app with TwitterLogin Integration using Twitter Api. Here I am not using any twitter 4j and fabric . I am able to get Twitter user name but unable to get Email Id. searched more for this issue, but got nothing with twitter api.
I followed this twitterAPI to login
and this is my code
twitterLoginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
System.out.println("=======twitterlogin success=======");
String username=result.data.getUserName();
getUsertwitteremail();
}
#Override
public void failure(TwitterException exception) {
System.out.println("=======twitterlogin failure==========");
}
});
please someone help me to get the details including email.
First of all make sure Request email addresses from users is checked for your Twitter app
Check out the code below and get the email
mTwitterAuthClient.authorize(this, new com.twitter.sdk.android.core.Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> twitterSessionResult) {
TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
long userId = session.getUserId();
String userNa = session.getUserName();
Log.d("twitter check", userNa + " " + secret);
mTwitterAuthClient.requestEmail(session, new Callback<String>() {
#Override
public void success(Result<String> result) {
Log.d("email", result.data);
// Do something with the result, which provides the email address
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
}
});
}
#Override
public void failure(TwitterException e) {
e.printStackTrace();
}
});
please enable permissions for email access form your twitter app console.
from here
https://apps.twitter.com/app/14057942/permissions

Twitter Integration - How to get user Login Details?

Twitter Integration
I want to get user email id,firstName,lastName after successful login.
#Override
public void onClick(View v)
AppConstants.auth_adapter_Twitter = new SocialAuthAdapter(new ResponseListener());
AppConstants.auth_adapter_Twitter.authorize(getActivity(), SocialAuthAdapter.Provider.TWITTER);
}
private final class ResponseListener implements DialogListener {
#Override
public void onComplete(Bundle values) {
AppConstants.auth_adapter_Twitter.getUserProfileAsync(new ProfileDataListener());
}
#Override
public void onError(SocialAuthError error) {
System.out.println("ResponseListener " + error);
}
#Override
public void onCancel() {
System.out.println("Dialog Cancelled");
}
#Override
public void onBack() {
System.out.println("Dialog Closed by pressing Back Key");
}
private final class ProfileDataListener implements SocialAuthListener<Profile> {
#Override
public void onExecute(String provider, Profile t) {
System.out.println("ProfileDataListener execute");
System.out.println("social_id " + t.getValidatedId());
System.out.println(t.getDisplayName() + "firstname " + t.getFirstName());
System.out.println(" email " + t.getEmail());
System.out.println("lastname " + t.getLastName());
System.out.println("provider " + provider);
}
#Override
public void onError(SocialAuthError e) {
System.out.println("SocialAuthError " + e);
}
}
I am using above code for login in twitter account to get login detail, but there is some problem please help me
You cannot get Email from the twitter OAuth unless or untill your app is whitelisted. For more Info you can visit this Link
If you have whitelisted your app than you can refer to this code to get user information-
Use the access token you get after
accessToken = twitterConnection.getOAuthAccessToken
(requestToken,editPinCode.getText().toString());
oHelper.storeAccessToken(accessToken);
Log.i("Access Token:", accessToken.getToken());
Log.i("Access Secret:", accessToken.getTokenSecret());
long userID = accessToken.getUserId();
User user = twitterConnection.showUser(userID);
user.getName();

Android - Fabric.io Twitter REST API profile image / picture

Does anyone know if there is a way to pull a signed in users profile picture to be placed through the app, to maybe place it on the ActionBar as they navigate around?
hints, tips, examples, downloads all welcome :)
If you can help me, please assume I very little knowledge regarding anything outside basic Java!
Again, thanks people x
You can get a user's profile image by using /1.1/users/show.json. You can refer to REST API URLs for Twitter data.
By extending TwitterApiClient we can retrieve Twitter data from the URL.
class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public UsersService getUsersService() {
return getService(UsersService.class);
}
}
interface UsersService {
#GET("/1.1/users/show.json")
void show(#Query("user_id") Long userId,
#Query("screen_name") String screenName,
#Query("include_entities") Boolean includeEntities,
Callback<User> cb);
}
Next, get the UsersService and call its show method, passing in the defined query parameters. I defined the query parameters based on the ones that are documented.
new MyTwitterApiClient(session).getUsersService().show(12L, null, true,
new Callback<User>() {
#Override
public void success(Result<User> result) {
Log.d("twittercommunity", "user's profile url is "
+ result.data.profileImageUrlHttps);
}
#Override
public void failure(TwitterException exception) {
Log.d("twittercommunity", "exception is " + exception);
}
});
Courtesy: https://twittercommunity.com/t/android-get-user-profile-image/30579/2
This is how I got mine to work:
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
twitterApiClient.getAccountService().verifyCredentials(false,false, new Callback<User>() {
#Override
public void success(Result<User> userResult) {
String name = userResult.data.name;
String profilebannerurl = userResult.data.profileBannerUrl;
String profileurl = userResult.data.profileImageUrl;
}
#Override
public void failure(TwitterException e) {
}
});
I have place this piece of code within my LoginButton callback method:
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) { <insert here> }
I did it with a custom button and this is the code that is executed by it's onClick listener :
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_API_KEY, TWITTER_API_SECRET);
Fabric.with(activity, new Twitter(authConfig));
TwitterCore.getInstance().getApiClient().getAccountService().verifyCredentials(false, false, new com.twitter.sdk.android.core.Callback<User>() {
#Override
public void success(Result<User> result) {
Log.d(TAG, "Twitter log in success");
String userName = result.data.screenName;
int userId = result.data.id;
String pictureUrl = result.data.profileImageUrl;
String coverUrl = result.data.profileBannerUrl;
}
#Override
public void failure(TwitterException e) {
Log.d(TAG, "Twitter log in error : " + e.getMessage());
}
});
I should ask the user to authorize access to your app and log him in if he accepts.

Categories

Resources