After spending days working on setting up a functional payment portal on my website, I have hit a roadblock. My website does not directly sell products, but I do need to accept payments for invoices generated from my Paypal business account. To achieve this, I am looking to integrate an invoicing API that will allow users to view and pay their invoices through my website. However, to access this functionality, I first need to retrieve a list of invoices associated with the user's email address by utilizing the Invoiced API. To do this, I have to make a request to the Authentication API to obtain an access token.
The documentation for the Authentication API provides instructions for making the request using cURL and Postman. Although I am unfamiliar with both, I found a tool that converted the cURL request into a fetch request, resulting in the following code snippet:
fetch("https://api-m.sandbox.paypal.com/v1/oauth2/token", {
body: "grant_type=client_credentials",
headers: {
Authorization: "Basic PENMSUVOVF9JRD46PENMSUVOVF9TRUNSRVQ+",
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST"
})
Realizing that the Authorization property string is derived from the original cURL flag format, I further investigated and discovered a way to modify it by appending the Client ID and Client Secret as 'Bearer ' + CLIENT_ID:CLIENT_SECRET. After extracting the Client ID and Secret from environment variables and storing them as clientID and secret respectively on the server side, I attempted to use the following code:
const token = await fetch("https://api-m.sandbox.paypal.com/v1/oauth2/token", {
body: "grant_type=client_credentials",
headers: {
Authorization: `Bearer ${clientID}:${secret}`,
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST"
})
console.log(await token)
Upon execution, the following output was displayed:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: {
body: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
url: 'https://api-m.sandbox.paypal.com/v1/oauth2/token',
status: 401,
statusText: 'Unauthorized',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
}
}
{
name: 'AUTHENTICATION_FAILURE',
message: 'Authentication failed due to invalid authentication credentials or a missing Authorization header.',
links: [
{
href: 'https://developer.paypal.com/docs/api/overview/#error',
rel: 'information_link'
}
]
}