6

I am trying to implement a curl request in node. In curl you can perform the following POST request:

curl -v https://api.sandbox.paypal.com/v1/oauth2/token \
  -H "Accept: application/json" \
  -H "Accept-Language: en_US" \
  -u "client_id:client_secret" \
  -d "grant_type=client_credentials"

I understand how to set headers and write the data payload using the node http module, but how do i implement -u client_id:client_secret using the http module?

1

2 Answers 2

3

Currently I do not know nodejs. But as you know how to set the Headers -H from nodejs, I believe I can help you now! -u client_id:client_secret is equivalent to the following one:

-H "Authorization: Basic XXXXXXXXXXXXX"

Here XXXXXXXXXXXXX is the base64 of the string client_id:client_secret. Don't forget the : at the middle of them.

Sign up to request clarification or add additional context in comments.

Comments

0

curl -u base64 encodes the "username:password" string and appends the result as a header.

In nodejs, it's as simple as adding auth field to http.request's options.

const req = http.request({
  hostname: "api.sandbox.paypal.com",
  path: "/v1/oauth2/token",
  auth: "client_id:client_secret",
  // ...

Behind the scenes, node is base64 encoding the string and adding a formatted header. If you're using another http client, it may also be helpful to know how to manually add the header.

  1. base64 encode your "username:password" with the Buffer module:
const credentials = Buffer.from("client_id:client_secret").toString("base64");
  1. Add the base64 encoded string as a header in the following format:
const req = http.request({
  hostname: "api.sandbox.paypal.com",
  path: "/v1/oauth2/token",
  headers: {
    Authorization: `Basic ${credentials}`
  // ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.