我正在尝试计算该字典的 MD5 哈希值
Dictionary<string, string> data = new Dictionary<string, string>
{
{ "PAYGATE_ID", companyInfo.PayGateId },
{ "REFERENCE", reference },
{ "AMOUNT", $"{pGPayReqDTO.Amount}" },
{ "CURRENCY", $"{companyInfo.PayGateCurrency}" },
{ "RETURN_URL", "mydomain/api/Paygate/ReturnFromPaygate" },
{ "TRANSACTION_DATE", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
{ "LOCALE", "en" },
{ "COUNTRY", $"{companyInfo.PayGateCountryCode}" },
{ "EMAIL", $"{pGPayReqDTO.Email}" },
{ "NOTIFY_URL", $"mydomain/api/Paygate/Notify" },
};
以上样例作品 但下面的示例没有,唯一的区别是 NOTIFY_URL 有参数。然而,当我尝试计算这个校验和时,它确实给了我该值,然后我将其发送到 Paygate 支付网关。但是,当他们使用同一字典来计算校验和时,他们给我一个错误,说校验和计算不正确。
Dictionary<string, string> data = new Dictionary<string, string>
{
{ "PAYGATE_ID", companyInfo.PayGateId },
{ "REFERENCE", reference },
{ "AMOUNT", $"{pGPayReqDTO.Amount}" },
{ "CURRENCY", $"{companyInfo.PayGateCurrency}" },
{ "RETURN_URL", "mydomain/api/Paygate/ReturnFromPaygate" },
{ "TRANSACTION_DATE", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
{ "LOCALE", "en" },
{ "COUNTRY", $"{companyInfo.PayGateCountryCode}" },
{ "EMAIL", $"{pGPayReqDTO.Email}" },
{ "NOTIFY_URL", $"mydomain/api/Paygate/Notify?domain={domain}&CustomerId={pGPayReqDTO.CustomerId}&CartId={pGPayReqDTO.CartId}&BranchId={pGPayReqDTO.BranchId}" },
};
我想做的计算是这样的
using (MD5 md5Hash = MD5.Create())
{
string dataString = string.Join("", data.Values) + companyInfo.PayGateSecret;
byte[] checksumBytes = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(dataString));
StringBuilder checksumBuilder = new StringBuilder();
for (int i = 0; i < checksumBytes.Length; i++)
{
checksumBuilder.Append(checksumBytes[i].ToString("x2"));
}
data["CHECKSUM"] = checksumBuilder.ToString();
// return sBuilder.ToString();
}
在第二个网址中,您有查询参数
domain
、CustomerId
、CartId
、BranchId
,并且值是动态的,因此它会在请求之间发生变化。因此它每次都会生成不同的 url。
您可以尝试以下代码:
using System;
using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
Dictionary<string, string> data = new Dictionary<string, string>
{
// actual dictionary contents...
};
string concatenatedString = string.Join("", data.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value));
string md5Hash = CalculateMD5Hash(concatenatedString);
Console.WriteLine(md5Hash);
}
public static string CalculateMD5Hash(string input)
{
using (MD5 md5 = MD5.Create())
{
byte[] inputBytes = Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
}
}