Exemplo n.º 1
0
        public override bool Process(PayChannelEntity pChannel, HttpContext pContext, out Entity.AppOrderEntity pEntity)
        {
            pContext.Response.ContentType = "text/plain";
            try
            {
                //var WXChannel = pChannel.ChannelParameters.DeserializeJSONTo<WeiXinPayChannel>();

                byte[] buffer = new byte[pContext.Request.InputStream.Length];
                pContext.Request.InputStream.Read(buffer, 0, (int)pContext.Request.InputStream.Length);
                string str = Encoding.UTF8.GetString(buffer);
                Loggers.Debug(new DebugLogInfo()
                {
                    Message = "WeiXinNotify:" + str
                });                                                                   //微信回调返回的信息*****可用于本地测试
                //构建通知对象(反序列化)
                WeiXinPayHelper.NotifyResult result = new XmlSerializer(typeof(WeiXinPayHelper.NotifyResult)).Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(str.Replace("xml>", "NotifyResult>")))) as WeiXinPayHelper.NotifyResult;

                Loggers.Debug(new DebugLogInfo()
                {
                    Message = "交易状态:" + result.result_code + Environment.NewLine + result.ToJSON()
                });                                                                                                                  //把反序列化的数据转换成json数据
                //根据通知结果更新订单
                AppOrderBLL bll = new AppOrderBLL(new Utility.BasicUserInfo());

                Loggers.Debug(new DebugLogInfo()
                {
                    Message = "WeiXinNotify_result.out_trade_no:" + result.out_trade_no
                });

                //根据订单号从数据库中找到记录
                pEntity = bll.GetByID(result.out_trade_no);

                if (result.result_code == "SUCCESS")
                {
                    #region 更新订单状态
                    pEntity.Status       = 2;
                    pEntity.ErrorMessage = "";
                    bll.Update(pEntity);
                    #endregion
                    pContext.Response.Write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
                    return(true);
                }
                else
                {
                    pEntity.ErrorMessage = result.err_code_des;
                    bll.Update(pEntity);
                    pContext.Response.Write("<xml><return_code><![CDATA[FAIL]]></return_code></xml>");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                pEntity = null;
                Loggers.Exception(new ExceptionLogInfo(ex));
                pContext.Response.Write("<xml><return_code><![CDATA[FAIL]]></return_code></xml>");
                return(false);
            }
        }
Exemplo n.º 2
0
        public override bool Process(PayChannelEntity pChannel, HttpContext pContext, out Entity.AppOrderEntity pEntity)
        {
            pContext.Response.ContentType = "text/plain";
            try
            {
                var orderId    = pContext.Request["outTradeNo"];
                var outTradeNo = pContext.Request.QueryString["outTradeNo"];
                Loggers.Debug(new DebugLogInfo()
                {
                    Message = "outTradeNo:" + outTradeNo
                });
                Loggers.Debug(new DebugLogInfo()
                {
                    Message = "ChannelID:104&OrderId:" + orderId
                });
                AppOrderBLL bll = new AppOrderBLL(new Utility.BasicUserInfo());
                //根据订单号从数据库中找到记录
                pEntity = bll.GetByID(orderId);


                #region 更新订单状态
                pEntity.Status       = 2;
                pEntity.ErrorMessage = "";
                bll.Update(pEntity);
                #endregion

                return(true);
            }
            catch (Exception ex)
            {
                pEntity = null;
                Loggers.Exception(new ExceptionLogInfo(ex));
                return(false);
            }
        }
Exemplo n.º 3
0
 void bw_DoWork(object sender, DoWorkEventArgs e)
 {
     while (true)
     {
         try
         {
             var bll = new AppOrderBLL(new JIT.Utility.BasicUserInfo());
             //获取未通知的订单信息
             var entitys = bll.GetNotNodify();
             Loggers.Debug(new DebugLogInfo()
             {
                 Message = string.Format("找到{0}条待通知记录", entitys.Length)
             });
             foreach (var item in entitys)
             {
                 string msg;
                 if (NotifyHandler.Notify(item, out msg))
                 {
                     item.IsNotified = true;
                 }
                 else
                 {
                     //设定下次通知时间
                     item.NextNotifyTime = GetNextNotifyTime(item.NotifyCount ?? 0);
                 }
                 //NotifyCount++
                 item.NotifyCount++;
                 //更新数据
                 bll.Update(item);
             }
         }
         catch (Exception ex)
         {
             Loggers.Exception(new ExceptionLogInfo(ex));
         }
         _runCount++;
         if (_runCount % 100 == 0)
         {
             Loggers.Debug(new DebugLogInfo()
             {
                 Message = string.Format("轮循了{0}次", _runCount)
             });
         }
         Thread.Sleep(TimeSpan.FromSeconds(_intval));
     }
 }
