PayPal is sending many multiples of the same webhook (node) - node.js

Update: Code is now working, I think there were a ton of unverified transactions that had to work their way back through the system after I added `res.send('on') to the code.
Edit: Adding res.send('on') fixed the 502 gateway error but the re-sending continues.
I have webhooks successfully configured and am receiving them at my listener. The documentation on how to verify is not very clear, but I am running the code for get_and_ verify.js given in the node SDK docs. Each webhook that is sent by PayPal is run through this code, which consistently returns true.
My issue is, PayPal is re-sending the same webhook over and over again, seemingly endlessly. Is there something I have not done in the configuration, or is this just how these work?
listener code:
app.post('/paymentauthed', (req,res) => {
res.status(200);
console.log(req.body);
paypal.configure({
mode: "sandbox", //sandbox or live
client_id:
"...",
client_secret:
"..."
});
const eventBody = `{"id": "${req.body.id}"}`
paypal.notification.webhookEvent.getAndVerify(eventBody, function (error, response) {
if (error) {
console.log(error);
throw error;
} else {
console.log(response);
}
});
});
app.listen(3000, () => console.log('Server Started'))
this response might be relevant also, it says there is a 502 bad gateway, not sure why...
"transmissions": [
{
"webhook_url": "https://cloudhookstester.net/paymentauthed",
"response_headers": {
"SERVER_INFO": "",
"Strict-Transport-Security": "“max-age=15768000”",
"HTTP/1.1 502 Bad Gateway": "",
"Server": "nginx/1.14.2",
"Connection": "keep-alive",
"Content-Length": "173",
"Date": "Tue, 15 Jan 2019 03:38:43 GMT",
"Content-Type": "text/html"
},
"transmission_id": "74323070-1874-11e9-8941-d953a11868e8",
"status": "PENDING",
"timestamp": "2019-01-15T03:20:05Z"
}
],
Any help is appreciated.

I was getting the same problem while implementing receiving paypal webhook in my django application, this is resolved after giving a valid working URL over a server for webhook call with returning HttpResponse.
Hope It will work for you and other people are getting this problem also.

Related

Why would a server deny a request?

I am working on a chrome extension that creates an Anki card and adds it to my desk.
Right now am I trying to get the request to work using the Anki API.
For some reason the server is denying my request.
Here is my code (JavaScript) to create a card and send it as a request to the localhost:
async function createCard() {
// Set the Anki API endpoint URL
const baseURL = 'http://localhost:8765';
// Set the Anki API action, version and params
const card = {
"action": "addNote",
"version": 6,
"params": {
"note": {
"deckName": "Default",
"modelName": "Basic",
"fields": {
"Front": "front content",
"Back": "back content"
},
"options": {
"allowDuplicate": false,
"duplicateScope": "deck",
"duplicateScopeOptions": {
"deckName": "Default",
"checkChildren": false,
"checkAllModels": false
}
}
}
}
};
// Send the request to the Anki API
try {
const response = await fetch(baseURL, {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(card)
});
// Check the status code of the response
if (response.ok) {
console.log('Card created successfully');
} else {
console.error(`Error creating card: ${response.statusText}`);
}
} catch (error) {
console.error(`Error creating card: ${error}`);
}
}
(The card by now is hardcoded.)
When I execute this code I get 2 errors thrown by chrome:
POST http://localhost:8765/ net::ERR_ABORTED 403 (Forbidden)
Error creating card:
The first error happens on the fetch function
and the second error at "console.error('Error creating card: ${response.statusText}');"
I suggest that the second error appears due to the first one.
Since I am new to computer science, all I tried so far is checking the logs of ANKI to find information about the error, but I couldn't find something. I tried different syntax to create the card since I pass this into the fetch function where the error occurs.
The localhost is running while I am working on this, so the server is accessible.
My solution is setting the webCorsOriginList config of AnkiConnect as "*"
"webCorsOriginList": ["*"]
It will allow CORS for all domains.

Getting "EHOSTUNREACH" when trying to connect to API using Axios + Express.js

I started playing around with the Philips Hue Bridge API by sending it requests using Postman. I was able to authenticate myself, create a user and even successfully turn lights on or off.
Conclusion: I am able to reach the API.
Next I made a mini test javascript file to do the exact same using Node.js and axios#0.21.4. When I try the following code everything works and I receive the expected JSON responses:
const axios = require('axios')
axios({
method: 'GET',
url: 'http://philips-hue.local/api/BYLCIlxABzz2eDHAxx70T'
})
.then(({data}) => {
console.log('------> AXIOS RES: ', data)
})
.catch((err) => {
console.log('------> AXIOS ERR: ', err)
})
Conclusion: Axios is able to communicate with the API.
Next I wanted to build this into an Express.js endpoint. However when I try to use the same code inside of express#4.17.1 I get an error:
router.route('/getlights').get((req, res) => {
axios({
method: 'GET',
url: 'http://philips-hue.local/api/BYLCIlxABzz2eDHAxx70T/lights'
})
.then(({data}) => {
console.log('------> AXIOS RES: ', data)
res.json({
state: 'SUCCESS',
data
})
})
.catch((err) => {
console.log('------> AXIOS ERR: ', err)
res.json({
state: 'ERROR',
err
})
})
})
Response:
{
"state": "ERROR",
"err": {
"message": "connect EHOSTUNREACH 192.168.0.107:80",
"name": "Error",
"stack": "Error: connect EHOSTUNREACH 192.168.0.107:80\n at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16)",
"config": {
"url": "http://philips-hue.local/api/BYLCIlxABzz2eDHAxx70T/lights",
"method": "get",
"headers": {
"Accept": "application/json, text/plain, */*",
"User-Agent": "axios/0.21.1"
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
},
"code": "EHOSTUNREACH"
}
}
I started troubleshooting the problem by first trying to changing the URL to a random online place holder like http://jsonplaceholder.typicode.com/posts/1 just to see if I could establish any connection at all. This actually worked right away.
This is where I got really confused. Why am I able to successfully communicate with the bridge using Postman or Axios in a javascript file, but NOT able to connect with it when the same Axios code is used by express. The problems seems to occur only when using both axios and express to connect to the bridge API.
I have already tried retesting this with node-fetch and 3 other versions of Axios. All tests failed the exact same way. The code by itself can always connect to the API but once the code is being called by express it causes the EHOSTUNREACH error.
I ran out of ideas on how to further google this issue since I am not sure what exactly is causing the problem (express and/or axios and/or bridge). Any trouble shooting ideas or google keywords are also very welcome. :)
I had the same error, for some reason the ip address of my hue bridge had changed so I went into the hue app on my smartphone and copied the new ip address. IDK if this is helpfull, im pretty new here.
I had the same error since yesterday, and couldn't find solution. What actually caused mine was, there was a bearer token on the 3rd party api I called and i also pass it through the header as well.
So it was removed and pass the token through header and it works fine.
UPDATE: error keeps showing up if send another request.
The solution i found was to use request.
const request = require('request');
const headers = {
'Content-Type': 'application/json',
'token': `${token}`
};
const data = {
username : 'username'
}
let options = {
method: 'POST',
url: 'url',
port: 443,
headers: headers,
body: data,
json: true
};
request(options, async (error, res, body) => {
if (error) {
console.log({error});
return response.status(500).json({
status: false,
message: "Error occured"
});
} else {
console.log({body});
return response.status(201).json({
message: "success"
});
}
});

Access Google Container builder logs with a service account - 403 Forbidden Error

I have a service account that triggers builds on Google Container Builder. This works fine but now I would like to retrieve build logs using that service account.
Here is the code that fetches the log (the token is obtained using google-auto-auth package and this part works well in other places, so I really don't think this is the issue):
var url = logsBucket + '/log-' + buildId + '.txt';
debug('Requesting log at %s', url);
request
.get(url)
.set('Authorization', 'Bearer ' + token)
.end(function(err, res) {
if (err) return cb(err);
var log = res.body;
debug('Received build log : %o', log);
cb(null, log);
});
Currently, this fails with 401 Unauthorized although the service account has access to the following roles:
Admin kubernetes engine
Admin storage
Admin objects in storage
Cloud container builder
Reader Cloud container builder
Reader storage objects
This is the error:
{
"message": "Forbidden",
"stack": "Error: Forbidden\n at Request.callback (/app/node_modules/superagent/lib/node/index.js:696:15)\n [...]",
"status": 403,
"response": {
"req": {
"method": "GET",
"url": "https://storage.googleapis.com/{PROJECT_ID}.cloudbuild-logs.googleusercontent.com/log-42602b35-af02-4e75-8100-8a3bd0e720fb.txt",
"headers": {
"user-agent": "node-superagent/3.8.2",
"authorization": "Bearer {BEARER_TOKEN}"
}
},
"header": {
"x-guploader-uploadid": "{SOME-UPLOAD-ID}",
"content-type": "application/xml; charset=UTF-8",
"content-length": "337",
"date": "Wed, 10 Jan 2018 11:06:54 GMT",
"expires": "Wed, 10 Jan 2018 11:06:54 GMT",
"cache-control": "private, max-age=0",
"server": "UploadServer",
"alt-svc": "...",
"connection": "close"
},
"status": 403
}
}
Any idea why the request fails with 403 ? Could it come from a missing scope ? I only set scopes: 'https://www.googleapis.com/auth/cloud-platform' so far.
GCS permissions predate IAM and thus work a little differently.
To view the build logs, the Service Account in question needs to be a Viewer on the project in addition to have the Builder Editor role.
role/viewer includes role role/cloudbuild.builds.viewer
role/cloudbuild.builds.editor
As a last step you may want to: (Not necessary)
Disable the Container Builder API and re-enable it. Doing so should give your service account access to your project again.
Please also look at: docs

$http request in ionic app to a simple node server throws "statusText": "" error

I've stripped down an $http request to the bones and it's still failing without a helpful error message. Within my Angular factory I have:
var url = "http://localhost:3000";
var deferred = $q.defer();
$http.get(url)
.then(function (success) {
deferred.resolve(success)
})
.catch(function (err) {
deferred.reject(err)
})
return deferred.promise;
Inside my node routes I have:
router.get('/', function(req, res, next) {
res.json({test: 'hi from node index.js'})
});
The full error I'm receiving within my ionic app is:
{
"data": null,
"status": -1,
"config": {
"method": "GET",
"transformRequest": [
null
],
"transformResponse": [
null
],
"url": "http://localhost:3000",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": ""
I've tried to catch the error inside my node server and I receive
TypeError: Cannot read property 'type' of undefined
I've disabled cors within my node app.js. I've tried to make a connection with sockets, but still haven't had any luck. I'm running my ionic app with ionic run.
Any help would be appreciated. Thanks.
Solution: naturally the device has it's own localhost, so when I'm sending an $http.get request from my ionic app, it's not sending it to the same localhost my node server is running on. The solution is to target your deployed server or your local machine.

google API calendar watch doesn't work but channel is created

I try to listen on my calendar change events (google-apps/calendar/v3/reference/events/watch).
I did everything from Google console side, domains - OK, everything is verified and I succeeded to create channel. Also i succeeded to get sync message with right headers (see below). From docs:
Sync message
After creating a new notification channel to watch a resource, the
Google Calendar API sends a sync message to indicate that
notifications are starting. The X-Goog-Resource-State HTTP header
value for these messages is sync. Because of network timing issues, it
is possible to receive the sync message even before you receive the
watch method response.
That mean that notifications are starting
However when I change something in snaggs#comp.com account -
nothing happens, no request sends to callback : 'https://dev-api.mycompany/google-watch/'
This is my working code:
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var _ = require('underscore-node');
var uuid = require('node-uuid');
// ......
var channel_id = uuid.v1();
_auth.credentials = {
access_token: _token.access_token,
token_type: _token.token_type,
refresh_token: _token.refresh_token,
expiry_date: _token.expiry_date
};
var data = {
auth: _auth,
calendarId: _token.provider_email,
singleEvents: true,
orderBy: 'startTime',
resource: {
id: channel_id,
token: 'email='+_token.provider_email,
address: 'https://dev-api.mycompany/google-watch/',
type: 'web_hook',
params: {
ttl: '36000'
}
}
};
calendar.events.watch(data, function (err, response) {
if (err) {
console.error('The API returned an error: ' + err);
return;
}
});
When I start above mentioned snippets of code i get response:
{
"kind": "api#channel",
"id": "277fa000-d4b6-12e5-ab58-e7afaf85ea65",
"resourceId": "C7vFL07CYfqaHy3vDss4qugWDfk",
"resourceUri": "https://www.googleapis.com/calendar/v3/calendars/snaggs#comp.com/events?orderBy=START_TIME&singleEvents=true&alt=json",
"token": "email=snaggs#comp.com",
"expiration": "1455667451000"
}
And in 'https://dev-api.mycompany/google-watch/' URL I get sync message regards to documents, like (See google-apps/calendar/v3/push):
{
"host": "dev-api.mycompany",
"accept": "*/*",
"accept-encoding": "gzip,deflate",
"user-agent": "APIs-Google; (+https://developers.google.com/webmasters/APIs-Google.html)",
"x-goog-channel-expiration": "Tue, 16 Feb 2016 22:44:51 GMT",
"x-goog-channel-id": "277fa000-d4b6-12e5-ab58-e7afaf85ea65",
"x-goog-channel-token": "email=snaggs#comp.com",
"x-goog-message-number": "1",
"x-goog-resource-id": "C7vFL07CYfqaHy3vDss4qugWDfk",
"x-goog-resource-state": "sync",
"x-goog-resource-uri": "https://www.googleapis.com/calendar/v3/calendars/snaggs#comp.com/events?orderBy=START_TIME&singleEvents=true&alt=json",
"x-forwarded-for": "56.102.7.132",
"x-forwarded-port": "443",
"x-forwarded-proto": "https",
"content-length": "0",
"connection": "keep-alive"
}
but not exists message
Do I miss something?
please help,
We have been using Push Notifications for a few years and noticed that for the last 24 hours we did not receive any notifications across several thousand calendars.
Like you we can create/stop a channel but no notifications are received for changes as normal.
As of about an hour ago we are receiving them again. Please try your channel again as it may be a glitch on the Google Push side of things that has been resolved.

Resources