Zxd.Core/code/Zxd.Core.Shared/Helpers/ApiDockHelper.cs

328 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using DG.Tool;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using Zxd.Core.Shared.Helpers;
namespace WX.CRM.Common.Employee
{
public class ApiDockHelper
{
public ApiDockHelper(string username, string secret)
{
UserName = username;
Secret = secret;
}
/// <summary>
/// Get方法访问API
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public ApiResultTemp<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.Write("alipay:" + req);
//返回
var reqInfo = JsonHelper.FromJson<ApiResultTemp<T>>(req);
if (reqInfo == null)
{
return new ApiResultTemp<T> { ret = 501, msg = "数据为空" };
}
return reqInfo;
}
catch (Exception ex)
{
return new ApiResultTemp<T> { ret = 501, msg = ex.Message };
}
}
/// <summary>
/// post方法访问api
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="param"></param>
/// <returns></returns>
public ApiResultTemp<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 = JsonHelper.FromJson<ApiResultTemp<T>>(req);
if (reqInfo == null)
{
return new ApiResultTemp<T> { ret = 501, msg = "数据为空" };
}
return reqInfo;
}
catch (Exception ex)
{
return new ApiResultTemp<T> { ret = 501, msg = 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;
}
}
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 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 = JsonHelper.ToJson(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.Write($"url:{url},param:{JsonHelper.ToJson(param)},header:{JsonHelper.ToJson(header)}");
return retString;
}
}
/// <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, n => n.Value);
var pJosn = JsonSerializer.Serialize(newP, new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
IgnoreNullValues = true
});
//二次排序
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>
private string GetTimeStamp()
{
TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
#endregion
}
/// <summary>
/// code状态码0为请求成功
/// 部分状态说明
/// -1 未知异常
/// -1001 签名不合法
/// -1002 签名验证失败
/// -1003 请求内容不合法
/// -1004 AppID不合法
// -1005 签名已过期
/// </summary>
/// <typeparam name="T"></typeparam>
public class ApiResultTemp<T>
{
public int code { get; set; }
/// <summary>
/// -1 未知异常
/// -1001 签名不合法
/// -1002 签名验证失败
/// -1003 请求内容不合法
/// -1004 AppID不合法
// -1005 签名已过期
/// </summary>
public int ret { get; set; }
public T data { get; set; }
public string msg { get; set; }
public string message { get; set; }
}
}