353 lines
13 KiB
C#
353 lines
13 KiB
C#
using Newtonsoft.Json;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Net;
|
||
using System.Net.Http;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
|
||
namespace WX.CRM.Common.StockHelper
|
||
{
|
||
public class ApiSignHelper
|
||
{
|
||
public ApiSignHelper(string username, string secret)
|
||
{
|
||
UserName = username;
|
||
Secret = secret;
|
||
}
|
||
/// <summary>
|
||
/// Get方法访问API
|
||
/// </summary>
|
||
/// <param name="param"></param>
|
||
/// <returns></returns>
|
||
public ApiResult<T> GetApi<T>(string url, Dictionary<string, object> param)
|
||
{
|
||
try
|
||
{
|
||
|
||
//拼接验证头
|
||
Dictionary<string, string> header = new Dictionary<string, string>();
|
||
var timestamps = GetTimeStamp();
|
||
var sign = GetSign(param, timestamps);
|
||
var authorization = $"{UserName}:{sign}";
|
||
|
||
header.Add("authorization", authorization);
|
||
header.Add("timestamps", timestamps);
|
||
|
||
//请求
|
||
var req = HttClientGet(url, param, header);
|
||
//LogHelper.Info("alipay:" + req);
|
||
//返回
|
||
var reqInfo = JsonConvert.DeserializeObject<ApiResult<T>>(req);
|
||
if (reqInfo == null)
|
||
{
|
||
return new ApiResult<T> { Code = 501, Message = "数据为空" };
|
||
}
|
||
return reqInfo;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
return new ApiResult<T> { Code = 501, Message = ex.Message };
|
||
}
|
||
}
|
||
#region 内部参数
|
||
private string UserName { get; set; }
|
||
private string Secret { get; set; }
|
||
//DG_SOFTWARE
|
||
//private string IdentityKey { get; set; }
|
||
#endregion
|
||
|
||
#region 内部方法
|
||
/// <summary>
|
||
/// 内置请求
|
||
/// </summary>
|
||
/// <param name=""></param>
|
||
/// <returns></returns>
|
||
private string HttClientGet(string url, Dictionary<string, object> param, Dictionary<string, string> header)
|
||
{
|
||
try
|
||
{
|
||
var urlParam = string.Join("&", param.Select(m => m.Key + "=" + m.Value));
|
||
if (url.IndexOf('?') > -1)
|
||
{
|
||
url = url + urlParam;
|
||
}
|
||
else
|
||
{
|
||
url = (url + "?" + urlParam);
|
||
}
|
||
|
||
//MethodInfo priMethod = webReq.Headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
|
||
//priMethod.Invoke(webReq.Headers, new[] { "Date", timestamps });
|
||
|
||
HttpRequestMessage httpRequestMessage = new HttpRequestMessage();
|
||
httpRequestMessage.RequestUri = new Uri(url);
|
||
httpRequestMessage.Method = HttpMethod.Get;
|
||
foreach (var item in header)
|
||
{
|
||
httpRequestMessage.Headers.TryAddWithoutValidation(item.Key, item.Value);
|
||
}
|
||
//HttpContent httpContent = new StringContent("");
|
||
//httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
|
||
//httpRequestMessage.Content = httpContent;
|
||
|
||
var result = Send(httpRequestMessage);
|
||
|
||
return result;
|
||
}
|
||
catch (Exception E)
|
||
{
|
||
throw E;
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// post方法访问api
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="url"></param>
|
||
/// <param name="param"></param>
|
||
/// <returns></returns>
|
||
public ApiResult<T> PostApi<T>(string url, Dictionary<string, object> param)
|
||
{
|
||
try
|
||
{
|
||
//拼接验证头
|
||
Dictionary<string, string> header = new Dictionary<string, string>();
|
||
var timestamps = GetTimeStamp();
|
||
var sign = GetSign(param, timestamps);
|
||
var authorization = $"{UserName}:{sign}";
|
||
|
||
header.Add("authorization", authorization);
|
||
header.Add("timestamps", timestamps);
|
||
|
||
//请求
|
||
var req = Post(url, param, header);
|
||
//LogHelper.Info("alipay:" + req);
|
||
//返回
|
||
var reqInfo = JsonConvert.DeserializeObject<ApiResult<T>>(req);
|
||
if (reqInfo == null)
|
||
{
|
||
return new ApiResult<T> { Code = 501, Message = "数据为空" };
|
||
}
|
||
return reqInfo;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
return new ApiResult<T> { Code = 501, Message = ex.Message };
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 内置请求
|
||
/// </summary>
|
||
/// <param name=""></param>
|
||
/// <returns></returns>
|
||
private string Post(string url, Dictionary<string, object> param, Dictionary<string, string> header)
|
||
{
|
||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||
//请求设置
|
||
request.Method = "POST";
|
||
request.ContentType = "application/json;charset=UTF-8";
|
||
request.Timeout = 3000;//设置超时时间
|
||
//拼接请求头
|
||
foreach (var item in header)
|
||
{
|
||
request.Headers.Add(item.Key, item.Value);
|
||
}
|
||
//拼接参数
|
||
if (param.Any())
|
||
{
|
||
var pStr = JsonConvert.SerializeObject(param);
|
||
byte[] data = Encoding.UTF8.GetBytes(pStr);
|
||
using (Stream stream = request.GetRequestStream())
|
||
{
|
||
stream.Write(data, 0, data.Length);
|
||
}
|
||
}
|
||
//提交请求
|
||
HttpWebResponse response;
|
||
try
|
||
{
|
||
response = (HttpWebResponse)request.GetResponse();
|
||
|
||
}
|
||
catch (WebException ex)
|
||
{
|
||
response = (HttpWebResponse)ex.Response;
|
||
}
|
||
//解析请求结果
|
||
using (Stream myResponseStream = response.GetResponseStream())
|
||
{
|
||
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
|
||
string retString = myStreamReader.ReadToEnd();
|
||
myStreamReader.Close();
|
||
//记录请求情况
|
||
LogHelper.Info($"url:{url},param:{JsonConvert.SerializeObject(param)},header:{JsonConvert.SerializeObject(header)},req:{retString}");
|
||
return retString;
|
||
}
|
||
}
|
||
public static string Send(HttpRequestMessage httpRequestMessage)
|
||
{
|
||
using (HttpClient client = new HttpClient())
|
||
{
|
||
HttpResponseMessage response = client.SendAsync(httpRequestMessage).Result;
|
||
return response.Content.ReadAsStringAsync().Result;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 内置请求
|
||
/// </summary>
|
||
/// <param name=""></param>
|
||
/// <returns></returns>
|
||
private string Get(string url, Dictionary<string, object> param, Dictionary<string, string> header)
|
||
{
|
||
var urlParam = string.Join("&", param.Select(m => m.Key + "=" + m.Value));
|
||
if (url.IndexOf('?') > -1)
|
||
{
|
||
url = url + urlParam;
|
||
}
|
||
else
|
||
{
|
||
url = (url + "?" + urlParam);
|
||
}
|
||
|
||
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
|
||
//MethodInfo priMethod = webReq.Headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
|
||
//priMethod.Invoke(webReq.Headers, new[] { "Date", timestamps });
|
||
|
||
foreach (var item in header)
|
||
{
|
||
webReq.Headers.Add(item.Key, item.Value);
|
||
}
|
||
webReq.Method = "GET";
|
||
webReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
|
||
webReq.Headers.Add("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
|
||
webReq.UserAgent = "Mozilla/5.0 (Windows NT 5.2; rv:12.0) Gecko/20100101 Firefox/12.0";
|
||
|
||
//webReq.Method = "get";
|
||
//webReq.ContentType = "application/x-www-form-urlencoded";
|
||
webReq.ContentType = "application/json;charset=UTF-8";
|
||
//webReq.Timeout = 3000;//设置超时时间
|
||
|
||
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
|
||
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
|
||
var _Result = sr.ReadToEnd();
|
||
sr.Close();
|
||
response.Close();
|
||
return _Result;
|
||
}
|
||
/// <summary>
|
||
/// 计算签名
|
||
/// </summary>
|
||
/// <param name="param"></param>
|
||
/// <param name="timestamps"></param>
|
||
/// <returns></returns>
|
||
private string GetSign(Dictionary<string, object> param, string timestamps)
|
||
{
|
||
|
||
//一次排序
|
||
var newP = param.OrderBy(m => m.Key).ToDictionary(m => m.Key.Substring(0, 1).ToLower() + m.Key.Substring(1), n => n.Value);
|
||
var pJosn = JsonConvert.SerializeObject(newP, new JsonSerializerSettings
|
||
{
|
||
NullValueHandling = NullValueHandling.Ignore,
|
||
ContractResolver = new OrderedContractResolver() //首字母转小写
|
||
});//去除null值数据
|
||
|
||
//二次排序
|
||
var enStrList = new string[] { UserName, pJosn, Secret, timestamps };
|
||
Array.Sort(enStrList, string.CompareOrdinal);
|
||
|
||
//拼接
|
||
var enStr = string.Join("", enStrList);
|
||
//md5 加密
|
||
return _md5(enStr);
|
||
}
|
||
/// <summary>
|
||
/// 计算 md5
|
||
/// </summary>
|
||
/// <param name="enCode"></param>
|
||
/// <returns></returns>
|
||
public string _md5(string enCode)
|
||
{
|
||
string res = "";
|
||
byte[] data = Encoding.GetEncoding("utf-8").GetBytes(enCode);
|
||
MD5 md5 = new MD5CryptoServiceProvider();
|
||
byte[] bytes = md5.ComputeHash(data);
|
||
for (int i = 0; i < bytes.Length; i++)
|
||
{
|
||
res += bytes[i].ToString("x2");
|
||
}
|
||
return res;
|
||
}
|
||
/// <summary>
|
||
/// 获取时间戳
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public string GetTimeStamp()
|
||
{
|
||
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
|
||
return Convert.ToInt64(ts.TotalSeconds).ToString();
|
||
}
|
||
public long GetTimeStampByTime(DateTime nowTime)
|
||
{
|
||
TimeSpan ts = nowTime - new DateTime(1970, 1, 1, 8, 0, 0, 0);
|
||
return long.Parse(Convert.ToInt64(ts.TotalSeconds).ToString());
|
||
}
|
||
#endregion
|
||
}
|
||
|
||
/// <summary>
|
||
/// code:状态码,0为请求成功;
|
||
/// 部分状态说明
|
||
/// -1 未知异常
|
||
/// -1001 签名不合法
|
||
/// -1002 签名验证失败
|
||
/// -1003 请求内容不合法
|
||
/// -1004 AppID不合法
|
||
// -1005 签名已过期
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
public class ApiResult<T>
|
||
{
|
||
/// <summary>
|
||
/// -1 未知异常
|
||
/// -1001 签名不合法
|
||
/// -1002 签名验证失败
|
||
/// -1003 请求内容不合法
|
||
/// -1004 AppID不合法
|
||
// -1005 签名已过期
|
||
/// </summary>
|
||
public int Code { get; set; }
|
||
public T Data { get; set; }
|
||
public string Message { get; set; }
|
||
}
|
||
|
||
public class ApiResult
|
||
{
|
||
/// <summary>
|
||
/// -1 未知异常
|
||
/// -1001 签名不合法
|
||
/// -1002 签名验证失败
|
||
/// -1003 请求内容不合法
|
||
/// -1004 AppID不合法
|
||
// -1005 签名已过期
|
||
/// </summary>
|
||
public int Code { get; set; }
|
||
public string Message { get; set; }
|
||
}
|
||
public class OrderedContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
|
||
{
|
||
protected override System.Collections.Generic.IList<Newtonsoft.Json.Serialization.JsonProperty> CreateProperties(System.Type type, MemberSerialization memberSerialization)
|
||
{
|
||
var list = base.CreateProperties(type, memberSerialization).OrderBy(p => p.PropertyName).ToList();
|
||
foreach (var item in list)
|
||
{
|
||
item.PropertyName = item.PropertyName.Substring(0, 1).ToLower() + item.PropertyName.Substring(1);
|
||
}
|
||
return list;
|
||
}
|
||
}
|
||
}
|