I am new to C# and I am trying to convert a PHP script I have that creates subscriptions in Chargify (https://docs.chargify.com/api-introduction). Below is the code I am using. I hardcoded the JSON string for testing purposes. After a day of working out little kinks and errors, I finally got it to a point where I am getting a 422 error back, but I cannot for the life of me figure out what is causing it. I have read several posts on Stack Overflow concerning JSON and C# but nothing has helped. Hopefully, someone that has more experience can look at this and point out something I am missing. Thank you so much in advance for any insight into this matter.
[HttpPost]
public ActionResult Register(SignupViewModel regInfo)
{
string user = "xxxxxxxxxxxx";
string password = "x";
string jsonData = "{\"subscription\":{\"product_handle\":\"149-package\", \"coupon_code\" : \"\", \"customer_attributes\":{\"first_name\":\"Jerry\",\"last_name\":\"Jenkins\",\"email\":\"[email protected]\"},\"credit_card_attributes\":{\"full_number\":\"1\",\"expiration_month\":\"10\",\"expiration_year\":\"2020\"}, \"components\" : [{\"component_id\" : 80012, \"enabled\" : false}, {\"component_id\" : 80014, \"enabled\" : true}]}}";
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://o-asandbox.chargify.com/subscriptions.json");
var encodedStr = Convert.ToBase64String(Encoding.Default.GetBytes(string.Format("{0}:{1}", user, password)));
var authorizationKey = "Basic" + " " + encodedStr; // Note: Basic case sensitive
httpWebRequest.Headers.Add("Authorization", authorizationKey);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "Content-Type: application/json";
byte[] byteArray = Encoding.UTF8.GetBytes(jsonData);
httpWebRequest.ContentLength = byteArray.Length;
Stream dataStream = httpWebRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
return View();
}
Your code is correct for sending JSON. The errorcode 422 is because of unprocessable data.
Search for '422' in their docs https://docs.chargify.com/api-charges They state that along with the errorcode there is a error-response in JSON format like:
Correct the mentionend errors and you should be fine.