Exemplo n.º 4
0
        public override bool Process(PayChannelEntity pChannel, HttpContext context, out Entity.AppOrderEntity entity)
        {
            using (StreamReader sr = new StreamReader(context.Request.InputStream))
            {
                try
                {
                    #region Channel
                    var UnionIVRChannel = pChannel.ChannelParameters.DeserializeJSONTo <UnionPayChannel>();
                    #endregion

                    //读取支付平台发送的交易通知密文
                    string strReq = sr.ReadToEnd();
                    Loggers.Debug(new DebugLogInfo()
                    {
                        Message = "[IVR]Encrypted Transaction Notification Request=" + strReq
                    });
                    //解析交易通知密文,获得交易通知请求的内容
                    var req = IVRGateway.ParseTransactionNotificationRequest(UnionIVRChannel.DecryptCertificateFilePath, strReq);
                    Loggers.Debug(new DebugLogInfo()
                    {
                        Message = "[IVR]Decrypted Transaction Notification Request=" + req.GetContent()
                    });
                    AppOrderBLL bll = new AppOrderBLL(new Utility.BasicUserInfo());
                    entity = bll.GetByID(req.MerchantOrderID);
                    if (req.IsPayOK)
                    {//用户支付成功
                        try
                        {
                            //TODO:业务系统自身的订单处理逻辑(通常为:更新订单状态为支付成功)
                            #region 更新订单状态
                            entity.Status       = 2;
                            entity.ErrorMessage = "";
                            bll.Update(entity);
                            #endregion

                            //业务处理完成后,告诉支付平台处理成功
                            var rsp = TransactionNotificationResponse.OK.GetContent();
                            Loggers.Debug(new DebugLogInfo()
                            {
                                Message = string.Format("[IVR]Transaction Notification Response={0}", rsp)
                            });
                            context.Response.Write(rsp);
                            return(true);
                        }
                        catch (Exception ex)
                        {//业务处理时如果出现异常
                            //记录日志
                            Loggers.Exception(new ExceptionLogInfo(ex));
                            //告诉支付前置,业务处理失败,支付平台会在一定的时间范围内重发交易通知
                            var rsp = TransactionNotificationResponse.FAILED.GetContent();
                            Loggers.Debug(new DebugLogInfo()
                            {
                                Message = string.Format("[IVR]Transaction Notification Response={0}", rsp)
                            });
                            context.Response.Write(rsp);
                            return(false);
                        }
                    }
                    else
                    {//用户支付失败
                        try
                        {
                            //TODO:业务系统自身的订单处理逻辑(通常为:更新订单状态为支付失败)
                            entity.ErrorMessage = req.PayFailedReason;
                            bll.Update(entity);
                            //业务处理完成后,告诉支付平台处理成功
                            var rsp = TransactionNotificationResponse.OK.GetContent();
                            Loggers.Debug(new DebugLogInfo()
                            {
                                Message = string.Format("[IVR]Transaction Notification Response={0}", rsp)
                            });
                            context.Response.Write(rsp);
                            return(false);
                        }
                        catch (Exception ex)
                        {//业务处理时如果出现异常
                            //记录日志
                            Loggers.Exception(new ExceptionLogInfo(ex));
                            //告诉支付前置,业务处理失败,支付平台会在一定的时间范围内重发交易通知
                            var rsp = TransactionNotificationResponse.FAILED.GetContent();
                            Loggers.Debug(new DebugLogInfo()
                            {
                                Message = string.Format("[IVR]Transaction Notification Response={0}", rsp)
                            });
                            context.Response.Write(rsp);
                            return(false);
                        }
                    }
                }
                catch (Exception ex)
                {//出错
                    entity = null;
                    Loggers.Exception(new ExceptionLogInfo(ex));
                    context.Response.Write(TransactionNotificationResponse.FAILED.GetContent());
                    return(false);
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// 使用汇付储值卡支付订单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        internal static PrePaidCardPayRD PrePaidCardPay(TradeRequest request)
        {
            PrePaidCardPayRD rd = new PrePaidCardPayRD();
            var rp       = request.GetParameter <PrePaidCardPayRP>();
            var userInfo = request.GetUserInfo();

            if (rp == null || string.IsNullOrEmpty(rp.OrderId) ||
                string.IsNullOrEmpty(rp.CardNo) || string.IsNullOrEmpty(rp.Password))
            {
                rd.errcode = 40000;
                rd.errmsg  = "参数错误";
                return(rd);
            }

            try
            {
                var appBll   = new AppOrderBLL(userInfo);
                var appOrder = appBll.GetAppOrderByAppOrderId(rp.OrderId);

                if (appOrder == null)
                {
                    rd.errcode = 40001;
                    rd.errmsg  = "未找到支付订单,请重试!";
                    return(rd);
                }

                if (CacheOrder.Contains(rp.OrderId))
                {
                    rd.errcode = 40003;
                    rd.errmsg  = "订单支付中,请稍后重试";
                    return(rd);
                }
                CacheOrder.Add(rp.OrderId); // 限制重复提交支付,只针对单服务器程序,多服务请走第三方缓存

                if (appOrder.Status == 2)
                {
                    rd.errcode = 0;
                    rd.errmsg  = "该订单已支付";
                    return(rd);
                }
                string msg    = string.Empty;
                var    result = Consumption(rp, appOrder, out msg);

                if (result.rspCd == "0000")
                {
                    rd.errcode = 200;
                    rd.errmsg  = "success";

                    AppOrderBLL bll = new AppOrderBLL(new Utility.BasicUserInfo());
                    if (!(appOrder.IsNotified ?? false))
                    {
                        Task.Factory.StartNew(() =>
                        {//起一个新线程通知业务系统处理订单
                            try
                            {
                                string errmsg;
                                if (NotifyHandler.Notify(appOrder, out errmsg))
                                {
                                    appOrder.IsNotified = true;
                                }
                                else
                                {
                                    appOrder.NextNotifyTime = DateTime.Now.AddMinutes(1);
                                }
                                //通知完成,通知次数+1

                                appOrder.NotifyCount = (appOrder.NotifyCount ?? 0) + 1;
                                bll.Update(appOrder);
                            }
                            catch (Exception ex)
                            {
                                Loggers.Exception(new ExceptionLogInfo(ex));
                            }
                        });
                    }
                }
                else
                {
                    rd.errcode = 40002;
                    rd.errmsg  = result.rspDesc;
                }
            }
            catch (Exception ex)
            {
                Loggers.Debug(new DebugLogInfo()
                {
                    Message = ex.Message
                });
            }
            finally
            {
                CacheOrder.Remove(rp.OrderId);
            }
            return(rd);
        }
Exemplo n.º 6
0
        /// <summary>
        /// 记录请求支付日志信息
        /// </summary>
        /// <param name="response"></param>
        /// <param name="para"></param>
        /// <param name="bll"></param>
        /// <param name="entity"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        private static string CreatePayRecord(CreateOrderResponse response, CreateOrderParameters para, AppOrderBLL bll, AppOrderEntity entity, PayChannelEntity channel)
        {
            string url = string.Empty;


            //用于记录支付平台的请求和响应
            string requestJson  = string.Empty;
            string responseJson = string.Empty;

            var recordBll    = new PayRequestRecordBLL(new Utility.BasicUserInfo());
            var recordEntity = new PayRequestRecordEntity()
            {
                ChannelID = channel.ChannelID,
                ClientID  = entity.AppClientID,
                UserID    = entity.AppUserID
            };

            #region 根据Channel类型创建支付订单
            try
            {
                switch (channel.PayType)
                {
                case 1:
                    recordEntity.Platform = 1;
                    #region 银联Wap支付
                    UnionPayChannel unionWapPaychannel = channel.ChannelParameters.DeserializeJSONTo <UnionPayChannel>();
                    PreOrderRequest Wapreq             = new PreOrderRequest()
                    {
                        BackUrl               = ConfigurationManager.AppSettings["UnionPayWapNotifyUrl"].Trim('?') + string.Format("?ChannelID={0}", channel.ChannelID),
                        FrontUrl              = string.IsNullOrEmpty(para.ReturnUrl) ? ConfigurationManager.AppSettings["UnionPayCallBackUrl"] : para.ReturnUrl,
                        MerchantID            = unionWapPaychannel.MerchantID,
                        SendTime              = DateTime.Now,
                        MerchantOrderCurrency = Currencys.RMB,
                        MerchantOrderDesc     = entity.AppOrderDesc,
                        MerchantOrderAmt      = entity.AppOrderAmount,
                        MerchantOrderID       = entity.OrderID.ToString(),
                        SendSeqID             = Guid.NewGuid().ToString("N"),
                        MerchantOrderTime     = entity.AppOrderTime
                    };
                    requestJson = Wapreq.ToJSON();
                    var unionWapResponse = JIT.Utility.Pay.UnionPay.Interface.Wap.WapGateway.PreOrder(unionWapPaychannel, Wapreq);
                    responseJson = unionWapResponse.ToJSON();
                    if (unionWapResponse.IsSuccess)
                    {
                        entity.PayUrl = unionWapResponse.RedirectURL;
                        entity.Status = 1;
                        bll.Update(entity);
                        url = unionWapResponse.RedirectURL;
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = string.Format("银联Wap创建订单成功{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, Wapreq.ToJSON(), unionWapResponse.ToJSON())
                        });
                    }
                    else
                    {
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = string.Format("银联Wap创建订单失败{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, Wapreq.ToJSON(), unionWapResponse.ToJSON())
                        });
                        response.ResultCode = 100;
                        response.Message    = unionWapResponse.Description;
                    }
                    #endregion
                    break;

                case 2:
                    recordEntity.Platform = 1;
                    #region 银联语音支付
                    UnionPayChannel unionIVRPaychannel = channel.ChannelParameters.DeserializeJSONTo <UnionPayChannel>();
                    JIT.Utility.Pay.UnionPay.Interface.IVR.Request.PreOrderRequest IVRreq = new Utility.Pay.UnionPay.Interface.IVR.Request.PreOrderRequest()
                    {
                        SendTime          = DateTime.Now,
                        SendSeqID         = Guid.NewGuid().ToString("N"),
                        FrontUrl          = string.IsNullOrEmpty(para.ReturnUrl) ? ConfigurationManager.AppSettings["UnionPayCallBackUrl"] : para.ReturnUrl,
                        BackUrl           = ConfigurationManager.AppSettings["UnionPayIVRNotifyUrl"].Trim('?') + string.Format("?ChannelID={0}", channel.ChannelID),
                        MerchantOrderDesc = entity.AppOrderDesc,
                        Mode                  = IVRModes.Callback,
                        TransTimeout          = entity.AppOrderTime,
                        MerchantOrderCurrency = Currencys.RMB,
                        MerchantOrderAmt      = entity.AppOrderAmount,
                        MerchantID            = unionIVRPaychannel.MerchantID,
                        MerchantOrderTime     = entity.AppOrderTime,
                        MerchantOrderID       = entity.OrderID.ToString(),
                        MobileNum             = entity.MobileNO
                    };
                    requestJson = IVRreq.ToJSON();
                    var IvrResponse = IVRGateway.PreOrder(unionIVRPaychannel, IVRreq);
                    responseJson = IvrResponse.ToJSON();
                    if (IvrResponse.IsSuccess)
                    {
                        entity.Status = 1;
                        bll.Update(entity);
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = string.Format("银联IVR创建订单成功{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, IVRreq.ToJSON(), IvrResponse.ToJSON())
                        });
                    }
                    else
                    {
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = string.Format("银联IVR创建订单失败{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, IVRreq.ToJSON(), IvrResponse.ToJSON())
                        });
                        response.ResultCode = 200;
                        response.Message    = IvrResponse.Description;
                    }
                    #endregion
                    break;

                case 3:
                    recordEntity.Platform = 2;
                    #region 阿里Wap支付
                    AliPayChannel         aliPayWapChannel = channel.ChannelParameters.DeserializeJSONTo <AliPayChannel>();
                    AliPayWapTokenRequest tokenRequest     = new AliPayWapTokenRequest(aliPayWapChannel)
                    {
                        CallBackUrl       = string.IsNullOrEmpty(para.ReturnUrl) ? ConfigurationManager.AppSettings["AliPayCallBackUrl"] : para.ReturnUrl,
                        NotifyUrl         = ConfigurationManager.AppSettings["AlipayWapNotify"].Trim('?') + string.Format("?ChannelID={0}", channel.ChannelID),
                        OutTradeNo        = entity.OrderID.ToString(),
                        Partner           = aliPayWapChannel.Partner,
                        SellerAccountName = aliPayWapChannel.SellerAccountName,
                        Subject           = entity.AppOrderDesc,
                        TotalFee          = Math.Round((Convert.ToDecimal(entity.AppOrderAmount) / 100), 2).ToString(),
                        ReqID             = Guid.NewGuid().ToString().Replace("-", "")
                    };
                    requestJson = tokenRequest.ToJSON();
                    var aliPayWapResponse = AliPayWapGeteway.GetQueryTradeResponse(tokenRequest, aliPayWapChannel);
                    responseJson = aliPayWapResponse.ToJSON();
                    if (aliPayWapResponse.IsSucess)
                    {
                        entity.PayUrl = aliPayWapResponse.RedirectURL;
                        entity.Status = 1;
                        bll.Update(entity);
                        url = aliPayWapResponse.RedirectURL;
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = string.Format("AliPayWap创建订单成功{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, tokenRequest.ToJSON(), aliPayWapResponse.ToJSON())
                        });
                    }
                    else
                    {
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = string.Format("AliPayWap创建订单失败{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, tokenRequest.ToJSON(), aliPayWapResponse.ToJSON())
                        });
                        response.ResultCode = 300;
                        response.Message    = aliPayWapResponse.Message;
                    }
                    #endregion
                    break;

                case 4:
                    recordEntity.Platform = 2;
                    #region 阿里OffLine支付
                    AliPayChannel aliPayChannel = channel.ChannelParameters.DeserializeJSONTo <AliPayChannel>();
                    //根据DynamicID判断是否预定单支付,DynamicID为空或者Null时调用OffLine预订单接口
                    if (string.IsNullOrWhiteSpace(para.DynamicID))
                    {
                        OfflineQRCodePreRequest qrRequest = new OfflineQRCodePreRequest(aliPayChannel)
                        {
                            OutTradeNo = entity.OrderID.ToString(),
                            NotifyUrl  = ConfigurationManager.AppSettings["AlipayOfflineNotify"].Trim('?') + string.Format("?ChannelID={0}", channel.ChannelID),
                            Subject    = entity.AppOrderDesc,
                            TotalFee   = Math.Round((Convert.ToDecimal(entity.AppOrderAmount) / 100), 2).ToString(),
                            //下面是测试数据,正式须更改
                            ExtendParams = new
                            {
                                MACHINE_ID  = "BJ_001", //?
                                AGENT_ID    = aliPayChannel.AgentID,
                                STORE_TYPE  = "0",      //?
                                STORE_ID    = "12314",  //?
                                TERMINAL_ID = "111",    //?
                                SHOP_ID     = "only"    //?
                            }.ToJSON()
                        };
                        requestJson = qrRequest.ToJSON();
                        var offlineQrResponse = AliPayOffLineGeteway.OfflineQRPay(qrRequest);
                        responseJson = offlineQrResponse.ToJSON();
                        if (offlineQrResponse.IsSucess)
                        {
                            entity.Status = 1;
                            entity.PayUrl = offlineQrResponse.PicUrl;
                            bll.Update(entity);
                            response.QrCodeUrl = offlineQrResponse.PicUrl;
                            Loggers.Debug(new DebugLogInfo()
                            {
                                Message = string.Format("AliPayOffline二维码支付创建订单成功{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, qrRequest.ToJSON(), offlineQrResponse.ToJSON())
                            });
                        }
                        else
                        {
                            Loggers.Debug(new DebugLogInfo()
                            {
                                Message = string.Format("AliPayOffline二维码支付创建订单失败{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, qrRequest.ToJSON(), offlineQrResponse.ToJSON())
                            });
                            response.ResultCode = 400;
                            response.Message    = offlineQrResponse.DetailErrorCode + ":" + offlineQrResponse.DetailErrorDes;
                        }
                    }
                    else
                    {
                        CreateAndPayRequest createAndPayrequest = new CreateAndPayRequest(aliPayChannel)
                        {
                            Subject       = entity.AppOrderDesc,
                            TotalFee      = Math.Round((Convert.ToDecimal(entity.AppOrderAmount) / 100), 2).ToString(),
                            NotifyUrl     = ConfigurationManager.AppSettings["AlipayOfflineNotify"].Trim('?') + string.Format("?ChannelID={0}", channel.ChannelID),
                            OutTradeNo    = entity.OrderID.ToString(),
                            DynamicIDType = para.DynamicIDType,
                            DynamicID     = para.DynamicID,
                        };
                        if (!string.IsNullOrEmpty(aliPayChannel.AgentID))
                        {
                            createAndPayrequest.ExtendParams = (new
                            {
                                AGENT_ID = aliPayChannel.AgentID,
                                MACHINE_ID = "BJ_001",
                                STORE_TYPE = "0",
                                STORE_ID = "BJ_ZZ_001",
                                TERMINAL_ID = "A80001",
                                SHOP_ID = "only"
                            }).ToJSON();
                        }
                        requestJson = createAndPayrequest.ToJSON();
                        var offlineCreateAndPayResponse = AliPayOffLineGeteway.OfflineCreateAndPay(createAndPayrequest);
                        responseJson = offlineCreateAndPayResponse.ToJSON();
                        if (offlineCreateAndPayResponse.IsSuccess)
                        {
                            entity.Status = 2;
                            bll.Update(entity);
                            Loggers.Debug(new DebugLogInfo()
                            {
                                Message = string.Format("AliPayOffline即支付创建订单成功{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, createAndPayrequest.ToJSON(), offlineCreateAndPayResponse.ToJSON())
                            });
                        }
                        else if (offlineCreateAndPayResponse.ResultCode == ResultCodes.ORDER_SUCCESS_PAY_FAIL.ToString())
                        {
                            entity.Status = 1;
                            bll.Update(entity);
                            Loggers.Debug(new DebugLogInfo()
                            {
                                Message = string.Format("AliPayOffline即支付创建订单成功{0},支付失败【请求】:{1}{0}【响应】:{2}", Environment.NewLine, createAndPayrequest.ToJSON(), offlineCreateAndPayResponse.ToJSON())
                            });
                        }
                        else if (offlineCreateAndPayResponse.ResultCode == ResultCodes.ORDER_SUCCESS_PAY_INPROCESS.ToString())
                        {
                            entity.Status = 1;
                            bll.Update(entity);
                            Loggers.Debug(new DebugLogInfo()
                            {
                                Message = string.Format("AliPayOffline即支付创建订单成功{0},支付处理中【请求】:{1}{0}【响应】:{2}", Environment.NewLine, createAndPayrequest.ToJSON(), offlineCreateAndPayResponse.ToJSON())
                            });
                        }
                        else
                        {
                            Loggers.Debug(new DebugLogInfo()
                            {
                                Message = string.Format("AliPayOffline即支付创建订单失败{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, createAndPayrequest.ToJSON(), offlineCreateAndPayResponse.ToJSON())
                            });
                            response.ResultCode = 400;
                            response.Message    = offlineCreateAndPayResponse.DetailErrorCode + ":" + offlineCreateAndPayResponse.DetailErrorDes;
                        }
                    }
                    #endregion
                    break;

                case 5:    //Native
                case 6:    //微信JS
                case 7:    //微信App
                    recordEntity.Platform = 3;
                    #region 微信Native支付,JS支付
                    //把channel里的参数传了过去
                    WeiXinPayHelper helper = new WeiXinPayHelper(channel.ChannelParameters.DeserializeJSONTo <WeiXinPayHelper.Channel>());
                    entity.PayUrl    = ConfigurationManager.AppSettings["WeiXinPrePay"];
                    entity.NotifyUrl = ConfigurationManager.AppSettings["WeiXinPayNotify"];
                    WeiXinPayHelper.PrePayResult result = null;

                    if (para.PaymentMode == 1)    //PaymentMode=1标示微信扫码支付进入
                    {
                        helper.channel.trade_type = "NATIVE";
                        channel.PayType           = 5; //走扫码回调返回参数
                    }

                    Loggers.Debug(new DebugLogInfo()
                    {
                        Message = "isSpPay:" + helper.channel.isSpPay
                    });

                    if (helper.channel.isSpPay == "1")     //isSpPay=1 服务商支付
                    {
                        result = helper.serPrePay(entity); //统一下单,服务商支付
                    }
                    else
                    {
                        result = helper.prePay(entity);    //统一下单,获取微信网页支付的预支付信息,app支付和js支付是一样的
                    }

                    Loggers.Debug(new DebugLogInfo()
                    {
                        Message = "微信支付_预支付返回结果:" + result.ToJSON()
                    });
                    requestJson  = helper.prePayRequest;
                    responseJson = helper.prePayResponse;
                    if (result.return_code == "SUCCESS" && result.result_code == "SUCCESS")
                    {
                        if (channel.PayType == 6)
                        {
                            response.WXPackage = helper.getJsParamater(result);
                        }
                        else if (channel.PayType == 7)    //后面传的参数和js支付的就不一样了
                        {
                            response.WXPackage = helper.getAppParamater(result);
                            response.OrderID   = entity.OrderID;
                        }
                        else    //Native
                        {
                            response.WXPackage = result.ToJSON();
                            response.QrCodeUrl = result.code_url;
                        }
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = "WXPackage:" + response.WXPackage
                        });
                    }
                    else
                    {
                        response.ResultCode = 101;                    //支付失败
                        if (!string.IsNullOrEmpty(result.return_msg)) //不同错误,错误信息位置不同
                        {
                            response.Message = result.return_msg;
                        }
                        else
                        {
                            response.Message = result.err_code_des;
                        }
                    }

                    #endregion
                    break;

                case 8:    //旺财支付
                    return(string.Empty);

                case 9:    //新版支付宝扫码支付
                    #region
                    AliPayChannel     aliPayScanChannel = channel.ChannelParameters.DeserializeJSONTo <AliPayChannel>();
                    RequestScanEntity scRequest         = new RequestScanEntity(aliPayScanChannel);
                    scRequest.notify_url = "" + ConfigurationManager.AppSettings["AlipayOfflineNotify"];

                    RequstScanDetail scanDetail = new RequstScanDetail();
                    scanDetail.out_trade_no = "" + entity.OrderID;
                    scanDetail.total_amount = "" + Math.Round((Convert.ToDecimal(entity.AppOrderAmount) / 100), 2);
                    scanDetail.seller_id    = aliPayScanChannel.Partner;
                    scanDetail.subject      = entity.AppOrderDesc;

                    var scResponseJson = AliPayScanGeteway.GetResponseStr(scRequest, scanDetail.ToJSON(), aliPayScanChannel.RSA_PrivateKey);
                    var scResponse     = scResponseJson.DeserializeJSONTo <ResponsetScanEntity>();

                    if (scResponse.alipay_trade_precreate_response.code == "10000")
                    {
                        response.QrCodeUrl = scResponse.alipay_trade_precreate_response.qr_code;
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = string.Format("aliPayScanChannel二维码支付创建订单成功{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, requestJson, scResponseJson)
                        });
                    }
                    else
                    {
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = string.Format("AliPayOffline二维码支付创建订单失败{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, requestJson, scResponseJson)
                        });
                        response.ResultCode = 400;
                        response.Message    = scResponse.alipay_trade_precreate_response.code + ":" + scResponse.alipay_trade_precreate_response.msg;
                    }
                    #endregion
                    break;

                default:
                    break;
                }
                recordEntity.RequestJson  = requestJson;
                recordEntity.ResponseJson = responseJson;
                recordBll.Create(recordEntity);
            }
            catch (Exception ex)
            {
                recordEntity.RequestJson  = requestJson;
                recordEntity.ResponseJson = responseJson;
                recordBll.Create(recordEntity);
                throw ex;
            }
            #endregion
            return(url);
        }
