简体   繁体   中英

What is the equivalent of this REST PHP code in C#?

I'm using a REST API and their sample code is in PHP. I don't know anything about PHP. I already write a HttpClient code but the response is not what I expected. Here is the PHP code:


    $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:

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 :

"{"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."}]}}"

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.

What I guess is that you are getting a wrong json serialization.

You should place a breakpoint just after the assignment of jsondata , and make sure the actual value of this variable is exactly:

"{\"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 . 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. 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.

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM