How do I add body for PayPal partial refund to Axios? - axios

I'm trying to post a partial refund to PayPal using Axios. If I use an empty object as the body I can complete a full refund. But I don't know how to add a body that will complete a partial refund. Here is my current code:
const axios = require('axios');
const qs = require('qs');
const refund = await axios.post("https://api-m.sandbox.paypal.com/v1/payments/capture/"
+ "myTransactionID" + "/refund",
qs.stringify({data:{amount:{currency_code:'USD',value:'20.00'}}}), //this works if I just use {};
{
headers: {
"Content-Type": `application/json`,
"Authorization": `Bearer ${ "myPayPalAccessToken" }`
},
});
console.log("refund: " + JSON.stringify(refund));
I get a "Request failed with status code 400" when I do this. I'm not sure if using a data object is necessary. Please help me figure out the syntax.

I figured it out. I should have been using application/json for the Content-Type. There was no need to stringify the body:
const axios = require('axios');
const qs = require('qs');
const PAYPAL_OAUTH_API = 'https://api.sandbox.paypal.com/v1/oauth2/token/';
const PAYPAL_PAYMENTS_API = 'https://api.sandbox.paypal.com/v2/payments/captures/';
const PayPalAuthorization = await axios({
method: 'POST',
url: PAYPAL_OAUTH_API,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Credentials': true
},
data: qs.stringify({
grant_type: 'client_credentials'
}),
auth: {
username: PAYPAL_CLIENT,
password: PAYPAL_SECRET
}
});
const PayPalToken = PayPalAuthorization.data.access_token;
const refund = await axios({
url: PAYPAL_PAYMENTS_API + "myTransactionID" + '/refund',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${ PayPalToken }`
},
data: {
amount: {
value: "10.99",
currency_code: "USD"
},
invoice_id: "INVOICE-123",
note_to_payer: "Defective product"
}
});
If you are posting an invoice_id don't forget to change the number for subsequent refunds.
Also check out these links:
https://developer.paypal.com/docs/checkout/integration-features/refunds/
https://developer.paypal.com/docs/api/payments/v2#captures_refund

Related

Connecting to WhatsApp API using axios.post using TypeScript

I just started using the WhatsApp Cloud API.
I took the example that was provided on glitch as a reference but there are things that are different since I'm taking the serverless approach.
As seen in glitch's example, it used axios(config) method and I tried it out and it worked fine after minor changes but when I tried axios.post() method I keep on getting the following error:
AxiosError: Request failed with status code 400
The axios(config) method (Which works)
await axios({
method: "POST", // Required, HTTP method, a string, e.g. POST, GET
url:"https://graph.facebook.com/{{Version}}/{{Phone-Number-ID}}/messages?access_token={{Token}}",
data: {
messaging_product: "whatsapp",
recipient_type: "individual",
to: {{Recipient-Phone-Number}},
text: {body: "Welcome back"},
},
headers: {"Content-Type": "application/json"},
});
The axios.post() method (Which doesn't works)
let url = "https://graph.facebook.com/{{Version}}/{{Phone-Number-ID}}/messages"
let payload = {
messaging_product: "whatsapp",
recipient_type: "individual",
to: {{Recipient-Phone-Number}},
text: {body: "Welcome back my friend"},
}
let headers = {"Content-Type": "application/json", "Authorization":"Bearer {{token}}"
}
let params = {}
try
{
const resp = await axios.post(url, {payload}, {headers, params});
log("POST RESP",resp)
}
catch(error)
{
throw error;
}
Try below code.
let url = 'https://graph.facebook.com/<Version>/<Your Phone number ID>/messages';
let payload = {
'messaging_product': 'whatsapp',
'recipient_type': 'individual',
'to': '123456789012',//Recipient Phone Number
'type': 'text',
'text': {
'body': 'Welcome back my friend'
}
};
let headers = {
'Authorization': 'Bearer <Your Temporary access token>',
'Content-Type': 'application/json'
};
axios.post(url, payload, {
headers: headers
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

Axios bad request 400 Spotify post

I am getting a bad request of 400 from Axios for trying to get the token from the Spotify API. Can someone please look at my code?. I would really appreciate someone's help.
app.get("/auth/callback", async (req, res) => {
try{
let code = req.query.code || null;
let state = req.query.state || null;
let data = qs.stringify({
grant_type: "authorization_code",
code: code,
redirect_uri: redirect_uri,
});
const response = await axios.post('https://accounts.spotify.com/api/token', data,
{
headers: {
'Authorization': `Basic ${Buffer.from(client_id + ':' + client_secret).toString('base64')}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
})
res.send(response)
}catch(error){
res.send(error)
}
})

