paypal express checkout - 400 bad request - javascript

I'm using this instruction https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/advanced-integration/ to set up paypal. The only different is that I need to send data to CREATE_PAYMENT_URL endpoint, so I transfer it as second parameter
paypal.request.post(
CREATE_PAYMENT_URL,
JSON.stringify([{"name": "test", "price": 10}]),
{ headers: { 'Content-Type': 'application/json' } }
)
after that I'm getting 400 error
{"success":false,"errors":{"statuscode":400,"message":"Invalid json message received"}}
Backend doesn't matter, cause it's never reached. Also I'm almost sure it worked fine few days ago
Any ideas?
Fiddler screen

Try setting the second param to null, and send an options object as the third param with an object named json in the third with a plain JS object inside.
paypal.request.post(PAYMENT_URL, null, {
json : {
name:'test',
price:10
}
})
It's not in the documentation, I was having similar issues but dug around in the source code to get it to work.

Related

Firebase error. Please ensure that you have the URL of your Firebase Realtime Database instance configured correctly

I am using getServerSideProps to fetch data from my firebase database into my Next.js application.
My code snippet looks like this:
export async function getServerSideProps(context) {
const session = await getSession(context);
const products = await fetch("https://database-73695.firebaseio.com/").then(
(res) => res.json()
);
return {
props: {
products,
session
},
};
}
The problem is that I get error message saying the following: "FetchError: invalid json response body at https://database-73695.firebaseio.com/ reason: Unexpected token F in JSON at position 0"
I have seen that some people report this error when the data fetched is actually text and not an object. I tried changing the response from res.json to res.text, but then I'm told that "text is undefined".
Does anybody have any idea of what could be happening?
UPDATE:
By testing different fetching methods, I have seen the error:
Firebase error. Please ensure that you have the URL of your Firebase Realtime Database instance configured correctly.
All fetching code (with or without getServerSideProps) work when used with other APIs.
My database URL comes from Firestore, and is formated as follows:
https://PROJECT-ID.firebaseio.com
It is located in us-central, which I know is important for the URL.
Something else that might be worth noting: the database has already a collection called "users" tied to Stripe transactions, which works.
Any ideas?
Thank you for your time.
->try adding headers:
headers:
{
Accept: 'application/json, text/plain, /'
'User-Agent': '*',
},
->try checking if data is not been fetch from the back-end

Uncaught (in promise) SyntaxError: Unexpected end of JSON input

