Since Graph API v2.3, the notification request have been deprecated. I am new to using the API's and I was wondering how to use the POST edge request found here: https://developers.facebook.com/docs/graph-api/reference/user/notifications/
More specifically, to retrieve the unread notification's for a user.
Here is the code I have so far:
function getInfo() {
FB.api("/me/notifications", function(response) {
console.log(response);
});
}
That endpoint is for sending notifications only, you canĀ“t get the unread notifications anymore. And you need to use an App Token with an App Scoped ID for that call. You should not use an App Token client side, so sending notifications should always be done server side.
More information: https://developers.facebook.com/docs/games/services/appnotifications
Related
I am trying to get a simple JSON package from putting the URL of my Google spreadsheet so I can use it on my webpage; I am using my Google Cloud Console API as it is said on the documentation of the v4 Google API format, but I still get the error of "Unauthorized API"
Documentation: https://developers.google.com/sheets/api/guides/migration#v4-api
I am using this URL:
https://sheets.googleapis.com/v4/spreadsheets/SHEET_ID/values/Sheet1?key=API_KEY
My google sheet is set as published on the web. And also I am the creator of the google sheet.
What could I be missing? I am new to API's!
First Edit:
Answering the comment of ABDULLOKH MUKHAMMADJONOV
Here is the code I am using to make a GET request to the google sheet, you can see the Sheet ID is there, and also the API of the google cloud platform.
fetch("https://sheets.googleapis.com/v4/spreadsheets/1S652uS2FLVoZ1m3apb6R4H783v6GkV58HbQ6Idec5aY/values/Sheet1?key=AIzaSyCpFZ7mcqMNc6Q_bP6h1kCEfAi6c_fd8AM", {"method": "get"})
.then( (httpResponse) => {
if (httpResponse.ok) {
console.log(httpResponse.json());
return httpResponse.json();
} else {
return Promise.reject("Fetch did not succeed");
}
} )
.then(json => console.log(json.someKey))
.catch(err => console.log(err));
This code is from the Wix code editor.
The caller doesnt not have permissions
Means that the user you are authenticated as does not have permission to do what it is you are trying to do.
The method
https://sheets.googleapis.com/v4/spreadsheets/SHEET_ID/values/Sheet1?key=API_KEY
I believe is this method spreadsheets.values/get if you check the documentation you will notice that it requires authorization with one of these scopes
You appear to only be sending an api key. You need to be authorized to access that sheet. You cant access it with an API key that only grants access to public data.
Ok, so I investigated about the OAuth 2.0 authentication and authorization for using Google Sheet's REST API. I added one of the needed scopes.
But I am stuck at the point on how to do the authorization process...
I am looking at this google documentation - How to use Google OAuth 2.0 authorization
But I haven't been able to get to the answer I seek. I am stuck at the part where it says "When your application needs access to user data, it asks Google for a particular scope of access." I do now know how to code this request or to do this request through the Insomnia software.
I am trying to do the GET request with a wix testing website, and also with Insomnia, but I haven't been able to achieve it.
These are the images from Insomnia, which tell me "Invalid authorization URL"
Insomnia's OAuth 2.0 authentication parameters
Insomnia's API Query parameter
I'm working on a Firebase project and I want to receive firebase cloud messages (send from a Node.js server) in my service worker in my javascript project. This works fine, but now I want to save some data in my firebase cloud firestore from my service worker after receiving the notification. And there is the problem, I'm running in the error listed below:
Uncaught ReferenceError: XMLHttpRequest is not defined at Ln.<anonymous> (xmlhttp.js:167) at Me (channelrequest.js:512) at Ce (webchannelbase.js:1249) at Kn.xa (webchannelbase.js:1251) at re (run.js:124)
Since a few days I'm trying to find the error, but could not find a solution until now. Therefore I hope that you can help me now. I've tried to save the data in the firebase realtime database which works, but because I need to have offline persistence, I had to switch to cloud firestore which runs in the error above.
Here is the code from my node.js server for sending the notification (userID and registrationToken is defined before):
payload = {
data: {
"title": "This is a Notification",
"body": "This is the body of the notification message."
},
};
options = {
priority: "high",
timeToLive: 7200
};
// send message to the registration token
admin.messaging().sendToDevice(registrationToken, payload, options).then(function(response) {
admin.firestore().collection("Logging").doc(userID).set({active: "true"});
}).catch(function(error) {
console.log("Error sending message:", error);
});
And here is the code for receiving the notification in my firebase-messagins service worker file (userID is defined before):
self.addEventListener('notificationclick', function(event) {
event.notification.close();
const keepAlive = async() => {
firebase.firestore().collection("Logging").doc(userID).update({"open": "true"});
}
event.waitUntil(keepAlive());
});
Can anyone help me, please? I have no more ideas for solving my problem :/
You can't use XMLHttpRequest inside of a service worker. Instead, you need to use the Fetch API.
Based on your code, it's the Firebase client library that's using XMLHttpRequest under the hood. I don't think that you have any control over that (at least not based on what I see in the current JavaScript documentation for Firebase).
Instead of using the Firebase client library in your service worker, you could try using the REST API directly, using fetch() to send your HTTP requests. You'll be responsible for things like authentication and setting whatever user ids, etc. that the client library would otherwise handle for you, but I think that's your best bet inside of a service worker.
Since version 9 the Firebase Web SDK uses fetch instead of XMLHttpRequest. So it works inside a service worker.
Is there a way to handle POST requests using the react-router-dom (npm) library?
Why? The payment gateway will redirect the user, who successfully payed, back to the platform. I can use a GET or POST request to transfer data with the redirection page. But I don't like having the data visible in the URL. Other options are always welcome, I'm using a REST API (Node.JS, Express) and a website/dashboard (ReactJS)
I get what you're after but you can't POST to the browser. If you're uncomfortable passing data as GET params in a URL, you could:
store data in LocalStorage when user submits
deliver server-rendered, static HTML upon redirect that contains purchase information
asynchronously get user's purchase data upon page load with AJAX or fetch() (or your favorite data-grabbing util).
Since you're in a React world, I'd recommend the third option here. How to fetch data, build an API endpoint, store data, then display it goes well beyond the scope of this question so I'd suggest some Googling. Here's a starting point: https://code.tutsplus.com/tutorials/introduction-to-api-calls-with-react-and-axios--cms-21027
You can handle the POST request on your express server then redirect to a static page of your app :
app.post('/payment_webhook', (req, res) => {
const paymentOk = req.body.payment // handle POST data
if (paymentOk) {
res.redirect('http://app.com/payment_success');
} else {
res.redirect('http://app.com/payment_failed');
}
});
I was discussing the same with a friend and so far we saw 2 ways of doing this:
let the payment gateway return_url be an endpoint of the backend API (rails api), which will do the commit to the payment gateway (and probably updating the order in the BD), and then it will do a redirect back to your frontend app
store the gateway trasaction token on the order object in the DB, and let the payment gateway return_url to return to a dynamic order url, therefore, react will now which order should render, then asynchronously ask the backend (rails service) to extract the token from the order object and do the commit (confirmation) and update it's status and return the order object back to react, then react can now show if the order was successful or not.
we opted for option #2, since I feel that the frontend (react) shall be the main communication gateway to our system, and the only one communicating to the backend shall be the frontend.
UPDATE: option #2 did not work since you cant do POST to a react-app therefore, we make the return_url to be dynamic, and we immediately redirect to the frontend with a url with the order_id as query param, then, the frontend when tries to load the order, in the backend we do the payment gatway confirmation, update the order object and return the updated order object to the frontend
I am building a SPA using vue.js which has a PHP backend server (slim framework 3). These are two separate projects, leave on two different servers and the backend has no front end at all.
SPA (vue.js) makes requests to backend via ajax.
Now I want to implement Google Calendar API to create a calendar and events every time user creates a todo item. To do that I need server to server access to Google Calendar API (I might need to make changes to the event on GCAL even if user is not logged in).
What I am trying to understand, how can I get the access token (and refresh token) using Google JS library using vue.js and save this in the db so that my backend can use it to make offline requests to GCAL Api.
When I use the Oauth v.2 using the JS library, all I get is the access_token which cannot be using for server to server communications.
[UPDATE]
Ok, a little bit more information. I am following the guides from Google and my front end looks like this at the moment
jsbin
So I can successfully authorise user and access their calendar using the javascript sdk. But the token Javascript SDK returns is something like this
{
_aa: "1"
access_token: "xxxxxxx"
client_id: "yyyyyyyyyy"
cookie_policy: undefined
expires_at: "1456400189"
expires_in: "3600"
g_user_cookie_policy: undefined
issued_at: "1456396589"
response_type: "token"
scope: "https://www.googleapis.com/auth/calendar"
state: ""
status: Object
google_logged_in: false
method: "AUTO"
signed_in: true
token_type: "Bearer"
}
I send this token to my backend server and try to make a request to GCAL api as follows
$token = $request->getParam('token');
$client = new Google_Client();
$client->setApplicationName('Web');
$client->setScopes([Google_Service_Calendar::CALENDAR]);
$client->setAuthConfigFile(ROOT_DIR . '/client_secret.json');
$client->setAccessType('offline');
$client->setAccessToken(json_encode($token));
$service = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
And it returns error saying the token is expired. I checked the Google Code and found out the reason it returns this error is because of these lines
public function isAccessTokenExpired()
{
if (!$this->token || !isset($this->token['created'])) {
return true;
}
// If the token is set to expire in the next 30 seconds.
$expired = ($this->token['created']
+ ($this->token['expires_in'] - 30)) < time();
return $expired;
}
As you can see the token that comes from the front end doesn't have created field as well as no refresh_token field.
Thanks for updating the question! I am thinking the issue is that using the client-side flow does not allow you to get a refresh token. From the docs:
OAuth 2.0 client-side flow (AKA Implicit flow) is used to obtain
access tokens (it does not support the issuance of refresh tokens) and
is optimized for public clients known to operate a particular
redirection URI. These clients are typically implemented in a browser
using a scripting language such as JavaScript.
The authorization server MUST NOT issue a refresh token.
see for more: How to get refresh token while using Google API JS Client
You'd need to use the server-auth flow to get a token you can refresh and use long-term. Here's a quickstart guide for PHP.
One other thing to consider is that you will only receive a refresh_token the first time someone authorizes your app. After that, auth attempts will only return an access token. So if you lose the refresh token, you will need to either disable the authorization from your google account, or use the "force re-auth" option in the API.
I'm trying to get graph api data for public Facebook events rendered in an html document. The site I need to put it on is made with a website builder so I don't have control over the server that generates the html. I can only insert JavaScript code into the page.
The only solution I've found now is by using an app access_token in the client side request:
FB.api(
"/<event_id>?fields=start_time,description",
function (response) {
if (response && !response.error) {
console.log(response.start_time, response.description);
}
},
{access_token: "<app access token>"}
);
I've read through the docs on access tokens
and the JavaScript sdk docs, but the app token solution I've found is not secure (from the docs):
... app access token should never be hard-coded into client-side code.
I don't think the user access token is the flow I want because I don't want people to have to log in; it's only for public events. I don't think the page access token is right either.
Is there:
a way to use the Graph API for public events without requiring a user to log in or without introducing an insecurity?
or a way to make sharing my app access token with the world have no bad consequences?