Could anyone Show me an example of your finished Parameters and Endpoint for a Twitter Reply maybe with a Screenshot? Because i dont understand exactly what to type in my Params and, do I got to change anything in the Pre-request Script?
Kind regards Alex
For the Params for https://api.twitter.com/2/tweets I tried:
Key : in_reply_to
Value : tweet_id
And the Result was "errors"
"message": "The query Parameters [in_reply_to] is not one of [expantions,tweet.fields,media.fields,poll.fields,place.fields,user.fields]"
"title":"Invalid Request"
"detail": "One or more Parameters to your request Was invalid.",
"type":"https://api.twitter.com/2/problems/invalid-request"
From the twitter's documentation
query parameter ids is required. You missed that parameter.
I will get tweet this demo
https://twitter.com/pascal_bornet/status/1604754709000200193
BY Postman
Full code by node.js
#1 Get an access token by API Key and API secret
#2 Get text by access token
Credential in config.json
{
"API_KEY" : "7hK your API Key GND",
"API_KEY_SECRET" : "Zr4 your API Key secret 0qX0"
}
Save as get-tweet.js
const axios = require('axios')
const config = require('./config.json');
const getAccessToken = async () => {
try {
const resp = await axios.post(
'https://api.twitter.com/oauth2/token',
'',
{
params: {
'grant_type': 'client_credentials'
},
auth: {
username: config.API_KEY,
password: config.API_KEY_SECRET
}
}
);
// console.log(resp.data);
return Promise.resolve(resp.data.access_token);
} catch (err) {
// Handle Error Here
console.error(err);
return Promise.reject(err);
}
};
const getTweetText = async (token, tweet_id) => {
try {
const resp = await axios.get(
`https://api.twitter.com/2/tweets?ids=${tweet_id}`,
{
headers: {
'Authorization': 'Bearer '+ token,
}
}
);
return Promise.resolve(resp.data);
} catch (err) {
// Handle Error Here
console.error(err);
return Promise.reject(err);
}
};
getAccessToken()
.then((token) => {
console.log(token);
getTweetText(token, '1604754709000200193')
.then((result) => {
console.log(result.data[0].text);
})
})
Get Result
$ node get-tweet.js
AAAAAksadf--very long access token in here ----JlIMJIIse
Is this the future of Christmas shopping?
Credit: Nike
#innovation #AR # VR #AugmentedReality https://~~~
Here is my code
import { Auth } from 'aws-amplify';
function forgotPassword() {
Auth.forgotPassword(phoneNumber)
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
});
}
function forgotPasswordSubmit() {
Auth.forgotPasswordSubmit(
phoneNumber,
code,
password
)
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
});
}
I am using Auth.forgotPassword from amplify sdk. When I submit phone number that is not existed in Cognito, Auth.forgotPassword function will not throw any error. I wonder if this function will check user existence? If not, any other method I can use to check it?
Thanks.
I'm trying to authenticate user using facebook through firebase:
Login
but getting [object Object] error:
Loginfailed
My code for login is:
facebookLogin(): void {
this.fb.login(['email']).then( (response) => {
const facebookCredential = firebase.auth.FacebookAuthProvider
.credential(response.authResponse.accessToken);
firebase.auth().signInWithCredential(facebookCredential)
.then((success) => {
alert("Firebase success: ");
this.userProfile = success;
})
.catch((error) => {
alert(error);
});
}).catch((error) => {alert(error); });
}
All of the documentation I see requests both the email and the public_profile in the login function, perhaps this is the error.
this.fb.login(['email', 'public_profile']).then( (response) => {
I am finishing up test for my actions test and am running into one test failing. The weird thing what is causing it to fail passes in other test.
import { browserHistory } from 'react-router';
//Passing action
export function signinUser({ email, password }) {
return function(dispatch) {
// Submit email/password to the server
return axios.post(`${ROOT_URL}/signin`, { email, password })
.then(response => {
// If request is good...
// - Update state to indicate user is authenticated
dispatch({ type: AUTH_USER });
// - Save the JWT token
localStorage.setItem('token', response.data.token);
localStorage.setItem('refreshToken', response.data.refreshToken);
// - redirect to the route '/feature'
browserHistory.push('/feature');
})
.catch(() => {
// If request is bad...
// - Show an error to the user
dispatch(authError('Bad Login Info'));
});
}
}
//failing action
export function confirmationEmail(token){
return function(dispatch) {
return axios.post(`${ROOT_URL}/confirmation`, { token })
.then(response => {
//dispatch(emailWasSent(response.data.return_msg));
// If request is good...
// - Update state to indicate user is authenticated
dispatch({ type: AUTH_USER });
// - Save the JWT token
localStorage.setItem('token', response.data.token);
localStorage.setItem('refreshToken', response.data.refreshToken);
// - redirect to the route '/feature'
browserHistory.push('/feature');
})
.catch(response => {
console.log(response)
dispatch(authError(response.data.error));});
}
}
The 2 methods are almost identical past the params passed. Both test are almost exactly the same also
describe('signinUser', () => {
it('has the correct type and payload', () => {
var scope = nock(ROOT_URL).post('/signin',function(body) {return { email: 'test#gmail.com', password: "test"}}).reply(200,{ token: "majorbs123" , refreshToken: "bs123"});
const store = mockStore({});
return store.dispatch(actions.signinUser('test#gmail.com',"test")).then(() => {
const act = store.getActions();
const expectedPayload = { type: AUTH_USER }
expect(act[0].type).to.equal(expectedPayload.type);
expect(localStorage.getItem("token")).to.equal("majorbs123");
expect(localStorage.getItem("refreshToken")).to.equal("bs123");
})
});
});
describe('confirmationEmail', () => {
it('has the correct type and payload', () => {
var scope = nock(ROOT_URL).post('/confirmation',function(body) {return { token: 'tokenbs123'}}).reply(200,{ token: "majorbs123" , refreshToken: "bs123"});
const store = mockStore({});
return store.dispatch(actions.confirmationEmail("tokenbs123")).then(() => {
const act = store.getActions();
const expectedPayload = { type: AUTH_USER }
expect(act[0].type).to.equal(expectedPayload.type);
expect(localStorage.getItem("token")).to.equal("majorbs123");
expect(localStorage.getItem("refreshToken")).to.equal("bs123");
})
});
});
The first test for signin passes no problem and the browserHistory.push has no problems. The second test throws this error stack.
SecurityError
at HistoryImpl._sharedPushAndReplaceState (/home/mikewalters015/client/node_modules/jsdom/lib/jsdom/living/window/History-impl.js:87:15)
at HistoryImpl.pushState (/home/mikewalters015/client/node_modules/jsdom/lib/jsdom/living/window/History-impl.js:69:10)
at History.pushState (/home/mikewalters015/client/node_modules/jsdom/lib/jsdom/living/generated/History.js:71:31)
at /home/mikewalters015/client/node_modules/history/lib/BrowserProtocol.js:87:27
at updateLocation (/home/mikewalters015/client/node_modules/history/lib/BrowserProtocol.js:82:3)
at pushLocation (/home/mikewalters015/client/node_modules/history/lib/BrowserProtocol.js:86:10)
at /home/mikewalters015/client/node_modules/history/lib/createHistory.js:117:15
at /home/mikewalters015/client/node_modules/history/lib/createHistory.js:90:9
at next (/home/mikewalters015/client/node_modules/history/lib/AsyncUtils.js:51:7)
at loopAsync (/home/mikewalters015/client/node_modules/history/lib/AsyncUtils.js:55:3)
at confirmTransitionTo (/home/mikewalters015/client/node_modules/history/lib/createHistory.js:80:31)
at transitionTo (/home/mikewalters015/client/node_modules/history/lib/createHistory.js:100:5)
at Object.push (/home/mikewalters015/client/node_modules/history/lib/createHistory.js:131:12)
at Object.push (/home/mikewalters015/client/node_modules/history/lib/useBasename.js:73:22)
at Object.push (/home/mikewalters015/client/node_modules/history/lib/useQueries.js:81:22)
at /home/mikewalters015/client/src/actions/authActions.js:106:2
at process._tickCallback (internal/process/next_tick.js:103:7)
It has thrown me for a loop cause the code is so similar and the line throwing the issue the react-router push method is used in other methods also and produces no problems.
I read the document, both on github and Facebook developers docs.
There is only sample, nothing more. No API document.
The code to make a Graph API request is
const infoRequest = new GraphRequest(
'/me',
null,
this._responseInfoCallback,
);
And the callback
_responseInfoCallback(error: ?Object, result: ?Object) {
if (error) {
alert('Error fetching data: ' + error.toString());
} else {
alert('Success fetching data: ' + result.toString());
}
}
And here is the function to make a Graph API request
testRequestGraphAPI(){
const infoRequest = new GraphRequest(
'/me',
null,
this._responseInfoCallback,
);
new GraphRequestManager().addRequest(infoRequest).start();
}
However, I can't find any further document. I have no idea what each parameters do.
The result for these codes above is this.
I also don't know how to get the result.
However, when I try to modify '\me' to 'me?fields=id,name', It failed.
Although I have asked for permission
<LoginButton
publishPermissions={["publish_actions,user_birthday, user_religion_politics, user_relationships, user_relationship_details, user_hometown, user_location, user_likes, user_education_history, user_work_history, user_website, user_managed_groups, user_events, user_photos, user_videos, user_friends, user_about_me, user_status, user_games_activity, user_tagged_places, user_posts, user_actions.video, user_actions.news, user_actions.books, user_actions.music, user_actions.fitness, public_profile, basic_info"]}
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
meow_accesstoken = data.accessToken
alert(meow_accesstoken.toString())
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
But it does not print out what error, just object Object.
So, the problem is that I don't understand the sample code which Facebook provide with no explanation.
Here is my question that I really need you help me:
First at all, please check the javascript code that I currently looking at?
How to use graph API in react-native-fbsdk to retrieve some user information (example: full name) and successfully display it (use alert) ?
What each parameters in GraphRequest() do ?
What is the structure of error object and result object in _responseInfoCallback ?
SOLUTION
Thanks to #Samuel answer, I have updated my code
testRequestGraphAPI: function(){
const infoRequest = new GraphRequest(
'/me',
{
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name' // what you want to get
},
access_token: {
string: meow_accesstoken.toString() // put your accessToken here
}
}
},
this._responseInfoCallback // make sure you define _responseInfoCallback in same class
);
new GraphRequestManager().addRequest(infoRequest).start();
}
And the callback
_responseInfoCallback: function(error: ?Object, result: ?Object) {
alert("meow response");
if (error) {
alert('Error fetching data: ' + error.toString());
console.log(Object.keys(error));// print all enumerable
console.log(error.errorMessage); // print error message
// error.toString() will not work correctly in this case
// so let use JSON.stringify()
meow_json = JSON.stringify(error); // error object => json
console.log(meow_json); // print JSON
} else {
alert('Success fetching data: ' + result.toString());
console.log(Object.keys(result));
meow_json = JSON.stringify(result); // result => JSON
console.log(meow_json); // print JSON
}
}
*Note: For console.log(), you need to use "Debug JS remotely" then open Chrome developer tools to see the log.
Unfortunately the react-native-fbsdk documentation is not updated and the examples do not work well.
I got the same problem and I solved it by try and error.
To solve your problem you'll need to change your GraphRequest adding params and fields to it like this:
<LoginButton
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
let accessToken = data.accessToken
alert(accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error)
alert('Error fetching data: ' + error.toString());
} else {
console.log(result)
alert('Success fetching data: ' + result.toString());
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
You'll need to enable the Remote JS Debug to see the console.log() info.
https://facebook.github.io/react-native/docs/debugging.html
And probably you need to get some permissions to get more info than names and email so it's a good idea to look the Facebook Graph API Documentation: https://developers.facebook.com/docs/graph-api/overview/
Reference:
https://github.com/facebook/react-native-fbsdk/issues/105#issuecomment-206501550
Here is an example of a custom button if you want to make one :)
FbLoginButton() {
LoginManager
.logInWithReadPermissions(['public_profile'])
.then(function (result) {
if (result.isCancelled) {
alert('Login cancelled');
} else {
AccessToken
.getCurrentAccessToken()
.then((data) => {
let accessToken = data.accessToken
alert(accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error)
alert('Error fetching data: ' + error.toString());
} else {
console.log(result)
alert('Success fetching data: ' + result.toString());
}
}
const infoRequest = new GraphRequest('/me', {
accessToken: accessToken,
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name'
}
}
}, responseInfoCallback);
// Start the graph request.
new GraphRequestManager()
.addRequest(infoRequest)
.start()
})
}
}, function (error) {
alert('Login fail with error: ' + error);
});
}
Thank you #Samuel.
I finally succeed to get user information from Facebook login because of your help!
But I struggled to figure out how can I get username and email literally from the result object cause I am a newbie in React & Javascript.
P.S. result["name"] is the point because it is object!!
So I added some code to yours for other people like me.
If you don't like using your code, just tell me that.
<LoginButton
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
let accessToken = data.accessToken
alert(accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error)
alert('Error fetching data: ' + error.toString());
} else {
console.log(result)
// Here's my code
alert('Success fetching data: ' + result["name"].toString() +
", " + result["email"].toString());
/*
if(your DB already got this email or something unique) {
// SignIn()
}
// when your DB doesn't have this email
else {
// Do signUp() with this infomation and SignIn()
}
*/
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
My code was not retriving the user email, if you are having the same problem, just put 'email' in parameter's logInWithPermission
Not Working
LoginManager.logInWithPermissions(['public_profile']).then(...)
Working
LoginManager.logInWithPermissions(['public_profile', 'email']).then(...)
All Function
loginWithFacebook = () => {
LoginManager.logInWithPermissions(['public_profile', 'email']).then(
login => {
if (login.isCancelled) {
console.log('Login Cancelado');
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
const accessToken = data.accessToken.toString()
this.getInfoFromToken(accessToken)
})
}
},
error => {
console.log('Erro no login ', console.error(error)
)
}
)
}
getInfoFromToken = token => {
const PROFILE_REQUEST_PARAMS = {
fields: {
string: 'id, name, first_name, last_name, birthday, email'
},
}
const profileRequest = new GraphRequest('/me', { token, parameters: PROFILE_REQUEST_PARAMS },
(error, result) => {
if (error) {
console.log('Login Info has an error:', error)
} else {
console.log(result)
}
},
)
new GraphRequestManager().addRequest(profileRequest).start()
}
try this
import { GraphRequest, GraphRequestManager } from 'react-native-fbsdk';
export const GetInfoUSer = () => {
return new Promise((resolve, reject) => {
const infoRequest = new GraphRequest('/me', null, ((error, result) => {
if (error) {
reject(error)
} else {
resolve(result)
}
}))
new GraphRequestManager().addRequest(infoRequest).start();
})
}
and then
onLoginConFacebook = () => {
LoginManager.logInWithReadPermissions(['public_profile']).then(result => {
if (result.isCancelled) {
console.log(':(')
} else {
AccessToken.getCurrentAccessToken().then((data) => {
let myAccessToken = data.accessToken.toString();
GetInfoUSer().then(response => {
console.log(response)
}).catch(error => {
console.log(error)
})
}
).catch(error => {
console.log(':(')
})
}
})
}