Home > Enterprise >  how to translate curl into javascript POST request
how to translate curl into javascript POST request

Time:09-22

I am trying to connect to payment api named PayU, they provide example on how to connect via curl one is to connect via rest api

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

and one is to connect via SDK which I would also like to use, but this one needs additional settings in the shop, and I'm having trouble with the first one so if someone would be kind enough to decipher the other one as well would be great

curl -X POST https://secure.payu.com/pl/standard/user/oauth/authorize \
   -H "Cache-Control: no-cache"
   -H "Content-Type: application/x-www-form-urlencoded"
   -d 'grant_type=trusted_merchant&client_id=[provided by PayU]&client_secret=[provided by PayU]&email=[users email]&ext_customer_id=[Id of the customer used in merchant system]'

In curl the first one delivered the token without problems, however I am trying to do this same in code, and I am unable to. This is my code:

fetch('https://secure.payu.com/pl/standard/user/oauth/authorize', {
    method: 'POST',
    body: JSON.stringify({
        'grant_type': 'client_credentials',
        'client_id': '145227',
        'client_secret': '12f071174cb7eb79d4aac5bc2f07563f',
    })

  }).then(res => {
        if (!res.ok) {
          throw new Error("Fetching payU failed, please try again later!");
        }
        return res;
      })
      .then(data => {
       console.log(data)
       return { payUdata: data }
      })
      .catch(err => {
        console.log(err);
       
      });

CodePudding user response:

A basic Post body isn't a serialized json, data looks like query params, just like in the curl

{
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
    body: "grant_type=client_credentials&client_id=145227&client_secret=12f071174cb7eb79d4aac5bc2f07563f")
}

from @BankBuilder comment:

function querifyObject(obj){
 return new URLSearchParams(Object.entries(obj)).toString();
}

and then:

{
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
        body: querifyObject({
          'grant_type': 'client_credentials',
          'client_id': '145227',
          'client_secret': '12f071174cb7eb79d4aac5bc2f07563f',
        })
    }

Working screenshot

  • Related