How to authorize to GitHub API using axios

How can I authorize to https://api.github.com using GitHub auth token and axios?
const axiosInstance = axios.create({
baseURL: 'https://api.github.com',
headers: {
Authorization: 'Bearer AUTH_TOKEN_HERE'
}
});
let response = await axiosInstance.get('/');
const fetchRepo = async () => {
const response = await axios.get(URL, {
method: "GET",
headers: {
'Authorization': 'token AUTH_TOKEN_HERE',
}
});
console.log(await response);
return response.data;
}

node.js / axios AUTHENTICATION_FAILURE with PayPal Subscriptions API

I'm using Axios to activate a PayPal subscription since the NODE SDK doesn't support the subscription activation. For doing so I've created this method that generate a PayPal access token:
let getAccessToken = async () => {
return await axios(options).then((response) => {
return response.data.access_token
});
}
the options contains the following details:
const options = {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Credentials': true
},
data: qs.stringify(data),
auth: {
username: PAYPAL_CLIENT_ID,
password: PAYPAL_CLIENT_SECRET
},
url: 'https://api.sandbox.paypal.com/v1/oauth2/token'
}
this working fine but I'm having some problems activating the subscription, this is the method that handle this:
let activateSubscription = async (accessToken, subscriptionId) => {
return await axios.post(
`${baseURL}/v1/billing/subscriptions/${subscriptionId}/activate`,
{
headers: {
"Authorization": `Bearer ${accessToken}`,
"Content-Type": 'application/json'
}
}).then((data) => {
return true;
})
.catch((error) => {
console.log(error.response.data);
return false;
});
}
Essentially I pass the generated accessToken and the subscriptionId, but I get as response this:
{
name: 'AUTHENTICATION_FAILURE',
message: 'Authentication failed due to invalid authentication credentials or a missing Authorization header.',
links: [
{
href: 'https://developer.paypal.com/docs/api/overview/#error',
rel: 'information_link'
}
]
}
My suspicion was that the generated token was incorrect, so I tried it in postman sending this request:
{{host}}/v1/billing/subscriptions/I-7D10FGKVNMD0/activate
and the returned content is 204 which is okay according to what doc says here.
The request seems correct, what am I doing wrong?
You're setting the headers wrong. From the pastebin:
data: '{"headers":{"Authorization":"Bearer A21AAEj_0lJjny7Hc1aL7l5irIxOqOjyW_pSfT2WC9APAQFXHTYzKL0womW1mZvS6mKWsWMytMc6H6NIMPMnOK7zhzHKHsSAw","Content-Type":"application/json"}}',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8',
'User-Agent': 'axios/0.19.2',
'Content-Length': 170
},
So, PayPal isn't actually getting your Authorization header

Posting Images using formData to a Django Rest API

I have a Django Rest API backend and am using a React Native Front End. I wanted to save an image to the rest API.
The POST method used is as follows:
async saveUserData() {
let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN);
var formData = new FormData();
formData.append("bio",this.state.bio);
formData.append("website",this.state.website);
formData.append("phoneno",this.state.phoneno);
formData.append("gender",this.state.gender);
formData.append("avatar",this.state.avatar.uri);
try {
let response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': ' Token '+accessToken,
},
body: formData
});
let responseJson = await response.text();
if(response.status>=200&&response.status<300){
console.log("POST Completed");
}else{
let error=responseJson;
console.log(error);
throw error;
}
return responseJson;
} catch(error) {
return error;
console.error(error);
}
}
I get the following error
{"avatar":["The submitted data was not a file. Check the encoding type on the form."]}
I have also tried this.state.avatar.data and tried to post it but I end up getting the same error. I know that the file upload works fine as I can do it properly from the REST Autogenerated form. What seems to be the problem in the image I am posting?
Here is how you can do it:
var formData = new FormData();
formData.append('avatar', {uri: this.state.avatar.uri, name: 'yourname.jpg', type: 'image/jpg'});
let response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': ' Token '+accessToken,
},
body: formData
});