Paypal says to make the following curl request
curl -v POST https://api-m.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-u "CLIENT_ID:SECRET" \
-d "grant_type=client_credentials"
However, I want to instead do that through an HTTP request. I tried the following:
const HTTP = require('http')
const data = JSON.stringify({
paypalclientid:paypalsecretid,
"grant_type": "client_credentials",
})
const options = {
host: 'api-m.sandbox.paypal.com',
port: 80,
path: '/v1/oauth2/token',
method: 'POST',
headers: {
'Accept': 'application/json',
"Accept-Language": "en_US"
}
}
const req = http.request(options, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})
req.on('error', error => {
console.error(error)
})
req.write(data)
req.end()
and I got the following:
<HTML><HEAD>
<TITLE>Access Denied</TITLE>
</HEAD><BODY>
<H1>Access Denied</H1>
You don't have permission to access "http://api-m.sandbox.paypal.com/v1/oauth2/token" on this server.<P>
Reference #18.9ce33e17.1609625956.708d702f
</BODY>
</HTML>
That is what you get when you do a normal GET request.
Authorization
header. Here's an example that works with a valid user
and pass
:
const https = require('https') const data = `grant_type=client_credentials`; const user = 'your client id'; const pass = 'your secret'; const authorization = `Basic ` + Buffer.from(`${user}:${pass}`).toString(`base64`); const options = { hostname: 'api.paypal.com', port: 443, path: '/v1/oauth2/token', method: 'POST', headers: { 'Authorization': authorization, 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': data.length }, } const req = https.request(options, res => { console.log(`statusCode: ${res.statusCode}`) res.on('data', d => { process.stdout.write(d) }) }) req.on('error', error => { console.error(error) }) req.write(data) req.end()
Seems you need basic authentication :
const options = {
auth: 'CLIENT_ID:SECRET',
...
You should also be using port 443 (HTTPS), as well as:
'Content-Type': 'application/x-www-form-urlencoded'
for this particular token request (almost all other PayPal REST endpoints take application/json
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.