Authenticating with Facebook Graph API & Parsing JSON Reviews from a Facebook Page - json

I am having trouble authenticating and parsing.
get Facebook Graph api page review
I have tried to submit the app for review and request manage_page access but I get an error:
"Invalid Scopes: manage_pages. This message is only shown to developers. Users of your app will ignore these permissions if present. Please read the documentation for valid permissions at: developers.facebook.com/docs/facebook-login/permissions" and possibly the API is deprecated
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<title>Ilan's Test</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div id="results">
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script>
var myurl = "http://graph.facebook.com/v3.3/FinancialSanityNow/ratings";
var getToken = function(req, res) {
var facebookToken = req.headers['facebooktoken'];
//TODO : check the expirationdate of facebooktoken
if(facebookToken) {
var path = 'https://graph.facebook.com/v3.3/FinancialSanityNow?access_token=' + facebookToken;
request(path, function (error, response, body) {
var facebookUserData = JSON.parse(body);
if (!error && response && response.statusCode && response.statusCode == 200) {
if(facebookUserData && facebookUserData.id) {
var accessToken = jsonWebToken.sign(facebookUserData, jwtSecret, {
//Set the expiration
expiresIn: 86400
});
res.status(200).send(accessToken);
} else {
res.status(403);
res.send('Access Forbidden');
}
}
else {
console.log(facebookUserData.error);
//console.log(response);
res.status(500);
res.send('Access Forbidden');
}
});
res.status(403);
res.send('Access Forbidden');
}
};
$.ajax({
url: myurl,
headers: {
'access_token':'xxxxxaccesstokenherexxxxx',
},
method: 'GET',
dataType: 'json',
success: function(data){
$.each(data.reviews, function(i, item) {
// Store each review object in a variable
var reviewdata = item.data.reviews;
// Append our result into our page
$('#results').append('test:' + reviewdata);
});
}
});
</script>
</body>
</html>
I just want to know if this is even possible through pages/ratings api from facebook
https://developers.facebook.com/docs/graph-api/reference/page/ratings/

Most permissions need review before you can use them. Without review, they will only work for users with a role in the App, and you need to keep the App in dev mode. If you put it live, unapproved permissions will not work at all.
Also, you have to use a Page Token of the Page in question to get reviews, you get a Page token by using the /me/accounts?fields=access_token endpoint, with a User Token that includes the manage_pages permission.
More information about Tokens: https://developers.facebook.com/docs/facebook-login/access-tokens/

Related

Re-render Django view based on jQuery-initiated AJAX POST request

