Search code examples
asp.netasp.net-mvcsquare-connect

422 error when charging the card nonce using Square Connect


I am asp.net developer. I used Square Connect Api for payment transaction. Below is my code for charging card nonce. But I am getting error(unsupported media type \"application/x-www-form-urlencoded\", only [application/json] are allowed) in response. Solutions are appreciated.

Square Connect REquest:::

       RestSharp.RestClient Client = new RestSharp.RestClient("https://connect.squareup.com");
        RestSharp.RestRequest Request = new RestSharp.RestRequest("v2/locations/"+LocationId+"/transactions", RestSharp.Method.POST);
        Request.RequestFormat = RestSharp.DataFormat.Json;
        Request.AddHeader("Authorization", "Bearer " + access_token);
        Request.AddHeader("Accept", "application/json");
        Request.AddHeader("Content-Type", "application/json");

        Request.AddParameter("name", "test");
        Request.AddParameter("card_nonce", card_nonce);
        Request.AddParameter("amount_money", "{\"amount\":100,\"currency\":\"USD\"}");
        //Request.AddParameter("idempotency_key", Guid.NewGuid().ToString());

        RestSharp.IRestResponse response = Client.Execute(Request);
        System.Net.HttpStatusCode getresponse = response.StatusCode;

Response From Square Up: {"errors":[{"category":"INVALID_REQUEST_ERROR","code":"BAD_REQUEST","detail":"unsupported media type \"application/x-www-form-urlencoded\", only [application/json] are allowed"}]}


Solution

  • (Fair warning that I don't have prior experience using RestSharp.)

    It appears that when creating a request with a body (i.e., a POST or a PUT), you must set the request's content type with the AddParameter method, rather than with the AddHeader method.

    As this answer demonstrates, when your request has a body, you call AddParameter only once:

    Request.AddParameter("application/json", strJSONContent, ParameterType.RequestBody);
    

    The first parameter specifies the content type, the second parameter is the entire JSON string you want to POST, and the third parameter indicates that the JSON string should be used as the request body.

    This means that you will need to construct the JSON string you want to POST before calling this method.