Search code examples
axiospaypal

How do I add body for PayPal partial refund to 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.


Solution

  • 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