I am trying to send a new push subscription to my server but am encountering an error "Uncaught (in promise) SyntaxError: Unexpected end of JSON input" and the console says it's in my index page at line 1, which obviously is not the case.
The function where I suspect the problem occurring (because error is not thrown when I comment it out) is sendSubscriptionToBackEnd(subscription) which is called in the following:
function updateSubscriptionOnServer(subscription) {
const subscriptionJson = document.querySelector('.js-subscription-json');
const subscriptionDetails = document.querySelector('.js-subscription-details');
if (subscription) {
subscriptionJson.textContent = JSON.stringify(subscription);
sendSubscriptionToBackEnd(subscription);
subscriptionDetails.classList.remove('is-invisible');
} else {
subscriptionDetails.classList.add('is-invisible');
}
}
The function itself (which precedes the above function):
function sendSubscriptionToBackEnd(subscription) {
return fetch('/path/to/app/savesub.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(subscription)
})
.then(function(response) {
if (!response.ok) {
throw new Error('Bad status code from server.');
}
return response.json();
})
.then(function(responseData) {
if (!(responseData.data && responseData.data.success)) {
throw new Error('Bad response from server.');
}
});
}
I have tried replacing single quotes with double quotes in the fetch call but that yields the same results.
I know that the JSON should be populated because it prints to the screen in the updateSubscriptionOnServer() function with subscriptionJson.textContent = JSON.stringify(subscription);, and I used that output in the google codelab's example server to receive a push successfully.
EDIT: Here is the JSON as a string, but I don't see a mistake in syntax:
{"endpoint":"https://fcm.googleapis.com/fcm/send/dLmthm1wZuc:APA91bGULRezL7SzZKywF2wiS50hXNaLqjJxJ869y8wiWLA3Y_1pHqTI458VIhJZkyOsRMO2xBS77erpmKUp-Tg0sMkYHkuUJCI8wEid1jMESeO2ExjNhNC9OS1DQT2j05BaRgckFbCN","keys":{"p256dh":"BBz2c7S5uiKR-SE2fYJrjPaxuAiFiLogxsJbl8S1A_fQrOEH4_LQjp8qocIxOFEicpcf4PHZksAtA8zKJG9pMzs=","auth":"VOHh5P-1ZTupRXTMs4VhlQ=="}}
Any ideas??
This might be a problem with the endpoint not passing the appropriate parameters in the response's header.
In Chrome's console, inside the Network tab, check the headers sent by the endpoint and it should contain this:
Example of proper response to allow requests from localhost and cross domains requests
Ask the API developer to include this in the headers:
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
This happened to me also when I was running a server with Express.js and using Brave browser. In my case it was the CORs problem. I did the following and it solved the problem in my case:
(since this is an Express framework, I am using app.get)
-on the server side:
res.set({
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
});
-on client side I used Fetch to get data but disabled the CORS option
// mode: "no-cors" //disabled this in Fetch
That took care of my issues with fetching data with Express
This can be because you're not sending any JSON from the server
OR
This can be because you're sending invalid JSON.
Your code might look like
res.end();
One of the pitfalls is that returned data that is not a JSON but just a plain text payload regardless of headers set. I.e. sending out in Express via something like
res.send({a: "b"});
rather than
res.json({a: "b"});
would return this confusing error. Not easy to detect in network activity as it looks quite legit.
For someone looking here later. I received this error not because of my headers but because I was not recursively appending the response body to a string to JSON.parse later.
As per the MDN example (I've taken out some parts of their example not immediately relevant):
reader.read().then(function processText({ done, value }) {
if (done) {
console.log("Stream complete");
return;
}
result += chunk;
return reader.read().then(processText);
});
For my issue I had to
Use a named function (not an anonymous ()=>{}) inside the .then
Append the result together recursively.
Once done is true execute something else on the total appended result
Just in case this is helpful for you in the future and your issue is not header related, but related to the done value not being true with the initial JSON stream response.
I know this question has already been answered but just thought I add my thoughts.
This will happen when your response body is empty and response.json() is expecting a JSON string. Make sure that your API is returning a response body in JSON format if must be.

Node.js + Sending API Request to Third Party Service

I have a Node console app. In my app, I am trying to send some data to a third-party web service. I can successfully add data via the third-party web service via POSTMAN. In my Postman, I have a request setup like this:
Headers
api-key
{my key}
Content-Type
application/json
Body
{
"value": [
{
"#operation": "send",
"id":"1",
"name":"Hello",
"position": { "type": "Point", "coordinates": [90.000000, 0.000000] },
"tags":["january", "friends"]
}
]
}
I am now trying to replicate sending this data via Node. In an attempt to do this, I've written the following:
var ops = {
host: 'example.com',
path: '/api/upload?version=2',
method: 'POST',
headers: {
'api-key':'[my key]',
'Content-Type': 'application/json'
}
};
var r = https.request(ops, (res) => {
res.on('data', (d) => {
console.log(res.statusCode);
console.log(res.statusMessage);
});
});
var data = {
"value": [
req.body.record // req is passed in via express
]
};
console.log(data);
r.write(JSON.stringify(data));
r.end();
When the line console.log(data); is executed, I see the following in the console window:
{ value:
[ { '#operation': 'send',
id: '1',
name: 'Hello',
position: [Object],
tags:[Object]
} ] }
I'm not sure if this is a printing problem or an actual problem. Either way, my real issue is that when I send my request, I see the following also printed in the console window:
400
Bad Request
That data looks correct. I don't understand why I'm getting a 400 when I try to send from Node. Yet, it works just fine from Postman. Does it have to do with the quotation marks? I thought JSON.stringify handled that.
What am I doing wrong?
Honestly, unless you have a really good reason not to, just use something like request. It's way easier/cleaner than trying to build it yourself.
I can't answer any more specifically without knowing what the API you're talking to is expecting.
Also, in your res.on('data'), just console.log(req); and see what else is hiding in there; it might help you solve this with your existing code.
I would try
console.log(JSON.stringify(data));
Instead of
console.log(data);
and then decide what is wrong. This will give me full data in way it is sent to server.
Update:
I have made quick experiment and received following output:
{"value":[{"#operation":"send","id":"1","name":"Hello","position":{"type":"Point","coordinates":[90,0]},"tags":["january","friends"]}]}
The difference with the original JSON is in way how the coordinates are sent to the web service (as integers), which can be your problem.

Posting time records to Active Collab

Currently I am working on an app for Active Collab with ionic (AngularJS). When I tracked some time I want to post this time, so that I'll have this time in Active Collab. But when I tried to do that, I got an 500 Internal Server Error. This is my Code (I used the data from the Active Collab API Documentation, to test):
var postData = {
"value": 1.5,
"user_id": 1,
"job_type_id": 1,
"record_date": "2014-05-14",
"billable_status": 0
};
$http.post(baseUrl+'/projects/' + projectId +'/time-records/', postData, { headers: { 'Content-Type': 'application/json' }}).then(function(res){ ... }
The post request work for getting the token (issue-token). So I have no idea what the problem is. I hope anyone can help me?
To make the token-post working I had to add some lines to api.php. Wouldn't this be good to be there per default?
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
// return only the headers and not the content
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
header('Access-Control-Allow-Headers: X-Requested-With');
}
exit;
}
Thanks in advance!
I am currently running Active Collab locally. So baseUrl is: http://my-ip-address/mypath-to-ac/api/v5/projects/56/time-records/ . I do have an authInterceptor, so token should be appended. I also tried to send it within the post-request, but got same error.
Now I debugged it a little more and it says that some fields are null. But I definitely filled those fields and sent them.
This is the logged Data, that I'll send with the request:
{"value":"1.5","user_id":10,"job_type_id":"0","record_date":1467965415.184,"billable_status":0}
And this is the error, I'll get:
debugged error as screenshot

