using System; using System.Data; using System.Collections; using System.Collections.Generic; using HcUtility.Core; using Newtonsoft.Json; using DSWeb.TruckMng.Helper; using Newtonsoft.Json.Converters; using DSWeb.Areas.Account.Models.Chfee_Invoice; using NuonuoSDK; using DSWeb.Areas.Account.Models.Chfee_Invoiceapplication; using DSWeb.Areas.CommMng.DAL; using Microsoft.Practices.EnterpriseLibrary.Data; using DSWeb.Areas.Account.DAL.Chfee_Invoice_HangXin; using HcUtility.Comm; using System.Web.Mvc; using DSWeb.MvcShipping.Models.CodeGoodInv; using Quartz; using DSWeb.Areas.MvcShipping.Comm; using Newtonsoft.Json.Linq; using DSWeb.Areas.SysMng.Models.DBTableConn; using DSWeb.Areas.SysMng.DAL.DBTableConn; namespace DSWeb.Areas.Account.Models.Chfee_Invoice_HangXin { [JsonObject] public class ChInvoice_HangXin : Chfee_Invoice.ChInvoice { #region 私有成员 在Chfee_Invoice.ChInvoice 基础上增加的字段 private string _CUSTTEL = string.Empty;//购方电话 private string _CUSTADDR = string.Empty;//购方地址 private string _PTORRED = "1"; //开票类型:1,正票;2,红票 80001 private string _REDCODE = string.Empty;//冲红时填写的对应蓝票票代码(红票必填,不满12位请左补0) private string _REDNUM = string.Empty;//冲红时填写的对应蓝票票号码(红票必填,不满8位请左补0) private string _PUSHMODE = "-1";//推送方式:-1,不推送;0,邮箱;1,手机(默认);2,邮箱、手机 80002 private string _PUSHMOBILE = string.Empty;//购方手机(开票成功会短信提醒购方,不受推送方式影响) private string _PUSHEMAIL = string.Empty;//推送邮箱(pushMode为0或2时,此项为必填) private string _INVOICELINE = "p"; //发票种类:p,普通发票(电票)(默认);c,普通发票(纸票);s,专用发票;e,收购发票(电票);f,收购发票(纸质) 80003 private string _EINVOICESTATE = string.Empty; //接口开票是否成功。开票成功时记录为true 80004 private string _INVOICEINFOURL = string.Empty; //发票详情地址 一个url 直接显示诺诺开票的发票详情页 开票成功后读取发票详情并记录 private string _INVOICEPDFURL = string.Empty; //发票PDF地址 开票成功后读取发票详情并记录 private string _PTORREDREF = string.Empty; // private string _PUSHMODEREF = string.Empty; private string _EINVOICESTATEREF = string.Empty; private string _INVOICELINEREF = string.Empty; private string _TAXCODE = string.Empty; private string _OFFICEPHONE = string.Empty; private string _ADDRESS = string.Empty; private string _invoiceSerialNum = string.Empty;//诺诺开票的流水号 private string _INVOICECODE = string.Empty;//发票代码 private string _PAYEE = string.Empty;//收款人 private string _CHECKER = string.Empty;//复核人 private string _SETRED = string.Empty;//是否被冲红 private string _INVITERFACE = string.Empty;//发票接口 #endregion #region 读写属性 [ModelDB] public string CUSTTEL { get { return _CUSTTEL; } set { _CUSTTEL = value; } } [ModelDB] public string CUSTADDR { get { return _CUSTADDR; } set { _CUSTADDR = value; } } /// /// 1正票 2红票 /// [ModelDB] public string PTORRED { get { return _PTORRED; } set { _PTORRED = value; } } [ModelDB] public string REDCODE { get { return _REDCODE; } set { _REDCODE = value; } } [ModelDB] public string REDNUM { get { return _REDNUM; } set { _REDNUM = value; } } /// /// -1不推送 0邮箱 1电话 2邮箱+电话 /// [ModelDB] public string PUSHMODE { get { return _PUSHMODE; } set { _PUSHMODE = value; } } [ModelDB] public string PUSHMOBILE { get { return _PUSHMOBILE; } set { _PUSHMOBILE = value; } } [ModelDB] public string PUSHEMAIL { get { return _PUSHEMAIL; } set { _PUSHEMAIL = value; } } [ModelDB] public string INVOICELINE { get { return _INVOICELINE; } set { _INVOICELINE = value; } } public bool ISEInvoice { get { if (INVOICELINE == "p" || INVOICELINE == "e") return true; else return false; } } [ModelDB] public string EINVOICESTATE { get { return _EINVOICESTATE; } set { _EINVOICESTATE = value; } } [ModelDB] public string INVOICEINFOURL { get { return _INVOICEINFOURL; } set { _INVOICEINFOURL = value; } } [ModelDB] public string INVOICEPDFURL { get { return _INVOICEPDFURL; } set { _INVOICEPDFURL = value; } } /// /// 发票流水号 诺诺平台接收正确的开票信息后返回该值 /// [ModelDB] public string INVOICESERIALNUM { get { return _invoiceSerialNum; } set { _invoiceSerialNum = value; } } [ModelDB] public string INVOICECODE { get { return _INVOICECODE; } set { _INVOICECODE = value; } } public string PTORREDREF { get { return _PTORREDREF; } set { _PTORREDREF = value; } } public string PUSHMODEREF { get { return _PUSHMODEREF; } set { _PUSHMODEREF = value; } } public string INVOICELINEREF { get { return _INVOICELINEREF; } set { _INVOICELINEREF = value; } } public string EINVOICESTATEREF { get { return _EINVOICESTATEREF; } set { _EINVOICESTATEREF = value; } } new public string TAXCODE { get { return _TAXCODE; } set { _TAXCODE = value; } } public string OFFICEPHONE { get { return _OFFICEPHONE; } set { _OFFICEPHONE = value; } } public string ADDRESS { get { return _ADDRESS; } set { _ADDRESS = value; } } public string BILLRISES { get; set; } [ModelDB] public string PAYEE { get { return _PAYEE; } set { _PAYEE = value; } } [ModelDB] public string CHECKER { get { return _CHECKER; } set { _CHECKER = value; } } [ModelDB] public string SETRED { get { return _SETRED; } set { _SETRED = value; } } [ModelDB] public string INVITERFACE { get { return _INVITERFACE; } set { _INVITERFACE = value; } } #endregion public ChInvoice_HangXin() { TableName = "ch_fee_invoice"; } public static decimal getarraysum(string[] feearray) { var result = 0M; for (var _i = 0; _i < feearray.Length; _i++) { try { result += Convert.ToDecimal(feearray[_i]); } catch { } } return result; } public void SetP2Value(BaseTableMC P2data) { var connList = DBTableConnDAL.getConn("联力P2发票"); BSNO = P2data.GetValue("BSNO"); CUSTOMERNAME = P2data.GetValue("CUSTOMERNAME"); INVOICECUSTNAME = P2data.GetValue("INVOICECUSTNAME"); VESSELVOYAGE = P2data.GetValue("VESSEL") + ";" + P2data.GetValue("VOYAGE"); ETD = P2data.GetValue("ETD"); POL = P2data.GetValue("POL"); POD = P2data.GetValue("POD"); RECVCURR = P2data.GetValue("CURRENCY"); CURRENCY = "RMB"; CUSTRATENO = P2data.GetValue("CUSTRATENO"); if (RECVCURR == "RMB") { AMOUNT = getarraysum(P2data.GetSplitField("AMOUNT", "\r\n")); }; if (RECVCURR != "RMB") { AMOUNT = 0M; var pricearray = P2data.GetSplitField("INVAMOUNT", "\r\n"); var numarray = P2data.GetSplitField("NUM", "\r\n"); for (var _i = 0; _i < pricearray.Length; _i++) { try { AMOUNT += Convert.ToDecimal(pricearray[_i]) * Convert.ToDecimal(numarray[_i]); } catch { } } } INVAMOUNT = AMOUNT; if (RECVCURR != "RMB") { OTCURRAMOUNT = getarraysum(P2data.GetSplitField("AMOUNT", "\r\n")); } else { OTCURRAMOUNT = 0M; } AMOUNTCAPITAL = P2data.GetValue("AMOUNTCAPITAL"); REMARK = P2data.GetValue("REMARK"); INVOICETYPE = 2; OPERATETIME = DateTime.Now; MBLNO = P2data.GetValue("MBLNO"); CUSTADDRTEL = P2data.GetValue("CUSTADDRTEL"); CUSTBANK = P2data.GetValue("CUSTBANK"); PUSHMODE = "0"; PUSHMOBILE = "0"; PUSHEMAIL = ""; //如果是红票 需要设定一些值 PTORRED = "1";//默认正票 INVOICELINE = "p";//默认普通电票 if (P2data.GetValue("REDINVOICE") == "1") { PTORRED = "2"; BaseTableMC fromdbbase = new BaseTableMC("M_INVOICE", "INVOICE_ID", "", "P2DB"); var BeREDDataList = DBTableConnDAL.getToList(fromdbbase, "联力P2发票", " INVOICE_ID='" + P2data.GetValue("REDBSNO") + "'"); if (BeREDDataList.Count > 0) { var BeRedinvoice = BeREDDataList[0]; REDNUM = BeRedinvoice.GetValue("INVOICENO"); REDCODE = BeRedinvoice.GetValue("INVOICECODE"); CUSTADDRTEL = BeRedinvoice.GetValue("CUSTADDRTEL"); CUSTBANK = BeRedinvoice.GetValue("CUSTBANK"); CUSTRATENO = BeRedinvoice.GetValue("CUSTRATENO"); } } } } [JsonObject] public class HXInvoice { public HXInvoice_Head order; public HXInvoice(ChInvoice_HangXin head, List body) { this.order = new HXInvoice_Head(head); List invoiceDetail = new List(); foreach (var detail in body) { var item = new HXInvoice_Detail(detail); invoiceDetail.Add(item); } this.order.invoiceDetail = invoiceDetail; } } [JsonObject] public class HXInvoice_Head { private ChInvoice_HangXin ChInvoice_HangXin; public HXInvoice_Head() { } public HXInvoice_Head(ChInvoice_HangXin ChInvoice_HangXin) { this.ChInvoice_HangXin = ChInvoice_HangXin; } public List invoiceDetail; #region R&W public string buyerName { get { return ChInvoice_HangXin.INVOICECUSTNAME; } } public string buyerTaxNum { get { return ChInvoice_HangXin.CUSTRATENO; } } public string buyerTel { get { return ChInvoice_HangXin.CUSTTEL; } } public string buyerAddress { get { return ChInvoice_HangXin.CUSTADDR; } } public string buyerAccount { get { return ChInvoice_HangXin.CUSTBANK; } } public string orderNo { get { return ChInvoice_HangXin.BILLNO; } } public string invoiceDate { get { return ChInvoice_HangXin.INVOICEMAKETIME + " 12:00:00"; } } public string clerk { get { return ChInvoice_HangXin.OPERATORNAME; } } public string salerTaxNum { get { return ChInvoice_HangXin.TAXCODE; } } public string salerTel { get { return ChInvoice_HangXin.OFFICEPHONE; } } public string salerAddress { get { return ChInvoice_HangXin.ADDRESS; } } public string salerAccount { get { return ChInvoice_HangXin.ACCOUNT; } } public string invoiceType { get { return ChInvoice_HangXin.PTORRED; } } public string remark { get { return ChInvoice_HangXin.REMARK; } } public string invoiceCode { get { return ChInvoice_HangXin.REDCODE; } } public string invoiceNum { get { return ChInvoice_HangXin.REDNUM; } } public string pushMode { get { return ChInvoice_HangXin.PUSHMODE; } } public string buyerPhone { get { return ChInvoice_HangXin.PUSHMOBILE; } } public string email { get { return ChInvoice_HangXin.PUSHEMAIL; } } public string invoiceLine { get { return ChInvoice_HangXin.INVOICELINE; } } public string payee { get { return ChInvoice_HangXin.PAYEE; } } public string checker { get { return ChInvoice_HangXin.CHECKER; } } #endregion } //ChInvoiceDetail [JsonObject] public class HXInvoice_Detail { private ChInvoiceDetail ChInvoiceDetail; public HXInvoice_Detail() { } public HXInvoice_Detail(ChInvoiceDetail ChInvoiceDetail) { this.ChInvoiceDetail = ChInvoiceDetail; } #region R&W public string goodsName//品名 { get { return ChInvoiceDetail.GOODSNAMEREF; } } public string num//数量 { get { return Math.Round(ChInvoiceDetail.PKGS, 0, MidpointRounding.AwayFromZero).ToString(); } } public string withTaxFlag//单价是否含税0不含1含税 固定为0 { get { return "0"; } } public string price//单价 { get { return Math.Round(ChInvoiceDetail.PRICE, 2, MidpointRounding.AwayFromZero).ToString(); } } public string tax //税额,[不含税金额] * [税率] = [税额];税额允许误差为 0.06。红票为负。不含税金额、税额、含税金额任何一个不传时,会根据传入的单价,数量进行计算,可能和实际数值存在误差,建议都传入 { get { return Math.Round(ChInvoiceDetail.TAX, 2, MidpointRounding.AwayFromZero).ToString(); } } public string taxIncludedAmount //"含税金额,[不含税金额] + [税额] = [含税金额],红票为负。不含税金额、税额、含税金额任何一个不传时,会根据传入的单价,数量进行计算,可能和实际数值存在误差,建议都传入" { get { return (Math.Round(ChInvoiceDetail.AMOUNT, 2, MidpointRounding.AwayFromZero) + Math.Round(ChInvoiceDetail.TAX, 2, MidpointRounding.AwayFromZero)).ToString(); } } public string taxExcludedAmount //不含税金额。红票为负。不含税金额、税额、含税金额任何一个不传时,会根据传入的单价,数量进行计算,可能和实际数值存在误差,建议都传入 { get { return Math.Round(ChInvoiceDetail.AMOUNT, 2, MidpointRounding.AwayFromZero).ToString(); } } public string taxRate { get { return Math.Round((ChInvoiceDetail.TAXRATE / 100), 2, MidpointRounding.AwayFromZero).ToString(); } } public string specType { get { return ChInvoiceDetail.SPEC; } } public string unit { get { return ChInvoiceDetail.UNIT; } } public string goodsCode { get { return ChInvoiceDetail.GOODCODE; } } /// ///下列三项从相关的code_goods_inv表中查找 优惠政策0不使用1使用 ///增值税特殊管理 ///零税率标识:空,非零税;1,免税;2,不征税;3,普通零税率 ///如无则分别填入 1:0不使用 2:空 3:空 非零税率 /// /// public string favouredPolicyFlag { get { return ChInvoiceDetail.ISUSEPREF; } } public string favouredPolicyName { get { return ChInvoiceDetail.DEFREMARK; } } public string zeroRateFlag { get { return ChInvoiceDetail.ZTAXTYPE; } } #endregion } //public class RefreshHangXinTokenJob : IJob //{ // public void Execute(IJobExecutionContext context) // { // //BasicDataRefDAL.SaveLog("方法被调用1", "诺诺平台", "刷新token", "方法被调用1"); // HangXinRequestHelper.RefreshTokens(); // } //} /// /// 航信接口token管理 /// public class HangXinRequestHelper { public Boolean CanUse = true; public string ERRORMSG = ""; public static List HXTokenHelperList = new List(); /// /// 刷新所有需要刷新的token /// 20191122 准备放弃该算法 改为从接口获取 /// //internal static void RefreshTokens() //{ // //BasicDataRefDAL.SaveLog("RefreshTokens; HXTokenHelperList.count="+ HXTokenHelperList.Count.ToString(), "诺诺平台", "刷新token", "方法被调用2"); // //if (HXTokenHelperList.Count == 0) { // ReadToken(); // //} // if (HXTokenHelperList == null) return; // foreach (var hx in HXTokenHelperList) { // hx.ResetToken(); // } // //throw new NotImplementedException(); //} //public static void clear(string accessToken) { // if (HXTokenHelperList == null) return; // foreach (var hx in HXTokenHelperList) // { // if (hx.accessToken == accessToken) // hx.accessToken = ""; // } //} #region 基础属性 /// /// 我公司的appKey和密码 不写入数据库 只存在程序内 /// /// /* 沙盒测试账户 需使用青岛鑫鹏威 * 339901999999142 Abcd1234 public static string appKey { get { return "SD23646802"; } } public static string appSecret { get { return "SDFAFF5B0AED4465"; } } */ /* 正式地址测试账户 纸票测试用 需使用深圳鑫鹏威 //339901999999516 public static string appKey { get { return "G6bvh0ke"; } } public static string appSecret { get { return "6850C5AED14E4177"; } } */ /* 正式地址 大简云*/ public static string appKey { get { return "23646802"; } } public static string appSecret { get { return "CBFAFF5B0AED4465"; } } /// /// 使用沙盒地址还是实际工作地址 /// public static string URL { get { //return sandboxUrl; //沙盒测试地址 return normalUrl; } } /// /// 商户模式的Token /// public string MerchantToken { get; set; } /// /// 在服务商模式当中,客户输入选定账户的认证信息后返回的一个随机码 /// 每次认证时会被更新。但执行getISVToken或refreshISVToken不会改变code /// public string code { get; set; } /// /// 税号 客户输入的选定账户 /// public string taxnum { get; set; } /// /// 接收诺诺平台返回值的url,需要在其中标好账户id,以对应正确的实例化helper对象 /// public static string redirectUri { get; set; } //private static string ISVToken { get; set; } /// /// getISVToken时返回 refreshToken 时不变 /// public string accessToken { get; set; } /// /// getISVToken时返回 refreshToken时改变 /// public string refreshToken { get; set; } /// /// 同一客户税号这个userid似乎不变 /// public string userId { get; set; } /// /// 如果此次返回内容有错误编号 则返回错误 /// public bool refstateTrue { get { if (!string.IsNullOrEmpty(error)) { return false; } else return true; } } public string error_description { get; set; } public string error { get; set; } private static string sandboxUrl = "https://sandbox.nuonuocs.cn/open/v1/services"; private static string normalUrl = "https://sdk.nuonuo.com/open/v1/services"; //爬虫服务器接口 private static string _IURL = "http://47.104.90.170:5200/fp/token/"; //private static string _IURL = "http://118.190.106.151:5200/fp/token/"; //沙盒爬虫 private static string _SandBoxURL = "http://47.104.90.170:5200/cs/token/"; //private static string _SandBoxURL = "http://118.190.106.151:5200/cs/token/"; private static string _url { get; set; } const string ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; public static string returnStr { get; set; } private static string getSendid() { return Guid.NewGuid().ToString().Replace("-", "").Substring(0, 32); // 唯一标识,由企业自己生成32位随机码 } private DateTime _tokenstarttime { get; set; } //public DateTime gettokenstarttime { get { return _tokenstarttime; } } public DateTime tokenstarttime { get { return _tokenstarttime; } set { _tokenstarttime = value; } } public DateTime tokenneedresettime { get { return _tokenstarttime.AddHours(23); } } /// /// 需要初始化。如果有用户认证的code,则返回true,否则需要前台弹出StartUrl窗口,录入认证信息; /// 20191122 改为接口维护token后 固定返回false /// public bool needStart { get { //if (string.IsNullOrEmpty(code)) //{ // return true; //} //else if (System.DateTime.Now > _tokenstarttime.AddHours(24)) //{ // return true; //} if (accessToken == "") return true; else return false; } } /// /// 需要刷新 即当前时间晚于上次刷新23小时 /// /// 20191122 改为接口维护token后 固定返回false /// public bool needresettoken { get { //if (System.DateTime.Now >= tokenneedresettime) //{ // return true; //} return false; } } /// /// 具备刷新条件 即token不为空 /// //public bool canresettoken //{ // get // { // if (!string.IsNullOrEmpty(refreshToken)) // return true; // else return false; // } //} #endregion //public bool ResetToken() //{ // //BasicDataRefDAL.SaveLog("tokenstarttime="+ tokenstarttime.ToString("yyyy-MM-dd HH:mm:ss")+ ";refreshToken=" + refreshToken + ";accessToken=" + accessToken + ";needresettoken=" + needresettoken.ToString() + ";canresettoken=" + canresettoken.ToString(), "诺诺平台", "刷新令牌", "判断"); // if (needresettoken && canresettoken) // { // refreshISVToken(); // return !needresettoken; // } // else return false; //} /// /// 商户获取访问令牌 /// /// //public string getMerchantToken() //{ // //BasicDataRefDAL.SaveLog("appKey="+appKey+ ";appSecret=" + appSecret, "诺诺平台", "商户获取访问令牌", "发送值"); // var result = NNOpenSDK.getMerchantToken(appKey, appSecret); // dealResponse_token(returnStr); // //DoSaveToken(); // BasicDataRefDAL.SaveLog(result, "诺诺平台", "商户获取访问令牌", "返回值"); // return result; //} //public string setMerchantToken() //{ // this.MerchantToken = getMerchantToken(); // return this.MerchantToken; //} /// /// ISV获取访问令牌 /// /// //private ISVTokenmb getISVToken() //{ // ISVTokenmb _ISVToken = new ISVTokenmb(); // //BasicDataRefDAL.SaveLog("appKey=" + appKey + ";appSecret=" + appSecret + ";code=" + code + ";taxnum=" + taxnum + ";redirectUri=" + redirectUri, "诺诺平台", "ISV获取访问令牌", "发送值"); // returnStr = NNOpenSDK.getISVToken(appKey, appSecret, code, taxnum, redirectUri); // BasicDataRefDAL.SaveLog(returnStr, "诺诺平台", "ISV获取访问令牌", "返回值"); // dealResponse_token(returnStr); // return _ISVToken; //} /// /// 用认证窗口返回的数据读取token /// /// //public string setISVToken() //{ // //此处应判断 // //1 token 是否已存在 如不存在则获取needStart // //如存在则判断更新时间needresettoken // //if (needStart || needresettoken) // //{ // var _ISVToken = getISVToken(); // return returnStr; // //} // //else return "no need to start Token"; // /*"{\"access_token\":\"98600c833f178852e2f4d51cexk9yegi\",\"refresh_token\":\"faf038898dec26eac62640aaed0506cb\",\"oauthUser\":\"{\\\"userName\\\":\\\"339901999999142\\\",\\\"registerType\\\":\\\"1\\\"}\",\"expires_in\":86356,\"userId\":\"d1aa0da6bc9840ae83c1120cecd057ac\"}"*/ // /*{"error_description":"The code is used a second time, please authorization again","error":"070317"}*/ // /*{"error_description":"Incorrect parameter or Authorization out of date","error":"070313"}*/ //} /// /// ISV获取刷新令牌 强制执行 /// /// //public string refreshISVToken() //{ // try // { // BasicDataRefDAL.SaveLog("refreshToken=" + refreshToken + ";userId=" + userId + ";appSecret=" + appSecret , "诺诺平台", "ISV获取刷新令牌", "发送值"); // returnStr = NNOpenSDK.refreshISVToken(refreshToken, userId, appSecret); // BasicDataRefDAL.SaveLog(returnStr, "诺诺平台", "ISV获取刷新令牌", "返回值"); // dealRefresh_token(returnStr); // return returnStr; // } // catch { // return ""; // } //} /// /// ISV获取刷新令牌 如非必要则不执行 /// /// //public string setrefreshISVToken() //{ // if (needStart) // { // return "need to start,can not refresh"; // } // if (needresettoken) // { // return (refreshISVToken()); // } // else return "no need to refresh"; //} public HangXinRequestHelper() { tokenstarttime = Convert.ToDateTime("1900-01-01"); } public HangXinRequestHelper(string taxnum) { this.taxnum = taxnum; if (HXTokenHelperList == null) HXTokenHelperList = new List(); HXTokenHelperList.Add(this); } public HangXinRequestHelper(string taxnum, string accessToken) { this.taxnum = taxnum; this.accessToken = accessToken; if (HXTokenHelperList == null) HXTokenHelperList = new List(); var curr = HXTokenHelperList.Find(o => o.taxnum == taxnum); if (!(curr == null)) { curr.accessToken = accessToken; } else { HXTokenHelperList.Add(this); } } /// /// 处理 获取令牌/刷新令牌 命令的返回值 /// /// //private void dealResponse_token(string response) { // var _ISVToken = DSWeb.TruckMng.Helper.JsonConvert.Deserialize(response); // error = _ISVToken.error; // if (string.IsNullOrEmpty(error)) // { // accessToken = _ISVToken.access_token; // refreshToken = _ISVToken.refresh_token; // userId = _ISVToken.userId; // var userinfo = _ISVToken._oauthUser; // taxnum = userinfo.userName; // tokenstarttime = System.DateTime.Now; // var i = BasicDataRefDAL.ExecSql(getUpdStr()); // if (i == 0) // { // try // { // i = BasicDataRefDAL.ExecSql(getInsertStr()); // BasicDataRefDAL.SaveLog(getInsertStr(), "诺诺平台", "保存Token", "Insert"); // } // catch { } // } // else // { // BasicDataRefDAL.SaveLog(getUpdStr(), "诺诺平台", "保存Token", "Update"); // } // } // else // { // error_description = _ISVToken.error_description; // } //} //private void dealRefresh_token(string response) { // var _ISVToken = DSWeb.TruckMng.Helper.JsonConvert.Deserialize(response); // error = _ISVToken.error; // if (string.IsNullOrEmpty(error)) // { // accessToken = _ISVToken.access_token; // refreshToken = _ISVToken.refresh_token; // var i = BasicDataRefDAL.ExecSql(getUpdStr()); // BasicDataRefDAL.SaveLog(getUpdStr(), "诺诺平台", "保存Token", "refresh Update"); // } // else // { // error_description = _ISVToken.error_description; // } //} public static HangXinRequestHelper getHelper(string taxnum) { //ReadToken(); //foreach (var h in HXTokenHelperList) //{ // if (h.taxnum == taxnum) // { // return h; // } //} //var result = new HangXinRequestHelper(taxnum); //return result; var _token = getPortToken(taxnum); return _token; } private static HangXinRequestHelper getPortToken(string taxnum) { try { ///读取接口token //JObject reqObj = new JObject(); //reqObj.Add("taxnum", taxnum); var dic = new Dictionary(); dic.Add("taxnum", taxnum); var rtn = WebRequestHelper.DoPost(_IURL, dic, 10000); //var rtn = WebRequestHelper.DoPost(_SandBoxURL, dic, 20000); //RepCZModel CZM = Newtonsoft.Json.JsonConvert.DeserializeObject(rtn); PortTokenmb pt = Newtonsoft.Json.JsonConvert.DeserializeObject(rtn); if (pt.status == "1") { foreach (var hx in HXTokenHelperList) { if (hx.taxnum == taxnum) { hx.accessToken = pt.message; hx.CanUse = true; hx.ERRORMSG = ""; return hx; } } var result = new HangXinRequestHelper(taxnum, pt.message); return result; } else return new HangXinRequestHelper(taxnum, ""); } catch (Exception e) { var result = new HangXinRequestHelper(taxnum, ""); result.CanUse = false; result.ERRORMSG = "没有取得开票密钥:" + e.Message; return result; } } /// /// 开出发票 /// /// /// /// public DBResult PostInvoice(ChInvoice_HangXin head, List detailList) { var billno = head.BILLNO; //20191028 如果该发票的状态为开票失败 则将其billno临时变更为billno+时分秒,以避开诺诺平台的orderNo不能重复的逻辑 //然后处理返回值时将新的流水号写回。 //20191108 //if (head.EINVOICESTATE == "3"|| head.EINVOICESTATE == "0") //{ // head.BILLNO= billno+ DateTime.Now.ToString("HHmmss"); //} var _head = new HXInvoice(head, detailList); var json = DSWeb.TruckMng.Helper.JsonConvert.Serialize(_head); var _r = ""; _r = PostInvoice(json); var _return = dealresponse_KP(_r); if (_return.code == "E0000") { //开票提交成功 var invoiceSerialNum = _return.result.invoiceSerialNum; //立即调用读取发票信息的方法 将返回值设置进head 并保存 head.INVOICESERIALNUM = invoiceSerialNum; head.BILLNO = billno; head.DbOperationType = DbOperationType.DbotUpd; head.ModelUIStatus = "E"; var modb = new ModelObjectDB(); var result = modb.Save(head); result = ReadInvoice(head); //var returndate = ChinvoiceDAL.GetDataList(0, 1, "cm.INVOICESERIALNUM='" + head.INVOICESERIALNUM + "'", head.OPERATOR); //result.Data = returndate; return result; } else if (_return.code == "070101" || _return.code == "070301") { //appkey与token问题 需要重新认证 //HangXinRequestHelper.clear(accessToken); var result = new DBResult(false, "需要重新认证", null); return result; } else if (_return.code == "E9106") { //E9106 订单编号不能重复 //同billno重复发送 执行一次用订单号读取 return ReadInvoice_BILLNO(head); } else { var reault = new DBResult(false, _return.message, head); return reault; } } public string PostInvoice(string json) { string method = "nuonuo.electronInvoice.requestBilling"; BasicDataRefDAL.SaveLog("URL=" + URL + ";appKey=" + appKey + ";appSecret=" + appSecret + ";accessToken=" + accessToken + ";taxnum=" + taxnum + ";method=" + method + ";content=" + json, "诺诺平台", "发票开出", "发送值"); string result = NNOpenSDK.sendPostSyncRequest(URL, getSendid(), appKey, appSecret, accessToken, taxnum, method, json); BasicDataRefDAL.SaveLog(result, "诺诺平台", "发票开出", "返回值"); return result; } public DBResult ReadInvoice(string INVOICESERIALNUM, string USERID) { var head = ChinvoiceDAL.GetData("cm.INVOICESERIALNUM='" + INVOICESERIALNUM + "'"); var _r = ReadInvoice(head); return _r; } public DBResult ReadInvoice(ChInvoice_HangXin head) { if (string.IsNullOrEmpty(head.INVOICESERIALNUM)) { var result = new DBResult { Success = false, Message = "还未成功进行平台开票,无可读数据", Data = "" }; return result; } string method = "nuonuo.electronInvoice.CheckEInvoice"; var json = "{" + "\"invoiceSerialNum\":[\"" + head.INVOICESERIALNUM + "\"]" + "}"; if (string.IsNullOrWhiteSpace(head.INVOICESERIALNUM)) { //如果流水号为空 则改为按业务编号读取 method = "nuonuo.electronInvoice.querySerialNum"; json = "{" + "\"orderNo\":[\"" + head.BILLNO + "\"]" + "}"; } //读取业务 //string method = "nuonuo.electronInvoice.querySerialNum"; //var json = "{" + "\"orderNo\":[\"" + head.BILLNO + "\"]" + "}"; BasicDataRefDAL.SaveLog("URL=" + URL + ";appKey=" + appKey + ";appSecret=" + appSecret + ";accessToken=" + accessToken + ";taxnum=" + taxnum + ";method=" + method + ";content=" + json, "诺诺平台", "读取发票信息", "发送值"); string _r = NNOpenSDK.sendPostSyncRequest(URL, getSendid(), appKey, appSecret, accessToken, taxnum, method, json); BasicDataRefDAL.SaveLog(_r, "诺诺平台", "读取发票信息", "返回值"); var _return = dealresponse_Read(_r); if (_return.code == "070101" || _return.code == "070301") { //appkey与token问题 需要重新认证 //HangXinRequestHelper.clear(accessToken); var result = new DBResult(false, "需要重新认证", null); return result; } if (_return.code == "070302") { //appkey与token问题 需要重新认证 //HangXinRequestHelper.clear(accessToken); var result = new DBResult(false, "需要联系诺诺平台开通相关权限", null); return result; } if (_return.code == "E0000") { //开票信息读取成功 var returndate = ChinvoiceDAL.GetData("cm.INVOICESERIALNUM='" + head.INVOICESERIALNUM + "'"); head = returndate; //var invoiceSerialNum = _return.result[0].invoiceSerialNum; var info = _return.result[0]; //立即调用读取发票信息的方法 将返回值设置进head 并保存 //head.INVOICESERIALNUM = invoiceSerialNum; head.INVOICECODE = info.invoiceCode; head.INVOICENO = info.invoiceNum; head.EINVOICESTATE = info.status; head.INVOICEINFOURL = info.invoiceImageUrl; head.INVOICEPDFURL = info.invoiceFileUrl; head.INVOICEMAKETIME = info.invoiceDate; //if (!string.IsNullOrWhiteSpace(info.invoiceSerialNum)) //{ // head.INVOICESERIALNUM = info.invoiceSerialNum; //} //head.REMARK = head.REMARK.Replace(info.remark,"")+ info.remark; head.DbOperationType = DbOperationType.DbotUpd; head.ModelUIStatus = "E"; var modb = new ModelObjectDB(); var result = modb.Save(head); result.Message = info.resultMsg; if (info.resultMsg.Contains("开具结果:0,开具失败原因:开票异常")) { result.Message = "开票异常,请尝试重新连接税控盘、重新启动税控软件和诺诺客户端,然后再次读取发票信息;如仍显示此提示,请联系诺诺平台客服人员,并提供销方税号和此发票的流水号"; } return result; } else { var msg = _return.code + ":" + _return.describe; var result = new DBResult { Success = false, Message = DSWeb.TruckMng.Helper.JsonConvert.Serialize(msg), Data = "" }; return result; } } public DBResult ReadInvoice_BILLNO(ChInvoice_HangXin head) { //读取业务 string method = "nuonuo.electronInvoice.querySerialNum"; var json = "{" + "\"orderNo\":[\"" + head.BILLNO + "\"]" + "}"; BasicDataRefDAL.SaveLog("URL=" + URL + ";appKey=" + appKey + ";appSecret=" + appSecret + ";accessToken=" + accessToken + ";taxnum=" + taxnum + ";method=" + method + ";content=" + json, "诺诺平台", "读取发票信息", "发送值"); string _r = NNOpenSDK.sendPostSyncRequest(URL, getSendid(), appKey, appSecret, accessToken, taxnum, method, json); BasicDataRefDAL.SaveLog(_r, "诺诺平台", "读取发票信息", "返回值"); var _return = dealresponse_Read(_r); if (_return.code == "070101" || _return.code == "070301") { //appkey与token问题 需要重新认证 //HangXinRequestHelper.clear(accessToken); var result = new DBResult(false, "需要重新认证", null); return result; } if (_return.code == "070302") { //appkey与token问题 需要重新认证 //HangXinRequestHelper.clear(accessToken); var result = new DBResult(false, "需要联系诺诺平台开通相关权限", null); return result; } if (_return.code == "E0000") { //开票信息读取成功 var returndate = ChinvoiceDAL.GetData("cm.INVOICESERIALNUM='" + head.INVOICESERIALNUM + "'"); head = returndate; //var invoiceSerialNum = _return.result[0].invoiceSerialNum; var info = _return.result[0]; //立即调用读取发票信息的方法 将返回值设置进head 并保存 //head.INVOICESERIALNUM = invoiceSerialNum; head.INVOICECODE = info.invoiceCode; head.INVOICENO = info.invoiceNum; head.EINVOICESTATE = info.status; head.INVOICEINFOURL = info.invoiceImageUrl; head.INVOICEPDFURL = info.invoiceFileUrl; head.INVOICEMAKETIME = info.invoiceDate; if (!string.IsNullOrWhiteSpace(info.invoiceSerialNum)) { head.INVOICESERIALNUM = info.invoiceSerialNum; } //head.REMARK = head.REMARK.Replace(info.remark,"")+ info.remark; head.DbOperationType = DbOperationType.DbotUpd; head.ModelUIStatus = "E"; var modb = new ModelObjectDB(); var result = modb.Save(head); result.Message = info.resultMsg; if (info.resultMsg.Contains("开具结果:0,开具失败原因:开票异常")) { result.Message = "开票异常,请尝试重新连接税控盘、重新启动税控软件和诺诺客户端,然后再次读取发票信息;如仍显示此提示,请联系诺诺平台客服人员,并提供销方税号和此发票的流水号"; } return result; } else { var msg = _return.code + ":" + _return.describe; var result = new DBResult { Success = false, Message = DSWeb.TruckMng.Helper.JsonConvert.Serialize(msg), Data = "" }; return result; } } public DBResult VoidInvoice(ChInvoice_HangXin head) { if (string.IsNullOrEmpty(head.INVOICESERIALNUM)) { var result = new DBResult { Success = false, Message = "还未成功进行平台开票,不需要执行作废", Data = "" }; return result; } //作废接口 string method = "nuonuo.electronInvoice.invoiceCancellation"; // String content = "{" + //"\"invoiceId\":\"19051413444101000011\"," + //"\"invoiceCode\":\"033001800211\"," + //"\"invoiceNo\":\"07912653\"" + //"}"; var json = "{" + "\"invoiceId\":\"" + head.INVOICESERIALNUM + "\"," + "\"invoiceCode\":\"" + head.INVOICECODE + "\"," + "\"invoiceNo\":\"" + head.INVOICENO + "\"" + "}"; BasicDataRefDAL.SaveLog("URL=" + URL + ";appKey=" + appKey + ";appSecret=" + appSecret + ";accessToken=" + accessToken + ";taxnum=" + taxnum + ";method=" + method + ";content=" + json, "诺诺平台", "发票作废", "发送值"); string _r = NNOpenSDK.sendPostSyncRequest(URL, getSendid(), appKey, appSecret, accessToken, taxnum, method, json); BasicDataRefDAL.SaveLog(_r, "诺诺平台", "发票作废", "返回值"); var _return = dealresponse_KP(_r); if (_return.code == "E0000") { //作废请求成功 var invoiceSerialNum = _return.result.invoiceId; head.INVOICESERIALNUM = invoiceSerialNum; head.ISDELETE = "true"; var result = ReadInvoice(head); //var result = new DBResult { Success = true, Message = _return.code + ":" + _return.describe, Data = head }; return result; } else { var msg = _return.code + _return.status + ":" + _return.describe + _return.msg; var result = new DBResult { Success = false, Message = DSWeb.TruckMng.Helper.JsonConvert.Serialize(msg), Data = "" }; return result; } } /// /// 处理开票命令返回值 /// /// /// private KPResponse dealresponse_KP(string json) { var result = new KPResponse(); result = DSWeb.TruckMng.Helper.JsonConvert.Deserialize(json.Trim('"')); return result; } /// /// 处理 读取发票信息命令 /// /// /// private ReadResponse dealresponse_Read(string json) { var result = new ReadResponse(); result = DSWeb.TruckMng.Helper.JsonConvert.Deserialize(json.Trim('"')); return result; } /// /// 执行save操作 /// //private void DoSaveToken() //{ // if (HXTokenHelperList==null ||HXTokenHelperList.Count == 0) return; // SaveToken(); //} /// /// 将数据库内记录的token信息读入static列表 /// private static void ReadToken() { //BasicDataRefDAL.SaveLog(" SELECT * from Invoice_HangXinToken ", "诺诺平台", "读取数据库token", "读取数据库token"); /* 20191210 废弃 var strSql = " SELECT * from Invoice_HangXinToken "; Database db = DatabaseFactory.CreateDatabase(); bool neednew = false; using (IDataReader reader = db.ExecuteReader(CommandType.Text, strSql.ToString())) { while (reader.Read()) { neednew = true; if (HXTokenHelperList == null) HXTokenHelperList = new List(); foreach (var hx in HXTokenHelperList) { //BasicDataRefDAL.SaveLog(" 循环税号token:" + hx.taxnum+";reader税号:"+ Convert.ToString(reader["TAXNUM"]), "诺诺平台", "读取数据库token", "读取数据库token"); if (hx.taxnum == Convert.ToString(reader["TAXNUM"])) { //BasicDataRefDAL.SaveLog(" 刷新税号token:"+ hx.taxnum, "诺诺平台", "读取数据库token", "读取数据库token"); hx.code = Convert.ToString(reader["CODE"]); hx.userId = Convert.ToString(reader["USERID"]); hx.accessToken = Convert.ToString(reader["ACCESSTOKEN"]); hx.refreshToken = Convert.ToString(reader["REFRESHTOKEN"]); if (reader["STARTTIME"] != DBNull.Value) hx.tokenstarttime = Convert.ToDateTime(reader["STARTTIME"]); //if (reader["SAVETIME"] != DBNull.Value) // hx = Convert.ToString(reader["SAVETIME"]); hx.error = Convert.ToString(reader["ERROR"]); hx.error_description = Convert.ToString(reader["ERROR_DESCRIPTION"]); neednew = false; break; } } if (neednew) { var hx = new HangXinRequestHelper(Convert.ToString(reader["TAXNUM"])); //BasicDataRefDAL.SaveLog(" 增加税号token:" + hx.taxnum, "诺诺平台", "读取数据库token", "读取数据库token"); hx.code = Convert.ToString(reader["CODE"]); hx.userId = Convert.ToString(reader["USERID"]); hx.accessToken = Convert.ToString(reader["ACCESSTOKEN"]); hx.refreshToken = Convert.ToString(reader["REFRESHTOKEN"]); if (reader["STARTTIME"] != DBNull.Value) hx.tokenstarttime = Convert.ToDateTime(reader["STARTTIME"]); //if (reader["SAVETIME"] != DBNull.Value) // hx = Convert.ToString(reader["SAVETIME"]); hx.error = Convert.ToString(reader["ERROR"]); hx.error_description = Convert.ToString(reader["ERROR_DESCRIPTION"]); } //BasicDataRefDAL.SaveLog(HangXinRequestHelper.HXTokenHelperList.Count.ToString(), "诺诺平台", "Token实体类总数", "读取数据库token"); } } */ } /// /// 保存token信息,当获取和刷新时执行一次 /// /// /// //private bool SaveToken() { // bool result = false; // var i = BasicDataRefDAL.ExecSql(getUpdStr()); // if (i == 0) { // try // { // i = BasicDataRefDAL.ExecSql(getInsertStr()); // BasicDataRefDAL.SaveLog(getInsertStr(), "诺诺平台", "保存Token", "SaveToken"); // } // catch { } // } // else { // BasicDataRefDAL.SaveLog(getUpdStr(), "诺诺平台", "保存Token", "SaveToken"); // } // if (i > 0) result = true; // return result; //} /// /// 获取插入数据库所需的语句 /// Invoice_HangXinToken /// TAXNUM,CODE,USERID,ACCESSTOKEN,REFRESHTOKEN,STARTTIME,SAVETIME,ERROR,ERROR_DESCRIPTION /// /// private string getInsertStr() { var result = string.Format(" insert into Invoice_HangXinToken values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", taxnum, code, userId, accessToken, refreshToken, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), error, error_description); return result; } private string getUpdStr() { var result = string.Format(" update Invoice_HangXinToken set CODE='{1}',USERID='{2}',ACCESSTOKEN='{3}',REFRESHTOKEN='{4}',STARTTIME='{5}',SAVETIME='{6}',ERROR='{7}',ERROR_DESCRIPTION='{8}' where TAXNUM='{0}'", taxnum, code, userId, accessToken, refreshToken, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), error, error_description); return result; } } public class PortTokenmb { public string message { get; set; } public string status { get; set; } } [JsonObject] public class ISVTokenmb : ModelObjectBillHead { public string access_token { get; set; } public string refresh_token { get; set; } public string expires_in { get; set; } public string userId { get; set; } public string oauthUser { get; set; } public oauthUser _oauthUser { get { oauthUser r_oauthUser = DSWeb.TruckMng.Helper.JsonConvert.Deserialize(oauthUser);//DSWeb.TruckMng.Helper. return r_oauthUser; } } public string error_description { get; set; } public string error { get; set; } /*"{\"access_token\":\"98600c833f178852e2f4d51cexk9yegi\", * \"refresh_token\":\"faf038898dec26eac62640aaed0506cb\", * \"oauthUser\":\" * {\\\"userName\\\":\\\"339901999999142\\\", * \\\"registerType\\\":\\\"1\\\"}\", * \"expires_in\":86356, * \"userId\":\"d1aa0da6bc9840ae83c1120cecd057ac\"}"*/ } [JsonObject] public class Refreshtokenmb { //{"access_token":"1213ef77eab8280536a1a41jehndvz3i","refresh_token":"1a743ee6fd1d965db2b39943e703da4a","expires_in":86400} //{"error_description":"Incorrect refreshToken[8ffb4a7e21691a5d295ee4f64920fc0d]","error":"070314"} public string access_token { get; set; } public string refresh_token { get; set; } public string error_description { get; set; } public string error { get; set; } } [JsonObject] public class oauthUser : ModelObjectBillBody { public string userName { get; set; } public string registerType { get; set; } } [JsonObject] ///解析开票命令返回值;作废命令返回值 public class KPResponse { public string code { get; set; } public string describe { get; set; } public string msg { get; set; } public string status { get; set; } public string message { get { return code + ":" + describe; } } //public KPResult _result { get {return DSWeb.TruckMng.Helper.JsonConvert.Deserialize(result);} } public KPResult result { get; set; } } [JsonObject] ///解析开票命令返回值内的result public class KPResult { public string invoiceSerialNum { get; set; } public string invoiceId { get; set; } } [JsonObject] ///解析读取发票信息命令返回值 public class ReadResponse { public string code { get; set; } public string describe { get; set; } public bool success { get { if (code == "E0000") return true; else return false; } } /* public List _result { get { List _list = new List(); foreach (var str in result) { var info = DSWeb.TruckMng.Helper.JsonConvert.Deserialize(str); _list.Add(info); } return _list; } //set { _result = value } } public List result { get; set; } */ public List result { get; set; } } [JsonObject] ///用于解析“读取发票信息”方法返回的发票信息 public class ReadResult { #region private Fields private string _orderNo = string.Empty; private string _invoiceSerialNum = string.Empty; private string _status = string.Empty; private string _statusMsg = string.Empty; private string _resultMsg = string.Empty; private string _invoiceFileUrl = string.Empty; private string _invoiceImageUrl = string.Empty; private string _invoiceDate = string.Empty; private string _invoiceCode = string.Empty; private string _invoiceNum = string.Empty; private string _taxExcludedAmount = string.Empty; private string _taxIncludedAmount = string.Empty; private string _buyerName = string.Empty; private string _buyerTaxNum = string.Empty; private string _invoiceLine = string.Empty; #endregion #region public Fields public string orderNo { get { return _orderNo; } set { _orderNo = value; } } public string invoiceSerialNum { get { return _invoiceSerialNum; } set { _invoiceSerialNum = value; } } public string status { get { return _status; } set { _status = value; } } public string statusMsg { get { return _statusMsg; } set { _statusMsg = value; } } public string resultMsg { get { return _resultMsg; } set { _resultMsg = value; } } public string invoiceFileUrl { get { return _invoiceFileUrl; } set { _invoiceFileUrl = value; } } public string invoiceImageUrl { get { return _invoiceImageUrl; } set { _invoiceImageUrl = value; } } public string invoiceDate { get { return _invoiceDate; } set { _invoiceDate = value; } } public string invoiceCode { get { return _invoiceCode; } set { _invoiceCode = value; } } public string invoiceNum { get { return _invoiceNum; } set { _invoiceNum = value; } } public string taxExcludedAmount { get { return _taxExcludedAmount; } set { _taxExcludedAmount = value; } } public string taxIncludedAmount { get { return _taxIncludedAmount; } set { _taxIncludedAmount = value; } } public string buyerName { get { return _buyerName; } set { _buyerName = value; } } public string buyerTaxNum { get { return _buyerTaxNum; } set { _buyerTaxNum = value; } } public string invoiceLine { get { return _invoiceLine; } set { _invoiceLine = value; } } public string remark { get; set; } #endregion } [JsonObject] public class P2INVOICE : BaseTableMC { } }