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

3

7

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 ?

Metalline answered 1/7, 2019 at 14:31 Comment(2)
What is the HTML? Is it an error page?Em
@Amy Hi, the html contains a huge svg file you can find the html file for your reference drive.google.com/…Metalline
M
6

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.

Metalline answered 2/7, 2019 at 13:15 Comment(2)
So basically they send the proper JSON with a 302 header redirecting to payment site. If redirect is disabled (in case of HttpWebRequest request.AllowAutoRedirect = false;) the JSON can be read normally from the response. The only reason I'm writing this comment is because, I couldn't get it from this question and answare (even though it's there) nor from API Documentation (and it's there as well). If I had trouble with this, maybe someone else will find this comment useful.Keifer
You saved my day, I was searching for a way to reach out to those guys, but this was much faster, thank you for sharing this answer.Stooge
W
6

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

postman redirects turoff

Worked answered 17/6, 2020 at 9:44 Comment(0)
P
0

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", "[email protected]" },
        {"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.

Premedical answered 12/5, 2020 at 14:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.