Search code examples
node.jspaypalaccess-tokenpaypal-rest-sdksuperagent

How to fix grant_type error is NULL - unsupported grant type with Pay Pal's REST API for access token


I'm calling Paypal's REST API to get an access token https://developer.paypal.com/docs/api/overview/#get-an-access-token

I'm using node with superagent to make the AJAX call.

Here is my code:

const basicAuth = Buffer.from(`${PAYPAL_CLIENT}:${PAYPAL_SECRET}`).toString('base64')

request
  .post(PAYPAL_OAUTH_API)
  .set('Accept', 'application/json')
  .set('grant_type', 'client_credentials')
  .set('Authorization', `Basic ${basicAuth}`)
  .send()
  .end((result) => {
    console.log(result.response.error)
  })

And here is the logs with the errors I'm getting


{ Error: cannot POST /v1/oauth2/token/ (400)
    at Response.toError (C:\Users\shlomo\projects\tribewise-backend-v1\node_modules\superagent\lib\node\response.js:94:15)
    at ResponseBase._setStatusProperties (C:\Users\shlomo\projects\tribewise-backend-v1\node_modules\superagent\lib\response-base.js:123:16)
    at new Response (C:\Users\shlomo\projects\tribewise-backend-v1\node_modules\superagent\lib\node\response.js:41:8)
    at Request._emitResponse (C:\Users\shlomo\projects\tribewise-backend-v1\node_modules\superagent\lib\node\index.js:850:20)
    at parser (C:\Users\shlomo\projects\tribewise-backend-v1\node_modules\superagent\lib\node\index.js:1036:38)
    at IncomingMessage.res.on (C:\Users\shlomo\projects\tribewise-backend-v1\node_modules\superagent\lib\node\parsers\json.js:19:7)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickDomainCallback (internal/process/next_tick.js:218:9)
  status: 400,
  text: '{"error":"unsupported_grant_type","error_description":"Grant Type is NULL"}',
  method: 'POST',
  path: '/v1/oauth2/token/' }

Why am I getting an error unssuported grant type - the grant type is NULL? In postman it works but I can't get it to work with superagent and node. Paypal gives two examples here with postman and curl. Why is it not working with superagent?


Solution

  • From paypal docs which you've linked to:

    If you use a command-line tool other than cURL, set the Accept header to application/x-www-form-urlencoded

    From superget docs which you've linked to:

    By default sending strings will set the Content-Type to application/x-www-form-urlencoded

    So change your request to:

    // PAYPAL_LINK = "https://api.sandbox.paypal.com"
    // PAYPAL_OAUTH_API = "/v1/oauth2/token"
    request(PAYPAL_LINK)
      .post(PAYPAL_OAUTH_API)
      .send('grant_type=client_credentials')
      .auth(PAYPAL_CLIENT, PAYPAL_SECRET)
      .then(response => console.log(response))
      .catch(error => console.error(error))
    

    Optionally set Accept: application/json if you want response as json