Exemple #1
0
        public TaskStatus Handle(IHttpProxy httpProxy)
        {
            using (Log log = new Log("CailutongGateway.Notify_RequestHandler"))
            {
                try
                {
                    string json = httpProxy.ReadRequestBody();
                    log.Log(json);

                    SortedDictionary <string, object> dict = Newtonsoft.Json.JsonConvert.DeserializeObject <SortedDictionary <string, object> >(json);
                    string outTradeNo = (string)dict["outTradeNo"];
                    var    config     = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.CailutongBTC, outTradeNo));

                    if (Cailutong_Helper.Sign(dict, config.Secret) != (string)dict["sign"])
                    {
                        throw new Exception("校验失败");
                    }

                    var status = Convert.ToInt32(dict["status"]);

                    if (status == 2)
                    {
                        PayFactory.OnPaySuccessed(outTradeNo, Convert.ToDouble(dict["payedAmount"]), null, json);
                    }

                    httpProxy.ResponseWrite("{\"status\":\"success\"}");
                }
                catch (Exception ex)
                {
                    log.Log(ex.ToString());
                }
            }
            return(TaskStatus.Completed);
        }
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            using (Log log = new Log("美团.CreateOrder", false))
            {
                httpHandler.ResponseContentType = "application/json";
                var forms = httpHandler.Form.ToObject <SortedDictionary <string, string> >();
                log.LogJson(forms);
                try
                {
                    if (forms.Count > 0)
                    {
                        //验证sign
                        var config = new Config(ResturantFactory.ResturantListener.OnGetPlatformConfigXml(ResturantPlatformType.Meituan));
                        if (forms["sign"] != MeituanHelper.Sign(forms, config.SignKey))
                        {
                            throw new Exception("签名验证失败");
                        }

                        handleContent(forms["order"], int.Parse(forms["ePoiId"]));
                    }
                }
                catch (Exception ex)
                {
                    using (Log logErr = new Log("美团CreateOrderCallback解析错误"))
                    {
                        logErr.Log(ex.ToString());
                    }
                    throw ex;
                }
                httpHandler.ResponseWrite("{\"data\":\"OK\"}");

                return(TaskStatus.Completed);
            }
        }
        public TaskStatus Handle(IHttpProxy httpProxy)
        {
            var json = httpProxy.Form["request"];

            try
            {
                using (CLog log = new CLog("IPaysoonNotify Notify"))
                {
                    log.Log(json);
                    var result = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                    if (result["resultCode"].ToString() == "0000" && result["statusId"].ToString() == "14")
                    {
                        var tradid = result["merchantGenCode"].ToString();
                        var charge = Convert.ToDouble(result["charge"].ToString()) / 100.0;
                        var amount = Convert.ToDouble(result["amount"].ToString()) / 100.0;
                        log.Log("tradid:{0} charge:{1} amount:{2}", tradid, charge, amount);
                        log.Log("excute OnPaySuccessed");
                        PayFactory.OnPaySuccessed(tradid, amount - charge, null, json);
                    }
                    httpProxy.ResponseWrite("SUCCESS");
                }
            }
            catch (Exception ex)
            {
                using (CLog log = new CLog("IPaysoon Notify error "))
                {
                    log.Log(ex.ToString());
                }
            }
            return(TaskStatus.Completed);
        }
        public TaskStatus Handle(IHttpProxy httpProxy)
        {
            try
            {
                var requestJson = httpProxy.Form["requestJson"];
                if (!string.IsNullOrEmpty(requestJson))
                {
                    var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject <ResponseObject>(requestJson);
                    var tradeId     = responseObj.body["out_trade_no"].ToString();
                    var config      = PayFactory.GetConfig <Config>(typeof(LianTuo_WeixinJsApi), tradeId);

                    string serverSign = responseObj.head["sign"].ToString();
                    if (LianTuo_Helper.Sign(config.key, responseObj.head, responseObj.body) != serverSign)
                    {
                        throw new Exception("服务器返回信息签名检验失败");
                    }

                    if ((string)responseObj.body["is_success"] == "S")
                    {
                        double?receipt_amount = null;
                        try
                        {
                            if (responseObj.body["receipt_amount"] != null)
                            {
                                receipt_amount = Convert.ToDouble(responseObj.body["receipt_amount"]);
                            }
                        }
                        catch
                        {
                        }
                        PayFactory.OnPaySuccessed(tradeId, receipt_amount, null, requestJson);
                    }
                    else if ((string)responseObj.body["is_success"] == "F")
                    {
                        PayFactory.OnPayFailed(tradeId, (string)responseObj.body["message"], requestJson);
                    }
                }
                httpProxy.ResponseWrite("success");
            }
            catch (Exception ex)
            {
                using (Log log = new Log("Jack.Pay.LianTuo.WXJSApi.Result Error", false))
                {
                    log.Log(ex.ToString());
                    log.LogJson(httpProxy.Form);
                }
            }
            return(TaskStatus.Completed);
        }
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            httpHandler.ResponseContentType = "application/json";
            var forms = httpHandler.Form.ToObject <SortedDictionary <string, string> >();

            try
            {
                if (forms.Count > 0)
                {
                    //验证sign
                    var config = new Config(ResturantFactory.ResturantListener.OnGetPlatformConfigXml(ResturantPlatformType.Meituan));
                    if (forms["sign"] != MeituanHelper.Sign(forms, config.SignKey))
                    {
                        throw new Exception("签名验证失败");
                    }

                    Newtonsoft.Json.Linq.JObject orderJSONObj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(forms["tradeDetail"]);
                    string orderId         = orderJSONObj.Value <string>("orderId");
                    double settleAmount    = orderJSONObj.Value <double>("settleAmount");
                    double commisionAmount = orderJSONObj.Value <double>("commisionAmount");
                    if (ResturantFactory.ResturantListener != null)
                    {
                        new Thread(() =>
                        {
                            try
                            {
                                ResturantFactory.ResturantListener.OnReceiveOrderSettlement(ResturantPlatformType.Meituan, orderId, new ServiceAmountInfo()
                                {
                                    PlatformServiceAmount = commisionAmount,
                                    SettleAmount          = settleAmount
                                });
                            }
                            catch { }
                        }).Start();
                    }
                }
            }
            catch (Exception ex)
            {
                using (Log log = new Log("美团SettlementCallback解析错误"))
                {
                    log.Log(ex.ToString());
                }
                throw ex;
            }
            httpHandler.ResponseWrite("{\"data\":\"OK\"}");

            return(TaskStatus.Completed);
        }
        public TaskStatus Handle(IHttpProxy httpProxy)
        {
            var tranId = httpProxy.QueryString["tranId"];

            //读取临时文件,还原PayParameter参数
            string tempFile = $"{Helper.GetSaveFilePath()}\\{tranId}.txt";
            var    body     = System.IO.File.ReadAllText(tempFile, Encoding.UTF8);

            var html = Helper.ReadContentFromResourceStream("Jack.Pay.Impls.AlipayPayPage.html");

            html = html.Replace("$body$", body);

            httpProxy.ResponseWrite(html);

            return(TaskStatus.Completed);
        }
