asp.net 取得邮政Ems物流数据
一、引用dll
二、SM4加密
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
namespace EC
{
/// <summary>
/// Sm4Util 的摘要说明
/// </summary>
public class Sm4Util
{
/// <summary>
/// 使用 SM4 ECB 模式加密并返回 |$4|Base64 编码字符串
/// </summary>
public static string EncryptSm4ToLogitcsInterface(string jsonPayload, string base64Key)
{
// 解码 Base64 密钥
byte[] keyBytes = Convert.FromBase64String(base64Key);
// 拼接内容:json + key
string contentToEncrypt = jsonPayload + base64Key;
byte[] contentBytes = Encoding.UTF8.GetBytes(contentToEncrypt);
// 初始化 SM4 引擎
var engine = new SM4Engine(); // ECB mode by default
engine.Init(true, new KeyParameter(keyBytes)); // true for encryption
// 填充数据为 16 字节倍数(PKCS#7)
contentBytes = AddPadding(contentBytes, 16);
// 加密数据
byte[] encrypted = new byte[contentBytes.Length];
int blockSize = engine.GetBlockSize();
for (int i = 0; i < contentBytes.Length; i += blockSize)
{
engine.ProcessBlock(contentBytes, i, encrypted, i);
}
// Base64 编码 + 前缀
string base64 = Convert.ToBase64String(encrypted);
return "|$4|" + base64;
}
private static byte[] AddPadding(byte[] data, int blockSize)
{
int padding = blockSize - (data.Length % blockSize);
byte[] padded = new byte[data.Length + padding];
Array.Copy(data, padded, data.Length);
for (int i = data.Length; i < padded.Length; i++)
{
padded[i] = (byte)padding;
}
return padded;
}
}
}三、发送api请求接口
using System.Collections.Specialized; using System.Net;
string url = "https://api.ems.com.cn/amp-prod-api/f/amp/api/open";
string apiCode = "040001";
string senderNo = "生产协议客户号";
string authorization = "生产授权码";
string timeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string bw = "{\"waybillNo\": \"1027222554236\",\"direction\":\"0\"}";
string key = "生产签名钥匙";
string logitcsInterface = Sm4Util.EncryptSm4ToLogitcsInterface(bw, key);
// 创建 WebClient 实例
using (var client = new WebClient())
{
// 设置请求的 Content-Type 头
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
// 构建请求参数
var requestParameters = new NameValueCollection
{
{"apiCode", apiCode},
{"senderNo", senderNo},
{"authorization", authorization},
{"timeStamp", timeStamp},
{"logitcsInterface", logitcsInterface}
};
// 发送 POST 请求并获取响应
byte[] responseBytes = client.UploadValues(url, "POST", requestParameters);
string str = System.Text.Encoding.UTF8.GetString(responseBytes);
}