Facebook leadgen webhook subscribe doesn't work - facebook-javascript-sdk

I'm Getting success response from my code, getting new leads in facebook, but nothing is posted to webhook.site.
What am I missing??
function subscribe(id, token) {
FB.api('/' + id + '/subscribed_apps',
'post',
{
object: 'page', subscribed_fields: "leadgen", access_token: token, callback_url: "https://webhook.site/93e65665-xxxxxx-xxxx"
}, function (response) {
if (response && response.success) {
console.log(response);
}
});
};
My app is LIVE and has manage_pages & subscribe permissions.

Related

Google OAuth2 in external window Asp.Net Core

I'm trying to implement google oauth external authorization to happen in external browser window. My code looks like below:
$('#signinButton').click(function () {
window.auth2.grantOfflineAccess()
.then(signInCallback)
.catch(error => console.log(error));
});
function start() {
gapi.load('auth2', function () {
window.auth2 = gapi.auth2.init({
client_id: 'CLIENT_Id'
});
});
};
function signInCallback(authResult) {
if (authResult['code']) {
var authCode = authResult['code'];
$.ajax({
type: 'POST',
url: '/Auth/GooglePostredirect',
data: authCode,
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function (result) {
},
processData: false,
});
} else {
}
};
And the question is after getting authToken, how i should call google api to get user info by auth token. Is there any handy libraries for that? I can't find any to request userInfo by token from c#.
Thanks you all in advance!
You can use Google.Apis.Auth library from nuget package manager, and get info from google token, which you get from your front-end
public async Task<IActionResult> ExternalLoginGoogleAsync(string googleTokenId)
{
GoogleJsonWebSignature.ValidationSettings settings = new GoogleJsonWebSignature.ValidationSettings();
settings.Audience = new List<string>() { Configuration["Authentication:Google:ClientId"] };
GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(googleTokenId, settings);
ApplicationUser user = await _userManager.FindByEmailAsync(payload.Email);
if (user == null) //create new user if not exsits
{
user = new ApplicationUser
{
Email = payload.Email,
UserName = payload.Name
};
...
}
return Ok(something);
}

Get AWS Cognito user from ID Token retrieved from Token Endpoint