Exemple #7
0
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            httpHandler.ResponseContentType = "image/png";
            var url = httpHandler.UrlAbsolutePath;

            var str   = $"/{ResponsePicture.NotifyPageName}/";
            var index = url.IndexOf(str);

            url = url.Substring(index + str.Length);
            var id = url.Substring(0, url.IndexOf("/"));

            byte[] content;
            Pictures.TryRemove(id, out content);
            httpHandler.ResponseWrite(content, 0, content.Length);

            return(TaskStatus.Completed);
        }
Exemple #8
0
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            httpHandler.ResponseContentType = "application/json";
            var forms = httpHandler.Form.ToObject <Dictionary <string, string> >();

            try
            {
                if (forms.Count > 0)
                {
                    var ePoiId       = forms["ePoiId"];
                    var appAuthToken = forms["appAuthToken"];
                    var businessId   = forms["businessId"];
                    if (businessId != "2")//不是外卖
                    {
                        return(TaskStatus.ContinueOtherTask);
                    }

                    if (ResturantFactory.ResturantListener != null && !string.IsNullOrEmpty(appAuthToken))
                    {
                        ResturantFactory.ResturantListener.OnStoreMapSuccess(ResturantPlatformType.Meituan, new StoreMapInfo()
                        {
                            ErpStoreId = int.Parse(ePoiId),
                            Token      = appAuthToken
                        });
                    }
                }
                else
                {
                    return(TaskStatus.ContinueOtherTask);
                }
            }
            catch (Exception ex)
            {
                using (Log log = new Log("美团StoreMapCallback解析错误"))
                {
                    log.Log(ex.ToString());
                }
                throw ex;
            }
            httpHandler.ResponseWrite("{\"data\":\"success\"}");

            return(TaskStatus.Completed);
        }
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            httpHandler.ResponseContentType = "application/json";
            var forms = httpHandler.Form.ToObject <SortedDictionary <string, string> >();

            try
            {
                if (forms.Count > 0)
                {
                    //验证sign
                    var config = new Config(ResturantFactory.ResturantListener.OnGetPlatformConfigXml(ResturantPlatformType.Meituan));
                    if (forms["sign"] != MeituanHelper.Sign(forms, config.SignKey))
                    {
                        throw new Exception("签名验证失败");
                    }

                    Newtonsoft.Json.Linq.JObject orderJSONObj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(forms["order"]);
                    string orderid = orderJSONObj.Value <string>("orderId");

                    if (ResturantFactory.ResturantListener != null)
                    {
                        new Thread(() =>
                        {
                            try
                            {
                                ResturantFactory.ResturantListener.OnOrderFinish(ResturantPlatformType.Meituan, orderid);
                            }
                            catch { }
                        }).Start();
                    }
                }
            }
            catch (Exception ex)
            {
                using (Log log = new Log("美团OrderFinishCallback解析错误"))
                {
                    log.Log(ex.ToString());
                }
            }
            httpHandler.ResponseWrite("{\"data\":\"OK\"}");

            return(TaskStatus.Completed);
        }
