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?

GiveMeAllYourCats
  • 890
  • 18
  • 23
gloo
  • 2,490
  • 3
  • 22
  • 38
  • I think this answer describes the process from the server side. http://stackoverflow.com/a/5957629/2966874 – aembke Mar 20 '14 at 17:58

2 Answers2

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.

Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85
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}`
  // ...
joematune
  • 1,087
  • 10
  • 16