[英]What is the equivalent of this REST PHP code in C#?
I'm using a REST API and their sample code is in PHP.我正在使用 REST API,它们的示例代码是 PHP 格式。 I don't know anything about PHP.我对 PHP 一无所知。 I already write a HttpClient code but the response is not what I expected.我已经写了一个 HttpClient 代码,但响应不是我所期望的。 Here is the PHP code:这是PHP代码:
$data = array("merchant_id" => "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"amount" => 1000,
"callback_url" => "http://www.yoursite.com/verify.php",
"description" => "خرید تست",
"metadata" => [ "email" => "info@email.com","mobile"=>"09121234567"],
);
$jsonData = json_encode($data);
$ch = curl_init('https://api.zarinpal.com/pg/v4/payment/request.json');
curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v1');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData)
));
$result = curl_exec($ch);
$err = curl_error($ch);
$result = json_decode($result, true, JSON_PRETTY_PRINT);
curl_close($ch);
if ($err) {
echo "cURL Error #:" . $err;
} else {
if (empty($result['errors'])) {
if ($result['data']['code'] == 100) {
header('Location: https://www.zarinpal.com/pg/StartPay/' . $result['data']["authority"]);
}
} else {
echo'Error Code: ' . $result['errors']['code'];
echo'message: ' . $result['errors']['message'];
}
}
?>
and this is my c# code so far:到目前为止,这是我的 C# 代码:
string MerchantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
string CallbackURL = "www.mysite.com/backurl";
string data = $"{\"merchant_id\": \"{MerchantId}\", \"amount\": \"1000\",
\"callback_url\": \"{CallbackURL}\"";
JavaScriptSerializer serializer = new JavaScriptSerializer();
var jsondata = serializer.Serialize(data);
var stringContent = new StringContent(jsondata, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
var response = await client.PostAsync("https://api.zarinpal.com/pg/v4/payment/request.json", stringContent);
var result = await response.Content.ReadAsStringAsync();
and this is what I get as result
:这就是我得到的result
:
"{"data":[],"errors":{"code":-9,"message":"The input params invalid, validation error.","validations":[{"merchant_id":"The merchant id field is required."},{"amount":"The amount field is required."},{"callback_url":"The callback url field is required."},{"description":"The description field is required."}]}}" "{"data":[],"errors":{"code":-9,"message":"输入参数无效,验证错误。","validations":[{"merchant_id":"商户id字段为必填项。"},{"amount":"金额字段为必填项。"},{"callback_url":"回调url字段为必填项。"},{"description":"说明字段为必填项。 “}]}}”
What am I doing wrong?我究竟做错了什么?
I can see some possible sources of problems in you c# code, but I can not say for sure, as your snippet is not compilable.我可以在您的 c# 代码中看到一些可能的问题来源,但我不能肯定地说,因为您的代码段不可编译。
What I guess is that you are getting a wrong json serialization.我猜你得到了错误的 json 序列化。
You should place a breakpoint just after the assignment of jsondata
, and make sure the actual value of this variable is exactly:你应该在jsondata
赋值之后放置一个断点,并确保这个变量的实际值正好是:
"{\"merchant_id\":\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\",\"amount\":1000,\"callback_url\":\"www.mysite.com/backurl\"}"
You are using the c# interpolated string (prefix $
) to substitute the values of your variables in jsondata
.您正在使用 c# 内插字符串(前缀$
)来替换jsondata
变量的值。 However, whenever you use the interpolated string, the characters {
and }
are meaningful, and used to capture a value for substitution.但是,无论何时使用内插字符串,字符{
和}
都是有意义的,用于捕获替换值。
When you do $"{\\"merchant_id\\":
, whatever comes after {
must be a value or variable, and you are inserting a escape character \\"
, which is wrong.当您执行$"{\\"merchant_id\\":
, {
之后的任何内容都必须是值或变量,并且您正在插入转义字符\\"
,这是错误的。 What could work for this case is the interpolated verbatim string (prefix $@
).在这种情况下可以使用的是内插逐字字符串(前缀$@
)。
But instead of trying to write your json by hand, the best practice with c# is to use System.Text.Json
for serialization, with the method JsonSerializer.Serialize
, where you can pass a meaninful structured object, like a class, struct or dictionary.但不是尝试手动编写 json,c# 的最佳实践是使用System.Text.Json
进行序列化,使用方法JsonSerializer.Serialize
,您可以在其中传递有意义的结构化对象,如类、结构或字典.
In this example, I am using an anonymous object :在这个例子中,我使用了一个匿名对象:
string MerchantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
string CallbackURL = "www.mysite.com/backurl";
var data = new { merchant_id = MerchantId, amount = 1000, callback_url = CallbackURL };
var jsondata = JsonSerializer.Serialize(data);
var stringContent = new StringContent(jsondata, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
var response = await client.PostAsync("https://api.zarinpal.com/pg/v4/payment/request.json", stringContent);
var result = await response.Content.ReadAsStringAsync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.