Exemple #10
0
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            httpHandler.ResponseContentType = "application/json";

            var forms = httpHandler.Form.ToObject <SortedDictionary <string, string> >();

            try
            {
                if (forms.Count > 0)
                {
                    //验证sign
                    var config = new Config(ResturantFactory.ResturantListener.OnGetPlatformConfigXml(ResturantPlatformType.Meituan));
                    if (forms["sign"] != MeituanHelper.Sign(forms, config.SignKey))
                    {
                        throw new Exception("签名验证失败");
                    }

                    OrderCancelInfo info = new OrderCancelInfo();
                    info.ErpStoreID = int.Parse(forms["ePoiId"]);
                    var orderCancelObj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(forms["orderCancel"]);
                    info.OrderID = orderCancelObj.Value <string>("orderId");
                    info.Reason  = orderCancelObj.Value <string>("reason");

                    new Thread(() =>
                    {
                        try
                        {
                            ResturantFactory.ResturantListener.OnOrderCancel(ResturantPlatformType.Meituan, info);
                        }
                        catch { }
                    }).Start();
                }
            }
            catch (Exception ex)
            {
                using (Log log = new Log("美团CancelOrderCallback解析错误"))
                {
                    log.Log(ex.ToString());
                }
            }
            httpHandler.ResponseWrite("{\"data\":\"OK\"}");
            return(TaskStatus.Completed);
        }
Exemple #11
0
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            httpHandler.ResponseContentType = "application/json";
            var forms = httpHandler.Form.ToObject <Dictionary <string, string> >();

            try
            {
                if (forms.Count > 0)
                {
                    var businessId = forms["businessId"];
                    if (businessId != "2")//不是外卖
                    {
                        return(TaskStatus.ContinueOtherTask);
                    }

                    var ePoiId = Convert.ToInt32(forms["ePoiId"]);

                    if (ResturantFactory.ResturantListener != null)
                    {
                        ResturantFactory.ResturantListener.OnReleaseStoreMapSuccess(ResturantPlatformType.Meituan, ePoiId);
                    }
                }
                else
                {
                    return(TaskStatus.ContinueOtherTask);
                }
            }
            catch (Exception ex)
            {
                using (Log log = new Log("美团ReleaseStoreMapCallback解析错误"))
                {
                    log.Log(ex.ToString());
                }
            }
            httpHandler.ResponseWrite("{\"data\":\"success\"}");

            return(TaskStatus.Completed);
        }
