2025-03-28 09:49:56 +08:00

248 lines
12 KiB
C#

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using WebService.SDK;
using HZQR.Common;
namespace KeRuYunClient
{
public partial class MainForm : Form
{
protected string _OracleConnStr = ConfigurationManager.AppSettings["OracleConnStr"].ToString();//数据库连接字符串
protected string req_url = "https://openapi.keruyun.com";
protected string appKey = "7c543898401f96659d7ac2c0dfe0c0c2";
protected string appSecret = "3b9f4e0d21efd652226cf9724774680c";
System.Timers.Timer _Timer = new System.Timers.Timer();
protected int startTimeSpan = ConfigurationManager.AppSettings["startTime"].TryParseToInt(); //查询起始时间,距离今天间隔的天数
protected int endTimeSpan = ConfigurationManager.AppSettings["endTime"].TryParseToInt(); //查询结束时间,距离今天间隔的天数
protected string hour = ConfigurationManager.AppSettings["time"];//定时器间隔时间,单位/小时
protected DateTime Date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public MainForm()
{
InitializeComponent();
_Timer.Interval = Convert.ToInt32(hour == "" ? "1" : hour) * 60 * 60 * 1000;
_Timer.AutoReset = true;
_Timer.Enabled = true;
_Timer.Elapsed += new System.Timers.ElapsedEventHandler(Action);
_Timer.Start();
getRevenueData();
}
public void Action(object sender, System.Timers.ElapsedEventArgs e)
{
getRevenueData();
}
#region ->
private void getRevenueData()
{
DateTime StartDate = DateTime.Now.Date.AddDays(startTimeSpan);
DateTime EndDate = DateTime.Now.Date.AddDays(endTimeSpan).AddSeconds(-1);
try
{
OracleHelper _OracleHelper = new OracleHelper(_OracleConnStr.Split(',')[0],
_OracleConnStr.Split(',')[1], _OracleConnStr.Split(',')[2], _OracleConnStr.Split(',')[3]);
//查询客如云-门店配置表
DataTable dt = _OracleHelper.ExcuteSqlGetDataSet(@"SELECT * FROM HIGHWAY_SELLDATA.T_KERUYUN_SHOP").Tables[0];
foreach (DataRow dr in dt.Rows)
{
for (int Days = 0; Days < (EndDate - StartDate).TotalDays; Days++)
{
string startTime = KeruyunHelper.GetTimeStamp(StartDate > StartDate.AddDays(Days) ?
StartDate : StartDate.AddDays(Days), false).ToString();
string endTime = KeruyunHelper.GetTimeStamp(EndDate > StartDate.AddDays(Days + 1).AddSeconds(-1) ?
StartDate.AddDays(Days + 1).AddSeconds(-1) : EndDate, false).ToString();
string result = getkeruyunRevenue(startTime, endTime, dr["TOKEN"].ToString(), dr["SHOPIDENTY"].ToString());
JObject info = JObject.Parse(result);
if (info["code"].ToString() == "0" && !string.IsNullOrWhiteSpace(info["result"].TryParseToString()))
{
JObject order = JObject.Parse(info["result"].ToString());
if (order["items"] != null)
{
int totalRows = order["totalRows"].TryParseToInt();
int pageSize = order["pageSize"].TryParseToInt();
InsertKRYOrder(_OracleHelper, dr, order);
if (totalRows > pageSize)
{
for (int pageIndex = 2; pageIndex <= totalRows / pageSize + 1; pageIndex++)
{
LogHelper.WriteReceiveLog("服务区编码【" + dr["SERVERPART_CODE"] + "】,门店编码【" +
dr["SERVERPARTSHOP_CODE"] + "】,时间【" + startTime + "至" + endTime +
"】正在获取第" + pageIndex + "页(每页" + pageSize + "条数据)的数据");
result = getkeruyunRevenue(startTime, endTime, dr["TOKEN"].ToString(),
dr["SHOPIDENTY"].ToString(), pageIndex, pageSize);
JObject infoChild = JObject.Parse(result);
if (infoChild["code"].ToString() == "0" && !string.IsNullOrWhiteSpace(infoChild["result"].TryParseToString()))
{
JObject orderChild = JObject.Parse(infoChild["result"].ToString());
if (orderChild["items"] != null)
{
InsertKRYOrder(_OracleHelper, dr, orderChild);
}
}
else
{
LogHelper.WriteReceiveLog("返回参数:" + result);
}
}
}
}
}
else
{
LogHelper.WriteReceiveLog("返回参数:" + result);
}
}
}
}
catch (Exception ex)
{
LogHelper.WriteReceiveLog("数据获取失败:" + ex.Message + ",程序停止");
_Timer.AutoReset = false;
_Timer.Enabled = false;
_Timer.Stop();
}
}
public string getkeruyunRevenue(string startTime, string endTime, string token, string shopIdenty, int pageNo = 1, int pageSize = 100)
{
string PublicParameter = "";
Dictionary<string, string> _Dictionary = new Dictionary<string, string>();
_Dictionary.Add("appKey", appKey);
_Dictionary.Add("shopIdenty", shopIdenty);
_Dictionary.Add("timestamp", Convert.ToInt32((DateTime.Now -
new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds).ToString());
_Dictionary.Add("version", "2.0");
PublicParameter = CommonHelper.paramsToString(_Dictionary);
Dictionary<string, string> body = new Dictionary<string, string>();
body.Add("endTime", endTime);
body.Add("pageNo", pageNo.ToString());
body.Add("pageSize", pageSize.ToString());
body.Add("shopIdenty", shopIdenty);
body.Add("startTime", startTime);
body.Add("timeType", "2");
_Dictionary.Add("body", JsonConvert.SerializeObject(body));
_Dictionary.Add("sign", getKeruyunSign(_Dictionary, token));
PublicParameter += "&sign=" + _Dictionary["sign"].ToString();
string parameters = CommonHelper.paramsToString(_Dictionary);
LogHelper.WriteReceiveLog("发送参数:" + parameters);
string jsonStr = CommonHelper.HttpUrlPost(JsonConvert.SerializeObject(body),
req_url + "/open/v1/data/order/export2?" + PublicParameter, "application/json", 5);
//LogHelper.WriteReceiveLog("返回参数:" + jsonStr);
return jsonStr;
}
public void InsertKRYOrder(OracleHelper _OracleHelper, DataRow dr, JObject order)
{
int dataCont = 0;
//获取返回值-订单列表,并插入数据库表 T_KERUYUN_ORDER
JArray jArray = JArray.Parse(order["items"].ToString());
foreach (var item in jArray)
{
string sql = string.Format(@"SELECT COUNT(1) FROM HIGHWAY_SELLDATA.T_KERUYUN_ORDER
WHERE SERVERPART_CODE='{0}' AND SERVERPARTSHOP_CODE='{1}' AND ORDERID={2}",
dr["SERVERPART_CODE"], dr["SERVERPARTSHOP_CODE"], item["orderId"]);
DataTable dtCount = _OracleHelper.ExcuteSqlGetDataSet(sql).Tables[0];
if (Convert.ToInt32(dtCount.Rows[0][0]) == 0)
{
sql = string.Format(@"INSERT INTO HIGHWAY_SELLDATA.T_KERUYUN_ORDER
(KERUYUN_ORDER_ID,SERVERPART_CODE,SERVERPARTSHOP_CODE,
ORDERID,TRADENO,TRADETYPE,TRADESTATUS,ORDERTIME,
CHECKOUTTIME,ORDER_SOURCE,SOURCENAME,RECEIVEDAMOUNT,
CUSTREALPAY,TRADEAMOUNT,PRIVILEGEAMOUNT)
VALUES(HIGHWAY_SELLDATA.SEQ_KERUYUN_ORDER.NEXTVAL,
'{0}','{1}',{2},'{3}',{4},{5},
TO_DATE('{6}','YYYY-MM-DD HH24:MI:SS'),
TO_DATE('{7}','YYYY-MM-DD HH24:MI:SS'),
{8},'{9}',{10} / 100,{11} / 100,{12} / 100,{13} / 100)",
dr["SERVERPART_CODE"], dr["SERVERPARTSHOP_CODE"],
item["orderId"], item["tradeNo"], item["tradeType"], item["tradeStatus"],
KeruyunHelper.TimeStampToDateTime((long)item["orderTime"], false).ToString("yyyy-MM-dd HH:mm:ss"),
KeruyunHelper.TimeStampToDateTime((long)item["checkOutTime"], false).ToString("yyyy-MM-dd HH:mm:ss"),
item["source"], item["sourceName"], item["receivedAmount"],
item["custRealPay"], item["tradeAmount"], item["privilegeAmount"]);
_OracleHelper.ExcuteSql(sql);
dataCont++;
}
}
LogHelper.WriteReceiveLog("服务区编码【" + dr["SERVERPART_CODE"] + "】,门店编码【" +
dr["SERVERPARTSHOP_CODE"] + "】获取" + jArray.Count + "条数据,成功插入" + dataCont + "条数据");
}
#endregion
#region -> token
public string getShopToken(string shopIdenty)
{
string token = "";
Dictionary<string, string> _Dictionary = new Dictionary<string, string>();
_Dictionary.Add("appKey", appKey);
_Dictionary.Add("shopIdenty", shopIdenty);
_Dictionary.Add("timestamp", Convert.ToInt32((DateTime.Now -
new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds).ToString());
_Dictionary.Add("version", "1.0");
_Dictionary.Add("sign", getKeruyunSign(_Dictionary, appSecret));
string parameters = CommonHelper.paramsToString(_Dictionary);
//LogHelper.WriteReceiveLog("发送参数:" + parameters);
string jsonStr = KeruyunHelper.HttpUrlGet(req_url + "/open/v1/token/get?" + parameters);
//LogHelper.WriteReceiveLog("返回参数:" + jsonStr);
JObject _JObject = JObject.Parse(jsonStr);
if (_JObject["code"].ToString() == "0")
{
token = _JObject["result"]["token"].ToString();
}
return token;
}
#endregion
#region ->
public string getKeruyunSign(Dictionary<string, string> _Dictionary, string otherString)
{
string Sign = "", str = "";
foreach (var e in _Dictionary)
{
str += e.Key + e.Value;
}
str += otherString;
LogHelper.WriteReceiveLog("签名前:" + str);
Sign = KeruyunHelper.SHA256EncryptString(str);
LogHelper.WriteReceiveLog("签名后:" + Sign);
return Sign;
}
#endregion
}
}