PayPal REST API fetch for access_token in react-native, "AUTHENTICATION_FAILURE" - paypal

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)
}

Related

axios post request returning wing ding symbols

I am able to successfully get a request through postman, however when i use axios to to my post request I get a status 200 but the returned data is just wing ding symbols.
here is my code for axios
const configAxios = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
axios
.post(url + 'connect/token', params, configAxios)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
Here is the return value.
���������⌂�N▼~����O�����ӟ�Ƀ����w~������͗{�������vwg�h~v����{/⌂zQ�^�O�=�⌂p�����_�
V��O�_<]>���☼��|q��ᓋ��Y�����ߙ�8}����꧿]����^�^���}^���ç�W_�{��էg�Κ�>ث▬?�����^��N�^����I���D�;����I5����⌂�t6�>x��↨U��‼m����d{y���⌂�������~ж_�>;/�/>⌂�{7�v�[⌂�ݫ����>�����f�s���>,�]}4�(⌂�*���♂��{���>b�����UN|�$�꼦vʹ�☼�>}v�*~�Wy6���?��§('♥
Here is the expected results that I get from postman
{
"access_token": {access_token},
"expires_in": 3600,
"token_type": "Bearer",
"scope": "api_read"
}
Add { 'accept-encoding': '*' } in the header.

PayPal Integration and payment status in react native

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>

Getting POST Request Message using React.JS

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

How to handle restful web service response in react native?

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.
});

Sending push notification using ionicframework cloud api

Hello am trying to send push notification from my nodejs server to ionicframework API and am getting an error here is my code
var token = '66a5c472b52d3210b591f717b5b996312f8xxxxxxxxxxxx';
var title = 'test';
var message = 'message';
var options = {
method: 'POST',
url: 'https://api.ionic.io/push/notifications',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
json : {
"send_to_all": true,
"profile" : "my-profile",
"notification": {
"title": title,
"message": message,
"android": {
"title": title,
"message": message
},
"ios": {
"title": title,
"message": message
}
}
}
};
request(options, function(err, response, body) {
if (err) throw new Error(err);
console.log(body);
});
am getting this error
{ error:
{ message: 'JWT decode error occurred.',
link: null,
type: 'Unauthorized' },
meta:
{ status: 401,
version: '2.0.0-beta.0',
request_id: '75726406-3060-4329-a59e-3bd7f9ca90c8' } }
What could I be doing wrong
I think there is issue with your authorization header.
In header you're putting token, but please make sure it is API token.
Also make a postman request first and check whether it is working fine.
add content-type and authroization parts in header only..
then check the difference..
Thanks
Basu