Exemplo n.º 7
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var channelid = Convert.ToInt32(context.Request["ChannelID"]);
                Loggers.Debug(new DebugLogInfo()
                {
                    Message = "ChannelID:" + channelid
                });
                var paychannelbll = new PayChannelBLL(new Utility.BasicUserInfo());
                var paychannel    = paychannelbll.GetByID(channelid);

                AppOrderEntity entity;
                AppOrderBLL    bll = new AppOrderBLL(new Utility.BasicUserInfo());
                if (Process(paychannel, context, out entity))
                {
                    Loggers.Debug(new DebugLogInfo()
                    {
                        Message = "entity:" + entity.ToJSON()
                    });
                    if (!entity.IsNotified.HasValue)
                    {
                        entity.IsNotified = false;
                    }
                    if (!entity.IsNotified.Value)
                    {
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = "IsNotified is false"
                        });
                        //var t = Task.Factory.StartNew(() =>
                        //  {//起一个新线程通知业务系统处理订单
                        try
                        {
                            string msg;
                            if (Notify(entity, out msg))
                            {
                                entity.IsNotified = true;
                            }
                            else
                            {
                                entity.NextNotifyTime = DateTime.Now.AddMinutes(1);
                            }
                            //通知完成,通知次数+1
                            entity.NotifyCount = (entity.NotifyCount ?? 0) + 1;
                            bll.Update(entity);
                        }
                        catch (Exception ex)
                        {
                            Loggers.Exception(new ExceptionLogInfo(ex));
                        }
                        //});
                        //t.Wait();
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = "task is end"
                        });
                    }
                    else
                    {
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = "已处理过的订单"
                        });
                    };
                }
                else
                {
                    if (entity != null)
                    {
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = "交易失败:" + entity.ErrorMessage
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Loggers.Debug(new DebugLogInfo()
                {
                    Message = "error:" + ex.Message
                });
                context.Response.Write(ex);
            }
        }
