C# JSON with Chargify API

本文关键字:API Chargify with JSON | 更新日期: 2023-09-27 17:49:48

我是c#的新手,我正试图转换我在Chargify (https://docs.chargify.com/api-introduction)中创建订阅的PHP脚本。下面是我正在使用的代码。为了测试的目的,我硬编码了JSON字符串。经过一天的工作,我终于得到了一个422错误,但我不能为我的生活弄清楚是什么原因。我读了几篇关于JSON和c#的Stack Overflow的文章,但是没有任何帮助。希望,有人有更多的经验可以看看这个,并指出一些我错过了。提前感谢您对此事的见解。

   [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'":'"joe@example.com'"},'"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();
    }

C# JSON with Chargify API

您的代码对于发送JSON是正确的。错误码422是由于不可处理的数据。

在他们的文档中搜索'422' https://docs.chargify.com/api-charges除了错误码,还有一个JSON格式的错误响应,如:

{"errors":[
    "Memo: cannot be blank.",
    "Amount: is not a number."
  ]}

改正上面的错误,你就会没事了