跳到主要内容

C#示例使用说明

该示例适用于C#编程语言,可以调用所有OpenAPI接口。示例封装了执行集成的过程,包括添加和验证调用支付网关API的签名。这只是一个例子,我们不保证代码适用于任何编程环境。它只是演示如何调用我们的API。您可以参考此代码来编写自己的程序。

使用条件

适用于符合的各种Microsoft框架。Net Standard 2.0规范(如.Net Framework>=4.6.1、.Net Core>=2.0等)。

下载地址

使用步骤

1. 添加依赖项并使用NuGet等工具下载以下包

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

Newtonsoft.Json 解析和处理Json数据包的工具。

2. 请参阅GitHub示例代码并编写您的程序,以下是主要代码:

    // 1. Global parameter settings
string appRsaPrivateKeyPem = "<YOUR APP RSA PRIVATE KEY>";
string gatewayRsaPublicKeyPem = "<YOUR GATEWAY RSA PUBLIC KEY>";
string gatewayUrl = "<YOUR GATEWAY URL>";
string appId = "<YOUR APP ID>";

// 2. Set parameters
Dictionary<string, string> parameters = new Dictionary<string, string>();
// Common parameters
parameters.Add("app_id", appId);
parameters.Add("charset", "UTF-8");
parameters.Add("format", "JSON");
parameters.Add("sign_type", "RSA2");
parameters.Add("version", "1.0");
parameters.Add("timestamp", "" + DateTimeOffset.Now.ToUnixTimeMilliseconds());
parameters.Add("method", "order.query");
// API owned parameters
parameters.Add("merchant_no", "312100000164");
parameters.Add("merchant_order_no", "TEST_1685946062143");

// 3. Build a string to be signed
string stringToBeSigned = buildToBeSignString(parameters);
Console.WriteLine("StringToBeSigned : {0} \n", stringToBeSigned);

// 4. Calculate signature
string sign = GenerateSign(stringToBeSigned, appRsaPrivateKeyPem);
parameters.Add("sign", sign);

// 5. Send HTTP request
string jsonString = JsonConvert.SerializeObject(parameters);

Console.WriteLine("Request to gateway[" + gatewayUrl + "] send data -->> " + jsonString + "\n");

var responseStr = "";
try{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = httpClient.PostAsync(gatewayUrl, new StringContent(jsonString, Encoding.UTF8, "application/json")).Result;
if (response.IsSuccessStatusCode){
responseStr = response.Content.ReadAsStringAsync().Result;
Console.WriteLine("Response from gateway[" + gatewayUrl + "] receive data <<-- " + responseStr + "\n");
}
else{
Console.WriteLine("Request to gateway[" + gatewayUrl + "] failed: " + response);
return;
}
}catch (Exception ex){
Console.WriteLine("Request exception: " + ex.Message);
}

// 6. Verify the signature of the response message
Dictionary<string, string> respParameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseStr);
string respStringToBeSigned = buildToBeSignString(respParameters);
Console.WriteLine("RespStringToBeSigned : {0} \n", respStringToBeSigned);
string respSignature = respParameters["sign"];
bool verified = VerifySignature(respStringToBeSigned, respSignature, gatewayRsaPublicKeyPem);
Console.WriteLine("SignVerifyResult : {0}", verified);