I am building a React Native app using Expo and AWS Cognito with AWS Amplify, and I am trying to enable signing in with Facebook, Google, etc. using AWS
I can create a user and sign in using Cognito APIs without any issue.
Using third-parties, though, requires using the Expo AuthSession functionality.
The functionality itself works fine, and I am able to get all the way to retrieving the proper tokens from my /oauth2/token endpoint.
However, as far as Amplify is concerned (and I am aware), the user is not signed in, so when I try to get Auth.currentAuthenticatedUser(), null is returned.
// Open URL in a browser
openURL = async (url) => {
let result = await AuthSession.startAsync({ authUrl: url })
this.getTokenbyCode(result.params.code)
};
getTokenbyCode = async (code) => {
const details = {
grant_type: 'authorization_code',
code,
client_id: '10eavoe3ufj2d70m5m3m2hl4pl',
redirect_uri: AuthSession.getRedirectUrl()
}
const formBody = Object.keys(details)
.map(
key => `${encodeURIComponent(key)}=${encodeURIComponent(details[key])}`
)
.join("&");
await fetch(
'https://presentor.auth.us-west-2.amazoncognito.com/oauth2/token',
{
method: "POST",
headers: {
'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: formBody
}
)
.then(async (res) => {
console.log('res: ', res);
let resJSON = await res.json();
let idToken = await resJSON.id_token;
let decodedToken = jwt(idToken);
let userData = {
Username : decodedToken["cognito:username"],
Pool : Auth.userPool
}
})
.catch(error => {
console.log('error: ', error);
});
}
When I decode the token, I see the payload as I expect, but if I want to, for example, utilize the APIs to refresh the token if it expires, I have to workaround manually (check for expiration and retrieve a new token if it's expired).
Am I missing something basic?
Ok, I figured it out. Not sure if this is the right path, but it's pretty clean and it works, so I'm good with it.
Create CognitoIdToken, CognitoAccessToken, and CognitoRefreshToken objects using amazon-cognito-identity-js
Create a user session from those tokens
Create a user from that user session
await fetch(
'TOKEN ENDPOINT',
{
method: "POST",
headers: {
'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: formBody
}
)
.then(async (res) => {
const IdToken = new CognitoIdToken({ IdToken: tokenRequestJson.id_token });
const AccessToken = new CognitoAccessToken({ AccessToken: tokenRequestJson.access_token });
const RefreshToken = new CognitoRefreshToken({ RefreshToken: tokenRequestJson.refresh_token })
try {
let userSession = new CognitoUserSession({ IdToken, AccessToken, RefreshToken });
console.log('userSession: ', userSession);
const userData = {
Username: userSession.idToken.payload.email,
Pool: userPool
};
console.log('userData: ', userData);
cognitoUser = new CognitoUser(userData);
cognitoUser.setSignInUserSession(userSession);
cognitoUser.getSession((err, session) => { // You must run this to verify that session (internally)
if (session.isValid()) {
console.log('session is valid');
this.setState({user: cognitoUser})
this.props.navigation.navigate('AuthLoading')
} else {
console.log('session is not valid: ', session);
}
})
}
catch (FBSignInError) {
console.log('FBSignInError: ', FBSignInError)
}
})
.catch(fetchError => console.log('fetchError: ', fetchError))

Redirect_uri mismatch in fetch and gapi

working on connecting users to google, and we're trying to get their access and refresh tokens from the google api, and we're getting an issue exchanging the OAuth2 Code for tokens. Both sets of code have the same error.
I initialize the gapi client and fill in the information needed like so:
gapi.load('client:auth2', _ => {
gapi.client.init({
'apiKey': 'omitted for security',
clientId: 'omitted for security',
'scope': 'https://www.googleapis.com/auth/drive',
'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
}).then(_ => {
gapi.auth2.getAuthInstance().grantOfflineAccess().then(resp => {
if(resp.code){
gapi.client.request({
path: 'https://www.googleapis.com/oauth2/v4/token',
method: 'post',
params: {code: resp.code},
body: {
code: resp.code,
client_id: opts.clientId,
client_secret: 'omitted for security',
grant_type: 'authorization_code',
redirect_uri: 'omitted for security',
access_type: 'offline'
},
}).then((onfulfill, onreject, context) => {
console.log('fulfilled', onfulfill);
console.log('rejected: ', onreject);
console.log('context', context);
}).catch(err => console.error(err.body));
}
});
});
});
What I'm trying to do in the .then() is to call the token endpoint to exchange the code in the response for a refresh and access token to store in my back end and the user's local storage.
I get this error response from both versions of the code. (better, more reliable code is provided here.)
{ "error": "redirect_uri_mismatch", "error_description": "Bad
Request" }
I also have a backend setup stashed as a last resort that accepts the code from gapi.auth2.getAuthInstance().grantOfflineAccess() calls the token endpoint, and returns the access_token and refresh_token to the client.
This code is similar, but not quite. instead of using the google api library, I used fetch, and it works fine. (Fetch and XHR on the front end have the same issues as the gapi.client.request function....)
const gConfig = require('./basic.json');
const scopes = ['https://www.googleapis.com/auth/drive'];
const { client_id, client_secret, redirect_uris } = gConfig.web;
const authClient = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
app.post('/', (req, res) => {
const { code } = req.body;
console.log('Received Code From Request: ', code);
let data = { code , client_id, client_secret,redirect_uri: redirect_uris[0], grant_type: 'refresh_token'};
let encodedParams = Object.keys(data).map(k => encodeURIComponent(k) + '=' + encodeURIComponent(data[k])).join('&');
fetch(
`https://www.googleapis.com/oauth2/v4/token?code=${code}`,
{ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: encodedParams }
).then((res) => {
console.log('called the api with fetch');
console.dir(res.json());
});
authClient.getToken(code, (err, token) => {
if (err) {
console.error(err);
res.status(500).json(err);
}
// console.dir(token);
console.log('TOKEN: =>', token);
res.json(token);
});
});
Is there anyone that's done this on the front end successfully?
You can't get a refresh token in a browser. Your example code would only work on a server. To do oauth at the client you should request "token" instead of "code".

Skype Web API sing in issues using login and password

I have issue with signing into Skype account using login and password. I use code from Skype Web SDK docs:
<script>
// Call the application object
var config = {
apiKey: 'a42fcebd-5b43-4b89-a065-74450fb91255', // SDK
apiKeyCC: '9c967f6b-a846-4df2-b43d-5167e47d81e1' // SDK+UI
};
var Application;
Skype.initialize({ apiKey: config.apiKey }, function (api) {
window.skypeWebApp = new api.application();
window.skypeWebApp.signInManager.signIn({
username: "test#yandex.ru",
password: "12345678"
}).then(function () {
console.log('Signed in successfully.');
}, function (error) {
console.log('Failed to sign in.');
}).then(reset);
}, function (err) {
console.log(err);
alert('Cannot load the SDK.');
});
The POST request is sent, but API returns nothing. Can anybody advice?

Can't login via facebook API

I'm using the Javascript SDK to allow the user to login to facebook, retrieve their friends profile pictures, and then finally post a message on the logged in users wall. Problem is I keep getting an error, "Error while loading page from Pencils of Promise," when the user has to authorize the application.
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({appId: '154058871279888', status: true, cookie: true,
xfbml: true});
console.log(FB.getLoginStatus());
$('div.voice-btn:eq(0)').click(function() {
FB.login(function(response) {
if(response.session) {
FB.api('/me', function(data) {
console.log(data);
});
donateVoiceSlider();
}
});
});
$('#voice-step-2-btn').click(function() {
var body = 'Test Facebook post';
FB.api('/me/feed', 'post', { body: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response);
}
});
});
// Donate Voice Content Slider
function donateVoiceSlider() {
var $ul = $('#donatevoice');
var cur_left = parseInt($ul.css('left'));
var li_width = 980;
$ul.animate( {'left': cur_left-li_width+'px'} );
}
</script>
Please help!
My friend who had created the application did NOT set the site URL. After doing that, everything ran smoothly.