Exemple #12
0
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            var tranId = httpHandler.QueryString["tranId"];

            //读取临时文件,还原PayParameter参数
            string tempFile  = $"{Helper.GetSaveFilePath()}\\{tranId}.txt";
            var    dict      = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(System.IO.File.ReadAllText(tempFile, Encoding.UTF8));
            var    returnUrl = dict["ReturnUrl"];
            var    tradeID   = dict["TradeID"];

            //移除不要的key
            dict.Remove("ReturnUrl");
            dict.Remove("TradeID");

            if (returnUrl.Contains("?"))
            {
                returnUrl += "&";
            }
            else
            {
                returnUrl += "?";
            }

            returnUrl += $"tradeId={tradeID}";

            var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(dict);
            var html    = Helper.ReadContentFromResourceStream("Jack.Pay.Impls.WeiXinPayPage.html");

            html = html.Replace("<%=payContent%>", jsonStr).Replace("<%=payReturnUrl%>", returnUrl);
            using (Log log = new Log("发起微信JsApi支付"))
            {
                log.LogJson(dict);
                log.Log(html);
            }
            httpHandler.ResponseWrite(html);

            return(TaskStatus.Completed);
        }
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            var querys = httpHandler.QueryString.ToObject <Dictionary <string, string> >();
            var forms  = httpHandler.Form.ToObject <Dictionary <string, string> >();

            using (Log log = new Log("饿了么.Callback", false))
            {
                log.Log("querys:");
                log.LogJson(querys);
                log.Log("forms:");
                log.LogJson(forms);
            }

            if (forms.ContainsKey("pairValue"))
            {
                //手动关联后,提交上来的关联信息
                EleResturant resturan  = new EleResturant();
                var          idinfo    = querys["state"].Split('_');
                int          companyid = int.Parse(idinfo[0]);

                string              token         = forms["token"];
                string              refresh_token = forms["refresh_token"];
                DateTime            expires_in    = Convert.ToDateTime(forms["expires_in"]);
                var                 pairs         = forms["pairValue"].Split(',');//配对字符串,格式为:erpShopId_eleShopId,erpShopId_eleShopId,
                List <StoreMapInfo> mapinfos      = new List <StoreMapInfo>();
                foreach (var str in pairs)
                {
                    if (str.Length == 0)
                    {
                        continue;
                    }
                    idinfo = str.Split('_');
                    int erpStoreId = int.Parse(idinfo[0]);
                    int eleShopId  = int.Parse(idinfo[1]);
                    resturan.BindShop(token, erpStoreId, eleShopId);

                    mapinfos.Add(new StoreMapInfo()
                    {
                        ErpStoreId    = erpStoreId,
                        Token         = token,
                        Refresh_token = refresh_token,
                        Expires       = expires_in
                    });
                }
                ResturantFactory.ResturantListener.OnCompanyMapSuccess(ResturantPlatformType.Ele, companyid, mapinfos.ToArray());
                //输出页面
                var    stream = typeof(Callback).Assembly.GetManifestResourceStream("Jack.Resturant.Impls.Ele.StoreMapSuccess.html");
                byte[] bs     = new byte[stream.Length];
                stream.Read(bs, 0, bs.Length);
                stream.Dispose();

                httpHandler.ResponseWrite(System.Text.Encoding.UTF8.GetString(bs));
            }
            else if (querys.ContainsKey("error"))//error=unauthorized_client
            {
                if (querys["error"] == "unauthorized_client")
                {
                    try
                    {
                        //确定饿了么解除绑定
                        int          erpShopId = Convert.ToInt32(querys["erpShopId"]);
                        string       token     = querys["token"];
                        EleResturant resturan  = new EleResturant();
                        try
                        {
                            //这时候,有可能token已经失效了
                            var shopid = resturan.getShopIdByErpStoreId(token, erpShopId);
                            resturan.UnBindShop(token, erpShopId, shopid);
                        }
                        catch (Exception ex)
                        {
                            using (Log log = new Log("Ele 处理解绑时的error"))
                            {
                                log.Log("此错误不影响代码运行,只是记录");
                                log.Log(ex.ToString());
                            }
                        }
                        ResturantFactory.ResturantListener.OnReleaseStoreMapSuccess(ResturantPlatformType.Ele, erpShopId);

                        //输出页面
                        var    stream = typeof(Callback).Assembly.GetManifestResourceStream("Jack.Resturant.Impls.Ele.ReleaseStoreMap.html");
                        byte[] bs     = new byte[stream.Length];
                        stream.Read(bs, 0, bs.Length);
                        stream.Dispose();
                        httpHandler.ResponseWrite(System.Text.Encoding.UTF8.GetString(bs));
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                httpHandler.ResponseWrite("OK");
            }
            else if (querys.ContainsKey("code"))
            {
                //把state参数解析出companyid和erpStoreId
                var idinfo     = querys["state"].Split('_');
                int companyid  = int.Parse(idinfo[0]);
                int erpStoreId = int.Parse(idinfo[1]);

                //组织回调地址
                var url = ResturantFactory.CurrentDomainUrl;
                if (url.StartsWith("https") == false)
                {
                    url = $"https{url.Substring(4)}";
                }
                url += Callbacks.Callback.NotifyPageName;
                url  = System.Net.WebUtility.UrlEncode(url);

                var    config = new Config(ResturantFactory.ResturantListener.OnGetPlatformConfigXml(ResturantPlatformType.Ele));
                string code   = querys["code"];

                //根据code获取token
                Dictionary <string, string> headers = new Dictionary <string, string>();
                headers["Authorization"] = "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{config.Key}:{config.Secret}"));
                string query = $"grant_type=authorization_code&code={code}&redirect_uri={url}&client_id={config.Key}";

                string result        = Helper.PostQueryString($"{EleResturant.ServerUrl}/token", headers, query, 8000);
                var    jsonObj       = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result);
                string access_token  = jsonObj.Value <string>("access_token");
                int    expires_in    = jsonObj.Value <int>("expires_in");
                string refresh_token = jsonObj.Value <string>("refresh_token");

                //根据token读取店信息
                EleResturant resturan  = new EleResturant();
                var          ele_shops = resturan.getShops(access_token);
                var          sys_shops = ResturantFactory.ResturantListener.OnGetShopList(ResturantPlatformType.Ele, companyid);

                if (ele_shops.Count == 1)
                {
                    resturan.BindShop(access_token, erpStoreId, ele_shops[0].id);
                    List <StoreMapInfo> mapinfos = new List <StoreMapInfo>();
                    mapinfos.Add(new StoreMapInfo()
                    {
                        ErpStoreId    = erpStoreId,
                        Expires       = DateTime.Now.AddSeconds(expires_in),
                        Refresh_token = refresh_token,
                        Token         = access_token
                    });
                    ResturantFactory.ResturantListener.OnCompanyMapSuccess(ResturantPlatformType.Ele, companyid, mapinfos.ToArray());

                    //输出页面
                    var    stream = typeof(Callback).Assembly.GetManifestResourceStream("Jack.Resturant.Impls.Ele.StoreMapSuccess.html");
                    byte[] bs     = new byte[stream.Length];
                    stream.Read(bs, 0, bs.Length);
                    stream.Dispose();
                    httpHandler.ResponseWrite(System.Text.Encoding.UTF8.GetString(bs));
                }
                else
                {
                    //输出手动关联门店页面
                    var    stream = typeof(Callback).Assembly.GetManifestResourceStream("Jack.Resturant.Impls.Ele.StoreMap.html");
                    byte[] bs     = new byte[stream.Length];
                    stream.Read(bs, 0, bs.Length);
                    stream.Dispose();
                    httpHandler.ResponseWrite(System.Text.Encoding.UTF8.GetString(bs) + $"<script lang=\"ja\">document.querySelector('#token').value='{access_token}';document.querySelector('#refresh_token').value='{refresh_token}';document.querySelector('#expires_in').value='{DateTime.Now.AddSeconds(expires_in)}';sys_shops={Newtonsoft.Json.JsonConvert.SerializeObject(sys_shops)};ele_shops={Newtonsoft.Json.JsonConvert.SerializeObject(ele_shops)};</script>");
                }
            }
            else
            {
                httpHandler.ResponseWrite("OK");
            }

            return(TaskStatus.Completed);
        }
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            httpHandler.ResponseContentType = "application/json";
            var forms = httpHandler.Form.ToObject <SortedDictionary <string, string> >();

            try
            {
                if (forms.Count > 0)
                {
                    //验证sign
                    var config = new Config(ResturantFactory.ResturantListener.OnGetPlatformConfigXml(ResturantPlatformType.Meituan));
                    if (forms["sign"] != MeituanHelper.Sign(forms, config.SignKey))
                    {
                        throw new Exception("签名验证失败");
                    }


                    string notifyType = forms["notifyType"];

                    /*
                     * part	发起退款
                     * agree	确认退款
                     * reject	驳回退款
                     */
                    OrderRefundInfo info = new OrderRefundInfo();
                    info.OrderID = forms["orderId"];
                    info.Reason  = forms["reason"];
                    info.Money   = Convert.ToDouble(forms["money"]);
                    if (ResturantFactory.ResturantListener != null)
                    {
                        new Thread(() =>
                        {
                            try
                            {
                                var foodJsonArr = (Newtonsoft.Json.Linq.JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(forms["food"]);
                                for (int i = 0; i < foodJsonArr.Count; i++)
                                {
                                    var dishinfo         = new RefundDishInfo();
                                    dishinfo.DishName    = foodJsonArr[i].Value <string>("food_name");
                                    dishinfo.ErpDishId   = foodJsonArr[i].Value <string>("app_food_code");
                                    dishinfo.RefundPrice = foodJsonArr[i].Value <double>("refund_price");
                                    dishinfo.Price       = foodJsonArr[i].Value <double>("origin_food_price");
                                    dishinfo.Quantity    = foodJsonArr[i].Value <int>("count");
                                    info.RefundDishInfos.Add(dishinfo);
                                }
                            }
                            catch
                            {
                            }
                            try
                            {
                                if (notifyType == "part")
                                {
                                    ResturantFactory.ResturantListener.OnOrderRefund(ResturantPlatformType.Meituan, info);
                                }
                                else if (notifyType == "agree")
                                {
                                    ResturantFactory.ResturantListener.OnOrderRefundCompleted(ResturantPlatformType.Meituan, info);
                                }
                            }
                            catch { }
                        }).Start();
                    }
                }
            }
            catch (Exception ex)
            {
                using (Log log = new Log("美团OrderPartRefundCallback解析错误"))
                {
                    log.Log(ex.ToString());
                }
                throw ex;
            }
            httpHandler.ResponseWrite("{\"data\":\"OK\"}");

            return(TaskStatus.Completed);
        }