Exemplo n.º 8
0
 public override bool Process(PayChannelEntity pChannel, HttpContext context, out Entity.AppOrderEntity entity)
 {
     context.Response.ContentType = "text/plain";
     try
     {
         var channel = pChannel.ChannelParameters.DeserializeJSONTo <AliPayChannel>();
         Dictionary <string, string> sPara = new Dictionary <string, string>();
         foreach (var item in context.Request.Form.AllKeys)
         {
             sPara[item] = context.Request.Form[item];
         }
         WapNotify notify = new WapNotify();
         notify.Load(sPara);
         var data = notify.GetNotifyData(channel);
         Loggers.Debug(new DebugLogInfo()
         {
             Message = "交易状态:" + data.TradeStatus
         });
         AppOrderBLL bll = new AppOrderBLL(new Utility.BasicUserInfo());
         entity = bll.GetByID(data.OutTradeNo);
         Loggers.Debug(new DebugLogInfo()
         {
             Message = "AppOrder:" + entity.ToJSON()
         });
         if (data.TradeStatus == TradeStatus.TRADE_FINISHED.ToString() || data.TradeStatus == TradeStatus.TRADE_SUCCESS.ToString())
         {
             #region 分润
             //PayChannelBLL pbll = new PayChannelBLL(new Utility.BasicUserInfo());
             //var channel = pbll.GetByID(entity.PayChannelID).ChannelParameters.DeserializeJSONTo<AliPayWapChannel>();
             //RoyaltyRequest royaltyrequest = new RoyaltyRequest()
             //{
             //    TradeNo = data.TradeNo,
             //    OutTradeNo = data.OutTradeNo,
             //    OutBillNo = Helper.GetDataRandom(),
             //    Partner = AliPayConfig.Partner,
             //    RoyaltyType = "10",
             //    RoyaltyParameters = "[email protected]^0.01^Test",
             //};
             //if (!string.IsNullOrEmpty(channel.GetRoyaltyStr()))
             //{
             //    royaltyrequest.RoyaltyParameters = channel.GetRoyaltyStr();
             //}
             //try
             //{
             //    var royalReaponse = AliPayWapGeteway.GetRoyaltyResponse(royaltyrequest);
             //    Loggers.Debug(new DebugLogInfo() { Message = royalReaponse.ToJSON() });
             //    if (royalReaponse.IsSuccess == "T")
             //    {
             //        Loggers.Debug(new DebugLogInfo() { Message = "分润成功" });
             //    }
             //    else
             //    {
             //        Loggers.Debug(new DebugLogInfo() { Message = "分润失败" });
             //    }
             //    context.Response.Write("successss");
             //    Loggers.Debug(new DebugLogInfo() { Message = "交易成功" });
             //}
             //catch (Exception ex)
             //{
             //    context.Response.Write("fail");
             //    Loggers.Exception(new ExceptionLogInfo(ex));
             //}
             #endregion
             #region 更新订单状态
             entity.Status       = 2;
             entity.ErrorMessage = "";
             bll.Update(entity);
             Loggers.Debug(new DebugLogInfo()
             {
                 Message = "更新订单状态成功!"
             });
             #endregion
             context.Response.Write("success");
             return(true);
         }
         else
         {
             entity.ErrorMessage = data.TradeStatus;
             bll.Update(entity);
             context.Response.Write("fail");
             return(false);
         }
     }
     catch (Exception ex)
     {
         Loggers.Exception(new ExceptionLogInfo(ex));
         entity = null;
         context.Response.Write("fail");
         return(false);
     }
 }
