Search code examples
c#paypal

PayPal API oauth2 request in C#: 401 unauthorized


I am trying to send auth request to PayPal API URL with username and password when I run the code I get:

The remote server returned an error: (401) Unauthorized Error.

This is the code:

private static HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api-m.sandbox.paypal.com/v1/oauth2/token");

        static void Main(string[] args)
        {
            string username = "..client id..";
            string password = "..client secret..";

            string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password));
            request.Method = WebRequestMethods.Http.Post;
            request.Accept = "application/json";
            request.Headers.Add("Authorization", "Basic " + svcCredentials);

            string text;
            var response = (HttpWebResponse)request.GetResponse();

            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                text = sr.ReadToEnd();
            }

            Console.WriteLine(text);
            Console.Read();
        }

Solution

  • It appears you're missing a request body with the contents: grant_type=client_credentials

    See PayPal's guide for REST API authentication, which has curl and postman samples.