node.jsexpresscurloauthpayu

Requesting OAuth credentials with node


Im implementing PayU API with node.js. This is the request example for obtaining access token that is written in PayU´s documentation

curl -X POST https://secure.payu.com/pl/standard/user/oauth/authorize \
-d 'grant_type=client_credentials&client_id=145227&client_secret=12f071174cb7eb79d4aac5bc2f07563f'

It is a curl request , so it works well when it is sent from the command line, but I need to send it from express server. Any ideas how can this be done?


Solution

  • You can use request module for making HTTP requests. The first argument to request can either be a URL string, or an object of options.

    url: The destination URL of the HTTP request

    method: The HTTP method to be used (GET, POST, DELETE, etc)

    headers: An object of HTTP headers (key-value) to be set in the request

    Example.

    var request = require('request');
    
    options = {
        "method":"POST",
        "url": "https://secure.payu.com/pl/standard/user/oauth/authorize",
        "headers": {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      "body": "grant_type=client_credentials&client_id=145227&client_secret=12f071174cb7eb79d4aac5bc2f07563f"
    }
    
    request(options, function(err, res, body){
      if(err){
        console.log(err);
      }
      const data = JSON.parse(body);
      console.log(data.access_token)
    });