Exemplo n.º 9
0
        public override bool Process(PayChannelEntity pChannel, HttpContext pContext, out Entity.AppOrderEntity pEntity)
        {
            pContext.Response.ContentType = "text/plain";
            try
            {
                //组织支付平台回调时回传的参数集
                Dictionary <string, string> sPara = new Dictionary <string, string>();
                foreach (var item in pContext.Request.Form.AllKeys)
                {
                    sPara[item] = pContext.Request.Form[item];
                }
                //构建通知对象
                OfflineNotify notify = new OfflineNotify();
                notify.Load(sPara);
                Loggers.Debug(new DebugLogInfo()
                {
                    Message = "交易状态:" + notify.TradeStatus + Environment.NewLine + notify.ToJSON()
                });
                //根据通知结果更新订单
                AppOrderBLL bll = new AppOrderBLL(new Utility.BasicUserInfo());
                //根据订单号从数据库中找到记录
                pEntity = bll.GetByID(notify.OutTradeNo);

                Loggers.Debug(new DebugLogInfo()
                {
                    Message = "OutTradeNo:" + notify.OutTradeNo + ", TradeStatus:" + notify.TradeStatus + ", pEntity:" + pEntity.ToJSON()
                });

                if (notify.TradeStatus == TradeStatus.TRADE_FINISHED.ToString() || notify.TradeStatus == TradeStatus.TRADE_SUCCESS.ToString())
                {
                    #region 更新订单状态
                    pEntity.Status       = 2;
                    pEntity.ErrorMessage = "";
                    bll.Update(pEntity);
                    #endregion
                    pContext.Response.Write("success");

                    Loggers.Debug(new DebugLogInfo()
                    {
                        Message = "更新订单状态成功!"
                    });

                    return(true);
                }
                else
                {
                    pEntity.ErrorMessage = notify.TradeStatus;
                    bll.Update(pEntity);
                    pContext.Response.Write("fail");

                    Loggers.Debug(new DebugLogInfo()
                    {
                        Message = "更新订单状态失败:" + notify.TradeStatus
                    });

                    return(false);
                }
            }
            catch (Exception ex)
            {
                pContext.Response.Write("fail");
                pEntity = null;
                Loggers.Exception(new ExceptionLogInfo()
                {
                    ErrorMessage = ex.Message
                });
                return(false);
            }
        }