RESTful Get Request with Angular & NodeJS Express

I'm just following tutorials and figuring out how to handle get requests in NodeJS.
Here are snippets of my code:
NodeJS:
router.get('/test', function(request, response, next) {
console.log("Received Get Request");
response.jsonp({
data: 'test'
});
});
Angular:
$http.get("http://localhost:3000/test").
success(function(response) {
alert("OK");
}).
error(function(response) {
alert("FAIL");
});
If I try to access the link directly # localhost:3000/test, I'm able to receive the JSON message correctly. But when I use angularJS $http call, the request always fails and I'll find this error in the network inspector (Response)
SyntaxError:JSON.parse:unexpected end of data at line 1 column 1 of
the JSON data
The reason for that is because the response is empty but the response code is 200 in both cases.
I've tried searching for hours but maybe someone can enlighten me on this?
you could try and send
res.send('test')
and then on your http request you can use 'then'
$http.get("http://localhost:3000/test").then(function(res) {
console.log(res);
})
unlike success, then will give you a complete object (with 'test' - string as res.data)
success will bring you only the data;
then will bring you the whole object (with the status and such)..
now about that jsonp .. it's used to override a json response. you could simply use 'res.json({data: 'test'})' and it should also work for you..
hope it helps
You're using jsonp in node, which you probably don't need to. This adds extra characters to the response and so the JSON parser fails to parse (that's what the error is telling you, the JSON is malformed)
Try changing the server to look like
response.json({
data: 'test'
});
If you look in the Network pane of the developer tools, you should be able to see the raw response. It should look something like:
{"data" : "test"}

Categories