Search code examples
c#restpayumoneypayu

Calling PayU rest api (create order) returns html instead of json response


I'm trying to post an order to PayU payment gateway, using Rest Client tools like post man also I got the same issue.

enter image description here

I'm trying to post using C#, the order created successfully but the response is not as expected, it should be a json object contains the inserted order id and the redirect url , but the current is html response!

C# Code response : enter image description here

My C# Code using restsharp library :

 public IRestResponse<CreateOrderResponseDTO> CreateOrder(CreateOrderDTO orderToCreate)
    {

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        var actionUrl = "/api/v2_1/orders/";

        var client = new RestClient(_baseUrl);

        var request = new RestRequest(actionUrl, Method.POST)
        {
            RequestFormat = DataFormat.Json
        };

        request.AddJsonBody(orderToCreate);


        request.AddHeader("authorization", $"Bearer {_accessToken}");
        request.AddHeader("Content-Type", "application/json");

        var response = client.Execute<CreateOrderResponseDTO>(request);

        if (response.StatusCode == HttpStatusCode.OK)
        {
            return response;
        }

        throw new Exception("order not inserted check the data.");


    }

My C# Code using built in WebRequest also returns same html :

 public string Test(string url, CreateOrderDTO order)
    {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Accept = "application/json";

        httpWebRequest.Method = "POST";
        httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + _accessToken);

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {

            streamWriter.Write(new JavaScriptSerializer().Serialize(order));
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }
    }

Can anyone advise what I missed here ?


Solution

  • After some tries I found that PayU rest api returns 302 (found) also ResponseUri not OK 200 as expected.

    by default rest client automatically redirect to this url so I received the html content of the payment page.

    The solution is :

    client.FollowRedirects = false;
    

    Hope this useful to anyone.