I want to build a payment API but I always get the following error:
{"Unexpected character encountered while parsing value: e. Path ”, line 0, position 0."}
The code looks like this:
var priceAmount = txtBoxTopUpBalance.Text;
var client = new RestClient("https://api.nowpayments.io/v1/invoice");
client.Timeout = -1;
var request1 = new RestRequest(Method.POST);
request1.AddHeader("x-api-key", apiKey);
request1.AddHeader("Content-Type", "application/json");
var body = @"{" + "n" +
@" ""price_amount"":" + priceAmount + "n" +
@" ""price_currency"": ""usd""," + "n" +
@" ""order_id"": ""RGDBP-21314""," + "n" +
@" ""order_description"": ""order #1""," + "n" +
@" ""ipn_callback_url"": ""https://nowpayments.io""," + "n" +
@" ""success_url"": ""https://nowpayments.io""," + "n" +
@" ""cancel_url"": ""https://nowpayments.io""" + "n" +
@"}" + "n" +
@"" + "n" +
@"";
request1.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response1 = client.Execute(request1);
JObject responseObject = JObject.Parse(response1.Content); // <--The error occurs here
invoiceUrl = responseObject["invoice_url"].ToString();
The issue is that ‘body’ can’t be parsed into a JSON object.
When I remove the priceAmount var it works, but it’s necessary.
I’m still a beginner, do you have any ideas?
2
Answers
Don’t build (serialize) the JSON manually. There will be a high chance of getting exposed to syntax errors such as missing quotes, missing opening/closing braces, etc.
Use JSON libraries such as System.Text.Json or Newtonsoft.Json to serialize to JSON.
From the sample NOWPayments API Create Invoice documentation, you should pass the
price_amount
as the number type.Or
You have a typo, need "," after priceAmount, but IMHO better to use this syntax. It was just tested and working Ok.