How to get user firstname from Facebook using access Token? - facebook

I'm trying to get some facebook current user basic information.
Here is my code. (It's Oracle PL/SQL)
URL := 'http://graphm-facebook.maxapex.ws/me?fields(id,name,email)&access_token=' || Token;
Method := 'GET';
Response := apex_web_service.make_rest_request(p_url => URL, p_http_method => Method);
But I'm getting the html answer : 503 Service Temporarily Unavailable
I'm sure it's not related to any service unavailability. Because when I run the following command, it works successfully.
URL := 'http://graphm-facebook.maxapex.ws/me?access_token=' || Token;
Can anyone help please ? Thanks.

Related

Salesforce Rest API call from typescript using axios

I am trying to fetch records from a scratch org using the tooling API provided by salesforce and user access token. Lets say
accesstoken = "abcd"
url = "https://example.my.salesforce.com/services/data/v49.0/tooling/query?q=SELECT+Id,Name+FROM+Account"
I have used axios node module to make the API call as given below
const options = {
headers: {
"Authorization": "Bearer " + accessToken,
"Content-Type": "application/json"
}
};
axios.get(url, options).then(response => {
console.log(response.status);
if(response.status == 200){
console.log(response.data);
} else {
//do something else
}
});
The call responds with a status 200 i.e the request provided a response. But instead of correct records from Account object, I get the login html page
' Login | Salesforcehtml{visibility:
hidden;}a{color:#0070d2;}body{background-color:#F4F6F9;}#content,.container{background-color:#ffffff;}#header{color:#16325c;}body{display:
table;
width:100%;}#content{margin-bottom:24px;}#wrap{height:100%;} html { visibility: hidden; } if (self == top)
{document.documentElement.style.visibility = 'visible';} else
{document.write = ''; top.location = self.location;
setTimeout(function(){document.body.innerHTML='';},
1);window.self.onload=function(evt){document.body.innerHTML='';};}var
SFDCSessionVars={"server":"https://test.salesforce.com/login/sessionserver212.html","im":true,"ah":"active","save":"Save","saveOne":"Save
1 Change","sum":"#p# Saved Usernames","iaac":false,"hac":"Choose a
Username","suo":"1 Saved Username","title":" |
Salesforce","saveMany":"Save #p#
Changes","lpt":"Login","lllbl":"Lightning
Login","host":"test.salesforce.com","le":false,"heu":"Edit Username
List","ic":false,"lh":false,"ur":"https://business-data-8148-dev-ed.cs79.my.salesforce.com","hidp":"Log
In Using","ih":"inactive","dc":"Username removed. Click Save to Commit
Changes."};LoginHint.hideLoginForm();Edit ListSaveCancel
UsernamePassword Caps Lock is on.Remember
meForgot Your
Password?To go to your company's login
page, enter the custom domain name.Custom Domainhttps://domain.my.salesforce.comContinueBackLog In with a Different
Username© 2020
salesforce.com, inc. All rights reserved.<iframe frameborder="0" src="/s.gif" id="marketing"
name="marketing" scrolling="no" title="Marketing"
tabindex="-1"sandbox="allow-forms allow-pointer-lock allow-popups
allow-same-origin allow-scripts" >LoginLoginHint.getSavedIdentities(false);function
handleLogin(){document.login.un.value=document.login.username.value;document.login.width.value=screen.width;document.login.height.value=screen.height;document.getElementById("Login").disabled=true;document.getElementById("login_form").submit();}function
lazyload(){document.getElementById("pwcapsicon").src="/img/icon/capslock_blue.png";document.getElementById("marketing").src="https://c.salesforce.com/login-messages/promos.html";}loader();
'
Does anyone know what am I missing in here? According to salesforce documentation
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_query.htm
the accessToken in the header should be enough to make the API call.
Note: I gained the access token by running
sfdx force:user:display -u <username>
Your query is wrong. You selected Tooling API service which is for metadata (info about classes, triggers, objects, fields, deployments, running unit tests...). If you want to query Accounts - that's normal data. Try just /services/data/v49.0/query?q=SELECT+Id,Name+FROM+Account
I don't think you need Content-Type header in there. You don't POST anything. At best you can send Accept (application/json, application/xml)
Are you sure the session id was valid? As in you could go to the org, Setup -> Session management, see it there? Or in the user's login history?
It might be that your SF admin did something nasty like locking sessions down to IP from which they originated or maybe the user doesn't have API access... See if you can create your call in Workbench -> Utilities -> REST Explorer first, then go back to Axios?

How to call the Dynamics 365 OData endpoint to get a list of users from Delphi

If I authenticate to D365 via the web browser, and then enter the following URL:
https://mytenantcode.crmserver.dynamics.com/api/data/v8.2/systemusers?$select=systemuserid,lastname,firstname,title&$top=3
I can get back the top 3 records with the data I requested.
I seem to be able to authenticate to D365 in code as per my other question (which I answered), and have an access token but I cannot seem to be able to determine how to setup the TRESTRequest object so that the Execute works.
Currently, it always returns a 401 Unauthorized error.
I've tried setting the TOAuth2Authenticator.AccessToken property to the token I received from D365, and then set the TRESTClient.Authenticator property to the TOAuth2Authenticator and the TRESTQuest.Client to the TRESTClient, which is how the examples work in the RESTDemos project, but I still get 401.
This is the last example of the code I tried, that should have worked, given that all the REST objects are linked correctly:
RESTClient.BaseURL := 'https://**mytenantcode**.**crmserver**.dynamics.com/api/data/v8.2/';
RESTRequest.Method := TRESTRequestMethod.rmGET;
RESTRequest.Resource := 'systemusers?$select={SELECT}&$top={TOP}';
RESTRequest.AddParameter('SELECT', 'systemuserid,'+
'lastname,'+
'firstname,'+
'title');
RESTRequest.AddParameter('TOP', '3');
RESTRequest.Execute;
I finally got it to return the correct information using the following code for calling the Web API:
RESTClient.BaseURL := 'https://mytenantcode.crmserver.dynamics.com/';
RESTRequest.Resource := 'api/data/v8.2/systemusers?$select=int_staffnumber,'+
'_int_serviceareaid_value,'+
'_territoryid_value,'+
'lastname,'+
'firstname,'+
'systemuserid,'+
'title';
RESTRequest.AddAuthParameter('Authorization', 'Bearer ' + AToken, TRESTRequestParameterKind.pkHTTPHEADER,
[TRESTRequestParameterOption.poDoNotEncode]);
RESTRequest.Execute;
The important change was the addition of the Authorization header parameter, and not using the Params for the query parameters as it seems the REST Client Library doesn't actually do it correctly.
Also had to change the ResourceURI for the token authorization to match the https://mytenantcode.crmserver.dynamics.com URL being used for the method call.

what is redirect_uri not supported error in facebook oauth

Can we do out of band authentication (oob) with facebook where we specify redirect_uri to be urn:ietf:wg:oauth:2.0:oob ?
Google clearly mentions it as one of the options:
https://developers.google.com/identity/protocols/OAuth2InstalledApp#formingtheurl
I am trying to do it with facebook and basically using R studio (for running a script on remote server).
I always get an error:
The redirect_uri URL is not supported
when I point to the url:
https://www.facebook.com/dialog/oauth?client_id=1256802200999873&scope=ads_management&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code
to get an authentication code.
How do I fix this?
Note: I am using package httr and here'w what my 2 authentication code looks like:
app <- oauth_app('facebook', 'ID', 'SECRET')
Sys.setenv("HTTR_SERVER_PORT" = "1410/")
tkn <- oauth2.0_token(
oauth_endpoints('facebook'),
app,
scope = 'ads_management',
type = 'application/x-www-form-urlencoded',
use_oob = TRUE,
cache = FALSE)

Golang Facebook Graph API App Engine

I'm using huandu/facebook for Golang to access the FB API. https://github.com/huandu/facebook
This works really well locally but when I try to run from the Google App Engine environment, I can't get it to run.
I used this code locally:
res, err := fb.Get("/me", fb.Params{
"fields": "id,first_name,last_name,name",
"access_token": usertoken,
})
In the documentation (link above) they do mention the App Engine environment but I can'f figure out how to ge this to work with the fb.Get convention.
Thanks.
Edit
Almost got it to work!:
// create a global App var to hold app id and secret.
var globalApp = fb.New("<appId>", "<appSecret>")
session := globalApp.Session(usertoken) //User token here
context := appengine.NewContext(r) //Not sure what r should be...
session.HttpClient = urlfetch.Client(context)
res, err := session.Get("/me", nil)
if err := json.NewEncoder(w).Encode(res); err != nil {
panic(err)
}
If I do this I get back the Id and name. Now all I need to do is request the other parameters. Do I do this in the r parameter to the app engine context?
To answer the last question asked, the appengine.NewContext(r) function takes a *http.Request as a parameter, but this refers to the current request, the one your code is executing in. You can use r.URL.Query() if you wanted to get the query parameters that were sent to this request.
If you want to send parameters in another request, like the one to the Facebook API, you can include them directly in the URL you pass to session.Get(). You can use url.Values.Encode if you want to build a query string from a map of values. If you need to make a request using a method other than GET, such as to an API method that expects JSON, you can use http.NewRequest eg.
session.HttpClient = urlfetch.Client(context)
request, err := http.NewRequest("PUT", url, strings.NewReader("{ "someProperty": 1234 }"))
response, err := session.Do(request)

How to do an external redirect in Flask framework

I want to do an external redirect in Flask so that, when the redirect() function is used and the page is being redirected, the url in the browser should change. I am aware that the browser has to send a second request to the server.
I have built a route so that when I request for localhost/profile/342/ or localhost/profile/342/wrong-username/, I want the server to serve the URL localhost/profile/342/right-username/ with the URL changed in the browser. Here is the code that I have so far:
#appHandler.route('/profile/<int:userid>/', defaults = {'username' : None})
#appHandler.route('/profile/<int:userid>/<username>/')
def profile(userid, username):
user = User.query.filter_by(id = userid).first()
if username != user.username:
redirect(url_for('profile', userid = userid, username = user.username), code = 307)
return render_template('profile/profile.html', user = user)
I tried giving code = 301 (though I was not even sure if it would work) as an argument for the redirect() function but it didn't work (the URL remained the same, but the page was served).
Any one has any suggestion?
You need to return the response object produced by redirect():
if username != user.username:
return redirect(url_for('profile', userid=userid, username=user.username),
code=301)
I picked code=301 here; Stack Overflow uses that status code for username redirects as well. You want browsers to use the 'current' username URL directly, not keep re-using the incorrect username.