Exemplo n.º 10
0
        /*
         * <xml><appid><![CDATA[wxb4f8f3d799d22f03]]></appid>
         * <attach><![CDATA[测试数据]]></attach>
         * <bank_type><![CDATA[CFT]]></bank_type>
         * <cash_fee><![CDATA[1]]></cash_fee>
         * <fee_type><![CDATA[CNY]]></fee_type>
         * <is_subscribe><![CDATA[Y]]></is_subscribe>
         * <mch_id><![CDATA[1264926201]]></mch_id>
         * <nonce_str><![CDATA[rdwbEb2FXXmV7LBF]]></nonce_str>
         * <openid><![CDATA[oY-Cqs7wZ6p_Cq_0AAP2QHLhANRc]]></openid>
         * <out_trade_no><![CDATA[126492620120160426005955291]]></out_trade_no>
         * <result_code><![CDATA[SUCCESS]]></result_code>
         * <return_code><![CDATA[SUCCESS]]></return_code>
         * <sign><![CDATA[C251718418AFA3FDEB764E258F220340]]></sign>
         * <time_end><![CDATA[20160426010056]]></time_end>
         * <total_fee>1</total_fee>
         * <trade_type><![CDATA[NATIVE]]></trade_type>
         * <transaction_id><![CDATA[4008492001201604265225452570]]></transaction_id>
         * </xml>
         */
        #endregion
        public void ProcessRequest(HttpContext context)
        {
            WxPayData res = new WxPayData();

            try
            {
                context.Response.ContentType = "text/plain";

                System.IO.Stream s    = context.Request.InputStream;
                int           count   = 0;
                byte[]        buffer  = new byte[1024];
                StringBuilder builder = new StringBuilder();
                while ((count = s.Read(buffer, 0, 1024)) > 0)
                {
                    builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
                }
                s.Flush();
                s.Close();
                s.Dispose();

                Loggers.Debug(new DebugLogInfo()
                {
                    Message = string.Format("Receive data from WeChat : {0}", builder.ToString())
                });

                string rspStr = builder.ToString().
                                Replace("<![CDATA[", "").Replace("]]>", "");
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(rspStr);

                string orderId    = doc.GetElementsByTagName("out_trade_no")[0].InnerText;
                string resultcode = doc.GetElementsByTagName("result_code")[0].InnerText;
                string openId     = doc.GetElementsByTagName("openid")[0].InnerText;

                AppOrderBLL    bll      = new AppOrderBLL(new Utility.BasicUserInfo());
                AppOrderEntity appOrder = bll.QueryByEntity(new AppOrderEntity()
                {
                    AppOrderID = orderId,
                }, null).FirstOrDefault();


                if (appOrder != null && resultcode == "SUCCESS" && appOrder.Status != 2)
                {
                    appOrder.Status = 2;
                    new RechargeBLL().RechargeTonysCardAct2(appOrder);
                }

                if (appOrder != null && !(appOrder.IsNotified ?? false))
                {
                    try
                    {
                        string msg;
                        if (NotifyHandler.Notify(appOrder, out msg, true))
                        {
                            appOrder.IsNotified = true;
                        }
                        else
                        {
                            appOrder.NextNotifyTime = DateTime.Now.AddMinutes(1);
                        }
                        //通知完成,通知次数+1
                        appOrder.NotifyCount = (appOrder.NotifyCount ?? 0) + 1;
                        bll.Update(appOrder);
                    }
                    catch (Exception ex)
                    {
                        Loggers.Exception(new ExceptionLogInfo(ex));
                        res.SetValue("return_code", "FAIL");
                        res.SetValue("return_msg", "FAIL");
                    }
                }

                NotifyHandler.NotifyTFSaveWxVipInfo(appOrder.AppOrderID, appOrder.AppClientID, openId);
                if ((appOrder.IsNotified ?? false) && appOrder.Status == 2)
                {
                    res.SetValue("return_code", "SUCCESS");
                    res.SetValue("return_msg", "OK");
                }
            }
            catch (Exception ex)
            {
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
            }
            context.Response.Write(res.ToXml());
            context.Response.End();
        }
