This is how I'm calling a web service.
fetch('http://**someurl**', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username : "admin",
password: "admin123",
})
})
When I call it from postman I get a response like this :
{
"code": 1,
"message": {
"Object1": [
{
"Id": 1,
"Name": "COWDUNG",
"manufacturer": "OWN",
"description": "ORGANIC MANUER",
"type": "Fertilizer"
}
]
}
}
Can anyone tell me how to handle the response?
Hope this helps.
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username : "admin",
password: "admin123",
})
}).then((response) => response.json()).then((responseJson) => {
// you'll get the response in responseJson
})
.catch((error) => {
//you will get error here.
});
Related
Hello friends I am learning to build apps in Flutter. it's a single screen must display data from second api using user_id value from the first api.I have api response from server like this :
{
"code": 0,
"message": "",
"data": [
{
"userbox_id": 7,
"user_id": 53,
"box_id": 55,
"status": 0,
"created_at": "2021-04-28T11:55:12.000000Z",
"updated_at": "2021-04-28T11:55:12.000000Z"
},
{
"userbox_id": 8,
"user_id": 53,
"box_id": 56,
"status": 0,
"created_at": "2021-04-29T10:29:43.000000Z",
"updated_at": "2021-04-29T10:29:43.000000Z"
},
"error": [],
"status": 200
}
I would like to use "user_id" value to fetch data from second API response .
How i can do that ?
the first method:
Future<List<ActiveBox>> fetchBoxes() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
String token = localStorage.getString('access_token');
await checkInternet();
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
};
var url = Uri.parse(ApiUtil.GET_ALL_BOXES);
var response = await http.get(url, headers: headers);
switch (response.statusCode) {
case 200:
// print(response.statusCode);
var body = jsonDecode(response.body);
print(body);
List<ActiveBox> boxes = [];
for (var item in body['data']) {
boxes.add(ActiveBox.fromJson(item));
}
print(boxes);
inspect(boxes);
return boxes;
and the second method :
Future<User> getUser() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
String token = localStorage.getString('access_token');
print(token);
await checkInternet();
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
};
var url = Uri.parse(ApiUtil.GET_USER);
var response = await http.get(url, headers: headers);
switch (response.statusCode) {
case 200:
var body = jsonDecode(response.body);
User users = User.fromJson(body);
return users;
how i can implement that ? any help please
I'm trying to integrate PayPal as a payment method in my react-native app. I get an access token by hitting https://api.sandbox.paypal.com/v1/oauth2/token API, but when I'm trying to pass access token to payment API https://api.sandbox.paypal.com/v1/payments/payment got response with status code 400 or 500 both are varying.
My code is
let currency = '100 INR'
currency.replace("INR", "")
const dataDetail = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"transactions": [{
"amount": {
"total": currency,
"currency": "INR",
"details": {
"subtotal": currency,
"tax": "0",
"shipping": "0",
"handling_fee": "0",
"shipping_discount": "0",
"insurance": "0"
}
}
}],
"redirect_urls": {
"return_url": "https://example.com",
"cancel_url": "https://example.com"
}
}
fetch('https://api.sandbox.paypal.com/v1/oauth2/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa('AUrtJxcHfMUlDjHgV2FHMOUnzMkUeu86_km7h67uEHzH5b5RN7Vo-q8AYPtcdz7Iaioc46xW0H9JQZmT:EMbbJ-YqQLT6liuPtJURq2pAgh9WuUTDKmV355_VIeADst0BMlnUNKiHVLK7itCyZFXrEQOex9p93WO8')
},
body: 'grant_type=client_credentials'
}).then(response => response.json())
.then(async (data) => {
console.log(data.access_token)
this.setState({accessToken:data.access_token})
// console.log(JSON.stringify(dataDetail))
fetch ('https://api.sandbox.paypal.com/v1/payments/payment',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+(this.state.accessToken)
},
body:dataDetail
}
)
.then(response => {
console.log('response=====',response)
// const { id, links } = response.data
// const approvalUrl = links.find(data => data.rel == "approval_url")
// this.setState({
// paymentId: id,
// approvalUrl: approvalUrl.href
// })
}).catch(err => {
console.log({ ...err })
})
}).catch(function (error) {
let edata = error.message;
console.log('Error:', edata)
}
)
Any one can help please ?
response
{"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "f2d967a5-2700-4f03-b2ac-2e4ec22f10e4", "offset": 0, "size": 232}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "f2d967a5-2700-4f03-b2ac-2e4ec22f10e4", "offset": 0, "size": 232}}, "bodyUsed": false, "headers": {"map": {"cache-control": "max-age=0, no-cache, no-store, must-revalidate", "content-language": "*", "content-length": "232", "content-type": "application/json", "date": "Tue, 23 Feb 2021 07:20:25 GMT", "paypal-debug-id": "27bb91ae40c3a"}}, "ok": false, "status": 400, "statusText": undefined, "type": "default", "url": "https://api.sandbox.paypal.com/v1/payments/payment"}
reference Link PAYPAL INTEGRATION IN REACT-NATIVE
https://api.sandbox.paypal.com/v1/payments/payment
v1/payments is a deprecated API. You should integrate the current v2/checkout/orders instead.
Here is some documentation -- you want "Create Order" and "Capture Order" API calls.
But, if you want to understand the problems with your v1 code, here they are fixed and with proper request+response data logging
Issues:
currency variable wasn't being set to a valid number w/o spaces
You need to JSON.stringify() your request body.
<script>
let currency = '100 INR';
currency = currency.replace("INR", "").trim() ; //this was a problem line, replace() is not in-place. And also extra space to trim
let accessToken = '';
const dataDetail = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"transactions": [{
"amount": {
"total": currency,
"currency": "INR",
"details": {
"subtotal": currency,
"tax": "0",
"shipping": "0",
"handling_fee": "0",
"shipping_discount": "0",
"insurance": "0"
}
}
}],
"redirect_urls": {
"return_url": "https://example.com",
"cancel_url": "https://example.com"
}
}
fetch('https://api.sandbox.paypal.com/v1/oauth2/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa('AUrtJxcHfMUlDjHgV2FHMOUnzMkUeu86_km7h67uEHzH5b5RN7Vo-q8AYPtcdz7Iaioc46xW0H9JQZmT:EMbbJ-YqQLT6liuPtJURq2pAgh9WuUTDKmV355_VIeADst0BMlnUNKiHVLK7itCyZFXrEQOex9p93WO8')
},
body: 'grant_type=client_credentials'
}).then(response => response.json())
.then(async (data) => {
console.log(data.access_token)
accessToken=data.access_token
// console.log(JSON.stringify(dataDetail))
let createRequest = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+(accessToken)
},
body:JSON.stringify(dataDetail)
}
console.log('Request body string',createRequest.body);
console.log('Request body (formatted)', JSON.stringify( JSON.parse(createRequest.body) ,null,4) );
fetch ('https://api.sandbox.paypal.com/v1/payments/payment',createRequest
)
.then(function(response) {
console.log('Response object', response);
return response.json()
})
.then(async(data) => {
console.log('Response data',data);
console.log('Response data (formatted)', JSON.stringify(data,null,4) );
}).catch(err => {
console.log({ ...err })
})
}).catch(function (error) {
let edata = error.message;
console.log('Error:', edata)
})
</script>
I'm trying to integrate PayPal in my react-native app by following https://medium.com/zestgeek/paypal-integration-in-react-native-9d447df4fce1 link. With postman I get a response, but with my code it gives this error:
{"links": [{"href": "https://developer.paypal.com/docs/api/overview/#error", "rel": "information_link"}], "message": "Authentication failed due to invalid authentication credentials or a missing Authorization header.", "name": "AUTHENTICATION_FAILURE"}
Expected response (with Postman - success case)
{
"scope": "https://uri.paypal.com/services/invoicing https://uri.paypal.com/services/vault/payment-tokens/read https://uri.paypal.com/services/disputes/read-buyer https://uri.paypal.com/services/payments/realtimepayment https://uri.paypal.com/services/disputes/update-seller https://uri.paypal.com/services/payments/payment/authcapture openid https://uri.paypal.com/services/disputes/read-seller Braintree:Vault https://uri.paypal.com/services/payments/refund https://api.paypal.com/v1/vault/credit-card https://api.paypal.com/v1/payments/.* https://uri.paypal.com/payments/payouts https://uri.paypal.com/services/vault/payment-tokens/readwrite https://api.paypal.com/v1/vault/credit-card/.* https://uri.paypal.com/services/subscriptions https://uri.paypal.com/services/applications/webhooks",
"access_token": "A21AAL0lvt6p5QhxL5p6KusbbwMNu8o_DWDyNHHWAc3KuOBK7MO4YY3s_1CTMiY1BCAZwQ-dX7MzixsxY5StFfEFrSI2pamNg",
"token_type": "Bearer",
"app_id": "APP-80W284485P519543T",
"expires_in": 32400,
"nonce": "2021-02-22T11:42:28ZIt4HFB53zPnqZtMo8CeBA17Aj1MKaRQDVAVRE9VqUJg"
}
My code that errors
fetch('https://api.sandbox.paypal.com/v1/oauth2/token',{ grant_type: 'client_credentials' },
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic QVVydEp4Y0hmTVVsRGpIZ1YyRkhNT1Vuek1rVWV1ODZfa203aDY3dUVIekg1YjVSTjdWby1xOEFZUHRjZHo3SWFpb2M0NnhXMEg5SlFabVQ6RU1iYkotWXFRTFQ2bGl1UHRKVVJxMnBBZ2g5V3VVVERLbVYzNTVfVkllQURzdDBCTWxuVU5LaUhWTEs3aXRDeVpGWHJFUU9leDlwOTNXTzg='
}
}) .then(response => response.json())
.then(async (data) => {
console.log(data)
})
.catch(function (error) {
let edata = error.message;
console.log('Error:', edata)
}
)
Wrong syntax for fetch (why separate object parameters?) and wrong syntax for URL-encoded form data in the part of the object intended as body.
Therefore, no request headers and also no form post data (in body) are being set for your call -- it evaluates and runs as a blank request to the endpoint, hence the error.
Here's how to do it
fetch('https://api.sandbox.paypal.com/v1/oauth2/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa('YOUR_CLIENTID:YOUR_SECRET')
},
body: 'grant_type=client_credentials'
}).then(response => response.json())
.then(async (data) => {
console.log(data)
}).catch(function (error) {
let edata = error.message;
console.log('Error:', edata)
}
I don't know how to get more information after subscription.
The following returns an error:
paypal.Buttons({
createSubscription: function (data, actions) {
console.log(data)
return actions.subscription.create({
'plan_id': PP_PLAN_ID
})
},
onApprove: function (data, actions) {
console.log(data)
fetch(`https://api.sandbox.paypal.com/v1/billing/subscriptions/${data.subscriptionID}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${data.facilitatorAccessToken}`
}
})
.then((r) => {
return r.json()
})
.then((r) => {
console.log(r)
})
}
}).render('#paypal-button-container')
Error response
{
"name": "NOT_AUTHORIZED",
"message": "Authorization failed due to insufficient permissions.",
"debug_id": "e0ba8b67ee540",
"details": [
{
"issue": "PERMISSION_DENIED",
"description": "You do not have permission to access or perform operations on this resource."
}
],
"links": [
{
"href": "https://developer.paypal.com/docs/api/v1/billing/subscriptions#NOT_AUTHORIZED",
"rel": "information_link",
"method": "GET"
}
]
}
I'm guessing some configuration is missing because of the permission error. Any pointers?
This is not a client-side operation, and a ClientID access token will not have permission.
You need to obtain the access token from a server, using a ClientID and Secret: https://developer.paypal.com/docs/api/overview/#get-an-access-token
I am writing a program which has a "sign up" functionality. The front-end is created using React.JS. So far, I am able to using this code to send a post request in React.JS:
fetch('http://localhost:2000/users/signup/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"email": "testing#gmail.com",
"password": "secret",
"name": "matthew",
"organization": "Apple"
})
}).then(function(response) {
return response.json();
});
This works perfectly - for the user information is now in the database. However I am not sure how to get the response JSON using response.json(). I want to be able to take the response, get the message string, and display it to my user on the front-end. This is the response when I run the same post request on Postman.
{
"message": "New user created"
}
Thanks for the help!
response.json() returns a promise, so you need one more then to get the actual data:
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
see https://developer.mozilla.org/en-US/docs/Web/API/Body/json