The problem I face has to do with re-rendering a Django view based on a context that is updated by an AJAX post request that is initiated by jQuery. The reason why I need an AJAX request is because I need to modify the page UI without refreshing the page, which is critical to what I want to build.
So far, I am able to trigger the AJAX post request to the URL of the same page where the update is supposed to occur, and the Django view.py adequately registers that it has been called. However, although I can reproduce the ability to update the Django view's context, the view does not seem to re-render an updated HTML based on the updated context.
The thread at How to re-render django template code on AJAX call seems to describe exactly my problem. The top-voted solution of this thread is to have a conditional that is only triggered in case of an AJAX call that renders only a partial template (not the full HTML page) - a partial template that corresponds to the component to be updated. This is what's being reproduced in the code snippets below, but the HTML does not change based on the updated context.
Attached are the relevant code snippets for a simple attempt where the page displays <h1>2<h1/> by default and is meant to be updated to 5 when we click anywhere on the window. Clicking anywhere on the window triggers the AJAX call, but the page is not updated with <h1>5<h1/>.
view.py
def index(request):
context = {"num": 2}
if (request.method == "POST"):
print("View hit due to AJAX call!") # // THIS CAN BE TRIGGERED ADEQUATELY!
context["num"] = 5
return render(request, 'num.html', context)
return render(request, 'override.html', context)
override.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="{% static 'js/num.js' %}" defer></script>
<title>Title</title>
</head>
<body class="">
<div class="">
{% include 'num.html' %}
</div>
</body>
</html>
num.html
<h1>{{ num }}</h1>
num.js
var postUrl = "http://localhost:8000/";
function getCSRFToken() {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, 10) == ('csrftoken' + '=')) {
cookieValue = decodeURIComponent(cookie.substring(10));
break;
}
}
}
return cookieValue;
}
$('html').click(function(){
values = [1, 2];
var jsonText = JSON.stringify(values);
$.ajax({
url: postUrl,
headers: { "X-CSRFToken": getCSRFToken(), "X-Requested-With": "XMLHttpRequest" },
type: 'POST',
data: jsonText, // note the data, jsonText, does not really matter. The Django context gets updated to 5 instead of 2.
traditional: true,
dataType: 'html',
success: function(result){
console.log("AJAX successful") // THIS CAN BE TRIGGERED ADEQUATELY!
}
});
});
If this part of code
success: function(result){
console.log(result)
}
prints the content of num.html you can change the num.html to get h1 id as
num.hml
<h1 id="numberToChange">{{ num }}</h1>
and in your num.js
$('html').click(function(){
values = [1, 2];
var jsonText = JSON.stringify(values);
$.ajax({
url: postUrl,
headers: { "X-CSRFToken": getCSRFToken(), "X-Requested-With": "XMLHttpRequest" },
type: 'POST',
data: jsonText, // note the data, jsonText, does not really matter. The Django context gets updated to 5 instead of 2.
traditional: true,
dataType: 'html',
success: function(result){
document.getElementById("numberToChange").innerHTML = result}
});
});

import data into H2 via API

I'm a programming beginner. . Now I'm having a problem that I struggle to solve ... I want to write a numeric data in the H2 tag that I import via API call. I have tried in various ways, making a console log the data exists but it seems that I am wrong something to richamarlo in H2. I seek help in understanding and resolving this error. Thank you
enter code here
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script>
const intervalTime = 10 * 1000;
const container = document.getElementsByClassName("u-text u-text-palette-3-base u-title u-text-3");
const endpoint = "https://*************/v0/*******/************************/collections/****************?offset=0&limit=unlikely";
function onInterval() {
fetch(endpoint, {
method: "GET",
headers: { Authorization: "Bearer **********************" }
})
.then((res) => res.json())
.then((data) => {
const title = data.records.map((a) => {
return{
close: (a.close)
};
});
const lastClose = title[title.length - 1];
console.log(lastClose);
});
}
onInterval();
window.setInterval(onInterval, intervalTime);
</script>
</head>
<body>
<h2><p class="u-text u-text-palette-3-base u-title u-text-3"></p>
</h2>
</body>
</html>

HTML code to invoke Azure automation runbook webhook

Trying to invoke two webhooks that I've defined on a runbook in an azure automation account.
I can run the webhook through powershell, and it works, but i'm having trouble getting it to run. Below is the code i'm using
<HTML>
<TITLE>Jumpbox Power</TITLE>
<BODY>
<CENTER>
<SCRIPT>
function startjumpbox() {
var _url = 'https://s5events.azure-automation.net/webhooks?token=asdf;
return $.ajax({
type: 'post',
url: _url
})
};
function startjumpbox() {
var _url = 'https://s5events.azure-automation.net/webhooks?token=fdsa';
return $.ajax({
type: 'post',
url: _url
})
};
</SCRIPT>
Start / Stop jumpbox<br>
<button onclick="startjumpbox()">Start Jumpbox</button>
<button onclick="stopjumpbox()">Stop Jumpbox</button
</CENTER>
</BODY>
</HTML>
The idea is that when the first button is pressed, the 'startjumpbox' function is run, which generates a post request to the webhook URL. same goes for the second button and a post to the second webhook URL.
Would appreciate any advise.
Please use the code below. It works at my side, just reference the jquery lib(You can also download it to local and then reference it):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
sample code:
<!DOCTYPE html>
<HTML>
<head>
<TITLE>Jumpbox Power</TITLE>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<BODY>
<SCRIPT>
function startjumpbox() {
alert("start call 1")
var _url = 'https://s4events.azure-automation.net/webhooks?token=your_token';
$.ajax({
type: 'POST',
url: _url
});
alert("completed call 1")
}
function startjumpbox2() {
alert("start call 2")
var _url = 'https://s4events.azure-automation.net/webhooks?token=your_token';
$.ajax({
type: 'POST',
url: _url
});
alert("completed call 2")
}
</SCRIPT>
Start / Stop jumpbox<br>
<button onclick="startjumpbox()">Start Jumpbox</button>
<button onclick="startjumpbox2()">Start Jumpbox2</button>
</BODY>
</HTML>

