/// <summary> /// send image to openid /// </summary> /// <param name="openid"></param> /// <param name="fileByte"></param> /// <returns></returns> public static async Task <bool> SendMessageAsync(string openid, string message, int maxAttamptTime = 3) { try { WxJsonResult sendRst = null; for (int i = 0; i < maxAttamptTime; i++) { sendRst = await CustomApi.SendTextAsync(_appId, openid, message); if (sendRst != null && sendRst.errcode == 0) { break; } } if (sendRst == null || sendRst.errcode != 0) { StallApplication.SysError($"[MSG]failed sending to wechat {openid}:{sendRst.errcode},{sendRst.errmsg}"); return(false); } return(true); } catch (Exception ex) { StallApplication.SysError($"[MSG]failed sending to wechat {openid}:", ex); return(false); } }
public async Task <bool> SendToWechat(IList <string> openids) { try { StallApplication.SysInfoFormat($"[MSG]start sending order {Id} to wechat"); //send message var msg = OwnerAlertMessage; var result = await WeChatHelper.SendMessageAsync(openids, msg); if (result) { StallApplication.SysInfoFormat($"[MSG]succeed sending order {Id} to wechat"); } else { StallApplication.SysInfoFormat($"[MSG]failed sending order {Id} to wechat"); } return(result); } catch (Exception ex) { StallApplication.SysError("[MSG]failed to send message", ex); return(false); } }
public static int?GetDistance(string depCountry, string depCity, string depSuburb, string destCountry, string destCity, string destSuburb) { //get from db using (var db = new StallEntities()) { var id = BuilId(depCountry, depCity, depSuburb, destCountry, destCity, destSuburb); var dbResult = GetDistance(id, db); if (dbResult != null) { return(dbResult); } //call google map api var glResult = GoogleMapHelper.GetSuburbDistanceFromGoogleMapApi(depCountry, depCity, depSuburb, destCountry, destCity, destSuburb, GreenspotConfiguration.AccessAccounts["google.map"].Secret); if (glResult == null) { StallApplication.SysError($"[GOOGLE DISTANCE]failed to get distance {depCountry},{depCity},{depSuburb} to {destCountry},{destCity},{destSuburb}"); return(null); } else { //save to db var distance = new SuburbDistance() { ID = id, DepartureCountryCode = depCountry, DepartureCity = depCity, DepartureSuburb = depSuburb, DestinationCountryCode = destCountry, DestinationCity = destCity, DestinationSuburb = destSuburb, Meters = glResult.Value }; db.SuburbDistances.Add(distance); db.SaveChanges(); return(glResult.Value); } } }
public async Task <bool> SendToPrinter() { try { if (await PrintHelper.PrintOrderAsync(this)) { //update return(true); } else { StallApplication.SysError("[MSG]fail to print"); return(false); } } catch (Exception ex) { StallApplication.SysError("[MSG]fail to print", ex); return(false); } }
public ActionResult AddAddress() { OperationResult <bool> result = new OperationResult <bool>(true); Stream req = Request.InputStream; req.Seek(0, System.IO.SeekOrigin.Begin); string json = new StreamReader(req).ReadToEnd(); DeliveryAddress addr = new DeliveryAddress(); try { var clntObj = JsonConvert.DeserializeObject <dynamic>(json); addr.UserId = CurrentUser.Id; addr.Name = clntObj.FullName; addr.Mobile = clntObj.Mobile; addr.Address1 = clntObj.AddressObject.AddressLine1; addr.Address2 = clntObj.Address2; addr.Suburb = clntObj.AddressObject.Suburb; addr.City = clntObj.AddressObject.CityTown; addr.StateOrRegion = ""; addr.CountryCode = "NZ"; addr.Postcode = clntObj.AddressObject.Postcode; addr.Area = clntObj.Area; addr.Save(_db); } catch (Exception ex) { // Try and handle malformed POST body result.Succeeded = false; result.Message = ex.Message; StallApplication.SysError("[ADD ADDR]failed to address", ex); } return(Json(result, JsonRequestBehavior.AllowGet)); }
public ActionResult PxPay(int id) { string paidFlag = Request["paid"]; if (paidFlag == null) { StallApplication.SysError("[MSG]pxpay callback without paid parameter"); return(View("Error")); } StallApplication.SysInfoFormat("[MSG]PxPay call back [{0}]:{1}", paidFlag, Request.Url.ToString()); bool isSuccess = "SUCCESS".Equals(paidFlag.ToUpper()); string payResultId = Request["result"]; if (string.IsNullOrEmpty(payResultId)) { StallApplication.SysError("[MSG]pxpay callback without result id"); return(View("Error")); } int paymentId = 0; if (!Accountant.VerifyPxPayPayment(payResultId, isSuccess, out paymentId)) { StallApplication.BizErrorFormat("[MSG]PxPay not verified, result id={0}", payResultId); return(View("Error")); } if (paymentId != id) { StallApplication.BizErrorFormat("[MSG]transaction not matched, px {0} <> url {1}", paymentId, id); return(View("Error")); } if (isSuccess) { if (StallApplication.IsPaymentOperating(paymentId)) { StallApplication.BizErrorFormat("[MSG]payment {0} is operating", paymentId); return(Redirect("/customer/orders")); } //set order as paid var orders = Models.Order.FindByPaymentId(paymentId, _db); foreach (var order in orders) { if (!order.HasPaid) { try { order.HasPaid = true; _db.SaveChanges(); //notify var openIds = new List <string>(); //owner var owner = UserManager.FindById(order.Stall.UserId); var ownerId = owner?.SnsInfos[WeChatClaimTypes.OpenId].InfoValue; openIds.Add(ownerId); //delivery man var deliveryMen = Models.User.GetByRole(_db, "DeliveryMan"); foreach (var d in deliveryMen) { var dId = d.SnsInfos.FirstOrDefault(x => WeChatClaimTypes.OpenId.Equals(x.InfoKey))?.InfoValue; if (!string.IsNullOrEmpty(dId)) { openIds.Add(dId); } } //await order.Notify(_db, openId); HostingEnvironment.QueueBackgroundWorkItem(x => order.Notify(_db, openIds)); } catch (Exception ex) { StallApplication.SysError($"[MSG]failed to save order {order.Id}", ex); } } } StallApplication.RemoveOperatingPayment(paymentId); return(Redirect("/customer/orders?act=paid")); } else { return(Redirect("/errorpage/payfailed")); } }
public ActionResult Pay() { OperationResult <string> result = new OperationResult <string>(true); Stream req = Request.InputStream; req.Seek(0, System.IO.SeekOrigin.Begin); string json = new StreamReader(req).ReadToEnd(); Payment payment = null; try { IList <Product> outOfStocks; var orders = ConvertToOrders(json, out outOfStocks); if (outOfStocks.Count > 0) { result.Succeeded = false; result.Message = "Some Products are out of stock"; var sb = new StringBuilder("["); var comma = ""; foreach (var p in outOfStocks) { sb.Append(string.Format("{0}{{\"StallName\":\"{1}\",\"ProductName\":\"{2}\",\"Stock\":{3}}}", comma, p.Stall.StallName, p.BaseName, p.Stock)); comma = ","; } sb.Append("]"); result.ErrorType = "OutOfStock"; result.Data = sb.ToString(); return(Json(result, JsonRequestBehavior.AllowGet)); } using (var tran = _db.Database.BeginTransaction()) { //calc total amnount, orderIds decimal amount = 0.0M; foreach (var order in orders) { amount += order.ChargeAmount; } //create payment payment = Payment.CreatePayment(_db, amount); if (payment == null) { tran.Rollback(); result.Succeeded = false; result.Message = "fail to create payment"; return(Json(result, JsonRequestBehavior.AllowGet)); } //create order string orderIds = null; foreach (var order in orders) { order.PaymentId = payment.Id; order.IsPrintOrder = order.Stall.IsPrintOrder; if (!order.Save(_db)) { tran.Rollback(); result.Succeeded = false; result.Message = "fail to create order"; return(Json(result, JsonRequestBehavior.AllowGet)); } //get order id if (string.IsNullOrEmpty(orderIds)) { orderIds = order.Id.ToString(); } else { orderIds += "," + order.Id.ToString(); } } //update payment payment.OrderIds = orderIds; payment.Save(_db); //save tran.Commit(); } //return payment url string payUrl = null; string urlSuccess = string.Format("{0}/Customer/PxPay/{1}?paid=SUCCESS", GreenspotConfiguration.RootUrl, payment.Id); string urlFail = string.Format("{0}/Customer/PxPay/{1}?paid=FAIL", GreenspotConfiguration.RootUrl, payment.Id); try { payUrl = Accountant.GeneratePayURL(payment, urlFail, urlSuccess); StallApplication.BizInfoFormat("[PAY]go to payment url:{0}", payUrl); result.Data = payUrl; } catch (Exception ex) { StallApplication.SysError("[PAY]", ex); result.Succeeded = false; result.Message = "fail to generate payment url"; } } catch (Exception ex) { // Try and handle malformed POST body StallApplication.SysError("[PAY]", ex); result.Succeeded = false; result.Message = "fail to pay"; } return(Json(result, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Send Order To Vend /// </summary> /// <param name="db"></param> /// <returns></returns> public async Task <bool> SendToVend() { try { //var tmpOrder = JsonConvert.DeserializeObject<Order>(JsonString); //var tmpStall = Models.Stall.FindById(StallId, db); //create vend api object var vendSale = new VendRegisterSaleRequest(); vendSale.InvoiceNumber = Id.ToString(); vendSale.RegisterId = Stall.RegisterId; vendSale.SaleDate = CreateTime.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"); vendSale.Status = OrderStatus.CLOSED; vendSale.TotalPrice = (double)CalcTotalPriceExcludeTax(); vendSale.TotalTax = (double)CalcTotalTax(); //vendSale.TaxName = Items[0].Product.TaxName; vendSale.RegisterSaleProducts = new List <VendRegisterSaleRequest.RegisterSaleProduct>(); vendSale.RegisterSalePayments = new List <VendRegisterSaleRequest.RegisterSalePayment>(); vendSale.Note = string.Format("#{0}@{1}\n{2}\n{3}\n{4}", Id, PaymentId, Receiver, DeliveryAddress, Note); foreach (var item in Items) { var salePdt = new VendRegisterSaleRequest.RegisterSaleProduct() { ProductId = item.ProductId, Quantity = item.Quantity, Price = (double)item.Price, Tax = (double)item.Tax, TaxId = item.TaxId, TaxTotal = (double)item.Tax }; salePdt.Attributes.Add(new VendRegisterSaleRequest.Attribute() { Name = "line_note", Value = item.LineNote }); vendSale.RegisterSaleProducts.Add(salePdt); } vendSale.RegisterSalePayments.Add(new VendRegisterSaleRequest.RegisterSalePayment() { RetailerPaymentTypeId = Stall.PaymentTypeId, PaymentDate = string.Format("{0:yyyy-MM-dd HH:mm:ss}", Payment.ResponseTime?.ToUniversalTime()), Amount = (double)StallAmount }); //do reqeust var response = await VendRegisterSale.CreateVendRegisterSalesAsync(vendSale, Stall.Prefix, await StallApplication.GetAccessTokenAsync(Stall.Prefix)); //update if (!string.IsNullOrEmpty(response.RegisterSale.Id) && OrderStatus.CLOSED.Equals(response.RegisterSale.Status)) { VendResponse = JsonConvert.SerializeObject(response); VendSaleId = response?.RegisterSale?.Id; return(true); } else { StallApplication.SysError("[MSG]fail to save to vend"); return(false); } } catch (Exception ex) { StallApplication.SysError("[MSG]fail to save to vend", ex); return(false); } }
/// <summary> /// verify px payment match transaction /// if pay success set transaction as paid /// </summary> /// <param name="resultId"></param> /// <param name="isSuccess"></param> /// <returns></returns> public static bool VerifyPxPayPayment(string resultId, bool isSuccess, out int outPaymentId) { outPaymentId = 0; try { //check response StallApplication.BizInfoFormat("[ACCOUNTANT-PXPAY]start to get pxpay payment result={0}", resultId); ResponseOutput output = _pxPay.ProcessResponse(resultId); if (output == null) { StallApplication.BizError("[ACCOUNTANT-PXPAY]can not get pxpay payment result - resposne is null"); return(false); } if (!(isSuccess ? "1" : "0").Equals(output.Success)) { StallApplication.BizErrorFormat("[ACCOUNTANT-PXPAY]payment result not match except {0} - actual {1}", output.Success, isSuccess); StallApplication.BizErrorFormat("[ACCOUNTANT-PXPAY]{0}", output); return(false); } //set payment int paymentId = int.Parse(output.TxnId.Split('-')[0]); decimal amount = decimal.Parse(output.AmountSettlement); using (StallEntities db = new StallEntities()) { Payment payment = db.Payments.FirstOrDefault(o => o.Id == paymentId); if (payment == null) { StallApplication.BizErrorFormat("[ACCOUNTANT-PXPAY]payment {0} can not mactch payment {1}", resultId, outPaymentId); StallApplication.BizErrorFormat("[ACCOUNTANT-PXPAY]{0}", output); return(false); } payment.ResponseTime = DateTime.Now; outPaymentId = paymentId; bool result = true; if (!isSuccess) { //pay fail StallApplication.BizErrorFormat("[ACCOUNT-PAPAY]pay failed payment id={0}", payment.Id); } else { //pay success if (payment.Amount != amount) { StallApplication.BizErrorFormat("[ACCOUNT-PAPAY]pxpay amount {0} <> transaction amount {1}", amount, payment.Amount); result = false; } else { payment.HasPaid = true; } } payment.PxPayResponse = output.ToString(); db.SaveChanges(); return(result); } } catch (Exception ex) { StallApplication.SysError("can not get pxpay payment result", ex); return(false); } }