Exemple #15
0
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            using (Log logPush = new Log("饿了么.Push", false))
            {
                httpHandler.ResponseContentType = "application/json";
                string postContent = httpHandler.ReadRequestBody();
                logPush.Log(postContent);

                Newtonsoft.Json.Linq.JObject jsonObj = postContent.JsonToObject <Newtonsoft.Json.Linq.JObject>();

                Config config = null;
                try
                {
                    //签名验证
                    config = new Config(ResturantFactory.ResturantListener.OnGetPlatformConfigXml(ResturantPlatformType.Ele));
                    if (EleHelper.CheckSign(jsonObj, config) == false)
                    {
                        throw new Exception("签名错误");
                    }

                    int type = jsonObj.Value <int>("type");
                    System.Diagnostics.Debug.WriteLine($"饿了么 callback type:{type}");
                    if (type == 10)
                    {
                        //新订单
                        new Thread(() =>
                        {
                            try
                            {
                                handleNewOrder(jsonObj);
                            }
                            catch (Exception ex)
                            {
                                using (Log log = new Log("handleNewOrder error"))
                                {
                                    log.Log(ex.ToString());
                                    log.Log("post content:{0}", postContent);
                                }
                            }
                        }).Start();
                    }
                    else if (type == 14)
                    {
                        //订单取消
                        new Thread(() =>
                        {
                            try
                            {
                                handleCancelOrder(jsonObj);
                            }
                            catch (Exception ex)
                            {
                                using (Log log = new Log("handleCancelOrder error"))
                                {
                                    log.Log(ex.ToString());
                                    log.Log("post content:{0}", postContent);
                                }
                            }
                        }).Start();
                    }
                    else if (type == 18)
                    {
                        //订单完结
                        new Thread(() =>
                        {
                            try
                            {
                                handleOrderFinish(jsonObj);
                            }
                            catch (Exception ex)
                            {
                                using (Log log = new Log("handleOrderFinish error"))
                                {
                                    log.Log(ex.ToString());
                                    log.Log("post content:{0}", postContent);
                                }
                            }
                        }).Start();
                    }
                    else if (type == 20)
                    {
                        //用户申请取消订单
                        new Thread(() =>
                        {
                            try
                            {
                                handleOrderToCancel(jsonObj);
                            }
                            catch (Exception ex)
                            {
                                using (Log log = new Log("handleOrderToCancel error"))
                                {
                                    log.Log(ex.ToString());
                                    log.Log("post content:{0}", postContent);
                                }
                            }
                        }).Start();
                    }
                    else if (type == 21 || type == 31)
                    {
                        //用户取消退单
                        new Thread(() =>
                        {
                            try
                            {
                                handleCancelOrderRefund(jsonObj);
                            }
                            catch (Exception ex)
                            {
                                using (Log log = new Log("handleCancelOrderRefund error"))
                                {
                                    log.Log(ex.ToString());
                                    log.Log("post content:{0}", postContent);
                                }
                            }
                        }).Start();
                    }
                    else if (type == 30)
                    {
                        //用户申请退单
                        new Thread(() =>
                        {
                            try
                            {
                                handleOrderRefund(jsonObj);
                            }
                            catch (Exception ex)
                            {
                                using (Log log = new Log("handleOrderRefund error"))
                                {
                                    log.Log(ex.ToString());
                                    log.Log("post content:{0}", postContent);
                                }
                            }
                        }).Start();
                    }
                    else if (type == 33)
                    {
                        //用户同意退单
                        new Thread(() =>
                        {
                            try
                            {
                                handleOrderAgreeRefund(jsonObj);
                            }
                            catch (Exception ex)
                            {
                                using (Log log = new Log("handleOrderAgreeRefund error"))
                                {
                                    log.Log(ex.ToString());
                                    log.Log("post content:{0}", postContent);
                                }
                            }
                        }).Start();
                    }
                }
                catch (Exception ex)
                {
                    using (Log log = new Log("饿了么回调解析错误"))
                    {
                        log.Log(ex.ToString());
                        log.Log("post content:{0}", postContent);
                        if (jsonObj != null)
                        {
                            log.LogJson(jsonObj);
                        }
                        if (config != null)
                        {
                            log.LogJson(config);
                        }
                    }
                    throw ex;
                }
                httpHandler.ResponseWrite("{\"message\": \"ok\"}");

                return(TaskStatus.Completed);
            }
        }
        public TaskStatus Handle(IHttpProxy httpProxy)
        {
            using (CLog log = new CLog("Alipay Notify", false))
            {
                var data = GetRequestData(httpProxy.Form);

                var dataJson = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                log.Log(dataJson);

                if (data.Count > 0)
                {
                    string out_trade_no = data["out_trade_no"];
                    string sign         = httpProxy.Form["sign"];
                    //string sign_type = form["sign_type"];


                    PayFactory.OnLog(out_trade_no, LogEventType.ReceiveNotify, dataJson);

                    var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayScanQRCode, out_trade_no));

                    var signStr = Helper.GetUrlString(data, false);

                    System.Security.Cryptography.RSA rsacore = Way.Lib.RSA.CreateRsaFromPublicKey(config.alipayPublicKey);

                    var isPass = rsacore.VerifyData(Encoding.GetEncoding("utf-8").GetBytes(signStr), Convert.FromBase64String(sign), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);


                    if (isPass == false)
                    {
                        log.Log("sign:{0}", sign);
                        log.Log("签名不一致");
                        httpProxy.ResponseWrite("fail");
                        return(TaskStatus.Completed);
                    }

                    //支付宝交易号
                    string trade_no = data["trade_no"];

                    //交易状态
                    //在支付宝的业务通知中,只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时,才是买家付款成功。
                    string trade_status = data["trade_status"];

                    double?receipt_amount = null;
                    try
                    {
                        receipt_amount = Convert.ToDouble(data["receipt_amount"]);
                    }
                    catch
                    {
                    }
                    log.Log(trade_status);

                    if (trade_status == "TRADE_SUCCESS")
                    {
                        log.Log("excute OnPaySuccessed");
                        PayFactory.OnPaySuccessed(out_trade_no, receipt_amount, null, dataJson);
                    }

                    httpProxy.ResponseWrite("success");
                }
                else
                {
                    httpProxy.ResponseWrite("无通知参数");
                }
            }

            return(TaskStatus.Completed);
        }
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            httpHandler.ResponseContentType = "application/json";
            var forms = httpHandler.Form.ToObject <SortedDictionary <string, string> >();

            try
            {
                if (forms.Count > 0)
                {
                    //验证sign
                    var config = new Config(ResturantFactory.ResturantListener.OnGetPlatformConfigXml(ResturantPlatformType.Meituan));
                    if (forms["sign"] != MeituanHelper.Sign(forms, config.SignKey))
                    {
                        throw new Exception("签名验证失败");
                    }

                    Newtonsoft.Json.Linq.JObject orderJSONObj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(forms["orderRefund"]);
                    string notifyType = orderJSONObj.Value <string>("notifyType");

                    /*
                     * apply	发起退款
                     * agree	确认退款
                     * reject	驳回退款
                     * cancelRefund	用户取消退款申请
                     * cancelRefundComplaint	取消退款申诉
                     */
                    OrderRefundInfo info = new OrderRefundInfo();
                    info.OrderID    = orderJSONObj.Value <string>("orderId");
                    info.ErpStoreID = Convert.ToInt32(forms["ePoiId"]);
                    info.Reason     = orderJSONObj.Value <string>("reason");

                    if (ResturantFactory.ResturantListener != null)
                    {
                        new Thread(() =>
                        {
                            try
                            {
                                if (notifyType == "apply")
                                {
                                    ResturantFactory.ResturantListener.OnOrderRefund(ResturantPlatformType.Meituan, info);
                                }
                                else if (notifyType == "agree")
                                {
                                    ResturantFactory.ResturantListener.OnOrderRefundCompleted(ResturantPlatformType.Meituan, info);
                                }
                                else if (notifyType == "cancelRefund" || notifyType == "cancelRefundComplaint")
                                {
                                    ResturantFactory.ResturantListener.OnCancelOrderRefund(ResturantPlatformType.Meituan, info);
                                }
                            }
                            catch { }
                        }).Start();
                    }
                }
            }
            catch (Exception ex)
            {
                using (Log log = new Log("美团OrderRefundCallback解析错误"))
                {
                    log.Log(ex.ToString());
                }
            }
            httpHandler.ResponseWrite("{\"data\":\"OK\"}");

            return(TaskStatus.Completed);
        }
