Search code examples
angularpaypalangular-httpclient

How to correctly send application/x-www-form-urlencoded in Angular post call


I'm trying to get Paypal access token and according to paypal, the data of the request is -d "grant_type=client_credentials" and have to send it in a application/x-www-form-urlencoded format, Below is the code that I'm trying now

let body = "grant_type=client_credentials"

return this.httpClient.post<any (`https://api.sandbox.paypal.com/v1/oauth2/token`,body);

and I'm setting the header in the auth interceptor like below

const copiedReq = req.clone({ 
    setHeaders: {
      'Authorization': `Basic  ${this.client_id}:${this.secrete}`, 
      'Accept': 'application/json',
      'Content-Type':'application/x-www-form-urlencoded',
    }
});
return next.handle(copiedReq); 

it always returning 401 Unauthorized but my client_id and secrete is okay because when I try the call with postman it's working fine

The Network Tab

The network tab it's working fine on the postman with same credential, but not here, what I'm doing wrong? How can I make a proper request to get the result

The Paypal curl example

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

Solution

  • Better late than never. I just had the same problem than you and I finally solved it. You have to base 64 encode your credentials:

    let credentials: btoa(`${this.client_id}:${this.secrete}`);
    
    const copiedReq = req.clone({ 
    setHeaders: {
      'Authorization': `Basic  `+credentials, 
      'Accept': 'application/json',
      'Content-Type':'application/x-www-form-urlencoded',
    }
    });
    return next.handle(copiedReq); 
    

    This just worked for me a few minutes ago. Hope it works for you next time :D