我想在添加订单 api 中添加自定义字段。如何创建这样的数组:“产品自定义字段值的 Base64 编码序列化数组的数组”
https://developers.whmcs.com/api-reference/addorder/
我已经尝试过
Dictionary<string, string> customfiled = new Dictionary<string, string>();
customfiled.Add("1", "Hello");
var tt2 = JsonConvert.SerializeObject(customfiled);
string str =Base64Encode(tt2);
我创建了一个类,它将保存序列化为 JSON 的键/值列表。
这是课程:
class ArrayOfBase64Array
{
// serialized JSON
private List<string> list = new List<string>();
public void Add(NameValueCollection collection)
{
foreach(var key in collection.AllKeys)
{
this.Add(key, collection[key]);
}
}
public void Add<T>(string key, T value) {
var dict = new Dictionary<string,T>();
dict.Add(key, value);
var json = JsonConvert.SerializeObject(dict);
list.Add(Base64Encode(json));
}
public string[] ToArray()
{
return list.ToArray();
}
string Base64Encode(string value)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
}
}
AddOrder 有效负载需要一个与此 C# 类匹配的形状:
// lots of fields omitted for brevity
class AddOrder
{
public string action {get;set;}
public string[] domain {get;set;}
public string[] customfields {get;set;}
}
要使用自定义字段创建 AddOrder 实例,您现在可以执行以下操作:
// create an AddOrder instance
var addOrder = new AddOrder
{
action = "AddOrder",
domain = new [] {"one.example.com", "two.example.com"}
};
// build our customfields collection
var cfarray = new ArrayOfBase64Array();
cfarray.Add("1", "FuBar");
cfarray.Add("2", 999);
cfarray.Add("3", true);
cfarray.Add("4", new JObject(new JProperty("Foo", 4711.42)));
// or if you have a namevaluecollection
var nvc = new NameValueCollection { {"5", "test namevalue 1"}, {"6", "another value"} };
cfarray.Add(nvc);
// store the customfields as an array of strings
addOrder.customfields = cfarray.ToArray();
这就是数据 POST 到服务器时的样子:
{ "action":"AddOrder",
"domain":["one.example.com","two.example.com"],
"customfields":[
"eyIxIjoiRnVCYXIifQ==",
"eyIyIjo5OTl9",
"eyIzIjp0cnVlfQ==",
"eyI0Ijp7IkZvbyI6NDcxMS40Mn19",
"eyI1IjoidGVzdCBuYW1ldmFsdWUgMSJ9",
"eyI2IjoiYW5vdGhlciB2YWx1ZSJ9"]
}
这就是每个编码的 Base64 字符串中的内容:
{"1":"FuBar"}
{"2":999}
{"3":true}
{"4":{"Foo":4711.42}}
{"5":"test namevalue 1"}
{"6":"another value"}