can load up the model due to the authentication

I just followed the startup tutorial to load up a model.
Firstly I have a exsiting client_id and client_secret from autodesk developer, and then built up a express based application with client_id and client_secret in order retrieve the access token such as
var config ={
credentials: {
client_id: 'xxxxxxxx',
client_secret: 'xxxxxxx',
grant_type: 'client_credentials',
scope:'data:read data:write data:create bucket:create bucket:read'
},
BaseEndPoint: 'https://developer.api.autodesk.com',
Version: 'v1'
} ;
config.AuthenticateEndPoint =config.BaseEndPoint + '/authentication/' + config.Version + '/authenticate' ;
unirest.post (config.AuthenticateEndPoint)
.header ('Accept', 'application/json')
.send (config.credentials)
.end (function (response) {
}
{"access_token":"ruTBP6POxlpcy8HK2KlWzoFu61oE","token_type":"Bearer","expires_in":86399}
This access token is then sent back to a simple html client.
<!DOCTYPE html>
<html>
<head>
<title>Very Basic 3D Viewer</title>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=no" />
<meta charset="utf-8">
<script src="js/jquery-3.1.1.min.js" ></script>
<!-- The Viewer CSS -->
<link rel="stylesheet" href="https://developer.api.autodesk.com/viewingservice/v1/viewers/style.min.css" type="text/css">
<link rel="stylesheet" href="https://developer.api.autodesk.com/viewingservice/v1/viewers/A360.css" type="text/css">
</head>
<body>
<div id="viewer"></div>
<!-- The Viewer JS -->
<script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/three.min.js?v=v1.2.22"></script>
<script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/viewer3D.min.js?v=v1.2.22"></script>
<script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/Autodesk360App.js"></script>
<!-- Developer JS -->
<script>
$(document).ready(function () {
var viewerApp;
var options = {
env: 'AutodeskProduction',
accessToken: 'YOUR ACCESS TOKEN'
};
var documentId = 'YOUR BASE 64 ENCODED URN';
$.getJSON( 'http://'+window.location.host+ "/gettoken", function( data ) {
console.log(data);
options.accessToken = data.accessToken;
documentId = data.urn;
options.document = data.urn;
});
console.log(options.accessToken, documentId);
Autodesk.Viewing.Initializer(options, function onInitialized(){
viewerApp = new Autodesk.A360ViewingApplication('viewer');
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D);
//viewerApp.loadDocumentWithItemAndObject(documentId);
});
});
</script>
</body>
</html>
The problem occurred on the client-side, which can successfully get the access token. However this gave me a error
'POST https://developer.api.autodesk.com/utility/v1/settoken 401 (Unauthorized)'
Autodesk.Viewing.Initializer(options, function onInitialized(){
viewerApp = new Autodesk.A360ViewingApplication('viewer');
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D);
//viewerApp.loadDocumentWithItemAndObject(documentId);
});
i can't figure out what is the problem, something wrong with api or client side or server side?
Note: on registering the developer api, i simply named callback as http://localhost:3000 because currently i am testing it on the local environment, is that the problem ?
The code here
var config ={
credentials: {
client_id: 'xxxxxxxx',
client_secret: 'xxxxxxx',
grant_type: 'client_credentials',
scope:'data:read data:write data:create bucket:create bucket:read'
},
BaseEndPoint: 'https://developer.api.autodesk.com',
Version: 'v1'
} ;
config.AuthenticateEndPoint =config.BaseEndPoint + '/authentication/' + config.Version + '/authenticate' ;
unirest.post (config.AuthenticateEndPoint)
.header ('Accept', 'application/json')
.send (config.credentials)
.end (function (response) {
}
is correct. You get a valid access token, and I assume you run this code from your node.js server. On your server you implement an endpoint, i.e /gettoken, which your client app will call to get the access token returned to your page which initialize the viewer. So far so good.
However, when you consider the calling sequence on your client, there is an issue.
$(document).ready(function () {
means that your code will execute when the DOM is ready - this is fine.
Here, you initialize your variables:
var options = {
env: 'AutodeskProduction',
accessToken: 'YOUR ACCESS TOKEN'
};
var documentId = 'YOUR BASE 64 ENCODED URN';
until here it is still ok, but note that both the accessToken and documentId have invalid valid.
Next, you query the access token using $.getJSON() which is an asynchronous way of calling an endpoint. That means this function returns immediatelly before you read the reply.
So the next code executed is not the one in the callback function, but this one:
console.log(options.accessToken, documentId);
Autodesk.Viewing.Initializer(options, function onInitialized(){
viewerApp = new Autodesk.A360ViewingApplication('viewer');
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D);
//viewerApp.loadDocumentWithItemAndObject(documentId);
});
at this time, the accessToken and documentId still got invalid values, which will cause your code to fail. In short you need to initialize the Viewer from the callback to wait for the /gettoken response to come back.
$.getJSON( 'http://'+window.location.host+ "/gettoken", function( data ) {
console.log(data);
options.accessToken = data.accessToken;
documentId = data.urn;
options.document = data.urn;
Autodesk.Viewing.Initializer(options, function onInitialized(){
viewerApp = new Autodesk.A360ViewingApplication('viewer');
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D);
//viewerApp.loadDocumentWithItemAndObject(documentId);
});
});

AngularJS databinding through responsemessage not working as expected

Code is as follows
var myApp = angular.module("gameModule", []);
myApp.controller("gamecontroller", function ($scope) {
$scope.message = "test";
// websocket connection.
var gameHub = $.connection.socketHub;
$.connection.hub.start().done(function () {
var clientid = $.connection.hub.id;
$(function () {
var user = { signalrsessionid: clientid };
$.ajax({
type: "POST",
data: JSON.stringify(user),
url: "http://localhost:53629/api/game/signalr",
contentType: "application/json"
}).done(function (response) {
alert(response);
$scope.responsemessage = response;
});
});
});
});
and front end code
<!DOCTYPE html>
<html ng-app="gameModule">
<head>
<title>game registration</title>
<meta charset="utf-8" />
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/jquery.signalR-2.2.1.js"></script>
<script src="Scripts/angular.js"></script>
<!--Automatisch gegenereerde signalR hub script -->
<script src="signalr/hubs"></script>
<script src="Scripts/rouletteAngular.js"></script>
</head>
<body>
<div ng-controller="gamecontroller">
{{ message }}
{{ responsemessage }}
</div>
So the 'message' is being displayed, the alert box with the response is showing the correct response, but the responsemessage doesnt show any value.
Can anyone tell me what i'm doing wrong.
you must call $scope.$apply(); or $scope.$digest(); after setting $scope.responsemessage = response; because you are using jQuery ajax call, which is outside Angulars context.
EDIT:
here you have nice way to use SignalR in AngularJS:
http://henriquat.re/server-integration/signalr/integrateWithSignalRHubs.html