public Response<string> Main(MonthPlanRequest request)
{
string apiName = "MonthPlan", postData = request.ToJson();
var result = ConnectCSB(apiName, postData);
return InvokeResult.Fail<string>("访问成功");
}
public static string ConnectCSB(string apiName, string postData)
{
var resultStr = "";
try
{
string ACCESS_KEY = System.Configuration.ConfigurationManager.AppSettings["ACCESS_KEY"].ToString();
string SECRET_KEY = System.Configuration.ConfigurationManager.AppSettings["SECRET_KEY"].ToString();
string CSBURL = System.Configuration.ConfigurationManager.AppSettings["CSBURL"].ToString();
long timeStamp = ToUnixTimeMilliseconds(DateTime.Now);
string signature = sign(apiName, "1.0.0", timeStamp, ACCESS_KEY, SECRET_KEY, null, postData);
Dictionary<string, string> headerDic = new Dictionary<string, string>();
headerDic.Add("_api_access_key", ACCESS_KEY);
headerDic.Add("_api_timestamp", timeStamp.ToString());
headerDic.Add("_api_name", apiName);
headerDic.Add("_api_signature", signature);
headerDic.Add("_api_version", "1.0.0");
resultStr = GetResult(CSBURL, "application/json", "application/json;charset=utf-8", "POST", postData, headerDic);
}
catch (Exception e)
{
ErpErrLog(e.Message, apiName);
return "[{'IsSuccess': 'false','Msg':'" + e.Message + "'}]";
}
return resultStr;
}
public static long ToUnixTimeMilliseconds(DateTime nowTime)
{
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
long unixTime = (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero);
return unixTime;
}
public static string sign(string apiName, string apiVersion, long timeStamp, string accessKey, string secretKey, Dictionary<string, object[]> formParamDict, object body)
{
Dictionary<string, object[]> newDict = new Dictionary<string, object[]>();
if (formParamDict != null)
{
foreach (KeyValuePair<string, object[]> pair in formParamDict)
{
newDict.Add(pair.Key, pair.Value.Select(v => { return HttpUtility.UrlEncode(v.ToString()); }
).ToArray());
}
}
newDict.Add("_api_name", new String[] { apiName });
newDict.Add("_api_version", new String[] { apiVersion });
newDict.Add("_api_access_key", new String[] { accessKey });
newDict.Add("_api_timestamp", new object[] { timeStamp });
var sortedDict = getSortByASCII(newDict);
StringBuilder builder = new StringBuilder();
foreach (KeyValuePair<string, object[]> pair in sortedDict)
{
foreach (object obj in pair.Value)
{
builder.Append(string.Format("{0}={1}&", pair.Key, obj));
}
}
string str = builder.ToString();
if (str.EndsWith("&"))
{
str = str.Substring(0, str.Length - 1);
}
System.Security.Cryptography.HMACSHA1 hmacsha = new System.Security.Cryptography.HMACSHA1
{
Key = Encoding.UTF8.GetBytes(secretKey)
};
byte[] bytes = Encoding.UTF8.GetBytes(str);
return Convert.ToBase64String(hmacsha.ComputeHash(bytes));
}
public static string GetResult(string url, string accept, string contentType, string requestType, string parms, Dictionary<string, string> headerDic = null)
{
var result = string.Empty;
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Timeout = 300000;
if (!string.IsNullOrEmpty(accept))
{
myRequest.Accept = accept;
}
if (!string.IsNullOrEmpty(contentType))
{
myRequest.ContentType = contentType;
}
myRequest.Method = requestType;
if (myRequest.Method == "POST")
{
var reqStream = myRequest.GetRequestStream();
var encoding = Encoding.GetEncoding("utf-8");
var inData = encoding.GetBytes(parms);
reqStream.Write(inData, 0, inData.Length);
reqStream.Close();
}
if (headerDic != null)
{
foreach (var h in headerDic)
{
myRequest.Headers.Add(h.Key, h.Value);
}
}
var res = (HttpWebResponse)myRequest.GetResponse();
if (res.StatusCode != HttpStatusCode.OK) return result;
var receiveStream = res.GetResponseStream();
var encode = Encoding.GetEncoding("utf-8");
if (receiveStream != null)
{
var readStream = new StreamReader(receiveStream, encode);
var oResponseMessage = readStream.ReadToEnd();
res.Close();
readStream.Close();
result = oResponseMessage;
ErpResult re = JsonConvert.DeserializeObject(result, typeof(ErpResult)) as ErpResult;
if (re.code.Equals("000000"))
{
return "[{'IsSuccess': 'true','Msg':'" + re.message + "'}]";
}
else
return "[{'IsSuccess': 'false','Msg':'" + re.message + "'}]";
}
stopWatch.Stop();
}
catch (Exception e)
{
ErpErrLog(e.Message, headerDic["_api_name"].ToString());
if (e is WebException && ((WebException)e).Status == WebExceptionStatus.ProtocolError)
{
WebResponse errResp = ((WebException)e).Response;
using (Stream respStream = errResp.GetResponseStream())
{
var readStream = new StreamReader(respStream, Encoding.GetEncoding("utf-8"));
var strError = readStream.ReadToEnd();
Console.Out.WriteLine(strError);
}
}
return "[{'IsSuccess': 'false','Msg':'"+e.Message+"'}]";
}
return "[{'IsSuccess': 'true','Msg':'" + result + "'}]";
}
public static Dictionary<string, object[]> getSortByASCII(Dictionary<string, object[]> dict)
{
var sortList = dict.ToList();
sortList.Sort((x, y) =>
{
return string.CompareOrdinal(x.Key, y.Key);
});
sortList.Sort((x, y) =>
{
var r = string.Compare(x.Key, y.Key, StringComparison.Ordinal);
return r;
});
Dictionary<string, object[]> sortDict = new Dictionary<string, object[]>();
var keys = dict.Keys.ToArray();
Array.Sort(keys, string.CompareOrdinal);
foreach (var key in keys)
{
sortDict.Add(key, dict[key]);
}
return sortDict;
}