How to get the PayPal access-token needed to leverage the REST Api by using node?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
}
回答2:
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);
}
})();
回答3:
You could use PayPal-Node-SDK to make calls to PayPal Rest APIs. It handles all the authorization and authentication for you.
回答4:
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))