6

如何使用节点获取利用 REST Api 所需的 PayPal 访问令牌?

4

5 回答 5

18

拥有 PayPal 客户端 ID 和客户端密码后,您可以使用以下内容:

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

如果成功,响应将如下所示:

{
    "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
}
于 2015-02-06T08:10:31.107 回答
13

此外,您可以使用axios, 和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 (e) {
    console.error(e);
  }
})();
于 2019-04-01T15:58:01.720 回答
2

现代问题需要现代解决方案:

const fetch = require('node-fetch');
const authUrl = "https://api-m.sandbox.paypal.com/v1/oauth2/token";
const clientIdAndSecret = "CLIENT_ID:SECRET_CODE";
const base64 = Buffer.from(clientIdAndSecret).toString('base64')

fetch(authUrl, { 
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Accept-Language': 'en_US',
        'Authorization': `Basic ${base64}`,
    },
    body: 'grant_type=client_credentials'
}).then(function(response) {
    return response.json();
}).then(function(data) {
    console.log(data.access_token);
}).catch(function() {
    console.log("couldn't get auth token");
});
于 2020-11-14T05:16:53.437 回答
1

您可以使用PayPal-Node-SDK调用 PayPal Rest API。它为您处理所有授权和身份验证。

于 2015-02-06T22:36:16.817 回答
0

这是我使用 superagent 获取 access_token 的方法

        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))
于 2017-04-20T14:52:09.567 回答