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

Viewed 1471

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 ?

3 Answers

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.

In postman, the solution is turning off redirects, like on the image below:

postman redirects turoff

Also, I would like to add that the above answer by Mohammad is correct as to get the response URL we need to set AllowAutoRedirect to false. I have been trying to implement PayU LatAM WebCheckout in a console app and I was facing similar issue. I got some inspiration from the answer given here: How to get Location header with WebClient after POST request

Based on the answer, I wrote a sample code:

public class NoRedirectWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        var temp = base.GetWebRequest(address) as HttpWebRequest;
        temp.AllowAutoRedirect = false;
        return temp;
    }
}

After creating the above class, I wrote the following code in my Main method:

var request = MakeRequestLocation(new NoRedirectWebClient());
var psi = new ProcessStartInfo("chrome.exe");

psi.Arguments = request.ResponseHeaders["Location"];
Process.Start(psi);

I am now calling the function MakeRequestLocation inside the same class.

private static WebClient MakeRequestLocation(WebClient webClient)
{
    var loginUrl = @"https://sandbox.checkout.payulatam.com/ppp-web-gateway-payu/";
    NameValueCollection formData = new NameValueCollection
    {
        {"ApiKey", "4Vj8eK4rloUd272L48hsrarnUA" },
        {"merchantId", "508029" },
        {"accountId", "512321" },
        {"description", "Test PAYU" },
        {"referenceCode", "SomeRandomReferenceCode" },
        {"amount", "2" },
        {"tax", "0" },
        {"taxReturnBase", "0" },
        {"currency", "USD" },
        {"signature", "Signature generated via MD5 sum" },
        {"buyerFullName", "test" },
        {"buyerEmail", "test@test.com" },
        {"responseUrl", @"http://www.test.com/response" },
        {"confirmationUrl",  @"http://www.test.com/confirmation" }
    };
    webClient.UploadValues(loginUrl, "POST", formData);

    return webClient;
}

The object that is returned by the above function contains a header called location. The value of the location is your required URL for webcheckout.

Related