Exemple #18
0
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            var forms = httpHandler.Form.ToObject <SortedDictionary <string, object> >();

            using (Log log = new Log("Baidu.Callback", false))
            {
                log.LogJson(forms);
            }
            try
            {
                if (forms.Count > 0)
                {
                    var signResult = checkSign(forms);

                    if (signResult)
                    {
                        if (forms["cmd"].Equals("order.create"))
                        {
                            var bodyJson  = (Newtonsoft.Json.Linq.JToken)Newtonsoft.Json.JsonConvert.DeserializeObject(forms["body"].ToString());
                            var order_id  = bodyJson.Value <string>("order_id");
                            var resturant = new BaiduResturant();
                            var orderinfo = resturant.GetOrder(order_id);
                            new Thread(() =>
                            {
                                try
                                {
                                    ResturantFactory.ResturantListener.OnReceiveNewOrder(ResturantPlatformType.Baidu, orderinfo);
                                }
                                catch { }
                            }).Start();
                        }
                        else if (forms["cmd"].Equals("order.status.push"))
                        {
                            var    bodyJson = (Newtonsoft.Json.Linq.JToken)Newtonsoft.Json.JsonConvert.DeserializeObject(forms["body"].ToString());
                            var    order_id = bodyJson.Value <string>("order_id");
                            var    status   = bodyJson.Value <int>("status");
                            string reason   = null;
                            try
                            {
                                reason = bodyJson.Value <string>("reason");
                            }
                            catch
                            {
                            }

                            new Thread(() =>
                            {
                                try
                                {
                                    if (status == 9)
                                    {
                                        //已完成
                                        try
                                        {
                                            //获取店铺实际到账金额
                                            BaiduResturant resturant = new BaiduResturant();
                                            var info = resturant.GetOrderServiceAmount(null, order_id);
                                            ResturantFactory.ResturantListener.OnReceiveOrderSettlement(ResturantPlatformType.Baidu, order_id, info);
                                        }
                                        catch
                                        {
                                        }
                                        ResturantFactory.ResturantListener.OnOrderFinish(ResturantPlatformType.Baidu, order_id);
                                    }
                                    else if (status == 10)
                                    {
                                        //已取消
                                        ResturantFactory.ResturantListener.OnOrderCancel(ResturantPlatformType.Baidu, new OrderCancelInfo()
                                        {
                                            OrderID = order_id,
                                            Reason  = reason
                                        });
                                    }
                                }
                                catch { }
                            }).Start();
                        }
                        else if (forms["cmd"].Equals("shop.unbind.msg"))
                        {
                            //门店解除绑定
                            var bodyJson  = (Newtonsoft.Json.Linq.JToken)Newtonsoft.Json.JsonConvert.DeserializeObject(forms["body"].ToString());
                            var shop_list = (Newtonsoft.Json.Linq.JArray)bodyJson["shop_list"];
                            foreach (var shopJson in shop_list)
                            {
                                var erpShopId = shopJson.Value <int>("supplier_id");
                                ResturantFactory.ResturantListener.OnReleaseStoreMapSuccess(ResturantPlatformType.Baidu, erpShopId);
                            }
                        }
                        else if (forms["cmd"].Equals("shop.bind.msg"))
                        {
                            //门店绑定
                            BaiduResturant resturant = new BaiduResturant();
                            var            bodyJson  = (Newtonsoft.Json.Linq.JToken)Newtonsoft.Json.JsonConvert.DeserializeObject(forms["body"].ToString());
                            var            shop_list = (Newtonsoft.Json.Linq.JArray)bodyJson["shop_list"];
                            foreach (var shopJson in shop_list)
                            {
                                var baidu_shop_id = shopJson.Value <string>("baidu_shop_id");
                                var erpShopId     = resturant.GetErpShopId(baidu_shop_id);
                                ResturantFactory.ResturantListener.OnStoreMapSuccess(ResturantPlatformType.Baidu, new StoreMapInfo()
                                {
                                    ErpStoreId = int.Parse(erpShopId)
                                });
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("签名校验失败");
                    }
                }
            }

            catch (Exception ex)
            {
                using (Log log = new Log("Baidu_Callback Error "))
                {
                    log.LogJson(forms);
                    log.Log(ex.ToString());
                }
                throw ex;
            }

            httpHandler.ResponseWrite("OK");
            return(TaskStatus.Completed);
        }
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            try
            {
                var xml = httpHandler.ReadRequestBody();
                using (CLog log = new CLog("WeiXinNotify Notify", false))
                {
                    log.Log("xml:{0}", xml);

                    XDocument xmldoc = XDocument.Parse(xml);
                    SortedDictionary <string, string> xmlDict = new SortedDictionary <string, string>();
                    var nodes = xmldoc.Root.Elements();
                    foreach (var element in nodes)
                    {
                        if (element.Name.LocalName != "sign")
                        {
                            xmlDict[element.Name.LocalName] = element.Value;
                        }
                    }

                    var return_code  = xmlDict["return_code"];
                    var result_code  = xmlDict["result_code"];
                    var out_trade_no = xmlDict["out_trade_no"];

                    PayFactory.OnLog(out_trade_no, LogEventType.ReceiveNotify, xml);

                    var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinScanQRCode, out_trade_no));

                    log.Log("签名校验");
                    var sign = xmldoc.Root.XPathSelectElement("sign").Value;

                    var computeSign = Helper.GetMd5Hash(xmlDict, config.Key);

                    if (sign != computeSign)
                    {
                        log.Log("正确签名:{0}", computeSign);
                        log.Log("签名校验不通过");
                        throw new Exception("签名校验不通过");
                    }

                    if (result_code == "SUCCESS" && return_code == "SUCCESS")
                    {
                        log.Log("excute OnPaySuccessed");
                        PayFactory.OnPaySuccessed(out_trade_no, null, null, xml);

                        WxPayData data = new WxPayData();
                        data.SetValue("return_code", "SUCCESS");
                        data.SetValue("return_msg", "OK");
                        data.SetValue("appid", config.AppID);
                        data.SetValue("mch_id", config.MchID);
                        data.SetValue("result_code", "SUCCESS");
                        data.SetValue("err_code_des", "OK");
                        data.SetValue("sign", data.MakeSign(config));

                        var writebackXml = data.ToXml();
                        log.Log("write to weixin:{0}", writebackXml);

                        httpHandler.ResponseWrite(writebackXml);
                    }
                }
            }
            catch (Exception ex)
            {
                using (CLog log = new CLog("WeiXin Notify error "))
                {
                    log.Log(ex.ToString());

                    WxPayData res = new WxPayData();
                    res.SetValue("return_code", "FAIL");
                    res.SetValue("return_msg", ex.Message);

                    var writebackXml = res.ToXml();
                    log.Log("write to weixin:{0}", writebackXml);

                    httpHandler.ResponseWrite(writebackXml);
                }
            }
            return(TaskStatus.Completed);
        }