Exemplo n.º 11
0
        public void ProcessRequest(HttpContext context)
        {
            string res = "{\"CODE\": \"00\", \"MSG\": \"OK\"}";// Y/N 接收成功或失败

            try
            {
                context.Response.ContentType = "application/json";
                #region 获取流数据
                System.IO.Stream s    = context.Request.InputStream;
                int           count   = 0;
                byte[]        buffer  = new byte[1024];
                StringBuilder builder = new StringBuilder();
                while ((count = s.Read(buffer, 0, 1024)) > 0)
                {
                    builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
                }
                s.Flush();
                s.Close();
                s.Dispose();
                #endregion

                string rspStr = builder.ToString();
                //Task.Factory.StartNew(() =>
                //{
                //    HttpHelper.SendSoapRequest(DateTime.Now + "  收到旺财支付回调:" + rspStr, "http://182.254.242.12:56789/log/push/");
                //});
                Loggers.Debug(new DebugLogInfo()
                {
                    Message = string.Format("Receive data from PALifePay : {0}", rspStr)
                });


                LifePayRP req = rspStr.DeserializeJSONTo <LifePayRP>();

                string orderId    = req.merOrderNo;
                string resultcode = req.notifyType;
                string openId     = req.openId;

                AppOrderBLL    bll      = new AppOrderBLL(new Utility.BasicUserInfo());
                AppOrderEntity appOrder = bll.QueryByEntity(new AppOrderEntity()
                {
                    AppOrderID = orderId,
                }, null).FirstOrDefault();

                // 00 成功 01 失败 02 其他
                if (appOrder != null && resultcode == "00" && appOrder.Status != 2)
                {
                    appOrder.Status = 2;
                }

                if (appOrder != null && !(appOrder.IsNotified ?? false))
                {
                    try
                    {
                        string    msg;
                        Hashtable ht = new Hashtable();
                        ht.Add("serialNo", req.serialNo);
                        // 异步通知cpos
                        if (NotifyHandler.Notify(appOrder, out msg, ht))
                        {
                            appOrder.IsNotified = true;
                        }
                        else
                        {
                            appOrder.NextNotifyTime = DateTime.Now.AddMinutes(1);
                        }
                        //通知完成,通知次数+1
                        appOrder.NotifyCount = (appOrder.NotifyCount ?? 0) + 1;
                        bll.Update(appOrder);
                    }
                    catch (Exception ex)
                    {
                        Loggers.Exception(new ExceptionLogInfo(ex));
                    }
                }
                if ((appOrder.IsNotified ?? false) && appOrder.Status == 2)
                {
                    res = "{\"CODE\": \"00\", \"MSG\": \"OK\"}";//
                }
            }
            catch (Exception ex)
            {
                res = "{\"CODE\": \"01\", \"MSG\": \"" + ex + "\"}";//
            }
            Loggers.Debug(new DebugLogInfo()
            {
                Message = string.Format("Response data from PALifePay : {0}", res)
            });
            context.Response.Write(res);
            context.Response.End();
        }