How to retrieve PayPal REST Api access-token using node

回眸只為那壹抹淺笑 提交于 2019-12-03 08:48:55

Once you have a PayPal client Id and a Client Secret you can use the following:

var request = require('request');

request.post({
    uri: "https://api.sandbox.paypal.com/v1/oauth2/token",
    headers: {
        "Accept": "application/json",
        "Accept-Language": "en_US",
        "content-type": "application/x-www-form-urlencoded"
    },
    auth: {
    'user': '---your cliend ID---',
    'pass': '---your client secret---',
    // 'sendImmediately': false
  },
  form: {
    "grant_type": "client_credentials"
  }
}, function(error, response, body) {
    console.log(body);
});

The response, if successful, will be something as the following:

{
    "scope":"https://api.paypal.com/v1/payments/.* ---and more URL callable with the access-token---",
    "access_token":"---your access-token---",
    "token_type":"Bearer",
    "app_id":"APP-1234567890",
    "expires_in":28800
}

Also, you can use axios, and async/await:

const axios = require('axios');

(async () => {
  try {
    const { data: { access_token } } = await axios({
      url: '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',
      },
      auth: {
        username: client_id,
        password: client_secret,
      },
      params: {
        grant_type: 'client_credentials',
      },
    });

    console.log('access_token: ', access_token);
  } catch (error) {
    console.log('error: ', error);
  }
})();

You could use PayPal-Node-SDK to make calls to PayPal Rest APIs. It handles all the authorization and authentication for you.

Here is how I get the access_token using superagent

        superagent.post('https://api.sandbox.paypal.com/v1/oauth2/token')
        .set("Accept","application/json")
        .set("Accept-Language","en_US")
        .set("content-type","application/x-www-form-urlencoded")
        .auth("Your Client Id","Your Secret")
        .send({"grant_type": "client_credentials"})
        .then((res) => console.log("response",res.body))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!