public void Process() { NetworkStream stream = null; kkmServiceResponseAtol respAtol = new kkmServiceResponseAtol(); try { stream = client.GetStream(); byte[] data = new byte[64]; // буфер для получаемых данных // получаем сообщение StringBuilder builder = new StringBuilder(); int bytes = 0; do { bytes = stream.Read(data, 0, data.Length); builder.Append(Encoding.GetEncoding(1251).GetString(data, 0, bytes)); }while (stream.DataAvailable); string message = builder.ToString(); string forceXml = ""; kkmServiceRequest m_requests = Serializer.FromXml <kkmServiceRequest>(message); kkmServiceResponse m_response = SendInfoToKKM(m_requests, out forceXml); } catch (Exception ex) { Logs.LogAdd("Ошибка " + ex.Message); } finally { if (stream != null) { stream.Close(); } if (client != null) { client.Close(); } } }
public string SendPaymentATOL(ServiceConfig m_Config, kkmServiceRequest m_request, CultureInfo FormatProvider, out string UUID, out string exeptionMessage, out string status) { UUID = "Не присвоен"; exeptionMessage = ""; status = ""; Logs.LogAdd("SendPaymentATOL()Пытаюсь отправить чек с групповой: " + m_request.groupOperId); exeptionMessage = GetToken(); if (!string.IsNullOrEmpty(exeptionMessage)) { return(exeptionMessage); } try { string url = m_Config.url + "/possystem/v4/" + m_Config.codeGroup + "/sell"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json; charset=utf-8"; request.Headers.Add("Token", token); string summ = m_request.summ; //m_request.groupOperId = new Random().Next(100000); // m_request.groupOperId = 319979252; m_request.email = "*****@*****.**"; decimal dSumm = Convert.ToDecimal(summ, ni); AtoRequest atolRequest = new AtoRequest(); atolRequest.external_id = m_request.groupOperId.ToString(); atolRequest.receipt = new Receipt(); atolRequest.receipt.client = new Client() { email = m_request.email }; atolRequest.receipt.company = new Company() { email = m_Config.emailCompany, inn = m_Config.inn, payment_address = m_Config.paymentAddr }; atolRequest.receipt.payments = new List <Payment>(); atolRequest.receipt.payments.Add(new Payment() { type = 1, sum = dSumm }); atolRequest.receipt.total = dSumm; atolRequest.service = new Service() { callbackUrl = m_Config.callBackUrl }; atolRequest.timestamp = timestamp; atolRequest.receipt.items = new List <Item>(); atolRequest.receipt.items.Add(new Item() { name = m_Config.nameServices, price = dSumm, quantity = 1, sum = dSumm, vat = new Vat() { type = "vat20" } }); //m_request.groupOperId = new Random().Next(100000); //m_request.groupOperId = 319979251; m_request.email = "*****@*****.**"; string pData = @"{ ""external_id"":""" + m_request.groupOperId.ToString() + @""", ""receipt"": {""client"":{""email"":""" + m_request.email + @"""}, ""company"": {""email"":""" + m_Config.emailCompany + @""", ""inn"":""" + m_Config.inn + @""", ""payment_address"":""" + m_Config.paymentAddr + @"""}, ""items"": [{""name"":""" + m_Config.nameServices + m_request.accountNumber + @""", ""price"":" + summ + @", ""quantity"":1, ""sum"":" + summ + @", ""payment_method"":""full_payment"", ""payment_object"":""service"", ""vat"":{""type"":""vat20""}}], ""payments"": [{""type"":1, ""sum"":" + summ + @"}], ""total"":" + summ + @"}, ""service"": {""callbackUrl"":""" + m_Config.callBackUrl + @"""}, ""timestamp"":""" + timestamp + @"""}"; string jSonStr = pData; // Serializer.ToJson<AtoRequest>(atolRequest); byte[] ByteArr = Encoding.UTF8.GetBytes(jSonStr); request.ContentLength = ByteArr.Length; request.GetRequestStream().Write(ByteArr, 0, ByteArr.Length); DataJSONPayload dataJSONPayload; if (m_Config.debugLevel > 20) { Logs.LogAdd("Отправленный чек: " + jSonStr); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(DataJSONPayload)); dataJSONPayload = (DataJSONPayload)jsonFormatter.ReadObject(myStreamReader.BaseStream); UUID = dataJSONPayload.uuid; status = dataJSONPayload.status; } } if (m_Config.debugLevel > 3) { Logs.LogAdd("Отправленная групповая: " + m_request.groupOperId + Environment.NewLine + "Полученный token: " + token + Environment.NewLine + "Полученный UID: " + UUID); } } catch (WebException ex) { var temp = ex.Response as HttpWebResponse; Logs.LogAdd("ОШИБКА: " + ex.Message); string content; using (var r = new StreamReader(ex.Response.GetResponseStream())) content = r.ReadToEnd(); try { using (var mm = new MemoryStream(Encoding.UTF8.GetBytes(content))) { using (StreamReader myStreamReader = new StreamReader(mm, Encoding.UTF8)) { DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(DataJSONPayload)); var errorDataJSONPayload = (DataJSONPayload)jsonFormatter.ReadObject(myStreamReader.BaseStream); if (errorDataJSONPayload.error != null) { exeptionMessage = errorDataJSONPayload.error.text; } } } } catch (Exception) { } switch (temp.StatusCode) { case HttpStatusCode.Unauthorized: Logs.LogAdd("ОШИБКА: " + content + Environment.NewLine + "Номер групповой операции: " + m_request.groupOperId + " UUID: " + m_UUID); break; } } catch (Exception ex) { Logs.LogAdd("ОШИБКА: " + ex.Message + " ОШИБКА 2 : "); } return(UUID); }
private kkmServiceResponse SendInfoToKKM(kkmServiceRequest request, out string forceXml) { forceXml = null; string a_uuid; string a_exeptionMessage; string a_status; CultureInfo m_formatProvider = new CultureInfo("en-US", true); m_formatProvider.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy"; m_formatProvider.NumberFormat.NumberDecimalSeparator = "."; kkmServiceResponse resp = new kkmServiceResponse(); lock (POSAtolOnline.SyncObj) { Logs.LogAdd("Данные для ККМ: m_Config.kkmTypeProtokol = " + m_Config.kkmTypeProtokol + " m_Config.kkmIPAddress = " + m_Config.kkmIPAddress + " m_Config.kkmPort = " + m_Config.kkmPort); POSAtolOnline POSATOffline = new POSAtolOnline(); POSATOffline.m_Config = m_Config; if (POSATOffline.SendPaymentATOL(m_Config, request, m_formatProvider, out a_uuid, out a_exeptionMessage, out a_status) != "") { Logs.LogAdd("Отправка на АТОЛОнлайн: "); resp.Kkmserialnumber = ""; resp.Kkmeklznumber = ""; resp.Kkmshiftsessionnumber = ""; resp.Kkmglobalsummpaymentfrom = 0.0m; resp.ShiftSummIncome = 0.0m; resp.LastKPKDateTime = DateTime.Now; resp.checkNumber = ""; resp.shiftSummPayment = 0.0m; resp.shiftSummPaymentRevert = 0.0m; resp.operationDocumentNumber = 0; resp.operationNumberFPD = ""; resp.shiftReceiptNumber = 0; resp.shiftReceiptRevertNumber = 0; resp.countDocumentNotSentOFD = ""; resp.registrationNumberKKT = ""; resp.atoluuid = a_uuid; if (m_Config.debugLevel > 1) { Logs.LogAdd("Отправлена грууповая операция: " + request.groupOperId + " Возвращенный UUID: " + a_uuid); } resp.groupOperId = request.groupOperId; resp.requestDate = DateTime.Now.ToString("yyyy-MM-ssTHH:mm:ss"); resp.code = 0; resp.errorMessage = ""; } else { Logs.LogAdd("Ошибка : "); } if (resp.code != 0) { resp.errorMessage += " (code=" + resp.code + ")"; } switch (resp.code) { case 0: //всё хорошо resp.code = 0; break; /*case 21: * //ошибка, повторите запрос на печать * resp.code = 1; * break;*/ default: //фатальная ошибка resp.code = 1; break; } } return(resp); }